Movatterモバイル変換


[0]ホーム

URL:


NAV
Cash/Margin APIsFutures APIs
shellpythonjava

Introducing Futures Pro (v2) APIs

General

MainnetURL:https://ascendex.com

Testnet

Testnet URL:https://api-test.ascendex-sandbox.com

You are free to register one or more accounts in the testnet. You can use the magic code888888 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 AscendEx including cash, margin and futures.

You can create and manage your API Keyshere.

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

Please remember below information after creation:

SDKs and Client Libraries

Official SDK

CCXT is our authorized SDK provider and you may access the AscendEX API through CCXT. For more information, please visit:https://ccxt.trade

Demo Code

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

Market Making Incentive Program

AscendEX offers a Market Making Incentive Program for professional liquidity providers. Key benefits of this program include:

Users with good maker strategies and significant trading volume are welcome to participate in this long-term program. If your account has a trading volume of more than 150,000,000 USDT in the last 30 days on any exchange, please send the following information via email to institution@ascendex.com, with the subject "Market Maker Incentive Application":

Got Questions?

Join our official telegram channel:https://t.me/AscendEX_Official_API

Change Log

2022-08-16

Funding Payment History added to get account funding payment history.

2022-05-19

Limit Info API is deprecated, useLimit Info API v2 to get ban info and message threshold info.

2022-02-28

2021-11-22

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

Futures Trading System Specification

Contract Position Notional (CPN)

CPN is defined for each contract.

Margin Group

The Isolated Group

The isolated group manages a single position with a certain amount of margin moved out of the crossed group. It isolates the risk of the position from other margin groups. Your maximum loss will be limited to the total margin moved into the isolated group.

Each account may have at most one isolated group per contract.

The Crossed Group

The crossed group manages all positions except those in isolated groups.

Total Margin

For the isolated group

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

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

For the isolated group, we also refer tototal margin asisolated margin.

For the crossed group

Discount factor can be found in thediscountFactor field from theFutures Collateral Asset Info endpoint.

Group Collateral Balance

For the isolated group

For the crossed group

TheGroup Collateral Balance is important to determine the risk level of the margin group. If it becomes lower than theposition maintanence margin, all positions in the margin group are expected to be liquidated.

Position Initial/Maintenance Margin Rate

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

You should compareContract 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

Unrealized PnL

TheUnrealized PnL of a position is calculated as:

Note thatposition andreference cost are of opposite signs.

TheUnrealized PnL will be rolled (settled) when:

Assume your current position is P, the current reference cost if RC, and unrealized PnL is L, after rolling:

You should always include the unrealized PnL when calculating the collateral balance.

Realized PnL

Realized Pnl is merely a bookkeeping entry for all profits and losses realized by the current position under the assumption that the position was built on an average cost basis.

If you are mostly concerned about the risk of your positions, you can ignore the realized PnL.

RESTful APIs

Exchange Latency Info

Latency Info

curl -X GET https://ascendex.com/api/pro/v1/exchange-info?requestTime="$(date +%s%N | cut -b1-13)"

Latency Info - Sample response::

{"code":0,"data":{"requestTimeEcho":1640052379050,"requestReceiveAt":1640052379063,"latency":13}}

HTTP Request

GET /api/pro/v1/exchange-info

Request Parameters

NameTypeRequiredValue RangeDescription
requestTimeLongYesmilliseconds since UNIX epoch in UTCthe client's local time. The server compare it with the system time to calculate latency.

General Info (Public)

Futures Contracts Info

Response - Futures Contracts Info

