NAV
shell python java

Introducing Futures Pro (v2) APIs (Mainnet / Testnet)

BitMax has officially rebranded to AscendEX! Please visit https://ascendex.github.io/ascendex-pro-api/ for the most recent document.

Change Log

2021-03-18

2021-03-03

2021-02-26

2021-02-25

2021-02-23

2021-02-22

2021-02-21

2021-02-19

2021-02-18

Mainnet

URL: https://bitmax.io

Testnet

Testnet URL: https://api-test.bitmax-sandbox.io

You are free to register one or more accounts in the testnet. You can use the magic code 888888 to bypass all verification code checks (email verification, phone number verification, two-step authentication, etc.).

You accounts will automatically receive initial funding.

Please expect the testnet to be reset every a few days.

Obtain API Keys

Prior to use API, you need to login the website to create API Key with proper permissions. The API key is shared for all instruments in BitMax including cash, margin and futures.

You can create and manage your API Keys here.

Every user can create up to 10 API Keys, each can be applied with either permission below:

Please remember below information after creation:

Demo Code

Python Demo: https://github.com/bitmax-exchange/bitmax-futures-api-demo-v2

General Info

Futures Trading System Specification

Contract Position Notional (CPN)

CPN is defined for each contract.

Total Margin

For the isolated group

Total margin is set by the user. You can find its value in the isolatedMargin field from the Position endpoint.

You can increase / decrease the total margin of the isolated margin group via the Change Margin endpoint.

For the crossed group

Discount factor can be found in the discountFactor field from the Futures Collateral Asset Info endpoint.

Position Initial/Maintenance Margin Rate

Initial/Maintenance Margin Rate is system-specified for each position bracket and each contract. You may refer to the marginRequirements section from the Futures Contract Info endpoint for position brackets.

You should compare Contract Position Notional (CPN) with each position bracket to determine your initial and maintenance margin rate.

Position Initial/Maintenance Margin

For the isolated group

For the crossed group

Liquidation Price

For long positions

If the calculated liquidation price is negative, the position won't be liquidation even when the price becomes zero.

For short positions

RESTful APIs

General Info (Public)

Futures Contracts Info

Response - Futures Contracts Info

{
    "code": 0,
    "data": [
        {
            "symbol"          : "BTC-PERP",
            "status"          : "Normal",
            "displayName"     : "BTCUSDT",    // the name displayed on the webpage
            "settlementAsset" : "USDT",       // settlement asset
            "underlying"      : "BTC/USDT",
            "tradingStartTime": 1579701600000,
            "priceFilter": {
                "minPrice"  : "0.25",     // the order price cannot be smaller than the minPrice
                "maxPrice"  : "1000000",  // the order price cannot be greater than the maxPrice
                "tickSize"  : "0.25"      // the order price must be a multiple of the tickSize
            },
            "lotSizeFilter": {
                "minQty"  : "0.0001",     // the order quantity cannot be smaller than the minQty
                "maxQty"  : "1000000000", // the order quantity cannot be greater than the maxQty
                "lotSize" : "0.0001"      // the order quantity must be a multiple of the lotSize
            },
            "marginRequirements": [
                {
                    "positionNotionalLowerbound": "0",     // position lower bound
                    "positionNotionalUpperbound": "50000", // position upper bound
                    "initialMarginRate"         : "0.01",  // initial margin rate
                    "maintenanceMarginRate"     : "0.006"  // maintenance margin rate
                },
                {
                    "positionNotionalLowerbound": "50000",
                    "positionNotionalUpperbound": "200000",
                    "initialMarginRate"         : "0.02",
                    "maintenanceMarginRate"     : "0.012"
                }
            ]
        }
    ]
}

Get information for all futures contracts.

HTTP Request

GET /api/pro/v2/futures/contract

Response

Futures Collateral Asset Info

Response - Futures Collateral Asset Info

{
    "code": 0,
    "data": [
        {
            "asset"           : "BTC",
            "assetName"       : "Bitcoin",
            "conversionFactor": "0.995",
            "discountFactor"  : "0.98",
            "displayName"     : "BTC",
            "statusCode"      : "Normal"
        },
        {
            "asset"           : "USDT",
            "assetName"       : "Tether",
            "conversionFactor": "1",
            "discountFactor"  : "1",
            "displayName"     : "USDT",
            "statusCode"      : "Normal"
        },
        {
            "asset"           : "USDTR",
            "assetName"       : "Futures Reward Token",
            "conversionFactor": "1",
            "discountFactor"  : "1",
            "displayName"     : "USDTR",
            "statusCode"      : "NoTransaction"
        }
    ]
}

Get information for all futures collateral assets.

HTTP Request

GET /api/pro/v2/futures/collateral

Market Data (Public)

Anyone can access public market data via the API endpoints. No authentication is needed.

Futures Pricing Data

Requesting pricing data for all futures contract

{
    "code": 0,
    "data": {
        "contracts": [
            {
                "symbol"         : "BTC-PERP",          // contract symbol
                "time"           : 1614815005717,       // server time (UTC timestamp in milliseconds)
                "fundingRate"    : "0.000564448",       // funding rate 
                "indexPrice"     : "50657.35",          // index price of the underlying
                "markPrice"      : "50667.130409723",   // mark price of the contract
                "openInterest"   : "90.7366",           // funding rate
                "nextFundingTime": 1614816000000        // next funding time (UTC timestamp in milliseconds)
            }
        ],
        "collaterals": [
            {
                "asset": "USDTR",
                "referencePrice": "1"
            },
            {
                "asset": "USDC",
                "referencePrice": "0.9994"
            },
            {
                "asset": "ETH",
                "referencePrice": "1582.3264074"
            },
            {
                "asset": "PAX",
                "referencePrice": "0.99645"
            },
            {
                "asset": "BTC",
                "referencePrice": "50636.14"
            },
            {
                "asset": "USDT",
                "referencePrice": "1"
            }
        ],
    }
}

Get pricing data for all futures contracts.

HTTP Request

GET /api/pro/v2/futures/pricing-data

Authenticate a RESTful Request

Create Request

To access private data via RESTful APIs, you must include the following headers:

The timestamp in the header will be checked against server time. If the difference is greater than 30 seconds, the request will be rejected.

Sign a Request

Signing a RESTful Request

