NAV Navigation
English
HTTP

Overview

Welcome to the BloFin API!

BloFin provides reliable REST and WebSocket APIs for secure trading operations. Our API suite supports:

General Info

Demo Trading

General Information on Endpoints

API Key Creation

Please refer to my API page regarding API Key creation.

Generating an API Key

Create an API Key on the website before signing any requests. After creating an API Key, keep the following information safe:

There are two permissions below that can be associated with an API Key. One or more permission can be assigned to any Key.

Each API Key can be linked with up to 20 IP addresses. API Keys that are not bound to IPs will expire after 90 days.

REST Authentication

Making Requests

All private REST requests must contain the following headers:

Request bodies should have content type application/json and be in valid JSON format.

Signature

The ACCESS-SIGN header is generated as follows:

  1. Create a prehash string by concatenating:
    1. requestPath (including query parameters for GET requests)
    2. method (HTTP method in uppercase: GET, POST, etc.)
    3. timestamp (milliseconds since epoch)
    4. nonce (unique identifier like UUID)
    5. body (JSON string for POST requests, empty string for GET)
  2. Generate HMAC-SHA256 signature using the SecretKey
  3. Convert signature to hexadecimal
  4. Encode the hex signature in Base64 format

GET Request Example:

# Python
path = "/api/v1/asset/balances?accountType=spot"
method = "GET"
timestamp = str(int(datetime.now().timestamp() * 1000))
nonce = str(uuid4())
body = "" # Empty for GET requests

prehash = f"{path}{method}{timestamp}{nonce}{body}"
hex_signature = hmac.new(
secret_key.encode(),
prehash.encode(),
hashlib.sha256
).hexdigest().encode()

signature = base64.b64encode(hex_signature).decode()
// JavaScript
const path = '/api/v1/asset/balances?accountType=spot';
const method = 'GET';
const body = ''; // Empty for GET requests

const prehash = path + method + timestamp + nonce + body;
const hex_signature = CryptoJS.HmacSHA256(prehash, secretKey).toString();
const signature = CryptoJS.enc.Base64.stringify(
CryptoJS.enc.Utf8.parse(hex_signature)
);

POST Request Example:

# Python
path = "/api/v1/spot/trade/order"
method = "POST"
timestamp = str(int(datetime.now().timestamp() * 1000))
nonce = str(uuid4())
body = {
"instType": "SPOT",
"instId": "BTC-USDT",
"side": "buy",
"orderType": "limit",
"price": "35000",
"size": "0.1"
}

body_str = json.dumps(body)
prehash = f"{path}{method}{timestamp}{nonce}{body_str}"
hex_signature = hmac.new(
secret_key.encode(),
prehash.encode(),
hashlib.sha256
).hexdigest().encode()

signature = base64.b64encode(hex_signature).decode()

Complete signing function:

def sign_request(secret: str, method: str, path: str, body: dict | None = None) -> str:
"""Generate BloFin API request signature.

Args:
secret: API secret key
method: HTTP method (GET, POST, etc.)
path: API endpoint path (including query params)
body: Request body for POST/PUT requests (None for GET)

Returns:
Base64-encoded signature string
"""

timestamp = str(int(datetime.now().timestamp() * 1000))
nonce = str(uuid4())

# Create prehash string
msg = f"{path}{method}{timestamp}{nonce}"
if body:
msg += json.dumps(body)

# Generate hex signature and convert to base64
hex_signature = hmac.new(
secret.encode(),
msg.encode(),
hashlib.sha256
).hexdigest().encode()

return base64.b64encode(hex_signature).decode()

The timestamp value is the same as the ACCESS-TIMESTAMP header with millisecond, e.g. 1597026383085.

The request method should be in UPPERCASE: e.g. GET and POST.

The requestPath is the path of requesting an endpoint.

Example: /api/v1/asset/balances?accountType=spot

The body refers to the String of the request body. It can be omitted if there is no request body (frequently the case for GET requests).

Example: {"instType":"SPOT","instId":"BTC-USDT","side":"buy","orderType":"limit","price":"35000","size":"0.1"}

GET request parameters are counted as requestPath, not body.

The SecretKey is generated when you create an APIKey.

Signature Verification Failed

If you encounter a “Signature verification failed” error, please follow the steps below to troubleshoot:

def create_signature_blofin(secret_key, nonce, method, timestamp, path, body=None):
# If it is a GET request, the body must be "".
if body:
prehash_string = f"{path}{method}{timestamp}{nonce}{json.dumps(body)}"
else:
prehash_string = f"{path}{method}{timestamp}{nonce}"
encoded_string = prehash_string.encode()
signature = hmac.new(secret_key.encode(), encoded_string, hashlib.sha256)
# It needs to be converted to a hexadecimal string and then converted to bytes.
# Please note that it is not hex2bytes, but rather string2bytes.
hexdigest = signature.hexdigest() # Convert the signature result into a hexadecimal string.
hexdigest_to_bytes = hexdigest.encode() # Convert this string into bytes.
base64_encoded = base64.b64encode(hexdigest_to_bytes).decode() # Base64 encoding
return base64_encoded

# If you are using python's `requests` library, for a POST request, the code would be:
# response = requests.post(url, headers=headers, json=body)
# Please note that the parameter name is `json` not `data`

WebSocket

Overview

WebSocket is a new HTML5 protocol that achieves full-duplex data transmission between the client and server, allowing data to be transferred effectively in both directions. A connection between the client and server can be established with just one handshake. The server will then be able to push data to the client according to preset rules. Its advantages include:

We recommend developers use WebSocket API to retrieve market data and order book depth.

WebSocket Authentication

The WebSocket API requires authentication for private channels. Use the login operation with a signed request to authenticate your connection.

Request Example:

{
"op": "login",
"args": [{
"apiKey": "YOUR_API_KEY",
"passphrase": "YOUR_PASSPHRASE",
"timestamp": "1597026383085",
"sign": "BASE64_ENCODED_SIGNATURE",
"nonce": "123e4567-e89b-12d3-a456-426614174000"
}]
}

Signature Generation

The signature (sign) parameter is generated using HMAC-SHA256 with fixed components:

  1. Fixed components for WebSocket authentication:
    1. path: Always /users/self/verify
    2. method: Always GET
    3. timestamp: Current time in milliseconds
    4. nonce: Random generated unique id
  2. Create signature string by concatenating: path + method + timestamp + nonce
  3. Generate HMAC-SHA256 hex digest using your SecretKey
  4. Encode the hex digest using Base64

Example implementation:

async def sign_websocket_login(secret: str, api_key: str, passphrase: str) -> tuple[str, str, str]:
"""Generate WebSocket login signature."""
timestamp = str(int(time.time() * 1000))
nonce = timestamp

# Fixed components for WebSocket auth
method = "GET"
path = "/users/self/verify"
# Create signature string
msg = f"{path}{method}{timestamp}{nonce}"
hex_signature = hmac.new(
secret.encode(),
msg.encode(),
hashlib.sha256
).hexdigest().encode()

return base64.b64encode(hex_signature).decode(), timestamp, nonce

Connection Management

The WebSocket connection requires proper authentication and connection management:

Request Parameters

Parameter Type Required Description
op String Yes Operation, login
args Array Yes List of account login parameters
> apiKey String Yes API Key
> passphrase String Yes The passphrase specified when creating the APIKey
> timestamp String Yes Unix Epoch time in milliseconds (e.g., 1597026383085)
> sign String Yes Base64-encoded HMAC-SHA256 signature
> nonce String Yes Unique identifier (UUID recommended) to prevent replay attacks

Successful Response Example:

{
"event": "login",
"code": "0",
"msg": ""
}

Failure Response Example:

{
"event": "error",
"code": "60009",
"msg": "Login failed."
}

Response Parameters

Parameter Type Description
event String Operation, login error
code String Error code
msg String Error message

Notes:

Important Notes:

The request will expire 1 minute after the timestamp.

Subscribe

Subscription Instructions

Request Format Description:

{
"op":"subscribe",
"args":[
"<SubscriptionTopic>"
]
}

WebSocket channels are divided into two categories: public and private channels.

Public channels – No authentication is required, include candlesticks channel, trades channel, order book channel etc.

Private channels – including orders channel, positions channel, and orders-algo channel, etc – require log in.

Users can choose to subscribe to one or more channels, and the total length of multiple channels cannot exceed 4,096 bytes.

Below is an example of subscription parameters. The requirement of subscription parameters for each channel is different. For details please refer to the specification of each channels.

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"books5",
"instId":"BTC-USDT"
},
{
"channel":"candle1m",
"instId":"BTC-USDT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name
> instId String Yes Instrument ID

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "books5",
"instId": "BTC-USDT"
}
}

Response Parameters

Parameter Type Description
event String Operation, subscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Unsubscribe

Subscription Instructions

Request Format Description:

{
"op":"unsubscribe",
"args":[
"<SubscriptionTopic>"
]
}

Unsubscribe from one or more channels.

Request Example:

