/trade/leverage

Updates leverage for positions of a given market and closes all open orders for that market.

Client Library

#!/usr/bin/env python

import asyncio
import logging
import time

from bluefin_pro_sdk import BluefinProSdk, Environment, RpcUrl
from crypto_helpers.signature import SuiWallet

# Set up logging
logging.basicConfig(level=logging.INFO)
log = logging.getLogger(__name__)


def now():
    """Return the current time in milliseconds since the Epoch."""
    return int(time.time() * 1000)


async def main():
    """
    Example showing how to update leverage on an account's position using the Bluefin Pro API
    using the PRODUCTION environment.
    """
    # Create a wallet with your private key
    sui_wallet = SuiWallet(
        mnemonic="dilemma salmon lake ceiling moral glide cute that ginger float area aunt vague remind cage mother concert inch dizzy present proud program time urge"
    )

    log.info(f"Using wallet address: {sui_wallet.sui_address}")

    # Initialize the Bluefin Pro SDK client with PRODUCTION environment and RPC
    async with BluefinProSdk(
            sui_wallet=sui_wallet,
            contracts=None,  # Not needed for this example
            rpc_url=RpcUrl.PROD,
            env=Environment.PRODUCTION,
            debug=False  # Set to True for more verbose output
    ) as client:
        try:
            # Initialize the client, which will handle authentication
            await client.init()
            
            # ========= Deauthorize a wallet ==========
            log.info("Updating leverage")
            await client.update_leverage("ETH-PERP", "1000000000")

        except Exception as e:
            log.error(f"Error updating leverage: {e}")
            raise


if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        log.info("Exiting due to keyboard interrupt")

use bluefin_api::apis::configuration::Configuration;
use bluefin_api::apis::trade_api::put_leverage_update;
use bluefin_api::models::LoginRequest;
use bluefin_api::models::{
    AccountPositionLeverageUpdateRequest, AccountPositionLeverageUpdateRequestSignedFields,
};
use bluefin_pro::prelude::*;
use chrono::Utc;
use hex::FromHex;
use rand::random;
use sui_sdk_types::SignatureScheme;

type Error = Box<dyn std::error::Error>;
type Result<T> = std::result::Result<T, Error>;

// Will return an Ok(()) if the request has successfully been submitted to Bluefin
async fn send_request(
    request: AccountPositionLeverageUpdateRequest,
    auth_token: &str,
) -> Result<()> {
    println!("Sending request...");
    // Send request and get back order hash
    let mut config = Configuration::new();
    config.bearer_access_token = Some(auth_token.into());
    config.base_path = trade::mainnet::URL.into();

    put_leverage_update(&config, request).await?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    // First, we construct an authentication request.
    let request = LoginRequest {
        account_address: "INSERT_ACCOUNT_ADDRESS_HERE",
        audience: auth::mainnet::AUDIENCE.into(),
        signed_at_millis: Utc::now().timestamp_millis(),
    };

    // Then, we generate a signature for the request.
    let signature = request.signature(
        SignatureScheme::Ed25519,
        PrivateKey::from_hex("INSERT_HEX_ENCODED_PRIVATE_KEY_HERE")?,
    )?;

    // Next, we submit our authentication request to the API for the desired environment.
    let auth_token = request
        .authenticate(&signature, Environment::Mainnet)
        .await?
        .access_token;

    // We get the exchange info to fetch the IDS_ID
    let contracts_info = exchange::info::contracts_config(Environment::Mainnet).await?;

    // Then, we construct the request.
    let signed_request = {
        let unsigned_request = AccountPositionLeverageUpdateRequest {
            signed_fields: AccountPositionLeverageUpdateRequestSignedFields {
                symbol: symbols::perps::ETH.into(),
                account_address: "INSERT_ACCOUNT_ADDRESS_HERE",
                leverage_e9: (10.e9()).to_string(),
                salt: random::<u64>().to_string(),
                ids_id: contracts_info.ids_id,
                signed_at_millis: Utc::now().timestamp_millis(),
            },
            ..Default::default()
        };

        unsigned_request.sign(
            PrivateKey::from_hex("INSERT_HEX_ENCODED_PRIVATE_KEY_HERE")?,
            SignatureScheme::Ed25519,
        )?
    };

    // Now, we send the request.
    send_request(signed_request, &auth_token).await?;
    println!("Leverage Updated");

    Ok(())
}

HTTPs

Alternatively, call the PUT /trade/leverage endpoint using the integrated editor on the right or locally from any language supporting HTTPs network calls.

Request & Response

Language
Credentials
Header
URL
Click Try It! to start a request and see the response here!