# bash 
APIPATH=info
APIKEY=CEcrjGyipqt0OflgdQQSRGdrDXdDUY2x
SECRET=hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk
TIMESTAMP=`date +%s%N | cut -c -13` # 1608133910000
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`
echo $SIGNATURE  # /pwaAgWZQ1Xd/J4yZ4ReHSPQxd3ORP/YR8TvAttqqYM=

curl -X GET -i \
  -H "Accept: application/json" \
  -H "Content-Type: application/json" \
  -H "x-auth-key: $APIKEY" \
  -H "x-auth-signature: $SIGNATURE" \
  -H "x-auth-timestamp: $TIMESTAMP" \
  https://bitmax.io/api/pro/v1/info
# python 3.6+
import time, hmac, hashlib, base64

api_path  = "info"
api_key   = "CEcrjGyipqt0OflgdQQSRGdrDXdDUY2x"
sec_key   = "hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk"
timestamp = int(round(time.time() * 1e3)) # 1608133910000

message = bytes(f"{timestamp}+{api_path}", 'utf-8')
secret = bytes(sec_key, 'utf-8')

signature = base64.b64encode(hmac.new(secret, message, digestmod=hashlib.sha256).digest())

header = {
  "x-auth-key": api_key,
  "x-auth-signature": signature, 
  "x-auth-timestamp": timestamp,
}
print(signature)  # b'/pwaAgWZQ1Xd/J4yZ4ReHSPQxd3ORP/YR8TvAttqqYM='
// java 1.8+
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Base64;

public class SignatureExample {

  public static void main(String[] args) {
    try {
      long timestamp = System.currentTimeMillis(); // 1562952827927
      String api_path = "user/info";
      String secret = "hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk";
      String message = timestamp + "+" + api_path;

      Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
      SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
      sha256_HMAC.init(secret_key);

      String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
      System.out.println(hash); // vBZf8OQuiTJIVbNpNHGY3zcUsK5gJpwb5lgCgarpxYI=
    }
    catch (Exception e) {
      System.out.println("Error");
    }
  }
}

To query APIs with private data, you must include a signature using base64 encoded HMAC sha256 algorithm. The prehash string is <timestamp>+<api-path>. The timestamp is the UTC timestamp in milliseconds. The api-path is provided in each API description.

See the code demos in (bash/python/java) on the right.

Account Data

Account Info

Account Info - Sample response:

{
    "code": 0,
    "data": {
        "accountGroup": 0,
        "email": "yyzzxxz@gmail.com",
        "expireTime": 1604620800000,         // expire time, UTC timestamp in milliseconds. If -1, the api key will not expire
        "allowedIps": ["123.123.123.123"],
        "cashAccount": [
            "sample-cash-account-id"
        ],
        "marginAccount": [
            "sample-margin-account-id"
        ],
        "futuresAccount": [
            "sample-futures-account-id"
        ],
        "userUID":            "U0866943712",
        "tradePermission":     true,
        "transferPermission":  true,
        "viewPermission":      true,
        "limitQuota":          1000
    }
}

HTTP Request

GET /api/pro/v2/account/info

Signature

You should sign the message in header as specified in Authenticate a RESTful Request section.

prehash string

<timestamp>+v2/account/info

Obtain the account information.

You can obtain your accountGroup from this API, which you will need to include in the URL for all your private RESTful requests.

Response Content

Name Type Description
accountGroup Int non-negative integer
email String
expireTime Long the time when the API key will be expired (UTC timestamp in milliseconds). If -1, the api key will not expire
allowedIps List[String] list of IPs allowed for the api key
cashAccount List[String]
marginAccount List[String]
tradePermission Boolean
transferPermission Boolean
viewPermission Boolean
userUID String an unique id associated with user

See a demo at query private account info.

Position

Response

{
    "code": 0,
    "data": {
        "ac"             : "FUTURES",                   // account category
        "accountId"      : "sample-futures-account-id", // account ID
        "collaterals": [
            {
                "asset"         : "ETH",          // collateral asset 
                "balance"       : "100",          // balance 
                "discountFactor": "0.95",         // discount factor
                "referencePrice": "481.79793092"  // reference price (quote in USDT)
            },
            {
                "asset"         : "BTC",
                "balance"       : "10",
                "discountFactor": "0.98",
                "referencePrice": "17600.095"
            },
            {
                "asset"         : "USDT",
                "balance"       : "10000",
                "discountFactor": "1",
                "referencePrice": "1"
            }
        ],
        "contracts": [
            {
                "symbol"               : "BTC-PERP",     // contract symbol
                "side"                 : "LONG",         // side
                "position"             : "0.5",          // positive for long position and negative for short position
                "referenceCost"        : "16800",        // reference cost
                "unrealizedPnl"        : "0",            // unrealized pnl 
                "realizedPnl"          : "0",            // realized pnl
                "avgOpenPrice"         : "0",            // Average Opening Price
                "marginType"           : "cross",        // margin type: isolated / cross
                "isolatedMargin"       : "0",            // isolated margin
                "leverage"             : "10",           // leverage
                "takeProfitPrice"      : "0",            // take profit price (by position exit order)
                "takeProfitTrigger"    : "market",       // take profit trigger (by position exit order)
                "stopLossPrice"        : "0",            // stop loss price (by position exit order)
                "stopLossTrigger"      : "market",       // stop loss trigger (by position exit order)
                "buyOpenOrderNotional" : "1362.419625",  // buy open order notional
                "sellOpenOrderNotional": "0",            // sell open order notional
                "indexPrice"           : "17600.095",    // price of the contract's underlying product price
                "markPrice"            : "-1"            // contract's mark price
            }
        ]
    }
}

Get current position data - a full snapshot of your futures account.

HTTP Request

GET /<grp>/api/pro/v2/futures/position

Prehash String

<timestamp>+v2/futures/position

Free Margin

Response

{
  "code": 0,
  "data": {
    "collaterals": [
      {
        "asset": "BTC",              // collateral asset
        "availableForTransfer": "1"  // maximum amount allowed to be transferred out
      },
      {
        "asset": "USDT",
        "availableForTransfer": "10000"
      }
    ],
    "crossed": {
      "freeMargin": "30000"
    },
    "isolated": [
      {
        "freeMargin": "0",
        "symbol": "BTC-PERP"
      }
    ]
  }
}

Get free margin for each margin group (crossed & isolated) and amount avaible for withdrawal for each collateral asset.

See Change Margin on how to increase or decrease margin for the isolated position.

change-isolated-margin

HTTP Request

GET /<grp>/api/pro/v2/futures/free-margin

Prehash String

<timestamp>+v2/futures/free-margin

Change Margin (for Isolated Positions)

Successful Response

{
    "code": 0
}

You can only change margin for isolated margin positions.

See Free Margin on the maximum amount you can increase / decrease the isolated margin.

HTTP Request

POST /<grp>/api/pro/v2/futures/isolated-position-margin

Prehash String

<timestamp>+v2/futures/isolated-position-margin

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
symbol String Yes e.g. BTC-PERP
amount String Yes margin amount in string type, e.g. "100". Set amount to positive will increase the isolated margin; set amount

to a negative number will decrease the isolated margin.

When you increase/decrease the isolated margin by a certain amount, the same amount X will be deducted/added from your USDT balance in the collateral.

When you have non-USDT collateral assets, you may be able to increase the isolated margin by an amount more than your USDT balance. In which case, your USDT balance will become negative after the operation.

Change Margin Type

Response

{
    "code": 0
}

You can change the margin type of a position:

change-margin-type

HTTP Request

POST /<grp>/api/pro/v2/futures/margin-type

Prehash String

<timestamp>+v2/futures/margin-type

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
symbol String Yes e.g. BTC-PERP
marginType ENUM Yes You can switch between two margin types: isolated and crossed

Change Contract Leverage

Response

{
    "code": 0,
    "data": {
        "leverage": 10,
        "symbol"  : "BTC-PERP"
    }
}

HTTP Request

POST /<grp>/api/pro/v2/futures/leverage

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
symbol String Yes e.g. BTC-PERP
leverage Int Yes the leverage should be an integer between 1 and 100

Deposit to the Futures Account

Successful Response

{
    "code": 0
}

You can deposit collateral assets to your Futures account from your Cash account.

HTTP Request

POST /<grp>/api/pro/v2/futures/transfer/deposit

Prehash String

<timestamp>+v2/futures/transfer/deposit

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
asset String Yes e.g. BTC
amount String Yes the amount to deposit in string type, e.g. "1". Only positive value is allowed.

Withdraw from the Futures Account

Successful Response

{
    "code": 0
}

You can withdraw collateral assets from your Futures account to your Cash account.

HTTP Request

POST /<grp>/api/pro/v2/futures/transfer/withdraw

Prehash String

<timestamp>+v2/futures/transfer/withdraw

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
asset String Yes e.g. BTC
amount String Yes the amount to withdraw in string type, e.g. "1". Only positive value is allowed.

Order

Generate Order Id

We use the following method to generate an unique id for each order place/cancel request. (You could get userUID from Account Info API.)

Method

Extra info on id

Code Sample

Please refer to python code to gen server order id

New Order

Successful Response

{
    "code": 0,
    "data": {
        "meta": {
            "action"  : "place-order",
            "id"      : "abcd1234abcd1234",
            "respInst": "ACCEPT"   // ACK, ACCEPT, or DONE
        },
        "order": {
            "ac"          : "FUTURES",
            "accountId"   : "sample-futures-account-id",
            "seqNum"      : 14,    // sequence number, also -1 in ACK mode
            "time"        : 1605677683714,
            "orderId"     : "sample-order-id",
            "orderType"   : "Limit",
            "side"        : "Buy",
            "symbol"      : "BTC-PERP",
            "price"       : "9500",
            "orderQty"    : "0.1",
            "stopPrice"   : "0",
            "stopBy"      : "market",
            "status"      : "New",
            "lastExecTime": 1605677684479,
            "lastPx"      : "0",
            "lastQty"     : "0",
            "avgFilledPx" : "0",
            "cumFilledQty": "0",
            "fee"         : "0",
            "cumFee"      : "0",
            "feeAsset"    : "USDT",
            "errorCode"   : ""
        }
    }
}

Error Response

{
    "ac": "FUTURES",
    "accountId": "sample-futures-account-id",
    "action": "place-order",
    "code": 300014,
    "info": {
        "id": "abcd1234abcd1234",
        "symbol": "BTC-PERP"
    },
    "message": "Order price doesn't conform to the required tick size: 1",
    "reason": "TICK_SIZE_VIOLATION"
}

HTTP Request

POST /<grp>/api/pro/v2/futures/order

Prehash String

<timestamp>+v2/futures/order

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
id String >=9 chars (letter and digit number only). Optional but recommended. We echo it back to help you match response with request. By setting this field, you can obtain the orderId before sending the request. It is also useful when you place order in batch mode.
time Long Yes Milliseconds since UNIX epoch in UTC. We do not process request placed more than 30 seconds ago.
symbol String Yes e.g. BTC-PERP
price String Required for Limit and StopLimit orders
orderQty String Yes Order size. Please set scale properly for each symbol.
orderType ENUM Yes
side ENUM Yes
respInst ENUM ACK for limit order and Done for market order by default
postOnly Boolean false by default
stopPrice String required for StopLimit and StopMarket orders
timeInForce ENUM GTC by default
execInst ENUM
posStopLossPrice String position stop loss price
posTakeProfitPrice String position take profit price

Place Batch Orders

Place Batch Orders - Request Body

{
    "orders": [
                {
                    "id"        : "sampleRequestId1",
                    "time"      : 1613878579169,
                    "symbol"    : "BTC-PERP",
                    "orderPrice": "34000",
                    "orderQty"  : "0.1",
                    "orderType" : "limit",
                    "side"      : "buy",
                    "respInst"  : "ACK"
                },
                {
                    "id"        : "sampleRequestId2",
                    "time"      : 1613878579169,
                    "symbol"    : "BTC-PERP",
                    "orderPrice": "35000",
                    "orderQty"  : "0.2",
                    "orderType" : "market",
                    "side"      : "buy",
                    "respInst"  : "ACK"
                }
              ]
}

Place Batch Orders - Successful ACK Response (Status 200, code 0)

{
    "code": 0,
    "data": {
        "meta": {
            "action"  : "batch-place-order",
            "respInst": "ACK"
        },
        "orders": [
            {
                "id"       : "sampleRequestId1",
                "orderId"  : "a177c2a8cfe1U0123456789eqntvwWsy",
                "orderType": "Limit",
                "symbol"   : "BTC-PERP",
                "timestamp": 1613878579202
            },
            {
                "id"       : "sampleRequestId2",
                "orderId"  : "a177c2a8cfe1U0123456789equestId2",
                "orderType": "Market",
                "symbol"   : "BTC-PERP",
                "timestamp": 1613878579202
            }
        ]
    }
}

Error Response

{
    "ac": "FUTURES",
    "accountId": "sample-futures-account-id",
    "action": "batch-place-order",
    "code": 300013,
    "info": [
        {
            "code": 300013,
            "id": "sampleRequestId1",
            "message": "Some invalid order in this batch.",
            "reason": "INVALID_BATCH_ORDER",
            "symbol": "BTC-PERP"
        },
        {
            "code": 320008,
            "id": "sampleRequestId2",
            "message": "Futures account exposure higher than system acceptable level.",
            "reason": "FUTURES_TOO_RISKY",
            "symbol": "BTC-PERP"
        }
    ],
    "message": "Batch Order failed, please check each order info for detail.",
    "reason": "INVALID_BATCH_ORDER"
}

Place multiple orders in a batch. If any order(s) fails our basic check, the whole batch request will fail.

You may submit up to 10 orders at a time. Server will respond with error if you submit more than 10 orders.

HTTP Request

POST /<grp>/api/pro/v2/futures/order/batch

Prehash String

<timestamp>+v2/futures/order/batch

Request Parameters

Name Data Type Description
orders List List of order items

please refer to placing new order for order item definition.

respInst field is required for market order and only ACK is allowed.

Cancel Order

Response

{
    "code": 0,
    "data": {
        "meta": {
            "action"  : "cancel-order",       // action
            "id"      : "abcd1234abcd1234",   // user provided ID
            "respInst": "ACCEPT"              // response instruction
        },
        "order": {
            "ac"          : "FUTURES",                    // account category
            "accountId"   : "sample-futures-account-id",  // account ID
            "seqNum"      : 14,                           // sequence number
            "time"        : 1605677683714,                // order creation time (UTC time in milliseconds)
            "orderId"     : "sample-order-id",            // order ID
            "orderType"   : "Limit",                      // order type
            "side"        : "Buy",                        // side
            "symbol"      : "BTC-PERP",                   // contract symbol
            "price"       : "9500",                       // order price 
            "orderQty"    : "0.1",                        // order qty
            "stopPrice"   : "0",                          // stop price
            "stopBy"      : "market",                     // stop price trigger 
            "status"      : "Canceled",                   // order status
            "lastExecTime": 1605677684479,                // last execution time (UTC time in milliseconds)
            "lastPx"      : "0",                          // last filled price
            "lastQty"     : "0",                          // last filled quantity
            "avgFilledPx" : "0",                          // average filled price of all fills 
            "cumFilledQty": "0",                          // cummulative filled quantity
            "fee"         : "0",                          // fee of the last fill
            "cumFee"      : "0",                          // cummulative fee
            "feeAsset"    : "USDT",                       // fee asset
            "errorCode"   : ""                            // error code
        }
    }
}

HTTP Request

DELETE /<grp>/api/pro/v2/futures/order

Prehash String

<timestamp>+v2/futures/order

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
id String >=9 chars (letter and digit number only). Optional but recommended. We echo it back to help you match response with request. This is especially useful when you cancel in batch mode.
orderId String Yes 32 chars order id. You should set the value to be the orderId of the target order you want to cancel.
symbol String Yes Symbol of the order to cancel
time Long Yes milliseconds since UNIX epoch in UTC. We do not process request sent more than 30 seconds ago.
respInst ENUM ACK by default

Response

respInst

Cancel Batch Orders

Cancel Batch Orders - Request Body

{
   "orders":[
      {
         "id":"sampleRequestId1",
         "orderId":"a177c2a8cfe1U0123456789eqntvwWsy",
         "symbol":"BTC-PERP",
         "time":1613900544076
      },
      {
         "id":"sampleRequestId2",
         "orderId":"a177c2a8cfe1U0123456789equestId2",
         "symbol":"BTC-PERP",
         "time":1613900544076
      }
   ]
}

Cancel Batch Orders - Successful ACK Response (Status 200, code 0)

{
   "code":0,
   "data":{
      "meta":{
         "action":"batch-cancel-order",
         "respInst":"ACK"
      },
      "orders":[
         {
            "id":"sampleRequestId1",
            "orderId":"a177c2a8cfe1U0123456789eqntvwWsy",
            "orderType":"",
            "symbol":"BTC-PERP",
            "timestamp":1613900544091
         },
         {
            "id":"sampleRequestId2",
            "orderId":"a177c2a8cfe1U0123456789equestId2",
            "orderType":"",
            "symbol":"BTC-PERP",
            "timestamp":1613900544168
         }
      ]
   }
}

Cancel multiple orders in a batch. If any order(s) fails our basic check, the whole batch request will fail.

You may submit up to 10 orders to cancel at a time. Server will respond with error if you submit more than 10 orders.

HTTP Request

DELETE /<grp>/api/pro/v2/futures/order/batch

Prehash String

<timestamp>+v2/futures/order/batch

Request Parameters

Name Data Type Description
orders List List of order items to cancel

please refer to cancel order for order item definition

Cancel All Open Orders

Response

{
    "code": 0
}

HTTP Request

DELETE /<grp>/api/pro/v2/futures/order/all

Prehash String

<timestamp>+v2/futures/order/all

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
symbol String No the optional symbol filter

List Open Orders

Response

{
    "code": 0,
    "data": [
        {
            "ac"          : "FUTURES",                   // account category
            "accountId"   : "sample-futures-account-id", // account ID
            "seqNum"      : 14,                          // sequence number
            "time"        : 1605677683714,               // order creation time
            "orderId"     : "sample-order-id",           // order ID
            "orderType"   : "Limit",                     // order type
            "side"        : "Buy",                       // order side
            "symbol"      : "BTC-PERP",                  // contract symbol
            "price"       : "9500",                      // order price
            "orderQty"    : "0.1",                       // order quantity
            "stopPrice"   : "0",                         // stop price
            "stopBy"      : "market",                    // stop price trigger         
            "status"      : "New",                       // order status 
            "lastExecTime": 1605677684479,               // last execution time
            "lastPx"      : "0",                         // last filled price 
            "lastQty"     : "0",                         // last filled quantity
            "avgFilledPx" : "0",                         // average filled price of all fills
            "cumFilledQty": "0",                         // cummulative filled quantity
            "fee"         : "0",                         // fee of the last fill
            "cumFee"      : "0",                         // cummulative fee 
            "feeAsset"    : "USDT",                      // fee asset
            "errorCode"   : ""                           // error code
        }
    ]
}

HTTP Request

POST /<grp>/api/pro/v2/futures/order/open

Prehash String

<timestamp>+v2/futures/order/open

List Current History Orders

Current History Orders - Request Body

{
   "symbol":"BTC-PERP",
   "n":20,
   "executedOnly":true
}

Successful Response (Status 200, code 0)

{
   "code":0,
   "data":[
      {
         "ac":"FUTURES",
         "accountId":"sampleFuturesAccountId",
         "avgFilledPx":"58501",
         "cumFee":"0.058501",
         "cumFilledQty":"0.001",
         "errorCode":"",
         "execInst":"NULL_VAL",
         "fee":"0.058501",
         "feeAsset":"USDT",
         "lastExecTime":1613992168196,
         "lastPx":"58501",
         "lastQty":"0.001",
         "orderId":"a177c29e4064U0123456789dVeUxlVyA",
         "orderQty":"0.001",
         "orderType":"Limit",
         "posStopLossPrice":"0",
         "posStopLossTrigger":"market",
         "posTakeProfitPrice":"0",
         "posTakeProfitTrigger":"market",
         "price":"59027",
         "seqNum":1041950,
         "side":"Buy",
         "status":"Filled",
         "stopBy":"market",
         "stopPrice":"0",
         "symbol":"BTC-PERP",
         "time":1613992168190
      },
      ...
   ]
}

This API returns all current history orders for futures account.

HTTP Request

GET <account-group>/api/pro/v2/futures/order/hist/current

Prehash String

<timestamp>+v2/futures/order/hist/current

Request Parameters

Name Type Required Description
symbol String No symbol filter, e.g. "BTC-PERP"
n Int No maximum number of orders to be included in the response
executedOnly Boolean No if True, include orders with non-zero filled quantities only.

Response

Return a list of history orders in "data" field.

Query Order By ID

Query order with single order id - Request Body

{
   "orderId":"a177c29e4064U0123456789dVeUxlVyA"
}

Successful Response (Status 200, code 0)

{
    "code"     : 0,
    "accountId": "sampleFuturesAccountId",
    "ac"       : "FUTURES",
    "data": {
        "ac"                  : "FUTURES",
        "accountId"           : "sampleFuturesAccountId",
        "avgFilledPx"         : "0",
        "cumFee"              : "0",
        "cumFilledQty"        : "0",
        "errorCode"           : "",
        "execInst"            : "NULL_VAL",
        "fee"                 : "0",
        "feeAsset"            : "USDT",
        "lastExecTime"        : 1613877923408,
        "lastPx"              : "0",
        "lastQty"             : "0",
        "orderId"             : "a177c29e4064U0123456789dVeUxlVyA",
        "orderQty"            : "0.1",
        "orderType"           : "Limit",
        "posStopLossPrice"    : "0",
        "posStopLossTrigger"  : "None",
        "posTakeProfitPrice"  : "0",
        "posTakeProfitTrigger": "None",
        "price"               : "34000",
        "seqNum"              : 18586710,
        "side"                : "Buy",
        "status"              : "New",
        "stopBy"              : "",
        "stopPrice"           : "0",
        "symbol"              : "BTC-PERP",
        "time"                : 1613877922641
    }
}

Query Order with multiple order ids - Request Body

{
   "orderId":"a177c29e4064U0123456789dVeUxlVyA,a177c29e4064U0123456789dVeUxlVyB"
}

Successful Response (Status 200, code 0)

{
    "code"     : 0,
    "accountId": "sampleFuturesAccountId",
    "ac"       : "FUTURES",
    "data": [
        {
            "ac"                  : "FUTURES",
            "accountId"           : "sampleFuturesAccountId",
            "orderId"             : "a177c29e4064U0123456789dVeUxlVyA",
            ...
        },
{
            "ac"                  : "FUTURES",
            "accountId"           : "sampleFuturesAccountId",
            "orderId"             : "a177c29e4064U0123456789dVeUxlVyB",
            ...
        }
    ]
}

HTTP Request

GET /<grp>/api/pro/v2/futures/order/status

Prehash String

<timestamp>+v2/futures/order/status

Request Parameters

PARAMETER TYPE REQUIRED DESCRIPTION
orderId String Yes a single order id, or multiple order ids separated by ,

The API will respond with a list of objects in the data field. Each object in the list contains information of a single order. There's one exception, if you use only a single orderId, the data field of the API response will be simplified to a single object. If you want the API to respond with a list of only one object in this case, add a comma (,) to the orderId.

WebSocket

How to Connect

Base endpoints:

WebSocket Authentication

You must authenticate the websocket session in order to recieve private data and send account specific requests (e.g. placing new orders).

You have two options to authenticate a websocket session.

Once you successfully connect to the websocket, you will receive a connected message:

If the session is disconnected for some reason, you will receive a disconnected message:

Method 1 - WebSocket Authentication with Request Headers

Authenticate with Headers

# # Install wscat from Node.js if you haven't
# npm install -g wscat  

APIPATH=v2/stream
APIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7r
SECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7q
TIMESTAMP=`date +%s%N | cut -c -13`
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`