{
"op":"unsubscribe",
"args":[
{
"channel":"books5",
"instId":"BTC-USDT"
},
{
"channel":"candle1m",
"instId":"BTC-USDT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name
> instId String Yes Instrument ID

Response Example:

{
"event": "unsubscribe",
"arg": {
"channel": "books5",
"instId": "BTC-USDT"
}
}

Response Parameters

Parameter Type Description
event String Operation, unsubscribe error
arg Object Unsubscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Rate Limits

Our REST and WebSocket APIs use rate limits to protect our APIs against malicious usage so our trading platform can operate reliably and fairly.

When a request is rejected by our system due to rate limits, the system will return error code 429 (Rate limit reached. Please refer to API documentation and throttle requests accordingly).

REST API Limits

WebSocket Connection Management

Connection Limits

If there’s a network problem, the system will automatically disable the connection.

The connection will break automatically if the subscription is not established or data has not been pushed for more than 30 seconds.

To keep the connection stable:

  1. Set a timer of N seconds whenever a response message is received, where N is less than 30.
  2. If the timer is triggered, which means that no new message is received within N seconds, send the String ‘ping’.
  3. Expect a ‘pong’ as a response. If the response message is not received within N seconds, please raise an error or reconnect.

Risk Control Restrictions

BloFin has two types of risk control strategies for APIs: rate limit, network firewall restrictions.

Network Firewall Restrictions

Currently, we do not provide explicit information about network firewall restrictions.

If you receive an HTTP 403 error message, it means you have violated a network firewall rule. In most cases, this error occurs due to excessive requests and will result in a five-minute temporary ban.

If your requests are deemed malicious, it could result in an extended ban or potentially even a permanent suspension.

Public Data

The API endpoints of Public Data do not require authentication.

REST API

GET Instruments

Retrieve a list of instruments with open spot.

HTTP Request

GET /api/v1/spot/market/instruments

Request Example:

https://openapi.blofin.com/api/v1/spot/market/instruments?instType=SPOT&instId=BTC-USDT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"instId": "BTC-USDT",
"baseCurrency": "BTC",
"quoteCurrency": "USDT",
"contractValue": null,
"listTime": "1638333031000",
"expireTime": "1704124800000",
"maxLeverage": "125",
"minSize": "0.1",
"lotSize": "0.1",
"tickSize": "0.5",
"instType": "SPOT",
"contractType": null,
"maxLimitSize": "100000000",
"maxMarketSize": "1000000",
"state": "live",
"settleCurrency": null
}
]
}

Response Parameters

Parameter Type Description
instId String Instrument ID, e.g. BTC-USDT
baseCurrency String Base currency, e.g. BTC in BTC-USDT
quoteCurrency String Quote currency, e.g. USDT in BTC-USDT
contractValue String Contract value in base currency (e.g. 0.001 BTC per contract for BTC-USDT)
Only applicable to SWAP
listTime String Listing time, Unix timestamp format in milliseconds, e.g. 1597026383085
expireTime String Instrument offline time, e.g. 1597026383085
maxLeverage String Max Leverage
minSize String Minimum order size
If it is a derivatives contract, the value is the number of contracts.
If it is SPOT, the value is the quantity in base currency.
lotSize String Lot size
If it is a derivatives contract, the value is the number of contracts.
If it is SPOT, the value is the quantity in base currency.
tickSize String Tick size, e.g. 0.0001
instType String Instrument type
contractType String Contract type
linear: linear contract
inverse: inverse contract
maxLimitSize String The maximum order quantity of the limit order
maxMarketSize String The maximum order quantity of the market order
state String Instrument status
live
suspend
settleCurrency String Settlement and margin currency, e.g. BTC

GET Tickers

Retrieve the latest price snapshot, best bid/ask price, and trading volume in the last 24 hours.

HTTP Request

GET /api/v1/spot/market/tickers

Request Example:

https://openapi.blofin.com/api/v1/spot/market/tickers?instType=SPOT&instId=BTC-USDT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"instId": "BTC-USDT",
"last": "27187",
"lastSize": "1",
"askPrice": "27187.5",
"askSize": "20",
"bidPrice": "27187",
"bidSize": "2",
"high24h": "27463.5",
"open24h": "27186.5",
"low24h": "26647.5",
"volCurrency24h": "3224.82",
"vol24h": null,
"ts": "1695261862487"
}
]
}

Response Parameters

Parameter Type Description
instId String Instrument ID, e.g. BTC-USDT
last String Last traded price
lastSize String Last traded size
askPrice String Best ask price
askSize String Best ask size
bidPrice String Best bid price
bidSize String Best bid size
high24h String Highest price in the past 24 hours
open24h String Open price in the past 24 hours
low24h String Lowest price in the past 24 hours
volCurrency24h String 24h trading volume, with a unit of base currency
vol24h String 24h trading volume, with a unit of contract
ts String Ticker data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085

GET Order Book

Retrieve order book of the instrument.

HTTP Request

GET /api/v1/spot/market/books

Request Example:

https://openapi.blofin.com/api/v1/spot/market/books?instType=SPOT&instId=BTC-USDT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
size String No Order book depth per side. Maximum 100, e.g. 100 bids + 100 asks
Default returns to 1 depth data

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"asks": [
["1620", "72"],
["1620.01", "317"],
["1620.03", "56"]
],
"bids": [
["1619.99", "49"],
["1619.98", "1905"],
["1619.97", "397"]
],
"ts": "1695262080136"
}
]
}

Response Parameters

Parameter Type Description
asks Array Order book on sell side
bids Array Order book on buy side
ts String Order book generation time e.g. 1597026383085

An example of the array of asks and bids values: ["411.8", "10"]

GET Trades

Retrieve the recent transactions of an instrument.

HTTP Request

GET /api/v1/spot/market/trades

Request Example:

https://openapi.blofin.com/api/v1/spot/market/trades?instType=SPOT&instId=BTC-USDT&limit=50

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
limit String No Number of results per request.
The maximum is 100;
The default is 100

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"tradeId": "124892894",
"instId": "ETH-USDT",
"price": "1620.11",
"size": "34",
"side": "sell",
"ts": "1695262343171"
}
]
}

Response Parameters

Parameter Type Description
tradeId Long Trade ID
instId String Instrument ID
price String Trade price
size String Trade quantity
side String Trade side
buy
sell
ts String Trade time, Unix timestamp format in milliseconds, e.g. 1597026383085

GET Candlesticks

Retrieve the candlestick charts.

HTTP Request

GET /api/v1/spot/market/candles

Request Example:

https://openapi.blofin.com/api/v1/spot/market/candles?instType=SPOT&instId=BTC-USDT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
bar String No Bar size, the default is 1m
e.g. 1m/3m/5m/15m/30m/1H/2H/4H/6H/8H/12H/1D/3D/1W/1M
after String No Pagination of data to return records earlier than the requested ts
before String No Pagination of data to return records newer than the requested ts. The latest data will be returned when using before individually
limit String No Number of results per request. The maximum is 1440. The default is 500.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
[
"1703484240000",
"2283.45",
"2283.45",
"2282.8",
"2282.8",
"835",
"8.35",
"19063.9805",
"1"
]
]
}

Response Parameters

Parameter Type Description
ts String Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1672502400000
open String Open price
high String Highest price
low String Lowest price
close String Close price
vol String Trading volume, with a unit of contracts
volCurrency String Trading volume, with a unit of base currency
volCurrencyQuote String Trading volume, with a unit of quote currency
confirm String The state of candlesticks.
0 represents that it is uncompleted, 1 represents that it is completed.

WebSocket

WS Trades Channel

This channel uses public WebSocket and authentication is not required.

Retrieve the recent trades data. Data will be pushed whenever there is a trade. Every update contain only one trade.

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"trades",
"instId":"ETH-USDT",
"instType": "SPOT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, trades
> instId String Yes Instrument ID
> instType String Yes Instrument type
SPOT: Spot

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "trades",
"instId": "ETH-USDT",
"instType": "SPOT"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"trades\", \"instId\" : \"ETH-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example:

{
"arg":{
"channel":"trades",
"instId":"ETH-USDT",
"instType": "SPOT"
},
"data":[
{
"instId":"ETH-USDT",
"tradeId":"106074994",
"price":"1640.4",
"size":"1",
"side":"sell",
"ts":"1696646190511"
}
]
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
> instId String Instrument ID
data Array Subscribed data
> instId String Instrument ID
> tradeId String Trade ID
> price String Trade price
> size String Trade size
> side String Trade direction, buy sell
> ts String Filled time, Unix timestamp format in milliseconds, e.g. 1597026383085

WS Candlesticks Channel

This channel uses public WebSocket and authentication is not required.

Retrieve the candlesticks data of an instrument. The push frequency is the fastest interval 1 second push the data.

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"candle1D",
"instId":"BTC-USDT",
"instType": "SPOT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name
candle1m
candle3m
candle5m
candle15m
candle30m
candle1H
candle2H
candle4H
candle6H
candle8H
candle12H
candle1D
candle3D
candle1W
candle1M
> instId String Yes Instrument ID
> instType String Yes Instrument type
SPOT: Spot

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "candle1D",
"instId": "BTC-USDT",
"instType": "SPOT"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"candle1D\", \"instId\" : \"BTC-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example:

{
"arg":{
"channel":"candle1D",
"instId":"BTC-USDT",
"instType": "SPOT"
},
"data":[
[
"1696636800000",
"27491.5",
"27495",
"27483",
"27489.5",
"95359",
"95.359",
"2621407.651",
"0"
]
]
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
> instId String Instrument ID
data Array Subscribed data
> ts String Opening time of the candlestick, Unix timestamp format in milliseconds, e.g. 1597026383085
> open String Open price
> high String Highest price
> low String Lowest price
> close String Close price
> volCurrency String Trading volume, with a unit of base currency
> volCurrencyQuote String Trading volume, with a unit of quote currency
> confirm String The state of candlesticks.
0 represents that it is uncompleted, 1 represents that it is completed.

WS Order Book Channel

This channel uses public WebSocket and authentication is not required.

Retrieve order book data. Use books for 400 depth levels, books5 for 5 depth levels.

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"books",
"instId":"BTC-USDT",
"instType": "SPOT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, books books5
> instId String Yes Instrument ID
> instType String Yes Instrument type
SPOT: Spot

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "books",
"instId": "BTC-USDT",
"instType": "SPOT"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"books\", \"instId\" : \"BTC-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example: Full Snapshot

{
"arg":{
"channel":"books",
"instId":"ETH-USDT",
"instType": "SPOT"
},
"action":"snapshot",
"data":{
"asks":[
[1639.75, 392],
[1639.95, 541]
],
"bids":[
[1639.7, 6817],
[1639.65, 4744]
],
"ts":"1696670727520",
"prevSeqId":"0",
"seqId":"107600747"
}
}

Push Data Example: Incremental Data

{
"arg":{
"channel":"books",
"instId":"ETH-USDT",
"instType": "SPOT"
},
"action":"update",
"data":{
"asks":[
[1639.95, 2208],
[1640, 4605]
],
"bids":[
[1639.65, 7115],
[1639.6, 4791]
],
"ts":"1696670728525",
"prevSeqId":"107600747",
"seqId":"107600806"
}
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
> instId String Instrument ID
action String Push data action, incremental data or full snapshot.
snapshot: full
update: incremental
data Object Subscribed data
> asks Array Order book on sell side
> bids Array Order book on buy side
> ts String Order book generation time, Unix timestamp format in milliseconds, e.g. 1597026383085
> prevSeqId String Sequence ID of the last sent message. Only applicable to books
> seqId String Sequence ID of the current message, implementation details below

An example of the array of asks and bids values: ["411.8", "10"]

Sequence ID

seqId is the sequence ID of the market data published. The set of sequence ID received by users is the same if users are connecting to the same channel through multiple websocket connections. Each instId has an unique set of sequence ID. Users can use prevSeqId and seqId to build the message sequencing for incremental order book updates. Generally the value of seqId is larger than prevSeqId. The prevSeqId in the new message matches with seqId of the previous message. In snapshot messages the prevSeqId is always 0.

Example:

  1. Snapshot message: prevSeqId = 0, seqId = 10
  2. Incremental message 1 (normal update): prevSeqId = 10, seqId = 15

Merging incremental data into full data

After subscribing to the incremental load push (such as books 200 levels) of Order Book Channel, users first receive the initial full load of market depth. After the incremental load is subsequently received, update the local full load.

  1. If there is the same price, compare the size. If the size is 0, delete this depth data. If the size changes, replace the original data.
  2. If there is no same price, sort by price (bid in descending order, ask in ascending order), and insert the depth information into the full load.

WS Tickers Channel

This channel uses public WebSocket and authentication is not required.

Retrieve the tickers data of an instrument. The push frequency is the fastest interval 1 second push the data.

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"tickers",
"instId":"BTC-USDT",
"instType": "SPOT"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, tickers
> instId String Yes Instrument ID
> instType String Yes Instrument type
SPOT: Spot

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "tickers",
"instId": "BTC-USDT",
"instType": "SPOT"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"tickers\", \"instId\" : \"BTC-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example:

{
"arg": {
"channel": "tickers",
"instId": "BTC-USDT",
"instType": "SPOT"
},
"data": [{
"instId": "BTC-USDT",
"last": "9999.99",
"lastSize": "0.1",
"askPrice": "9999.99",
"askSize": "11",
"bidPrice": "8888.88",
"bidSize": "5",
"open24h": "9000",
"high24h": "10000",
"low24h": "8888.88",
"volCurrency24h": "2222",
"vol24h": "2222",
"ts": "1597026383085"
}]
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
> instId String Instrument ID
data Array Subscribed data
> instId String Instrument ID
> last String Last traded price
> lastSize String Last traded size
> askPrice String Best ask price
> askSize String Best ask size
> bidPrice String Best bid price
> bidSize String Best bid size
> open24h String Open price in the past 24 hours
> high24h String Highest price in the past 24 hours
> low24h String Lowest price in the past 24 hours
> volCurrency24h String 24h trading volume, with a unit of base currency
> volCurrencyQuote24h String 24h trading volume, with a unit of quote currency
> ts String Ticker data generation time. Unix timestamp format in milliseconds, e.g. 1597026383085

Account

REST API

GET Balance

Retrieve the balances of all the assets and the amount that is available or on hold.

HTTP Request

GET /api/v1/asset/balances

Request Example:

GET /api/v1/asset/balances?accountType=funding

Request Parameters

Parameter Type Required Description
accountType String Yes Account type
funding/futures/copy_trading/earn/spot/inverse_contract
unified account use futures
currency String No Currency

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"currency": "USDT",
"balance": "10012514.919418081548717298",
"available": "9872132.414278782284622898",
"frozen": "138556.471805965930761067",
"bonus": "0"
}
]
}

Response Parameters

Parameter Type Description
currency String Currency
balance String Balance
frozen String Frozen balance
available String Available balance
The balance that can be withdrawn or transferred or used for trading
bonus String Bonus balance

Funds Transfer

Only API Keys with TRANSFER privilege can call this endpoint.

This endpoint supports the transfer of funds between your accounts.

HTTP Request

POST /api/v1/asset/transfer

Request Example:

POST /api/v1/asset/transfer
body
{
"currency":"USDT",
"amount":"1.5",
"fromAccount":"funding",
"toAccount":"futures",
"clientId":"1211211"
}

Request Parameters

Parameter Type Required Description
currency String Yes Transfer currency, e.g. USDT
fromAccount String Yes The remitting account
funding
futures
copy_trading
earn
spot
inverse_contract
unified account use futures
toAccount String Yes The beneficiary account
funding
futures
copy_trading
earn
spot
inverse_contract
unified account use futures
amount String Yes Amount to be transferred
clientId String No Client-supplied ID
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
subAccount String No Sub Account Uid
mainToSubAccount bool No true: master->sub
false: sub->master
Required for inter-account transfer

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"transferId": "3743",
"clientTransferId": "1211211"
}
}

Response Parameters

Parameter Type Description
transferId String Transfer ID
clientId String Client-supplied ID

GET Funds Transfer History

Query the funds transfer records.

HTTP Request

GET /api/v1/asset/bills

Request Example:

GET /api/v1/asset/bills

Request Parameters

Parameter Type Required Description
currency String No Transfer currency, e.g. USDT
fromAccount String No The remitting account
funding
futures
copy_trading
earn
spot
inverse_contract
unified account use futures
toAccount String No The beneficiary account
funding
futures
copy_trading
earn
spot
inverse_contract
unified account use futures
before String No Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1656633600000
after String No Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1654041600000
limit String No Number of results per request. The maximum is 100; The default is 100

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"transferId": "3743",
"currency": "USDT",
"fromAccount": "futures",
"toAccount": "funding",
"amount": "1.000000000000000000",
"ts": "1695264049618",
"clientId": "cccc12121"
}
]
}

Response Parameters

Parameter Type Description
currency String Transfer currency
fromAccount String The remitting account
funding
futures
copy_trading
earn
spot
toAccount String The beneficiary account
funding
futures
copy_trading
earn
spot
amount String Balance at the account level
ts String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
clientId String Client-supplied ID for transfer
transferId String Transfer ID

GET Withdraw History

Retrieve the withdrawal records according to the currency, withdrawal status, and time range in reverse chronological order.

HTTP Request

GET /api/v1/asset/withdrawal-history

Request Example:

GET /api/v1/asset/withdrawal-history

Request Parameters

Parameter Type Required Description
currency String No Currency, e.g. USDT
withdrawId String No Withdrawal ID
type String No Withdraw type
0: blockchain withdraw
1: internal transfers
txId String No Hash record of the withdrawal
state String No Status of withdrawal
0: waiting manual review
2: failed
3: success
4: canceled
6: kyt
7: processing
before String No Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1656633600000
after String No Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1654041600000
limit String No Number of results per request.
The maximum is 100; The default is 20

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"currency": "USDT",
"chain": "TRC20",
"address": "THmWeEJKyb976L76MvrTjeYMyNgiS9aKTu",
"txId": "f7c47f3911a2f27f3b647c5ef4c09c9e7d3f69ab123456789abcdef0123456789",
"type": "0",
"amount": "40.011111",
"fee": "0.1",
"feeCurrency": "USDT",
"state": "0",
"clientId": null,
"ts": "1695262311039",
"tag": null,
"memo": null,
"withdrawId": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6"
},
{
"currency": "USDT",
"chain": "TRC20",
"address": "THmWeEJKyb976L76MvrTjeYMyNgiS9aKTu",
"txId": "g8d58f4022b3f38f4c758d6ef5d10d0f8e4f70bc234567890bcdef1234567890",
"type": "0",
"amount": "9999.899",
"fee": "0.1",
"feeCurrency": "USDT",
"state": "4",
"clientId": null,
"ts": "1695262311039",
"tag": null,
"memo": null,
"withdrawId": "b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7"
}
]
}

Response Parameters