{"code":0,"data":[{"symbol":"BTC-PERP","status":"Normal","displayName":"BTCUSDT",//thenamedisplayedonthewebpage"settlementAsset":"USDT",//settlementasset"underlying":"BTC/USDT","tradingStartTime":1579701600000,"priceFilter":{"minPrice":"0.25",//theorderpricecannotbesmallerthantheminPrice"maxPrice":"1000000",//theorderpricecannotbegreaterthanthemaxPrice"tickSize":"0.25"//theorderpricemustbeamultipleofthetickSize},"lotSizeFilter":{"minQty":"0.0001",//theorderquantitycannotbesmallerthantheminQty"maxQty":"1000000000",//theorderquantitycannotbegreaterthanthemaxQty"lotSize":"0.0001"//theorderquantitymustbeamultipleofthelotSize},"marginRequirements":[{"positionNotionalLowerbound":"0",//positionlowerbound"positionNotionalUpperbound":"50000",//positionupperbound"initialMarginRate":"0.01",//initialmarginrate"maintenanceMarginRate":"0.006"//maintenancemarginrate},{"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",//contractsymbol"time":1614815005717,//servertime(UTCtimestampinmilliseconds)"fundingRate":"0.000564448",//fundingrate"indexPrice":"50657.35",//indexpriceoftheunderlying"markPrice":"50667.130409723",//markpriceofthecontract"openInterest":"90.7366",//fundingrate"nextFundingTime":1614816000000//nextfundingtime(UTCtimestampinmilliseconds)}],"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

Bar Info

Request

curl -X GET "https://ascendex.com/api/pro/v1/barhist/info"

Sample response

{"code":0,"data":[{"name":"1","intervalInMillis":60000},{"name":"5","intervalInMillis":300000},{"name":"15","intervalInMillis":900000},{"name":"30","intervalInMillis":1800000},{"name":"60","intervalInMillis":3600000},{"name":"120","intervalInMillis":7200000},{"name":"240","intervalInMillis":14400000},{"name":"360","intervalInMillis":21600000},{"name":"720","intervalInMillis":43200000},{"name":"1d","intervalInMillis":86400000},{"name":"1w","intervalInMillis":604800000},{"name":"1m","intervalInMillis":2592000000}]}

HTTP Request

GET /api/pro/v1/barhist/info

This API returns a list of all bar intervals supported by the server.

Request Parameters

This API endpoint does not take any parameters.

Resposne

NameTypeDescription
nameStringname of the interval
intervalInMillisLonglength of the interval

Plesae note that the one-month bar (1m) always resets at the month start. TheintervalInMillis value for the one-monthbar is only indicative.

The value in thename field should be your input to theHistorical Bar Data API.

Historical Bar Data

Request

curl -X GET "https://ascendex.com/api/pro/v1/barhist?symbol=BTC-PERP&interval=1"

Sample response

{"code":0,"data":[{"m":"bar","s":"BTC-PERP","data":{"i":"1","ts":1637619240000,"o":"56263","c":"56260","h":"56263","l":"56239","v":"0.0126"}},{"m":"bar","s":"BTC-PERP","data":{"i":"1","ts":1637619300000,"o":"56243","c":"56243","h":"56243","l":"56243","v":"0.0001"}}]}

HTTP Request

GET /api/pro/v1/barhist

This API returns a list ofbars, with each contains the open/close/high/low prices of a symbol for a specific time range.

Request Parameters

NameTypeRequiredDescription
symbolStringYese.g."BTC-PERP"
intervalStringYesa string representing the interval type.
toLongNoUTC timestamp in milliseconds. If not provided, this field will be set to the current time.
fromLongNoUTC timestamp in milliseconds.
nIntNodefault 10, number of bars to be returned, this number will be capped at 500

The requested time range is determined by three parameters -to,from, andn - according to rules below:

Response

NameTypevalueDescription
mStringbarmessage type
sStringsymbol
data:tsLongbar start time in milliseconds
iStringinterval
oStringopen price
cStringclose price
hStringhigh price
lStringlow price
vStringvolume in quote asset

Code Sample

Please refer python code to [get bar history]{https://github.com/ascendex/ascendex-pro-api-demo/blob/main/python/query_pub_barhist.py}

Ticker

Ticker for one trading pair

//curl-XGET'https://ascendex.com/api/pro/v2/futures/ticker?symbol=BTC-PERP'{"code":0,"data":{"symbol":"BTC-PERP","open":"59488","close":"56725","high":"59724","low":"56672","baseVol":"208.7414","ask":["56730","0.0005"],"bid":["56710","0.0042"]}}

List of Tickers for one or multiple trading pairs

//curl-XGET"https://ascendex.com/api/pro/v2/futures/ticker?symbol=BTC-PERP,"{"code":0,"data":[{"symbol":"BTC-PERP","open":"59488","close":"56716","high":"59724","low":"56672","baseVol":"208.7414","ask":["56720","0.2315"],"bid":["56712","0.0024"]}]}

HTTP Request

GET api/pro/v2/futures/ticker

You can get summary statistics of one or multiple symbols (spot market) with this API.

Request Parameters

NameTypeRequiredValue RangeDescription
symbolStringNoyou may specify one, multiple, or all symbols of interest. See below.

This API endpoint accepts one optional string fieldsymbol:

Respond Content

The API will respond with a ticker object or a list of ticker objects, depending on how you set thesymbol parameter.

Each ticker object contains the following fields:

FieldTypeDescription
symbolString
openStringthe traded price 24 hour ago
closeStringthe last traded price
highStringthe highest price over the past 24 hours
lowStringthe lowest price over the past 24 hours
volumeStringthe total traded volume in quote asset over the paste 24 hours
ask[String, String]the price and size at the current best ask level
bid[String, String]the price and size at the current best bid level

Code Sample

Please refer to python code to [query ticker info]{https://github.com/ascendex/ascendex-pro-api-demo/blob/main/python/query_pub_ticker.py}

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

# bashAPIPATH=infoAPIKEY=CEcrjGyipqt0OflgdQQSRGdrDXdDUY2xSECRET=hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNkTIMESTAMP=`date +%s%N |cut-c-13`# 1608133910000MESSAGE=$TIMESTAMP+$APIPATHSIGNATURE=`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://ascendex.com/api/pro/v1/info
# python 3.6+importtime,hmac,hashlib,base64api_path="info"api_key="CEcrjGyipqt0OflgdQQSRGdrDXdDUY2x"sec_key="hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk"timestamp=int(round(time.time()*1e3))# 1608133910000message=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+importjavax.crypto.Mac;importjavax.crypto.spec.SecretKeySpec;importorg.apache.commons.codec.binary.Base64;publicclassSignatureExample{publicstaticvoidmain(String[]args){try{longtimestamp=System.currentTimeMillis();// 1562952827927Stringapi_path="user/info";Stringsecret="hV8FgjyJtpvVeAcMAgzgAFQCN36wmbWuN7o3WPcYcYhFd8qvE43gzFGVsFcCqMNk";Stringmessage=timestamp+"+"+api_path;Macsha256_HMAC=Mac.getInstance("HmacSHA256");SecretKeySpecsecret_key=newSecretKeySpec(secret.getBytes(),"HmacSHA256");sha256_HMAC.init(secret_key);Stringhash=Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));System.out.println(hash);// vBZf8OQuiTJIVbNpNHGY3zcUsK5gJpwb5lgCgarpxYI=}catch(Exceptione){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>. Thetimestamp is the UTC timestamp in milliseconds. Theapi-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,//expiretime,UTCtimestampinmilliseconds.If-1,theapikeywillnotexpire"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 inAuthenticate a RESTful Request section.

prehash string

<timestamp>+v2/account/info

Obtain the account information.

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

Response Content

NameTypeDescription
accountGroupIntnon-negative integer
emailString
expireTimeLongthe time when the API key will be expired (UTC timestamp in milliseconds). If -1, the api key will not expire
allowedIpsList[String]list of IPs allowed for the api key
cashAccountList[String]
marginAccountList[String]
tradePermissionBoolean
transferPermissionBoolean
viewPermissionBoolean
userUIDStringan unique id associated with user

See a demo atquery private account info.

VIP Fee Schedule

Fee Schedule - Sample response for general info::

{"code":0,"data":{"domain":"futures","userUID":"U0866943712","vipLevel":0,"genericFee":{"largeCap":{"maker":"0.00085","taker":"0.00085"},"smallCap":{"maker":"0.001","taker":"0.001"}}}}

HTTP Request

GET <account-group>/api/pro/v1/futures/fee/info

Signature

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

prehash string

<timestamp>+fee/info

See a demo atquery fee.

Fee Schedule by Symbol

Fee Schedule - Sample response for each symbol::

{"code":0,"data":{"domain":"futures","userUID":"U0866943712","vipLevel":0,"productFee":[{"fee":{"maker":"0.0001","taker":"0.0001"},"symbol":"BTC-PERP"},{"fee":{"maker":"0.0001","taker":"0.0001"},"symbol":"ETH-PERP"}]}}

HTTP Request

GET <account-group>/api/pro/v1/futures/fee

Signature

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

prehash string

<timestamp>+fee

See a demo atquery fee.

Risk Limit Info(Deprecated)

This API has been deprecated, please userisk limit info v2 instead.

Risk Limit Info

curl -X GET https://ascendex.com/api/pro/v1/risk-limit-info"

Risk Limit Info - Sample response::

{"code":0,"data":{"ip":"0.0.0.0","webSocket":{"windowSizeInMinutes":5,"maxNumRequests":45,"maxSessionPerIp":30,"isBanned":true,"bannedUntil":1644807691158,"violationCode":100014,"reason":"exceeds MAX_REQ_COUNT_PER_IP[45], 49 requests recently"}}}

HTTP Request

GET /api/pro/v1/risk-limit-info

Request Parameters

NameTypeRequiredValue RangeDescription
ipStringNovalid ip addressthe client's ip address to be checked if it is banned due to violation of risk limits.

Risk Limit Info (v2)

Risk Limit Info v2

Our message thresholds in web socket are based onop field andaction field. Each threshold will have two levels, which are based on counts of messages received in1 minute. If level 1 threshold is violated, this type of messages will be ignored in the following 15 minutes, other functions are not affected. If you keep sending these messages and triggered level 2 threshold, the violated WebSocket session will be killed and this ip will be banned for 15 minutes. Currently, We have following threshold groups:

All the operations fall into sameop/req group will share a threshold, meaning the sum of count of these messages should not violate the threshold.

Forreq op, we have two fine granularity thresholdorder req andsnapshot req, which will have their specialized threshold value for messages belonging to their types.

curl -X GET https://ascendex.com/api/pro/v2/risk-limit-info"

Risk Limit Info - Sample response::

{"code":0,"data":{"ip":"173.123.133.23","webSocket":{"status":{"isBanned":false,"bannedUntil":-1,"violationCode":0,"reason":""},"limits":{"maxWebSocketSessionsPerIpAccountGroup":20,"maxWebSocketSessionsPerIpTotal":300},"messageThreshold":{"level1OpThreshold":{"auth":800,"ping":800,"pong":800,"sub":150,"unsub":150,"req":10000},"level2OpThreshold":{"auth":1000,"ping":1000,"pong":1000,"sub":200,"unsub":200,"req":10000},"level1ReqThreshold":{"place_order":8000,"cancel_order":8000,"cancel_all":8000,"batch_place_order":10000,"batch_cancel_order":10000,"depth_snapshot":400,"depth_snapshot_top100":400,"market_trades":10000,"balance":10000,"open_order":10000,"margin_risk":10000,"futures_account_snapshot":10000,"futures_open_orders":10000},"level2ReqThreshold":{"place_order":10000,"cancel_order":10000,"cancel_all":10000,"batch_place_order":10000,"batch_cancel_order":10000,"depth_snapshot":500,"depth_snapshot_top100":500,"market_trades":10000,"balance":10000,"open_order":10000,"margin_risk":10000,"futures_account_snapshot":10000,"futures_open_orders":10000}}}}}

HTTP Request

GET /api/pro/v2/risk-limit-info

Request Parameters

NameTypeRequiredValue RangeDescription
ipStringNovalid ip addressthe client's ip address to be checked if it is banned due to violation of risk limits.

Position

Response

{"code":0,"data":{"ac":"FUTURES",//accountcategory"accountId":"sample-futures-account-id",//accountID"collaterals":[{"asset":"ETH",//collateralasset"balance":"100",//balance"discountFactor":"0.95",//discountfactor"referencePrice":"481.79793092"//referenceprice(quoteinUSDT)},{"asset":"BTC","balance":"10","discountFactor":"0.98","referencePrice":"17600.095"},{"asset":"USDT","balance":"10000","discountFactor":"1","referencePrice":"1"}],"contracts":[{"symbol":"BTC-PERP",//contractsymbol"side":"LONG",//side"position":"0.5",//positiveforlongpositionandnegativeforshortposition"referenceCost":"-16800",//referencecost"unrealizedPnl":"0",//unrealizedpnl"realizedPnl":"0",//realizedpnl"avgOpenPrice":"0",//AverageOpeningPrice"marginType":"cross",//margintype:isolated/cross"isolatedMargin":"0",//isolatedmargin"leverage":"10",//leverage"takeProfitPrice":"0",//takeprofitprice(bypositionexitorder)"takeProfitTrigger":"market",//takeprofittrigger(bypositionexitorder)"stopLossPrice":"0",//stoplossprice(bypositionexitorder)"stopLossTrigger":"market",//stoplosstrigger(bypositionexitorder)"buyOpenOrderNotional":"1362.419625",//buyopenordernotional"sellOpenOrderNotional":"0",//sellopenordernotional"indexPrice":"17600.095",//priceofthecontract'sunderlyingproductprice"markPrice":"-1"//contract'smarkprice}]}}

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",//collateralasset"availableForTransfer":"1"//maximumamountallowedtobetransferredout},{"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.

SeeChange 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.

SeeFree 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

PARAMETERTYPEREQUIREDDESCRIPTION
symbolStringYese.g.BTC-PERP
amountStringYesmargin amount in string type, e.g. "100". Setamount to positive will increase the isolated margin; setamount

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

PARAMETERTYPEREQUIREDDESCRIPTION
symbolStringYese.g.BTC-PERP
marginTypeENUMYesYou can switch between two margin types:isolated andcrossed

Change Contract Leverage

Response

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

HTTP Request

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

Request Parameters

PARAMETERTYPEREQUIREDDESCRIPTION
symbolStringYese.g.BTC-PERP
leverageIntYesthe leverage should be an integer between1 and100

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

PARAMETERTYPEREQUIREDDESCRIPTION
assetStringYese.g.BTC
amountStringYesthe 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

PARAMETERTYPEREQUIREDDESCRIPTION
assetStringYese.g.BTC
amountStringYesthe amount to withdraw in string type, e.g. "1". Only positive value is allowed.

Funding Payment History

Response

{"code":0,"data":{"data":[{"fundingRate":"0.00003666","paymentInUSDT":"-0.000142423","symbol":"BTC-PERP","timestamp":1642780800000},{"fundingRate":"0.000109429","paymentInUSDT":"-0.000428031","symbol":"BTC-PERP","timestamp":1642752000000}],"hasNext":true,"page":1,"pageSize":2}}

Get funding payment history of your account.

HTTP Request

GET /<grp>/api/pro/v2/futures/funding-payments

Prehash String

<timestamp>+v2/futures/funding-payments

Request Parameters

NameTypeRequiredDescription
symbolStringNoe.g.BTCUSDT
pageIntNopage number, default 1
pageSizeIntNosize of the page, 1~100, default 20.

Code Sample

Please refer to python code toget funding history

Order

Generate Order Id

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

Method

Extra info onid

Code Sample

Please refer to python code togen server order id

New Order

Successful Response

{"code":0,"data":{"meta":{"action":"place-order","id":"abcd1234abcd1234","respInst":"ACCEPT"//ACK,ACCEPT,orDONE},"order":{"ac":"FUTURES","accountId":"sample-futures-account-id","seqNum":14,//sequencenumber,also-1inACKmode"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

PARAMETERTYPEREQUIREDDESCRIPTION
idString>=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.
timeLongYesMilliseconds since UNIX epoch in UTC. We do not process request placed more than 30 seconds ago.
symbolStringYese.g.BTC-PERP
orderPriceStringRequired forLimit andStopLimit orders
orderQtyStringYesOrder size. Please set scale properly for each symbol.
orderTypeENUMYes
sideENUMYes
respInstENUMACK for limit order andDone for market order by default
postOnlyBooleanfalse by default
stopPriceStringrequired forStopLimit andStopMarket orders
timeInForceENUMGTC by default
execInstENUM
posStopLossPriceStringposition stop loss price
posTakeProfitPriceStringposition take profit price

Place Batch Orders

Place Batch Orders - Request Body

{"orders":[{"id":"sampleRequestId1","time":1613878579169,"symbol":"BTC-PERP","price":"34000","orderQty":"0.1","orderType":"limit","side":"buy","respInst":"ACK"},{"id":"sampleRequestId2","time":1613878579169,"symbol":"BTC-PERP","price":"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

NameData TypeDescription
ordersListList of order items

please refer toplacing new order for order item definition.

respInst field is required for market order and onlyACK is allowed.

Cancel Order

Response

{"code":0,"data":{"meta":{"action":"cancel-order",//action"id":"abcd1234abcd1234",//userprovidedID"respInst":"ACCEPT"//responseinstruction},"order":{"ac":"FUTURES",//accountcategory"accountId":"sample-futures-account-id",//accountID"seqNum":14,//sequencenumber"time":1605677683714,//ordercreationtime(UTCtimeinmilliseconds)"orderId":"sample-order-id",//orderID"orderType":"Limit",//ordertype"side":"Buy",//side"symbol":"BTC-PERP",//contractsymbol"price":"9500",//orderprice"orderQty":"0.1",//orderqty"stopPrice":"0",//stopprice"stopBy":"market",//stoppricetrigger"status":"Canceled",//orderstatus"lastExecTime":1605677684479,//lastexecutiontime(UTCtimeinmilliseconds)"lastPx":"0",//lastfilledprice"lastQty":"0",//lastfilledquantity"avgFilledPx":"0",//averagefilledpriceofallfills"cumFilledQty":"0",//cummulativefilledquantity"fee":"0",//feeofthelastfill"cumFee":"0",//cummulativefee"feeAsset":"USDT",//feeasset"errorCode":""//errorcode}}}

HTTP Request

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

Prehash String

<timestamp>+v2/futures/order

Request Parameters

PARAMETERTYPEREQUIREDDESCRIPTION
idString>=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.
orderIdStringYes32 chars order id. You should set the value to be the orderId of the target order you want to cancel.
symbolStringYesSymbol of the order to cancel
timeLongYesmilliseconds since UNIX epoch in UTC. We do not process request sent more than 30 seconds ago.
respInstENUMACK 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

NameData TypeDescription
ordersListList of order items to cancel

please refer tocancel 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

PARAMETERTYPEREQUIREDDESCRIPTION
symbolStringNothe optional symbol filter

List Open Orders

Response

{"code":0,"data":[{"ac":"FUTURES",//accountcategory"accountId":"sample-futures-account-id",//accountID"seqNum":14,//sequencenumber"time":1605677683714,//ordercreationtime"orderId":"sample-order-id",//orderID"orderType":"Limit",//ordertype"side":"Buy",//orderside"symbol":"BTC-PERP",//contractsymbol"price":"9500",//orderprice"orderQty":"0.1",//orderquantity"stopPrice":"0",//stopprice"stopBy":"market",//stoppricetrigger"status":"New",//orderstatus"lastExecTime":1605677684479,//lastexecutiontime"lastPx":"0",//lastfilledprice"lastQty":"0",//lastfilledquantity"avgFilledPx":"0",//averagefilledpriceofallfills"cumFilledQty":"0",//cummulativefilledquantity"fee":"0",//feeofthelastfill"cumFee":"0",//cummulativefee"feeAsset":"USDT",//feeasset"errorCode":""//errorcode}]}

HTTP Request

GET /<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

NameTypeRequiredDescription
symbolStringNosymbol filter, e.g."BTC-PERP"
nIntNomaximum number of orders to be included in the response
executedOnlyBooleanNoifTrue, 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

PARAMETERTYPEREQUIREDDESCRIPTION
orderIdStringYesa 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.

Balance Snapshot And Update Detail

Here we provide rest API to get daily balance snapshot, and intraday balance and order fills update details. We recommend calling balance snapshot endpoint(futures/balance/snapshot) to get balance at the beginning of the day, and get the sequence numbersn; then start to query balance or order fills update fromfutures/balance/history by setting parametersn value to besn + 1.

Please note we enforce rate limit 8 / minute. Data query for most recent 7 days is supported.

Futures Account Balance Snapshot

This API returns futures balance snapshot on daily basis.

HTTP Request

GET api/pro/data/v1/futures/balance/snapshot

Signature

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

Prehash String

<timestamp>+data/v1/futures/balance/snapshot

Request Parameters

NameTypeRequiredValue RangeDescription
dateStringYesYYYY-mm-ddbalance date

Response Content

NameTypeDescription
metaJsonmeta info. See detail below
collateralBalanceJson Arraycollateral balance info. See detail below
contractBalanceJson Arraycontract balance info. See detail below

meta field provides some basic info about the balance snapshot data.

meta schema

NameTypeDescriptionSample Response
acStringaccount category"futures
accountIdStringaccountId
snLongsequence number
balanceTimeLongbalance snapshot time in milli seconds

collateralBalance field provides array of ‘asset’ and ‘totalBalance’ for collateral balance.

collateralBalance schema

NameTypeDescriptionSample Response
assetStringasset code"USDT"
totalBalanceStringcurrent asset total balance"1234.56"

contractBalance field provides array of current contract positions infomation.

contractBalance schema

NameTypeDescriptionSample Response
contractStringcontract name"USDT"
futuresAssetBalanceStringcurrent contract position"1234.56"
isolatedMarginStringIsolated margin"134.56"
refCostBalanceStringReference cost"34.56"

Code Sample

Please refer to python code toquery balance snapshot

Futures Order and Balance Detail

This API is for intraday balance change detail from balance event and order fillss.

HTTP Request

GET api/pro/data/v1/futures/balance/history

Prehash String

<timestamp>+data/v1/futures/balance/history

Futures Account Balance Detail - Sample response

{"balance":[{"data":[{"asset":"XPRTPC","curBalance":"-7.873230189","deltaQty":"0.004117158"}],"eventType":"Fundingpayment","sn":18591022051,"transactTime":1634947227877},{"data":[{"asset":"BTCPC","curBalance":"-307.654491085","deltaQty":"10.673854479"},{"asset":"USDT","curBalance":"149.493187792","deltaQty":"10.673854479"}],"eventType":"Futuressettlement","sn":18590550015,"transactTime":1634913817331}],"meta":{"ac":"futures","accountId":"futfi7p9j312936d2hkjJpAahWyb4RCJ"},"order":[{"data":[{"asset":"PORTP","curBalance":"1","dataType":"trade","deltaQty":"1"},{"asset":"PORTPC","curBalance":"-6.213726","dataType":"trade","deltaQty":"-6.21"},{"asset":"PORTPC","curBalance":"-6.213726","dataType":"fee","deltaQty":"-0.003726"}],"liquidityInd":"RemovedLiquidity","orderId":"r17ca5840c64U7684578612bportL84r","orderType":"Market","side":"Buy","sn":18589783182,"transactTime":1634864467246}]}

Request Parameters

NameTypeRequiredValue RangeDescription
snLongYesstart from snapshotsnStart sn
limitIntNo1 to 500Number of records. max 500

Response Content

NameTypeDescription
metaJsonmeta info. See detail below
orderJson Arrayorder info. See detail below
balanceJson Arraybalance info. See detail below
Meta

meta field provides some basic info.

meta schema

NameTypeDescriptionSample Response
acStringaccount category"cash", "margin", "futures
accountIdStringaccountId
Order

order field provides an array of asset balance detail from order fill event.

order schema

NameTypeDescriptionSample Response
liquidityIndStringliquidity indicatorRemovedLiquidity for taker order,AddedLiquidity for maker order, orNULL_VAL
orderIdStringorderIdorder Id
orderTypeStringorder typemarket,limit
sideStringorder sidebuy,sell
snLongsequence numberunique and increasing sequence number
transactTimeLongtransactTime in milli seconds
dataJson Arraylist of order info json objectssee detail below

order balance detail by asset

data schema

NameTypeDescriptionSample Response
assetStringasset code"USDT"
curBalanceStringasset balance after this transaction"1234.56"
dataTypeStringtrade for trading asset;fee for fee balance assettrade,fee
deltaQtyStringbalance change in this transaction100
Balance

balance field provides an array of asset balance detail due to balance event.

balance schema

NameTypeDescriptionSample Response
eventTypeStringbalance event typedeposit,withdrawal
snLongsequence number
transactTimeLongtransactTime in milli seconds
dataJson Arraylist of balance info json objectssee detail below

data schema

NameTypeDescriptionSample Response
assetStringasset code"USDT"
curBalanceStringasset balance after this transaction"1234.56"
deltaQtyStringbalance change in this transaction100

Code Sample

Please refer to python code toquery order and balance detail

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 aconnected message:

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

Method 1 - WebSocket Authentication with Request Headers

Authenticate with Headers

# # Install wscat from Node.js if you haven't# npm install -g wscatAPIPATH=v2/streamAPIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7rSECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7qTIMESTAMP=`date +%s%N |cut-c-13`MESSAGE=$TIMESTAMP+$APIPATHSIGNATURE=`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.ascendex-sandbox.com:443/api/pro/v2/stream-w 1-x'{"op":"sub", "id": "abc123", "ch": "order:cshQtyfq8XLAA9kcf19h8bXHbAwwoqDo:ASD/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 theauth Message

# # Install wscat from Node.js if you haven't# npm install -g wscatAPIPATH=v2/streamAPIKEY=BclE7dBGbS1AP3VnOuq6s8fJH0fWbH7rSECRET=fAZcQRUMxj3eX3DreIjFcPiJ9UR3ZTdgIw8mxddvtcDxLoXvdbXJuFQYadUUsF7qTIMESTAMP=`date +%s%N |cut-c-13`MESSAGE=$TIMESTAMP+$APIPATHSIGNATURE=`echo-n$MESSAGE | openssl dgst-sha256-hmac$SECRET-binary |base64`wscat-c wss://api-test.ascendex-sandbox.com: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 anop:auth message to the server.

NameTypeRequiredDescription
opStringYes"auth"
idStringNooptional id field, you may safely skip it
tLongYesUTC timestamp in milliseconds, use this timestamp to generate signature
keyStringYesyour api key
sigStringYesthe 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.

FieldTypeDescription
mString"auth"
idStringecho back the id if you provide one in the request
codeLongAny code other than 0 indicate an error in authentication
errOptional[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 aping message to the client. Once theping message is received,the client should promptly send apong message to the server. If you missed two consecutiveping messages, the session will be disconnected.

Server Ping Message Schema

NameTypeDescription
opStringping
hpInthealth 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 sendping message to the server every 15 seconds to keep the connection alive. The server will stop sendingping message for 30 seconds if a client initiatedping message is received.

Server Pong Message Schema

NameTypeDescription
mStringpong
codeInterror code, for the pong mesage, the error code is always 0 (success)
tsLongserver time in UTC miliseconds
hpInthealth 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,//datatime"ip":"50702.8",//indexprice"mp":"50652.3553",//markprice"r":"0.000565699",//fundingrate"oi":"90.7367",//openinterest"f":1614816000000//nextfundingtime}],"col":[//collateralassets{"a":"USDTR",//asset"p":"1"//referenceprice(quoteinUSDT)},{"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 toBTC-PERP quote stream

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

Unsubscribe toBTC-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 toBTC-PERP depth updates stream

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

Unsubscribe toBTC-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 thedepth channel.

Eachdepth message contains abids list and anasks list in itsdata 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 andsize is always non-negative.

SeeOrderbook Snapshot for code examples.

Channel: Market Trades

Subscribe toBTC-PERP market trades stream

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

Unsubscribe toBTC-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}]}

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

NameTypeDescription
seqnumLongthe sequence number of the trade record.seqnum is always increasing for each symbol, but may not be consecutive
pStringthe executed price expressed as a string
qStringthe aggregated traded amount expressed as string
tsLongthe UTC timestamp in milliseconds of the first trade
bmBooleanif true, the buyer of the trade is the maker.

Channel: Bar Data

Subscribe toBTC-PERP 1 minute bar stream

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

Unsubscribe toBTC-PERP 1 minute bar stream

{"op":"unsub","id":"abc123","ch":"bar:1:BTC-PERP"}//Alternatively,youcanunsubscribeallbarstreamsforBTC-PERP{"op":"unsub","id":"abc123","ch":"bar:*:BTC-PERP"}//Orunsubscribeall1minutebarstream{"op":"unsub","id":"abc123","ch":"bar:1"}//Orunsubscribeallbarstream{"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"}}

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

NameTypeDescription
seqnumLongthe sequence number of the trade record.seqnum is always increasing for each symbol, but may not be consecutive
pStringthe executed price expressed as a string
qStringthe aggregated traded amount expressed as string
tsLongthe UTC timestamp in milliseconds of the first trade
bmBooleanif true, the buyer of the trade is the maker.

Private Stream Data

Channel: Order

{"m":"futures-order","sn":127,//sequencenumber"e":"ExecutionReport",//event"a":"sample-futures-account-id",//accountId"ac":"FUTURES",//accountcategory"t":1606335352348,//lastexecutiontime"ct":1606335351541,//ordercreationtime"orderId":"a176010c4957U68469127074abcd1234",//orderId"sd":"Buy",//side"ot":"Limit",//ordertype"q":"0.1",//orderquantity(baseasset)"p":"18000",//orderprice"sp":"0",//stopprice"spb":"",//stoptrigger"s":"BTC-PERP",//symbol"st":"New",//orderstatus"lp":"0",//lastfilledprice"lq":"0",//lastfilledquantity(baseasset)"ap":"0",//averagefilledprice"cfq":"0",//cummulativefilledquantity(baseasset)"f":"0",//commissionfeeofthecurrentexecution"cf":"0",//cumulativecommissionfee"fa":"USDT",//feeasset"ei":"NULL_VAL",//executioninstruction"err":""//errormessage}

Subscribe to the Channel

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

Channel: Account Update

{"m":"futures-account-update",//message"e":"ExecutionReport",//eventtype"t":1612508562129,//servertime(UTCtimeinmilliseconds)"acc":"sample-futures-account-id",//accountID"at":"FUTURES",//accounttype"sn":23128,//sequencenumber,strictlyincreasingforeachaccount"id":"r177710001cbU3813942147C5kbFGOan",//requestIDforthisaccountupdate"col":[{"a":"USDT",//assetcode"b":"1000000",//balance"f":"1"//discountfactor}],"pos":[{"s":"BTC-PERP",//symbol"sd":"LONG",//side"pos":"0.011",//position"rc":"-385.840455",//referencecost"up":"18.436008668",//unrealizedpnl"rp":"0",//realizedpnl"aop":"35041.363636363",//AverageOpeningPrice"boon":"0",//BuyOpenOrderNotional"soon":"0",//SellOpenOrderNotional"mt":"crossed",//margintype:isolated/cross"iw":"0",//isolatedmargin"lev":"10",//leverage"tp":"0",//takeprofitprice(bypositionexitorder)"tpt":"market",//takeprofittrigger(bypositionexitorder)"sl":"0",//stoplossprice(bypositionexitorder)"slt":"market",//stoplosstrigger(bypositionexitorder)}]}

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",//echobacktherequestId"e":"ClientRequest",//eventname"t":1613748277356,//servertimeinmilliseconds(UTC)"acc":"futH9N59hR0BMVEjHnBleHLn0mfUl5lo",//accountId"ac":"FUTURES",//accountcategory"sn":9982,//sequencenumber"col":[//collateralbalances{"a":"ETH",//collateralassetcode"b":"500",//collateralbalance"f":"0.95"//discountfactor},{"a":"BTC","b":"100","f":"0.98"},{"a":"USDT","b":"1000000","f":"1"}],"pos":[//contractpositions{"s":"BTC-PERP",//contractsymbol"sd":"NULL_VAL",//side:LONG/SHORT/NULL_VAL"pos":"0",//position"rc":"0",//referencecost"up":"0",//unrealizedpnl"rp":"0",//realizedpnl"aop":"0",//averageopeningprice"mt":"crossed",//margintype:isolated/cross"boon":"0",//buyopenordernotional"soon":"0",//sellopenordernotional"lev":"10",//leverage"iw":"0",//isolatedmargin"tp":"0",//takeprofitprice(bypositionexitorder)"tpt":"market",//takeprofittrigger(bypositionexitorder)"sl":"0",//stoplossprice(bypositionexitorder)"slt":"market"//stoplosstrigger(bypositionexitorder)}]}

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

The request schema:

NameData TypeDescription
opStringreq
actionStringfutures-account-snapshot
idStringfor result match purpose

WS: Place Order

Request to place new order

{"op":"req","action":"place-order","ac":"futures",//theAccountCategory"id":"sampleRequestID",//theserverwillechobackthisidintheackmessage."args":{"time":1613753879921,"symbol":"BTC-PERP","price":"30000","orderQty":"0.12","orderType":"limit","side":"buy","postOnly":false,"respInst":"ACK"}}

Successful ACK message

{"m":"order","code":0,"id":"sampleRequestID",//echobacktheoriginalrequestId"action":"place-order","ac":"FUTURES","info":{"orderId":"s177bbb671b7U1234567890leOrderId","symbol":"BTC-PERP"}}

Error response message

{"m":"order","code":300001,"id":"sampleRequestID",//echobacktheoriginalrequestId"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 forargs field.

seeplacing order via RESTful API.

id

As described inGenerate 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 withm field asorder, andaction field asplace-order; if you provideid in your request, it will be echoed back asid to help you identify;code field to indicate if this is a successfulzero or failednon-zero.

code=0

Withcode field aszero 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 provideid in your request, it will be echoed back asid to help you identify; we also provide server side generatedorderId, which is the id you should use for future track or action on the order.

code=non-zero

Withcode field asnon-zero to indicate there is some obvisous errors in your request.

info field provide some detail: we also provide errorreason anderrorMsg detail.

WS: Cancel Order

Request to cancel existing open order

{"op":"req","action":"cancel-order","ac":"futures","id":"sampleRequestId",//serverwillechobackthisId."args":{"time":1613744943323,"orderId":"s177bab1b474U5051470287bbtcpKiOR","symbol":"BTC-PERP"}}

Successful ACK message

{"m":"order","action":"cancel-order","ac":"FUTURES","id":"sampleRequestId",//echobacktheoriginalrequestId"code":0,"info":{"orderId":"s177bab1b474U5051470287bbtcpKiOR","symbol":"BTC-PERP"}}

Error response message

{"m":"order","action":"cancel-order","ac":"FUTURES","code":300006,"id":"sampleRequestId",//echobacktheoriginalrequestId"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 settingaction to becancel-orde, with proper cancel order parameters as specified in rest api forargs field.

Response

Respond withm field asorder, andaction field ascancel-order;code field to indicate if this is a successfulzero or failednon-zero.

code=0

Withcode field aszero 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 providesymbol in your request, it will be echoed back assymbol to help you idintify; we also echo back targetorderId to be cancelled.

code=non-zero

Withcode field asnon-zero to indicate there is some obvisous errors in your cancel order request.

info field provide some detail: we also provide errorreason anderrorMsg detail.

WS: Cancel All Orders

Request to cancel all existing open orders

{"op":"req","action":"cancel-all","ac":"futures","id":"sampleRequestId",//serverwillechobackthisId."args":{//youcanalsoomittheargsfield}}

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

{"op":"req","action":"cancel-all","ac":"futures","id":"sampleRequestId",//serverwillechobackthisId."args":{"symbol":"BTC-PERP"}}

Successful ACK message

{"m":"order","code":0,"action":"cancel-all","ac":"FUTURES","id":"sampleRequestId",//echobacktheoriginalrequestId"info":{"symbol":""}}

Error response message

{"m":"order","code":300012,"action":"cancel-all","ac":"FUTURES","id":"sampleRequestId",//echobacktheoriginalrequestId"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 withaction field ascancel-All and set properac value(futures), and providesymbol value inargs.

Response

Withcode field aszero to indicate this cancel all order request has been received by server and sent to matching engine.

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

Withcode field asnon-zero to indicate there is some obvisous errors in your request.

info field provide some detail: we also provide errorreason anderrorMsg 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 afutures-open-orders action.

The request schema:

NameData TypeDescription
opStringreq
actionStringfutures-open-orders
idStringfor result match purpose
args:symbolOptional[String]add the (optional) symbol filter, see below for details.

Thesymbol key in theargs 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)

Order Status (status)

Margin Type (marginType)

WebSocket Operations (op)

WebSocket Message Types (m)

shellpythonjava

[8]ページ先頭

©2009-2025 Movatter.jp