wscat -H "x-auth-key: $APIKEY" \
  -H "x-auth-signature: $SIGNATURE" \
  -H "x-auth-timestamp: $TIMESTAMP" \
  -c wss://api-test.bitmax-sandbox.io:443/api/pro/v2/stream -w 1 -x '{"op":"sub", "id": "abc123", "ch": "order:cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo:BTMX/USDT"}'

This is similar to the way you authenticate any RESTful request. You need to add the following header fields to the connection request:

The server will then check if the data is correctly signed before upgrading the connection protocol to WebSocket.

Note that if you specify these header fields, the server will reject the websocket connection request if authentication fails.

Method 2 - WebSocket Authentication by Sending the Auth Message

Authenticate by Sending the auth Message

# # Install wscat from Node.js if you haven't
# npm install -g wscat  

APIPATH=v2/stream
APIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7r
SECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7q
TIMESTAMP=`date +%s%N | cut -c -13`
MESSAGE=$TIMESTAMP+$APIPATH
SIGNATURE=`echo -n $MESSAGE | openssl dgst -sha256 -hmac $SECRET -binary | base64`

wscat -c wss://api-test.bitmax-sandbox.io:443/1/api/pro/v2/stream -w 1 -x "{\"op\":\"auth\", \"id\": \"abc123\", \"t\": $TIMESTAMP, "key": \"$APIKEY\", \"sig\": \"$SIGNATURE\"}"