Parameter Type Description
currency String Withdraw currency
chain String Chain name, e.g. ERC20, TRC20
address String Receiving address
type String Withdraw type
0: blockchain withdraw
1: internal transfers
txId String Hash record of the withdrawal
amount String Withdrawal amount
fee String Withdrawal fee amount
feeCurrency String Withdrawal fee currency, e.g. USDT
state String Status of withdrawal
0: waiting manual review
2: failed
3: success
4: canceled
6: kyt
7: processing
clientId String Client-supplied ID
ts String Time the withdrawal request was submitted, Unix timestamp format in milliseconds, e.g. 1655251200000
tag String Some currencies require a tag for withdrawals. This is not returned if not required.
memo String Some currencies require this parameter for withdrawals. This is not returned if not required.
withdrawId String Withdrawal ID

GET Deposit History

Retrieve the deposit records according to the currency, status, and time range in reverse chronological order.

HTTP Request

GET /api/v1/asset/deposit-history

Request Example:

GET /api/v1/asset/deposit-history

Request Parameters

Parameter Type Required Description
currency String No Currency, e.g. USDT
depositId String No Deposit ID
txId String No Hash record of the deposit
state String No Status of deposit
0: pending
1: done
2: failed
3: kyt
before String No Pagination of data to return records newer than the requested ts, Unix timestamp format in milliseconds, e.g. 1656633600000
after String No Pagination of data to return records earlier than the requested ts, Unix timestamp format in milliseconds, e.g. 1654041600000
limit String No Number of results per request.
The maximum is 100; The default is 20

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"currency": "USDT",
"chain": "TRC20",
"address": "EXAMPLE_WALLET_ADDRESS",
"txId": "h9e69f5133c4f49f5d869d7ef6e11e0f9f5f81cd345678901cdef2345678901",
"type": "0",
"amount": "9",
"state": "1",
"ts": "1597026383085",
"confirm": "12",
"depositId": "c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8"
},
{
"currency": "USDT",
"chain": "TRC20",
"address": "EXAMPLE_WALLET_ADDRESS",
"txId": "i0f70f6244d5f50f6e970e8ef7f22f1f0f6f92de456789012def3456789012",
"type": "0",
"amount": "9",
"state": "1",
"ts": "1597026383085",
"confirm": "12",
"depositId": "d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9"
}
]
}

Response Parameters

Parameter Type Description
currency String Currency
chain String Chain name, e.g. ERC20, TRC20
address String Deposit address
type String Deposit type
0: blockchain deposit
1: internal transfers
txId String Hash record of the deposit
amount String Deposit amount
state String Status of deposit
0: pending
1: done
2: failed
3: kyt
confirm String Confirmations
ts String Time the deposit request was submitted, Unix timestamp format in milliseconds, e.g. 1656633600000
depositId String Deposit ID

Trading

REST API

Place Order

HTTP Request

POST /api/v1/spot/trade/order

Request Example:

POST /api/v1/spot/trade/order
body
{
"instType": "SPOT",
"instId":"BTC-USDT",
"side":"sell",
"orderType": "limit",
"price":"23212.2",
"size":"2"
}

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
side String Yes Order side, buy sell
orderType String Yes Order type
market: market order
limit: limit order
post_only: Post-only order
fok: Fill-or-kill order
ioc: Immediate-or-cancel order
price String Yes Order price. Not applicable to market
targetCurrency ENUM No Whether the target currency uses the quote or base currency. base_currency quote_currency
Only applicable to Market Orders
size String Yes Quantity to buy or sell
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
brokerId String No Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.

Response Example:

{
"code": "0",
"msg": "",
"data": [
{
"orderId": "28150801",
"clientOrderId": "test1597321",
"msg": "",
"code": "0"
}
]
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

Place Multiple Orders

HTTP Request

POST /api/v1/spot/trade/batch-orders

Request Example:

POST /api/v1/spot/trade/batch-orders
body
[
{
"instType": "SPOT",
"instId": "ETH-USDT",
"side": "buy",
"orderType": "limit",
"price": "1601.1",
"size": "1",
"clientOrderId": "eeeeee11223112"
},
{
"instType": "SPOT",
"instId": "ETH-USDT",
"side": "buy",
"orderType": "limit",
"price": "1602.1",
"size": "2",
"clientOrderId": "eeeeee1122321"
}
]

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
side String Yes Order side, buy sell
orderType String Yes Order type
market: market order
limit: limit order
post_only: Post-only order
fok: Fill-or-kill order
ioc: Immediate-or-cancel order
price String Yes Order price. Not applicable to market
size String Yes Quantity to buy or sell
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
targetCurrency ENUM No Whether the target currency uses the quote or base currency. base_currency quote_currency
Only applicable to Market Orders
brokerId String No Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"orderId": "22617453",
"clientOrderId": "eeeeee11223112"
},
{
"orderId": "22617454",
"clientOrderId": "eeeeee1122321"
}
]
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

Place Algo Order

HTTP Request

POST /api/v1/spot/trade/order-algo

Request Example:

POST /api/v1/spot/trade/order-algo
body
{
"instType": "SPOT",
"instId": "ETH-USDT",
"side": "sell",
"size": "1",
"clientOrderId":"",
"orderPrice": "-1",
"orderType": "trigger",
"triggerPrice": "3000",
"triggerPriceType": "last",
"brokerId": ""
}

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
side String Yes Order side, buy sell
size String Yes Quantity
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
orderType String Yes Algo type, trigger
orderPrice String No Order Price
If the price is -1, the order will be executed at the market price.
brokerId String No Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
triggerPrice String Yes Trigger price
triggerPriceType String No Trigger price type
last: last price
targetCurrency ENUM No Whether the target currency uses the quote or base currency. base_currency quote_currency
Only applicable to Market Orders

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"algoId": "1012",
"clientOrderId": null,
"code": "0",
"msg": null
}
}

Response Parameters

Parameter Type Description
algoId String Algo order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

Cancel Order

HTTP Request

POST /api/v1/spot/trade/cancel-order

Request Example:

POST /api/v1/spot/trade/cancel-order
body
{
"instType": "SPOT",
"orderId": "23209016"
}

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
orderId String Yes Order ID
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"orderId": "1012",
"clientOrderId": null,
"code": "0",
"msg": null
}
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

Cancel Multiple Orders

HTTP Request

POST /api/v1/spot/trade/cancel-batch-orders

Request Example:

POST /api/v1/spot/trade/cancel-batch-orders
body
[
{
"instType": "SPOT",
"instId": "ETH-USDT",
"orderId": "22619976",
"clientOrderId": ""
},
{
"instType": "SPOT",
"instId": "ETH-USDT",
"orderId": "22619977",
"clientOrderId": ""
}
]

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
orderId String Yes Order ID
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"orderId": "22619976",
"clientOrderId": "eeeeee112231121"
},
{
"orderId": "22619977",
"clientOrderId": "eeeeee11223211"
},
{
"orderId": "22619977111",
"clientOrderId": null,
"msg": "Cancel failed as the order has been filled, triggered, canceled or does not exist.",
"code": "1000"
}
]
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

Cancel Algo Order

HTTP Request

POST /api/v1/spot/trade/cancel-algo

Request Example:

POST /api/v1/spot/trade/cancel-algo
body
{
"instType": "SPOT",
"instId": "ETH-USDT",
"algoId": "22619976",
"clientOrderId": ""
}

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
algoId String No Algo order ID
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.

Response Example:

{
"code": "0",
"msg": "success",
"data":
{
"algoId": "1009",
"clientOrderId": null,
"code": "500",
"msg": "Cancel failed as the order has been filled, triggered, canceled or does not exist."
}
}

Response Parameters

Parameter Type Description
algoId String Algo order ID
clientOrderId String Client Order ID as assigned by the client
code String The code of the event execution result, 0 means success.
msg String Rejection or success message of event execution.

GET Active Orders

Retrieve all incomplete orders under the current account.

HTTP Request

GET /api/v1/spot/trade/orders-pending

Request Example:

GET /api/v1/spot/trade/orders-pending?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
state String No State
live
partially_filled
after String No Pagination of data to return records earlier than the requested orderId
before String No Pagination of data to return records newer than the requested orderId
limit String No Number of results per request. The maximum is 100; The default is 20

The before and after parameters cannot be used simultaneously.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"orderId": "29531103",
"clientOrderId": "",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "buy",
"orderType": "limit",
"price": "1514.150000000000000000",
"size": "1.000000000000000000",
"reduceOnly": null,
"leverage": null,
"state": "live",
"filledSize": "0.000000000000000000",
"filled_amount": "0.000000000000000000",
"averagePrice": "0.000000000000000000",
"fee": "0.000000000000000000",
"pnl": "0.000000000000000000",
"createTime": "1697031292762",
"updateTime": "1697031292788",
"orderCategory": "normal",
"tpTriggerPrice": "1688.000000000000000000",
"slTriggerPrice": "1299.000000000000000000",
"slOrderPrice": null,
"tpOrderPrice": null,
"algoClientOrderId": "aaa",
"algoId": "11756185",
"brokerId": ""
},
{
"orderId": "29530845",
"clientOrderId": "",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "buy",
"orderType": "limit",
"price": "1554.150000000000000000",
"size": "2.000000000000000000",
"reduceOnly": null,
"leverage": null,
"state": "live",
"filledSize": "0.000000000000000000",
"filled_amount": "0.000000000000000000",
"averagePrice": "0.000000000000000000",
"fee": "0.000000000000000000",
"pnl": "0.000000000000000000",
"createTime": "1697031251410",
"updateTime": "1697031251430",
"orderCategory": "normal",
"tpTriggerPrice": null,
"slTriggerPrice": null,
"slOrderPrice": null,
"tpOrderPrice": null,
"algoClientOrderId": "",
"algoId": "",
"brokerId": ""
}
]
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
instId String Instrument ID
marginMode String Margin mode
positionSide String Position side
side String Order side
orderType String Order type
price String Price
size String Quantity to buy or sell
reduceOnly String Whether orders can only reduce in position size
leverage String Leverage
state String State
filledSize String Accumulated fill quantity
averagePrice String Average filled price. If none is filled, it will return “”.
fee String Fee and rebate
pnl String Profit and loss, Applicable to orders which have a trade and aim to close position
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
updateTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
orderCategory String Order category
normal
full_liquidation
partial_liquidation
adl
tp
sl
tpTriggerPrice String Take-profit trigger price
tpOrderPrice String Take-profit order price.
If the price is -1, take-profit will be executed at the market price.
slTriggerPrice String Stop-loss trigger price
slOrderPrice String Stop-loss order price.
If the price is -1, stop-loss will be executed at the market price.
algoClientOrderId String There will be a value when algo order attaching clientOrderId is triggered, or it will be “”.
algoId String Algo ID. There will be a value when algo order is triggered, or it will be “”.
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
feeCurrency String Fee currency
For maker sell orders of Spot and Margin, this represents the quote currency. For all other cases, it represents the currency in which fees are charged.

