/trade/orders

Submit a new order for execution.

Client Library

#!/usr/bin/env python

import asyncio
import logging
import time

import openapi_client as api
from bluefin_pro_sdk import BluefinProSdk, Environment, RpcUrl, Order
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 create an order 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()

            # Get Market Data from the Exchange Data API.
            exchange_info = await client.exchange_data_api.get_exchange_info()
            log.info(f"{exchange_info=}")

            # We'll work with the ETH-PERP market for this example, but you could as
            # well choose any other market available on the Bluefin Pro exchange.
            market = next(
                market for market in exchange_info.markets if market.symbol == "ETH-PERP"
            )
            log.info(f"{market=}")

            # ========= Place an Order ==========
            log.info("Creating Order")
            response = await client.create_order(
                Order(
                    client_order_id="123456",
                    type=api.OrderType.LIMIT,
                    symbol=market.symbol,
                    price_e9="36790000000",
                    quantity_e9="100000000000",
                    side=api.OrderSide.SHORT,
                    leverage_e9="2000000000",
                    is_isolated=False,
                    # Ten minutes hence.
                    expires_at_millis=now() + 60 * 10 * 1000,
                )
            )

            # Log the response
            log.info("Order:")
            log.info(f"{response=}")

            # Return the response for further use if needed
            return response

        except Exception as e:
            log.error(f"Error creating order: {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::post_create_order;
use bluefin_api::models::{
    CreateOrderRequest,
    OrderSide, OrderTimeInForce, OrderType, SelfTradePreventionType,
};
use bluefin_api::models::{CreateOrderRequestSignedFields, LoginRequest};
use bluefin_pro::prelude::*;
use chrono::{TimeDelta, Utc};
use hex::FromHex;
use rand::random;
use std::ops::Add;
use sui_sdk_types::SignatureScheme;

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

async fn send_request(signed_request: CreateOrderRequest, auth_token: &str) -> Result<String> {
    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();

    let response = post_create_order(&config, signed_request).await?;

    Ok(response.order_hash)
}

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

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

    // Then, 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?;

    // Next, we construct an unsigned request.
    let request = CreateOrderRequest {
        signed_fields: CreateOrderRequestSignedFields {
            symbol: symbols::perps::ETH.into(),
            account_address: "INSERT_ACCOUNT_ADDRESS_HERE",
            price_e9: (10_000.e9()).to_string(),
            quantity_e9: (1.e9()).to_string(),
            side: OrderSide::Short,
            leverage_e9: (10.e9()).to_string(),
            is_isolated: false,
            salt: random::<u64>().to_string(),
            ids_id: contracts_info.ids_id,
            expires_at_millis: Utc::now().add(TimeDelta::minutes(6)).timestamp_millis(),
            signed_at_millis: Utc::now().timestamp_millis(),
        },
        client_order_id: None,
        r#type: OrderType::Limit,
        reduce_only: false,
        post_only: Some(true),
        time_in_force: Some(OrderTimeInForce::Gtt),
        trigger_price_e9: None,
        self_trade_prevention_type: Some(SelfTradePreventionType::Maker),
        ..Default::default()
    };

    // Then, we sign our order.
    let request = request.sign(
        PrivateKey::from_hex("INSERT_HEX_ENCODED_PRIVATE_KEY_HERE")?,
        SignatureScheme::Ed25519,
    )?;

    let received_order_hash = send_request(request.clone(), &auth_token).await?;
    println!("Order Submitted: {received_order_hash}");
    Ok(())
}

HTTPs

Alternatively, call the POST /trade/orders 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!