You can also authenticate a live websocket session by sending an op:auth message to the server.

Name Type Required Description
op String Yes "auth"
id String No optional id field, you may safely skip it
t Long Yes UTC timestamp in milliseconds, use this timestamp to generate signature
key String Yes your api key
sig String Yes the signature is generated by signing "<timestamp>+v2/stream"

More comprehensive examples can be found at:

Authentication Response

Auth success message

{  
  "m": "auth",
  "id": "abc123",
  "code": 0
}

Auth error message

{
  "m":"auth",
  "id": "abc123",
  "code": 200006,
  "err": "Unable to find User Account Data"
}

You will receive a message for authentication result after you send authentication request.

Field Type Description
m String "auth"
id String echo back the id if you provide one in the request
code Long Any code other than 0 indicate an error in authentication
err Optional[String] Provide detailed error message if code is not 0

Keep the Connection Alive

In order to keep the websocket connection alive, you have two options, detailed below.

Method 1: Responding to Server's ping messages

Method 1. keep the connection alive by responding to Server pushed ping message

<<< { "m": "ping", "hp": 3 }  # Server pushed ping message
>>> { "op": "pong" }   # Client responds with pong

If the server doesn't receive any client message after a while, it will send a ping message to the client. Once the ping message is received, the client should promptly send a pong message to the server. If you missed two consecutive ping messages, the session will be disconnected.