GET Order Detail

Retrieve order detail.

HTTP Request

GET /api/v1/spot/trade/order-detail

Request Example:

GET /api/v1/spot/trade/order-detail?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
orderId String Conditional Order ID. Either orderId or clientOrderId is required, if both are passed, orderId will be used
clientOrderId String Conditional Client Order ID as assigned by the client

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"orderId": "29531103",
"clientOrderId": "",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "buy",
"orderType": "limit",
"price": "1514.150000000000000000",
"size": "1.000000000000000000",
"reduceOnly": null,
"leverage": null,
"state": "live",
"filledSize": "0.000000000000000000",
"filled_amount": "0.000000000000000000",
"averagePrice": "0.000000000000000000",
"fee": "0.000000000000000000",
"pnl": "0.000000000000000000",
"createTime": "1697031292762",
"updateTime": "1697031292788",
"orderCategory": "normal",
"tpTriggerPrice": "1688.000000000000000000",
"slTriggerPrice": "1299.000000000000000000",
"slOrderPrice": null,
"tpOrderPrice": null,
"algoClientOrderId": "aaa",
"algoId": "11756185",
"brokerId": ""
}
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
instId String Instrument ID
marginMode String Margin mode
positionSide String Position side
side String Order side
orderType String Order type
price String Price
size String Quantity to buy or sell
reduceOnly String Whether orders can only reduce in position size
leverage String Leverage
state String State
filledSize String Accumulated fill quantity
averagePrice String Average filled price. If none is filled, it will return “”.
fee String Fee and rebate
pnl String Profit and loss, Applicable to orders which have a trade and aim to close position
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
updateTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
orderCategory String Order category
normal
full_liquidation
partial_liquidation
adl
tp
sl
tpTriggerPrice String Take-profit trigger price
tpOrderPrice String Take-profit order price.
If the price is -1, take-profit will be executed at the market price.
slTriggerPrice String Stop-loss trigger price
slOrderPrice String Stop-loss order price.
If the price is -1, stop-loss will be executed at the market price.
algoClientOrderId String There will be a value when algo order attaching clientOrderId is triggered, or it will be “”.
algoId String Algo ID. There will be a value when algo order is triggered, or it will be “”.
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
feeCurrency String Fee currency
For maker sell orders of Spot and Margin, this represents the quote currency. For all other cases, it represents the currency in which fees are charged.

GET Active Algo Orders

Retrieve a list of untriggered algo orders under the current account.

HTTP Request

GET /api/v1/spot/trade/orders-algo-pending

Request Example:

GET /api/v1/spot/trade/orders-algo-pending?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
algoId String No Algo order ID
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
after String No Pagination of data to return records earlier than the requested algoId
before String No Pagination of data to return records newer than the requested algoId
limit String No Number of results per request. The maximum is 100; The default is 20
orderType String Yes Algo type, trigger

The before and after parameters cannot be used simultaneously.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"algoId": "2101",
"clientOrderId": "BBBBqqqq",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "sell",
"orderType": "trigger",
"size": "1",
"leverage": null,
"state": "canceled",
"triggerPrice": "1661.100000000000000000",
"triggerPriceType": "last",
"brokerId": "",
"attachAlgoOrders": null
}
]
}

Response Parameters

Parameter Type Description
algoId String Algo order ID
clientOrderId String Client Order ID as assigned by the client
instId String Instrument ID
marginMode String Margin mode
positionSide String Position side, long short net
side String Order side
orderType String Algo type, trigger
size String Quantity to buy or sell
reduceOnly String Whether the order can only reduce the position size. Valid options: true or false. The default value is false.
leverage String Leverage
state String State, live effective canceled order_failed
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
triggerPrice String Trigger price
triggerPriceType String Trigger price type
last: last price
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
attachAlgoOrders Array of object Attached SL/TP orders info
> tpTriggerPrice String Take-profit trigger price
> tpOrderPrice String Take-profit order price
If the price is -1, take-profit will be executed at the market price.
> tpTriggerPriceType String Trigger price type
last: last price
> slTriggerPrice String Stop-loss trigger price
> slOrderPrice String Stop-loss order price
If the price is -1, stop-loss will be executed at the market price.
> slTriggerPriceType String Stop-loss order trigger price type
last: last price

GET Order History

Get completed order history.

HTTP Request

GET /api/v1/spot/trade/orders-history

Request Example:

GET /api/v1/spot/trade/orders-history?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
state String No State
canceled
filled
partially_canceled (partially_canceled is the final state, if it is a closing order, pnl has value)
after String No Pagination of data to return records earlier than the requested orderId
before String No Pagination of data to return records newer than the requested orderId
begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
limit String No Number of results per request. The maximum is 100; The default is 20

The before and after parameters cannot be used simultaneously.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"orderId": "29419717",
"clientOrderId": "aabbc",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "buy",
"orderType": "limit",
"price": "1523.000000000000000000",
"size": "1.000000000000000000",
"reduceOnly": null,
"leverage": null,
"state": "canceled",
"filledSize": "0.000000000000000000",
"pnl": "0.000000000000000000",
"averagePrice": "0.000000000000000000",
"fee": "0.000000000000000000",
"createTime": "1697010303781",
"updateTime": "1697014607770",
"orderCategory": "normal",
"tpTriggerPrice": null,
"tpOrderPrice": null,
"slTriggerPrice": null,
"slOrderPrice": null,
"cancelSource": "user_canceled",
"cancelSourceReason": "Order canceled by user",
"algoClientOrderId": "aaa",
"algoId": "11756185",
"brokerId": ""
},
{
"orderId": "29419496",
"clientOrderId": "",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "buy",
"orderType": "limit",
"price": "1523.000000000000000000",
"size": "1.000000000000000000",
"reduceOnly": null,
"leverage": null,
"state": "canceled",
"filledSize": "0.000000000000000000",
"pnl": "0.000000000000000000",
"averagePrice": "0.000000000000000000",
"fee": "0.000000000000000000",
"createTime": "1697010193531",
"updateTime": "1697010227577",
"orderCategory": "normal",
"tpTriggerPrice": "1666.000000000000000000",
"tpOrderPrice": null,
"slTriggerPrice": "1100.000000000000000000",
"slOrderPrice": null,
"cancelSource": "user_canceled",
"cancelSourceReason": "Order canceled by user",
"algoClientOrderId": "",
"algoId": "",
"brokerId": ""
}
]
}

Response Parameters

Parameter Type Description
orderId String Order ID
clientOrderId String Client Order ID as assigned by the client
instId String Instrument ID
marginMode String Margin mode
positionSide String Position side
side String Order side
orderType String Order type
price String Price
size String Quantity to buy or sell
reduceOnly String Whether orders can only reduce in position size
leverage String Leverage
state String State
filledSize String Accumulated fill quantity
pnl String Profit and loss, Applicable to orders which have a trade and aim to close position
averagePrice String Average filled price. If none is filled, it will return “”.
fee String Fee and rebate
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
updateTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
orderCategory String Order category
normal
full_liquidation
partial_liquidation
adl
tp
sl
tpTriggerPrice String Take-profit trigger price
tpOrderPrice String Take-profit order price. If the price is -1, take-profit will be executed at the market price.
slTriggerPrice String Stop-loss trigger price
slOrderPrice String Stop-loss order price. If the price is -1, stop-loss will be executed at the market price.
cancelSource String Type of the cancellation source
cancelSourceReason String Reason for the cancellation
algoClientOrderId String There will be a value when algo order attaching clientOrderId is triggered, or it will be “”.
algoId String Algo ID. There will be a value when algo order is triggered, or it will be “”.
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
feeCurrency String Fee currency
For maker sell orders of Spot and Margin, this represents the quote currency. For all other cases, it represents the currency in which fees are charged.

GET Algo Order History

Retrieve a list of all Algo orders under the current account.

HTTP Request

GET /api/v1/spot/trade/orders-algo-history

Request Example:

GET /api/v1/spot/trade/orders-algo-history?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
algoId String No Algo order ID
clientOrderId String No Client Order ID as assigned by the client
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 32 characters.
state String No State, effective canceled order_failed
after String No Pagination of data to return records earlier than the requested algoId
before String No Pagination of data to return records newer than the requested algoId
limit String No Number of results per request. The maximum is 100; The default is 20
orderType String Yes Algo type, trigger

