/trade/orders/cancel

Cancel orders for a market using order hashes.

  • May be a single order hash or a list of order hashes.

  • All orders must belong to the same account.

  • If no order hashes are specified, then will cancel all orders for the given market

  • All orders being cancelled by request will receive the same time priority.

Recent Requests
Log in to see full request history
TimeStatusUser Agent
Retrieving recent requests…
LoadingLoading…
  • May be a single order hash or a list of order hashes
  • All orders must belong to the same account
  • If no order hashes are specified, then will cancel all orders for the given market
  • All orders being cancelled by request will receive the same time priority

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
from openapi_client import CancelOrdersRequest

# 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 cancel orders 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=}")

            # ========= Cancel an Order(s) ==========
            log.info("Cancelling Orders for this market")
            await client.cancel_order(
                CancelOrdersRequest(
                    symbol=market.symbol,
                )
            )

        except Exception as e:
            log.error(f"Error cancelling orders: {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::cancel_orders;
use bluefin_api::models::{
    CancelOrdersRequest, LoginRequest
    ,
};
use bluefin_pro::prelude::*;
use chrono::Utc;
use hex::FromHex;
use sui_sdk_types::SignatureScheme;

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

/// Submits the specified request to Bluefin.
///
/// # Errors
///
/// Will return `Err` if the request fails, or cannot be submitted.
async fn send_request(request: CancelOrdersRequest, auth_token: &str) -> Result<()> {
    println!("Sending request...");
    let mut config = Configuration::new();
    config.bearer_access_token = Some(auth_token.into());
    config.base_path = trade::mainnet::URL.into();
    cancel_orders(&config, request).await?;

    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    // Then, 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(),
    };

    // Next, we generate a signature for our 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;

    // Next, we construct our cancellation request.
    let request = CancelOrdersRequest {
        symbol: symbols::perps::ETH.into(),
        order_hashes: None,
    };

    // Now, we submit our cancellation request to Blufin.
    send_request(request, &auth_token).await?;

    // Finally, we print a confirmation message.
    println!("Orders Cancellation submitted successfully.");

    Ok(())
}

HTTPs

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

Request & Response

Body Params

Cancelling Orders for a specific symbol. If order hashes are not specified, all orders are canceled for this symbol

string
required

The symbol of the perpetual for which to cancel orders.

orderHashes
array of strings

List of order hashes of the orders to be cancelled. All orders must belong to accountAddress. Max 10 order hashes

orderHashes
Responses
202

Order cancellation submitted successfully.

400

Bad Request. Invalid body parameters.

429

Too Many Requests. The request was rate limited.

Language
Credentials
Header
URL
LoadingLoading…
Response
Click Try It! to start a request and see the response here! Or choose an example:
application/json