Server Ping Message Schema

Name Type Description
op String ping
hp Int health point: when this value decreases to 0, the session will be disconnected.

Method 2: Sending ping messages to Server

Method 2. keep the connection alive by sending ping message to the server

>>> { "op": "ping" }                                    # Client initiated ping message (every 30 seconds)
<<< { "m":"pong", "code":0, "ts":1614164189, "hp": 2 }  # Server responds to client ping 

You can also send ping message to the server every 15 seconds to keep the connection alive. The server will stop sending ping message for 30 seconds if a client initiated ping message is received.

Server Pong Message Schema

Name Type Description
m String pong
code Int error code, for the pong mesage, the error code is always 0 (success)
ts Long server time in UTC miliseconds
hp Int health point: when this value decreases to 0, the session will be disconnected.

Public Stream Data

Channel: Futures Pricing Data

Sample Futures Pricing Data Message

{
    "m": "futures-pricing-data",
    "con": [  // contracts
        {
            "s" : "BTC-PERP",        // symbol
            "t" : 1614814705716,     // data time
            "ip": "50702.8",         // index price
            "mp": "50652.3553",      // mark price
            "r" : "0.000565699",     // funding rate 
            "oi": "90.7367",         // open interest
            "f" : 1614816000000      // next funding time
        }
    ], 
    "col": [  // collateral assets
        {
            "a": "USDTR",  // asset
            "p": "1"       // reference price (quote in USDT)
        },
        {
            "a": "USDC",
            "p": "0.99935"
        },
        {
            "a": "ETH",
            "p": "1582.505"
        },
        {
            "a": "PAX",
            "p": "0.9964"
        },
        {
            "a": "BTC",
            "p": "50621.795"
        },
        {
            "a": "USDT",
            "p": "1"
        }
    ]
}