The before and after parameters cannot be used simultaneously.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"algoId": "2101",
"clientOrderId": "BBBBqqqq",
"instId": "ETH-USDT",
"marginMode": null,
"positionSide": null,
"side": "sell",
"orderType": "trigger",
"size": "1",
"actualSize": "1",
"leverage": null,
"state": "canceled",
"triggerPrice": "1661.100000000000000000",
"triggerPriceType": "last",
"brokerId": "",
"attachAlgoOrders": [
{
"tpTriggerPrice": "1666.000000000000000000",
"tpOrderPrice": "-1",
"tpTriggerPriceType": "last",
"slTriggerPrice": "1222.000000000000000000",
"slOrderPrice": "-1",
"slTriggerPriceType": "last"
}
]
}
]
}

Response Parameters

Parameter Type Description
algoId String Algo order ID
clientOrderId String Client Order ID as assigned by the client
instId String Instrument ID
marginMode String Margin mode
positionSide String Position side, long short net
side String Order side
reduceOnly String Whether the order can only reduce the position size. Valid options: true or false. The default value is false.
orderType String Algo type, trigger
size String Quantity to buy or sell
leverage String Leverage
state String State, live effective canceled order_failed
actualSize String Actual order quantity
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
triggerPrice String Trigger price
triggerPriceType String Trigger price type
last: last price
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
attachAlgoOrders Array of object Attached SL/TP orders info
> tpTriggerPrice String Take-profit trigger price
> tpOrderPrice String Take-profit order price
If the price is -1, take-profit will be executed at the market price.
> tpTriggerPriceType String Trigger price type
last: last price
> slTriggerPrice String Stop-loss trigger price
> slOrderPrice String Stop-loss order price
If the price is -1, stop-loss will be executed at the market price.
> slTriggerPriceType String Stop-loss order trigger price type
last: last price

GET Trade History

Retrieve recently-filled transaction details.

HTTP Request

GET /api/v1/spot/trade/fills-history

Request Example:

GET /api/v1/spot/trade/fills-history?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String No Instrument ID, e.g. BTC-USDT
orderId String No Order ID
after String No Pagination of data to return records earlier than the requested tradeId
before String No Pagination of data to return records newer than the requested tradeId
begin String No Filter with a begin timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
end String No Filter with an end timestamp. Unix timestamp format in milliseconds, e.g. 1597026383085
limit String No Number of results per request. The maximum is 100; The default is 20

The before and after parameters cannot be used simultaneously.

Response Example:

{
"code": "0",
"msg": "success",
"data": [
{
"instId": "ETH-USDT",
"tradeId": "7772187",
"orderId": "28697026",
"fillPrice": "1587.800000000000000000",
"fillSize": "2.000000000000000000",
"fillPnl": "0.000000000000000000",
"side": "buy",
"fee": "0.190536000000000000",
"ts": "1696853354238",
"brokerId": "",
"feeCurrency": "base_currency"
},
{
"instId": "ETH-USDT",
"tradeId": "7772186",
"orderId": "28697025",
"fillPrice": "1587.800000000000000000",
"fillSize": "1.000000000000000000",
"fillPnl": "0.000000000000000000",
"side": "buy",
"fee": "0.095268000000000000",
"ts": "1696853354224",
"brokerId": "",
"feeCurrency": "base_currency"
}
]
}

Response Parameters

Parameter Type Description
instId String Instrument ID
tradeId String Trade ID
orderId String Order ID
fillPrice String Filled price
fillSize String Filled quantity
fillPnl String Last filled profit and loss, applicable to orders which have a trade and aim to close position
side String Order side
fee String Fee
ts String Data generation time, Unix timestamp format in milliseconds, e.g. 1597026383085
brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
feeCurrency String Fee currency
For maker sell orders of Spot and Margin, this represents the quote currency. For all other cases, it represents the currency in which fees are charged.

GET Trade Order Price Range

Query price limit range.

HTTP Request

GET /api/v1/spot/trade/order/price-range

Request Example:

GET /api/v1/spot/trade/order/price-range?instType=SPOT

Request Parameters

Parameter Type Required Description
instType String Yes Instrument type
SPOT: Spot
instId String Yes Instrument ID, e.g. BTC-USDT
side String Yes Order side, buy sell

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"maxPrice": "1587.800000000000000000",
"minPrice": "1187.000000000000000000"
}
}

Response Parameters

Parameter Type Description
maxPrice String Maximum Price
minPrice String Minimum Price

WebSocket

WS Order Channel

This channel uses private WebSocket and authentication is required.

Retrieve order information. Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.

Request Example: Single

{
"op":"subscribe",
"args":[
{
"channel":"orders",
"instId":"ETH-USDT"
}
]
}

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"orders"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, orders
> instId String No Instrument ID

Response Example: Single

{
"event": "subscribe",
"arg": {
"channel": "orders",
"instId": "ETH-USDT"
}
}

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "orders"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"orders\", \"instId\" : \"ETH-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example:

{
"action":"snapshot",
"arg":{
"channel":"orders"
},
"data":[
{
"instType":"SPOT",
"instId":"BTC-USDT",
"orderId":"28334314",
"clientOrderId":"",
"price":"28000.000000000000000000",
"size":"10",
"orderType":"limit",
"side":"sell",
"filledSize":"0",
"filledAmount":"0.000000000000000000",
"averagePrice":"0.000000000000000000",
"state":"live",
"tpTriggerPrice":"27000.000000000000000000",
"tpTriggerPriceType":"last",
"tpOrderPrice":"-1",
"slTriggerPrice":null,
"slTriggerPriceType":null,
"slOrderPrice":null,
"fee":"0.000000000000000000",
"pnl":"0.000000000000000000",
"cancelSource":"",
"orderCategory":"pre_tp_sl",
"createTime":"1696760245931",
"updateTime":"1696760245973",
"brokerId":"",
"targetCurrency":"base_currency",
"feeCurrency":""
}
]
}

Push Data Parameters

Parameter Type Description
action String Push data action, incremental data or full snapshot.
snapshot: full
update: incremental
arg Object Successfully subscribed channel
> channel String Channel name
data Array Subscribed data
> instId String Instrument ID, e.g. BTC-USDT
> instType String Instrument type
> orderId String Order ID
> clientOrderId String Client Order ID as assigned by the client
> price String Price
> size String Quantity to buy or sell
> orderType String Order type
> side String Order side
> filledSize String Accumulated fill quantity
> filledAmount String Filled amount
> averagePrice String Average filled price. If none is filled, it will return “”.
> state String State
> tpTriggerPrice String Take-profit trigger price
> tpTriggerPriceType String Trigger price type of take-profit and stop-loss. last
> tpOrderPrice String Take-profit order price. If the price is -1, take-profit will be executed at the market price.
> slTriggerPrice String Stop-loss trigger price
> slOrderPrice String Stop-loss order price. If the price is -1, stop-loss will be executed at the market price.
> fee String Fee and rebate
> pnl String Profit and loss, Applicable to orders which have a trade and aim to close position
> cancelSource String Type of the cancellation source
> orderCategory String Order category
normal
full_liquidation
partial_liquidation
adl
tp
sl
> createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
> updateTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
> brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
> targetCurrency String Order quantity unit setting for size
base_currency: Base currency, quote_currency: Quote currency
Only applicable to SPOT Market Orders
Default is quote_currency for buy, base_currency for sell
> feeCurrency String Fee currency
For maker sell orders of Spot and Margin, this represents the quote currency. For all other cases, it represents the currency in which fees are charged.

WS Algo Orders Channel

This channel uses private WebSocket and authentication is required.

Retrieve algo orders (includes trigger order, TP/SL order). Data will not be pushed when first subscribed. Data will only be pushed when there are order updates.

Request Example: Single

{
"op":"subscribe",
"args":[
{
"channel":"orders-algo",
"instId":"ETH-USDT"
}
]
}

Request Example:

{
"op":"subscribe",
"args":[
{
"channel":"orders-algo"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, orders-algo
> instId String No Instrument ID

Response Example: Single

{
"event": "subscribe",
"arg": {
"channel": "orders-algo",
"instId": "ETH-USDT"
}
}

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "orders-algo"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"orders-algo\", \"instId\" : \"ETH-USDT\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
> instId String Instrument ID
code String Error code
msg String Error message

Push Data Example:

{
"action": "snapshot",
"arg": {
"channel": "orders-algo"
},
"data": [
{
"instType": "SPOT",
"instId": "BTC-USDT",
"tpslId": "11779982",
"algoId": "11779982",
"clientOrderId": "",
"size": "100",
"orderType": "trigger",
"side": "buy",
"state": "live",
"tpTriggerPrice": "73000.000000000000000000",
"tpOrderPrice": "-1",
"slTriggerPrice": null,
"slOrderPrice": null,
"triggerPrice": null,
"triggerPriceType": "last",
"orderPrice": null,
"actualSize": null,
"actualSide": null,
"cancelType": "not_canceled",
"createTime": "1731056529341",
"updateTime": "1731056529341",
"brokerId": ""
},
{
"instType": "SPOT",
"instId": "BTC-USDT",
"tpslId": "11779984",
"algoId": "11779984",
"clientOrderId": "",
"size": "100",
"orderType": "trigger",
"side": "buy",
"state": "live",
"tpTriggerPrice": null,
"tpOrderPrice": null,
"slTriggerPrice": null,
"slOrderPrice": null,
"triggerPrice": "73000.000000000000000000",
"triggerPriceType": "last",
"orderPrice": "-1",
"actualSize": null,
"actualSide": null,
"cancelType": "not_canceled",
"createTime": "1731057086771",
"updateTime": "1731057086771",
"brokerId": "",
"attachAlgoOrders": null
}
]
}

Push Data Parameters

Parameter Type Description
action String Push data action, incremental data or full snapshot.
snapshot: full
update: incremental
arg Object Successfully subscribed channel
> channel String Channel name
data Array Subscribed data
> instId String Instrument ID, e.g. BTC-USDT
> instType String Instrument type
> algoId String Algo ID
> clientOrderId String Client Order ID as assigned by the client
> size String Quantity to buy or sell
> orderType String Order type
conditional: One-way stop order
trigger: Trigger order
> side String Order side
buy
sell
> positionSide String Position side
> marginMode String Margin mode
> leverage String Leverage
> state String State
live: to be effective
effective: effective
canceled: canceled
order_failed: order failed
> tpTriggerPrice String Take-profit trigger price
> tpOrderPrice String Take-profit order price. If the price is -1, take-profit will be executed at the market price.
> slTriggerPrice String Stop-loss trigger price
> slOrderPrice String Stop-loss order price. If the price is -1, stop-loss will be executed at the market price.
> triggerPrice String Trigger price
> triggerPriceType String Trigger price type.
last: last price
index: index price
mark: mark price
> orderPrice String Order price for the trigger order
> actualSize String Actual order quantity
> actualSide String Actual order side
sl: stop loss
tp: take profit
Only applicable to conditional order
> reduceOnly String Whether orders can only reduce in position size
> cancelType String Type of the cancellation source.
not_canceled
user_canceled
system_canceled
> createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
> updateTime String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
> tag String Order tag
> brokerId String Broker ID provided by BloFin.
A combination of case-sensitive alphanumerics, all numbers, or all letters of up to 16 characters.
> attachAlgoOrds String Attached TP/SL orders info
>> tpTriggerPrice String Take-profit trigger price
If you fill in this parameter, you should fill in the take-profit order price as well.
>> tpTriggerPriceType String Take-profit trigger price type
last: last price
index: index price
mark: mark price
>> tpOrderPrice String Take-profit order price
If you fill in this parameter, you should fill in the take-profit trigger price as well.
If the price is -1, take-profit will be executed at the market price.
>> slTriggerPrice String Stop-loss trigger price
If you fill in this parameter, you should fill in the stop-loss order price as well.
>> slTriggerPriceType String Stop-loss trigger price type
last: last price
index: index price
mark: mark price
>> slOrderPrice String Stop-loss order price
If you fill in this parameter, you should fill in the stop-loss trigger price.
If the price is -1, stop-loss will be executed at the market price.

WS Spot Account Channel

This channel uses private WebSocket and authentication is required.

Retrieve account information. Data will be pushed when triggered by events such as placing order, canceling order, transaction execution, etc. It will also be pushed in regular interval according to subscription granularity.

Request Example: Single

{
"op":"subscribe",
"args":[
{
"channel":"spot-account"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, spot-account

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "spot-account"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"spot-account\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
code String Error code
msg String Error message

Push Data Example:

{
"arg": {
"channel": "spot-account"
},
"data": {
"ts": "1597026383085",
"totalEquity": "41624.32",
"isolatedEquity": "3624.32",
"details": [
{
"currency": "USDT",
"equity": "1",
"balance": "1",
"ts": "1617279471503",
"isolatedEquity": "0",
"equityUsd": "45078.3790756226851775",
"availableEquity": "1",
"available": "0",
"frozen": "0",
"orderFrozen": "0",
"unrealizedPnl": "0",
"isolatedUnrealizedPnl": "0"
}
]
}
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
data Object Subscribed data
> ts String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
> totalEquity String The total amount of equity in USD
> isolatedEquity String Isolated margin equity in USD
> details Array Detailed asset information in all currencies
>> currency String Currency
>> equity String Equity of the currency
>> balance String Cash balance
>> ts String Update time of currency balance information, Unix timestamp format in milliseconds, e.g. 1597026383085
>> isolatedEquity String Isolated margin equity of the currency
>> available String Available balance of the currency
>> availableEquity String Available equity of the currency
>> frozen String Frozen balance of the currency
>> orderFrozen String Margin frozen for open orders
>> equityUsd String Equity in USD of the currency
>> isolatedUnrealizedPnl String Isolated unrealized profit and loss of the currency
>> coinUsdPrice String Price index USD of currency
>> spotAvailable String Spot balance of the currency
>> liability String Liabilities of currency, Applicable to Multi-currency margin
>> borrowFrozen String Potential borrowing IMR of currency in USD. Only applicable to Multi-currency margin. It is “” for other margin modes.
>> marginRatio String Cross maintenance margin requirement at the currency level. Applicable to Multi-currency margin and when there is cross position

WS Trading Account Channel

This channel uses private WebSocket and authentication is required.

Retrieve account information. Data will be pushed when triggered by events such as placing order, canceling order, transaction execution, etc. It will also be pushed in regular interval according to subscription granularity.

Request Example: Single

{
"op":"subscribe",
"args":[
{
"channel":"account"
}
]
}

Request Parameters

Parameter Type Required Description
op String Yes Operation, subscribe unsubscribe
args Array Yes List of subscribed channels
> channel String Yes Channel name, account

Response Example:

{
"event": "subscribe",
"arg": {
"channel": "account"
}
}

Failure Response Example:

{
"event": "error",
"code": "60012",
"msg": "Invalid request: {\"op\": \"subscribe\", \"args\":[{ \"channel\" : \"account\"}]}"
}

Response Parameters

Parameter Type Description
event String Event, subscribe unsubscribe error
arg Object Subscribed channel
> channel String Channel name
code String Error code
msg String Error message

Push Data Example:

{
"arg": {
"channel": "account"
},
"data": {
"ts": "1597026383085",
"totalEquity": "41624.32",
"isolatedEquity": "3624.32",
"details": [
{
"currency": "USDT",
"equity": "1",
"balance": "1",
"ts": "1617279471503",
"isolatedEquity": "0",
"equityUsd": "45078.3790756226851775",
"availableEquity": "1",
"available": "0",
"frozen": "0",
"orderFrozen": "0",
"unrealizedPnl": "0",
"isolatedUnrealizedPnl": "0"
}
]
}
}

Push Data Parameters

Parameter Type Description
arg Object Successfully subscribed channel
> channel String Channel name
data Object Subscribed data
> ts String Update time, Unix timestamp format in milliseconds, e.g. 1597026383085
> totalEquity String The total amount of equity in USD
> isolatedEquity String Isolated margin equity in USD
> details Array Detailed asset information in all currencies
>> currency String Currency
>> equity String Equity of the currency
>> balance String Cash balance
>> ts String Update time of currency balance information, Unix timestamp format in milliseconds, e.g. 1597026383085
>> isolatedEquity String Isolated margin equity of the currency
>> available String Available balance of the currency
>> availableEquity String Available equity of the currency
>> frozen String Frozen balance of the currency
>> orderFrozen String Margin frozen for open orders
>> equityUsd String Equity in USD of the currency
>> isolatedUnrealizedPnl String Isolated unrealized profit and loss of the currency
>> coinUsdPrice String Price index USD of currency
>> spotAvailable String Spot balance of the currency
>> liability String Liabilities of currency, Applicable to Multi-currency margin
>> borrowFrozen String Potential borrowing IMR of currency in USD. Only applicable to Multi-currency margin. It is “” for other margin modes.
>> marginRatio String Cross maintenance margin requirement at the currency level. Applicable to Multi-currency margin and when there is cross position

Complete Trading Example

This section demonstrates a complete trading workflow that combines REST API calls with WebSocket updates. The example shows how to:

  1. Query the order book to get current price
  2. Place a limit buy order 10% below market price
  3. Receive order confirmation via WebSocket
  4. Cancel the order and clean up resources

Python Implementation

import asyncio
import base64
import hmac
import hashlib
import json
import requests
import time
import websockets

async def sign_websocket_login(secret: str, api_key: str, passphrase: str) -> tuple[str, str, str]:
"""Generate WebSocket login signature."""
timestamp = str(int(time.time() * 1000))
nonce = timestamp

# Fixed components for WebSocket auth
method = "GET"
path = "/users/self/verify"
body = ""

# Create signature string
msg = f"{path}{method}{timestamp}{nonce}{body}"
hex_signature = hmac.new(
secret.encode(),
msg.encode(),
hashlib.sha256
).hexdigest().encode()

return base64.b64encode(hex_signature).decode(), timestamp, nonce

async def trading_example():
"""Complete trading workflow example."""
try:
# Example credentials (replace with your own)
api_key = "YOUR_API_KEY"
secret = "YOUR_SECRET"
passphrase = "YOUR_PASSPHRASE"

# 1. Get order book price
response = requests.get(
"https://openapi.blofin.com/api/v1/spot/market/books",
params={"instId": "BTC-USDT", "size": "1"}
)
response.raise_for_status()
best_ask = float(response.json()["data"][0]["asks"][0][0]) # Note: data[0] for first order book entry
limit_price = round(best_ask * 0.9, 1) # 10% below market, rounded to 0.1
print(f"Best ask: {best_ask}, Limit price: {limit_price}")

# 2. Connect to WebSocket and authenticate
ws = await websockets.connect("wss://openapi.blofin.com/ws/spot/private")
sign, timestamp, nonce = await sign_websocket_login(secret, api_key, passphrase)

# Login
await ws.send(json.dumps({
"op": "login",
"args": [{
"apiKey": api_key,
"passphrase": passphrase,
"timestamp": timestamp,
"sign": sign,
"nonce": nonce
}]
}))

await asyncio.sleep(1)
# Subscribe to orders channel
await ws.send(json.dumps({
"op": "subscribe",
"args": [{"channel": "orders", "instId": "BTC-USDT"}]
}))

# 3. Place limit buy order
order_request = {
"instType": "SPOT",
"instId": "BTC-USDT",
"side": "buy",
"orderType": "limit",
"price": str(limit_price),
"size": "0.1",
}
# order_request["brokerId"] = "your broker id" #if needed
# Generate signature for REST API
timestamp = str(int(time.time() * 1000))
nonce = timestamp # Use timestamp as nonce for consistency
path = "/api/v1/spot/trade/order"
method = "POST"
msg = f"{path}{method}{timestamp}{nonce}{json.dumps(order_request)}"
hex_signature = hmac.new(
secret.encode('utf-8'),
msg.encode('utf-8'),
hashlib.sha256
).hexdigest().encode('utf-8')
signature = base64.b64encode(hex_signature).decode()

# Prepare headers with broker ID
headers = {
"ACCESS-KEY": api_key,
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-NONCE": nonce,
"ACCESS-PASSPHRASE": passphrase,
"Content-Type": "application/json"
}

# Place order
response = requests.post(
"https://openapi.blofin.com/api/v1/spot/trade/order",
headers=headers,
json=order_request
)
response.raise_for_status()
order_response = response.json()

# Verify response format and success
if not isinstance(order_response, dict):
raise Exception(f"Invalid order response format: {order_response}")

if "code" in order_response and order_response["code"] != "0":
raise Exception(f"Order API error: {order_response}")

if "data" not in order_response:
raise Exception(f"No data in order response: {order_response}")

order_id = order_response["data"][0]["orderId"]
print(f"Order placed: {order_id}")

# 4. Wait for order confirmation
async def listen_for_confirmation():
while True:
data = json.loads(await ws.recv())
if data.get("action") == "update":
for order in data.get("data", []):
if order.get("orderId") == order_id:
return order

try:
order_update = await asyncio.wait_for(
listen_for_confirmation(),
timeout=10
)
print(f"Order confirmed: {order_update}")
except asyncio.TimeoutError:
print("Timeout waiting for order confirmation")
raise

# 5. Cancel order
# Generate new signature for cancel request
timestamp = str(int(time.time() * 1000))
nonce = timestamp
path = "/api/v1/spot/trade/cancel-order"
method = "POST"
cancel_request = {"orderId": order_id}
msg = f"{path}{method}{timestamp}{nonce}{json.dumps(cancel_request)}"
hex_signature = hmac.new(
secret.encode('utf-8'),
msg.encode('utf-8'),
hashlib.sha256
).hexdigest().encode('utf-8')
signature = base64.b64encode(hex_signature).decode()

# Update headers with new signature
headers.update({
"ACCESS-SIGN": signature,
"ACCESS-TIMESTAMP": timestamp,
"ACCESS-NONCE": nonce
})

response = requests.post(
"https://openapi.blofin.com/api/v1/spot/trade/cancel-order",
headers=headers,
json=cancel_request
)
response.raise_for_status()
print("Order canceled")

# Clean up WebSocket connection
await ws.close()

except Exception as e:
print(f"Error: {str(e)}")
if isinstance(e, requests.exceptions.RequestException):
print(f"Request error details: {e.response.text if e.response else 'No response'}")
if 'ws' in locals():
await ws.close()
raise # Re-raise the exception after cleanup

if __name__ == "__main__":
asyncio.run(trading_example())

The example above demonstrates a complete trading workflow:

  1. Market Data Retrieval
    1. Fetches current order book for BTC-USDT
    2. Extracts best ask price from first level
    3. Calculates limit price 10% below market
  2. WebSocket Integration
    1. Establishes authenticated WebSocket connection
    2. Subscribes to order updates channel
    3. Handles connection cleanup properly
  3. Order Management
    1. Places limit buy order with proper parameters
    2. Uses current API parameter names (marginMode, orderType, price, size)
    3. Includes required broker ID in headers and request body
  4. Real-time Updates
    1. Waits for order confirmation via WebSocket
    2. Implements timeout handling for confirmation
    3. Processes order status updates in real-time
  5. Error Handling
    1. Validates API responses thoroughly
    2. Implements proper exception handling
    3. Ensures WebSocket cleanup on errors

Note: Replace the example credentials with your own API key, secret, and passphrase. The broker ID shown is specific to test credentials and may not be required for your API key.

User

REST API

GET API Key Info

Get the information of the api key. Use the api key pending to be checked to call the endpoint.

HTTP Request

GET /api/v1/user/query-apikey

Request Example:

GET /api/v1/user/query-apikey

Response Example:

{
"code": "0",
"msg": "success",
"data": {
"uid": "YOUR_USER_ID",
"apiName": "read_test",
"apiKey": "YOUR_API_KEY",
"readOnly": 0,
"ips": [
"YOUR_IP_ADDRESS_1",
"YOUR_IP_ADDRESS_2"
],
"type": 1,
"expireTime": "1597026383085",
"createTime": "1597026383085",
"referralCode": "blofin",
"parentUid": "YOUR_PARENT_USER_ID"
}
}

Response Parameters

Parameter Type Description
referralCode String Referral code
uid String UID
apiName String API key name
apiKey String API key
readOnly Integer 0: Read and Write. 1: Read only
type Integer 1: Transaction, 2: Connect to third-party
expireTime String Expiration time, Unix timestamp format in milliseconds, e.g. 1597026383085
createTime String Creation time, Unix timestamp format in milliseconds, e.g. 1597026383085
ips Array IP bound
parentUid String If use sub account api key, it shows main account uid; if use main account api key, it shows “0”

Errors

Here is the REST API Error Code.

Error Code HTTP Status Code Error Message
400 200 Bad Request
401 200 Invalid signature.
500 200 Internal Server Error
404 200 not found
405 200 Method Not Allowed
406 200 Not Acceptable
429 429 Too Many Requests
1 200 All operations failed
2 200 Batch operation partially succeeded.
152001 200 Parameter {} cannot be empty.
152002 200 Parameter {} error.
152003 200 Either parameter {} or {} is required.
152004 200 JSON syntax error, Please check if the parameter should be an array or an object.
152005 200 Parameter error: wrong or empty
152006 200 Batch orders can be placed for up to 20 at once.
152007 200 Batch orders can only be placed with the same instId and marginMode.
152008 200 Only the same field is allowed for bulk cancellation of orders, orderId is preferred.
152009 200 {} must be a combination of numbers, letters, or underscores, and the maximum length of characters is 32.
152011 200 Transaction API Key does not support brokerId
152012 200 BrokerId is required
152013 200 Unmatched brokerId, please check your API key’s bound broker
152014 200 Instrument ID does not exist
152015 200 Number of instId values exceeds the maximum limit of 20
152401 200 Access key does not exist, Please go to the API Management page and check if it exists and is in an active state.
152402 200 Access key has expired, Please go to the API Management page and check if it exists and is in an active state.
152404 200 This operation is not supported, Please check the requestPath or API key permissions.
152405 200 Timestamp in header or signature has expired, need to be within 60s
152406 200 Your IP is not included in your API key’s IP whitelist
152407 200 Repeated nonce, Reusing within 60 seconds is not allowed.
152408 200 Passphrase error
152409 200 Signature verification failed, Please refer to Signature Verification Failed
152410 200 The value of ACCESS-TIMESTAMP needs to be a millisecond timestamp, e.g: 1704038400000.
150003 200 clientId already exist
150004 200 Insufficient balance. please adjust the amount and try again.
542 200 Exceeded the maximum order size limit
102002 200 Duplicate customized order ID
102005 200 Position had been closed
102014 200 Limit order exceeds maximum order size limit
102015 200 Market order exceeds maximum order size limit
102022 200 Failed to place order. You don’t have any positions of this contract. Turn off Reduce-only to continue.
102037 200 TP trigger price should be higher than the latest trading price
102038 200 SL trigger price should be lower than the latest trading price
102039 200 TP trigger price should be lower than the latest trading price
102040 200 SL trigger price should be higher than the latest trading price
102047 200 Stop loss trigger price should be higher than the order price
102048 200 stop loss trigger price must be higher than the best bid price
102049 200 Take profit trigger price should be lower than the order price
102050 200 stop loss trigger price must be lower than the best ask price
80001 200 Parameters error
80006 200 Affiliate do not exit. Please apply to be affiliate first.
102051 200 stop loss trigger price should be lower than the order price
102052 200 take profit trigger price should be higher than the order price
102053 200 take profit trigger price should be lower than the best bid price
102054 200 take profit trigger price should be higher than the best ask price
102055 200 stop loss trigger price should be lower than the best ask price
102064 200 Buy price is not within the price limit (Minimum: 310.40; Maximum: 1,629.40)
102065 200 Sell price is not within the price limit
102068 200 Cancel failed as the order has been filled, triggered, canceled or does not exist.
102089 200 Position mode mismatch
103003 200 Order failed. Insufficient USDT margin in account
103013 200 Internal error; unable to process your request. Please try again.
110006 200 You have pending cross orders. Please cancel them before adjusting your leverage.
110019 200 Setting failed. Cancel any open orders, and close positions first.
1000 200 The order has been canceled.