Subscribe to the Channel

{"op":"sub", "id":"sample-id", "ch":"futures-pricing-data"}

Channel: Level 1 Order Book Data (BBO)

Subscribe to BTC-PERP quote stream

{ "op": "sub", "id": "abc123", "ch":"bbo:BTC-PERP" }

Unsubscribe to BTC-PERP quote stream

{ "op": "unsub", "id": "abc123", "ch":"bbo:BTC-PERP" }

BBO Message

{
    "m": "bbo",
    "symbol": "BTC-PERP",
    "data": {
        "ts": 1573068442532,
        "bid": [
            "9309.11",
            "0.0197172"
        ],
        "ask": [
            "9309.12",
            "0.8851266"
        ]
    }
}

You can subscribe to updates of best bid/offer data stream only. Once subscribed, you will receive BBO message whenever the price and/or size changes at the top of the order book.

Each BBO message contains price and size data for exactly one bid level and one ask level.

Channel: Level 2 Order Book Updates

Subscribe to BTC-PERP depth updates stream

{ "op": "sub", "id": "abc123", "ch":"depth:BTC-PERP" }

Unsubscribe to BTC-PERP depth updates stream

{ "op": "unsub", "id": "abc123", "ch":"depth:BTC-PERP" }

The Depth Message

{
    "m": "depth",
    "symbol": "BTC-PERP",
    "data": {
        "ts": 1573069021376,
        "seqnum": 2097965,
        "asks": [
            [
                "0.06844",
                "10760"
            ]
        ],
        "bids": [
            [
                "0.06777",
                "562.4"
            ],
            [
                "0.05",
                "221760.6"
            ]
        ]
    }
}

If you want to keep track of the most recent order book snapshot in its entirety, the most efficient way is to subscribe to the depth channel.

Each depth message contains a bids list and an asks list in its data field. Each list contains a series of [price, size] pairs that you can use to update the order book snapshot. In the message, price is always positive and size is always non-negative.

See Orderbook Snapshot for code examples.

Channel: Market Trades

Subscribe to BTC-PERP market trades stream

{ "op": "sub", "id": "abc123", "ch":"trades:BTC-PERP" }

Unsubscribe to BTC-PERP market trades stream

{ "op": "unsub", "id": "abc123", "ch":"trades:BTC-PERP" }

Trade Message

{
    "m": "trades",
    "symbol": "BTC-PERP",
    "data": [
        {
            "p":      "0.068600",
            "q":      "100.000",
            "ts":      1573069903254,
            "bm":      false,
            "seqnum":  144115188077966308
        }
    ]
}

The data field is a list containing one or more trade objects. The server may combine consecutive trades with the same price and bm value into one aggregated item. Each trade object contains the following fields:

Name Type Description
seqnum Long the sequence number of the trade record. seqnum is always increasing for each symbol, but may not be consecutive
p String the executed price expressed as a string
q String the aggregated traded amount expressed as string
ts Long the UTC timestamp in milliseconds of the first trade
bm Boolean if true, the buyer of the trade is the maker.

Channel: Bar Data

Subscribe to BTC-PERP 1 minute bar stream

{ "op": "sub", "id": "abc123", "ch":"bar:1:BTC-PERP" }

Unsubscribe to BTC-PERP 1 minute bar stream

{ "op": "unsub", "id": "abc123", "ch":"bar:1:BTC-PERP" }

//  Alternatively, you can unsubscribe all bar streams for BTC-PERP
{ "op": "unsub", "id": "abc123", "ch":"bar:*:BTC-PERP" }

// Or unsubscribe all 1 minute bar stream
{ "op": "unsub", "id": "abc123", "ch":"bar:1" }

// Or unsubscribe all bar stream
{ "op": "unsub", "id": "abc123", "ch":"bar" }

Bar Data Message

{
    "m": "bar",
    "s": "BTC-PERP",    
    "data": {
        "i":  "1",
        "ts": 1575398940000,
        "o":  "0.04993",
        "c":  "0.04970",
        "h":  "0.04993",
        "l":  "0.04970",
        "v":  "8052"
    }
}

The data field is a list containing one or more trade objects. The server may combine consecutive trades with the same price and bm value into one aggregated item. Each trade object contains the following fields:

Name Type Description
seqnum Long the sequence number of the trade record. seqnum is always increasing for each symbol, but may not be consecutive
p String the executed price expressed as a string
q String the aggregated traded amount expressed as string
ts Long the UTC timestamp in milliseconds of the first trade
bm Boolean if true, the buyer of the trade is the maker.

Private Stream Data

Channel: Order

{
  "m"      : "futures-order",
  "sn"     : 127,                   // sequence number
  "e"      : "ExecutionReport",     // event
  "a"      : "sample-futures-account-id",  // account Id
  "ac"     : "FUTURES",             // account category 
  "t"      : 1606335352348,         // last execution time
  "ct"     : 1606335351541,         // order creation time
  "orderId": "a176010c4957U68469127074abcd1234",  // order Id
  "sd"     : "Buy",                 // side 
  "ot"     : "Limit",               // order type 
  "q"      : "0.1",                 // order quantity (base asset)
  "p"      : "18000",               // order price
  "sp"     : "0",                   // stop price
  "spb"    : "",                    // stop trigger
  "s"      : "BTC-PERP",            // symbol 
  "st"     : "New",                 // order status
  "lp"     : "0",                   // last filled price
  "lq"     : "0",                   // last filled quantity (base asset)
  "ap"     : "0",                   // average filled price
  "cfq"    : "0",                   // cummulative filled quantity (base asset)
  "f"      : "0",                   // commission fee of the current execution
  "cf"     : "0",                   // cumulative commission fee
  "fa"     : "USDT",                // fee asset
  "ei"     : "NULL_VAL",            // execution instruction
  "err"    : ""                     // error message
}

Subscribe to the Channel

{"op":"sub", "id":"sample-id", "ch":"futures-order"}

Channel: Account Update



{
  "m"     : "futures-account-update",            // message
  "e"     : "ExecutionReport",                   // event type
  "t"     : 1612508562129,                       // server time (UTC time in milliseconds)
  "acc"   : "sample-futures-account-id",         // account ID
  "at"    : "FUTURES",                           // account type
  "sn"    : 23128,                               // sequence number, strictly increasing for each account
  "id"    : "r177710001cbU3813942147C5kbFGOan",  // request ID for this account update
  "col": [
    {
      "a": "USDT",               // asset code
      "b": "1000000",            // balance 
      "f": "1"                   // discount factor
    }
  ],
  "pos": [
    {
      "s"   : "BTC-PERP",        // symbol
      "sd"  : "LONG",            // side
      "pos" : "0.011",           // position
      "rc"  : "-385.840455",     // reference cost
      "up"  : "18.436008668",    // unrealized pnl
      "rp"  : "0",               // realized pnl
      "aop" : "35041.363636363", // Average Opening Price
      "boon": "0",               // Buy Open Order Notional
      "soon": "0",               // Sell Open Order Notional
      "mt"  : "crossed",         // margin type: isolated / cross
      "iw"  : "0",               // isolated margin
      "lev" : "10",              // leverage
      "tp"  : "0",               // take profit price (by position exit order)
      "tpt" : "market",          // take profit trigger (by position exit order)
      "sl"  : "0",               // stop loss price (by position exit order)
      "slt" : "market",          // stop loss trigger (by position exit order)
    }
  ]
}

Subscribe to the Channel

{"op":"sub", "id":"sample-id", "ch":"futures-account-update"}

WebSocket - Data Request

WS: Account Snapshot

Requesting Futures Account Snapshot

{
   "op"    : "req",
   "id"    : "abc123456",
   "action": "futures-account-snapshot"
}

Futures Account Snapshot response

{
   "m"  : "futures-account-snapshot",  // message
   "id" : "abc123456",                 // echo back the request Id
   "e"  : "ClientRequest",             // event name
   "t"  : 1613748277356,               // server time in milliseconds (UTC)
   "acc": "futH9N59hR0BMVEjHnBleHLn0mfUl5lo",  // accountId
   "ac" : "FUTURES",                   // account category
   "sn" : 9982,                        // sequence number
   "col":[  // collateral balances
      {
         "a": "ETH",     // collateral asset code
         "b": "500",     // collateral balance
         "f": "0.95"     // discount factor
      },
      {
         "a": "BTC",
         "b": "100",
         "f": "0.98"
      },
      {
         "a": "USDT",
         "b": "1000000",
         "f": "1"
      }
   ],
   "pos":[  // contract positions
      {
         "s"   : "BTC-PERP",  // contract symbol
         "sd"  : "NULL_VAL",  // side: LONG / SHORT / NULL_VAL
         "pos" : "0",         // position
         "rc"  : "0",         // reference cost
         "up"  : "0",         // unrealized pnl
         "rp"  : "0",         // realized pnl
         "aop" : "0",         // average opening price
         "mt"  : "crossed",   // margin type: isolated / cross
         "boon": "0",         // buy open order notional
         "soon": "0",         // sell open order notional
         "lev" : "10",        // leverage
         "iw"  : "0",         // isolated margin
         "tp"  : "0",         // take profit price (by position exit order)
         "tpt" : "market",    // take profit trigger (by position exit order)
         "sl"  : "0",         // stop loss price (by position exit order)
         "slt" : "market"     // stop loss trigger (by position exit order)
      }
   ]
}

You can request the futures account snapshot via websocket by a futures-account-snapshot action.

The request schema:

Name Data Type Description
op String req
action String futures-account-snapshot
id String for result match purpose

WS: Place Order

Request to place new order

{
   "op"    : "req",
   "action": "place-order",
   "ac"    : "futures",         // the Account Category
   "id"    : "sampleRequestID", // the server will echo back this id in the ack message. 
   "args":{
      "time"      : 1613753879921,
      "symbol"    : "BTC-PERP",
      "orderPrice": "30000",
      "orderQty"  : "0.12",
      "orderType" : "limit",
      "side"      : "buy",
      "postOnly"  : false,
      "respInst"  : "ACK"
   }
}

Successful ACK message

{
   "m"     : "order",
   "code"  : 0,
   "id"    : "sampleRequestID",   // echo back the original request Id
   "action": "place-order",
   "ac"    : "FUTURES",
   "info": {
      "orderId": "s177bbb671b7U1234567890leOrderId",
      "symbol" : "BTC-PERP"
   }
}

Error response message

{
   "m"     : "order",
   "code"  : 300001,
   "id"    : "sampleRequestID",  // echo back the original request Id
   "action": "place-order",
   "ac"    : "FUTURES",
   "info": {
      "symbol"  : "BTC-PERP",
      "reason"  : "INVALID_PRICE",
      "errorMsg": "Order price is too low from market price."
   }
}

Place order via websocket

Request

Make new order request follow the general websocket request rule, with proper place new order parameters as specified in rest api for args field.

see placing order via RESTful API.

id

As described in Generate Order Id, the server uses a deterministic algorithm to compute the orderId based on client inputs. For every order request placed via WebSocket, We strongly recommend you put a non-repeatable id.

Response

Respond with m field as order, and action field as place-order; if you provide id in your request, it will be echoed back as id to help you identify; code field to indicate if this is a successful zero or failed non-zero.

code=0

With code field as zero to indicate this new order request pass some basic sanity check, and has been sent to matching engine.

info field provide some detail: if you provide id in your request, it will be echoed back as id to help you identify; we also provide server side generated orderId, which is the id you should use for future track or action on the order.

code=non-zero

With code field as non-zero to indicate there is some obvisous errors in your request.

info field provide some detail: we also provide error reason and errorMsg detail.

WS: Cancel Order

Request to cancel existing open order

{
   "op"    : "req",
   "action": "cancel-order",
   "ac"    : "futures",
   "id"    : "sampleRequestId",    // server will echo back this Id.
   "args":{
      "time":1613744943323,
      "orderId":"s177bab1b474U5051470287bbtcpKiOR",
      "symbol":"BTC-PERP"
   }
}

Successful ACK message

{
   "m"     : "order",
   "action": "cancel-order",
   "ac"    : "FUTURES",
   "id"    : "sampleRequestId", // echo back the original request Id
   "code":0,
   "info":{
      "orderId": "s177bab1b474U5051470287bbtcpKiOR",
      "symbol" : "BTC-PERP"
   }
}

Error response message

{
   "m"     : "order",
   "action": "cancel-order",
   "ac"    : "FUTURES",
   "code"  : 300006,
   "id"    : "sampleRequestId", // echo back the original request Id
   "info":{
      "symbol"  : "BTC-PERP",
      "reason"  : "INVALID_ORDER_ID",
      "errorMsg": "Client Order Id too Long: s177bab1b474U5051470287bbtcpKiOR1"
   }
}

Cancel an existing open order via websocket

Request

Make order cancelling request follow the general websocket request rule by setting action to be cancel-orde, with proper cancel order parameters as specified in rest api for args field.

Response

Respond with m field as order, and action field as cancel-order; code field to indicate if this is a successful zero or failed non-zero.

code=0

With code field as zero to indicate this cancel order request pass some basic sanity check, and has been sent to matching engine.

info field provide some detail: if you provide symbol in your request, it will be echoed back as symbol to help you idintify; we also echo back target orderId to be cancelled.

code=non-zero

With code field as non-zero to indicate there is some obvisous errors in your cancel order request.

info field provide some detail: we also provide error reason and errorMsg detail.

WS: Cancel All Orders

Request to cancel all existing open orders

{
   "op"    : "req",
   "action": "cancel-all",
   "ac"    : "futures",
   "id"    : "sampleRequestId", // server will echo back this Id.
   "args": {   // you can also omit the args field
   }
}

Request to cancel existing open order related to symbol "BTC-PERP"

{
   "op"    : "req",
   "action": "cancel-all",
   "ac"    : "futures",
   "id"    : "sampleRequestId", // server will echo back this Id.
   "args":{ 
        "symbol": "BTC-PERP"     
   }
}

Successful ACK message

{
   "m"     : "order",
   "code"  : 0,
   "action": "cancel-all",
   "ac"    : "FUTURES",
   "id"    : "sampleRequestId", // echo back the original request Id
   "info":{
      "symbol":""
   }
}

Error response message

{
   "m"     : "order",
   "code"  : 300012,
   "action": "cancel-all",
   "ac"    : "FUTURES",
   "id"    : "sampleRequestId", // echo back the original request Id
   "info":{
      "symbol"  : "",
      "reason"  : "INVALID_PRODUCT",
      "errorMsg": "Invalid Product Symbol"
   }
}

Cancel all open orders on account level via websocket with optional symbol.

Request

Make general websocket request with action field as cancel-All and set proper ac value(futures), and provide symbol value in args.

Response

With code field as zero to indicate this cancel all order request has been received by server and sent to matching engine.

info field provide some detail: if you provide symbol in your request to cancel orders.

With code field as non-zero to indicate there is some obvisous errors in your request.

info field provide some detail: we also provide error reason and errorMsg detail.

WS: Query Open Orders

Requesting open orders on symbol BTC-PERP

{
   "op"    : "req",
   "id"    : "abc123456",
   "action": "futures-open-orders",
   "args":{
      "symbol":"BTC-PERP"
   }
}

Open orders response

{
   "m":"futures-open-orders",
   "code":0,
   "id":"abc123456",
   "ac":"FUTURES",
   "data":[
      {
         "ac":"FUTURES",
         "accountId":"sample-futures-account-id",
         "time":1615696544843,
         "orderId":"r1782f04c58aU3792951278sbtcp7EbA",
         "seqNum":13,
         "orderType":"Limit",
         "execInst":"NULL_VAL",
         "side":"Sell",
         "symbol":"BTC-PERP",
         "price":"66000",
         "orderQty":"0.0001",
         "stopPrice":"0",
         "stopBy":"market",
         "status":"New",
         "lastExecTime":1615696544851,
         "lastQty":"0",
         "lastPx":"0",
         "avgFilledPx":"0",
         "cumFilledQty":"0",
         "fee":"0",
         "cumFee":"0",
         "feeAsset":"USDT",
         "errorCode":"",
         "posStopLossPrice":"0",
         "posStopLossTrigger":"None",
         "posTakeProfitPrice":"0",
         "posTakeProfitTrigger":"None"
      },
      ...
   ]
}

Error response message

{
   "m":"error",
   "id":"abc123456",
   "code":100005,
   "reason":"INVALID_WS_REQUEST_DATA",
   "info":"Missing required parameter: args"
}

You can request the open order via websocket by a futures-open-orders action.

The request schema:

Name Data Type Description
op String req
action String futures-open-orders
id String for result match purpose
args:symbol Optional[String] add the (optional) symbol filter, see below for details.

The symbol key in the args map allows you to customize the symbol filter in a flexible way:

Appendix

ENUM Definitions

Account Category (ac)

Order Type (orderType)

Side (side)

Response Type (respInst)

Time in Force (timeInForce)

Execution Instruction (execInst)

Margin Type (marginType)

WebSocket Operations (op)

WebSocket Message Types (m)