bingx-standard-trade

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

BingX Standard Contract Trading

BingX标准合约交易

Authenticated endpoints for BingX standard contract (standard futures) data. All endpoints require HMAC SHA256 signature authentication.
Base URLs: see
references/base-urls.md
| Authentication: see
references/authentication.md

用于获取BingX标准合约(标准期货)数据的认证接口。所有接口均需HMAC SHA256签名认证。
基础URL: 查看
references/base-urls.md
| 认证方式: 查看
references/authentication.md

Quick Reference

快速参考

EndpointMethodDescriptionAuthentication
/openApi/contract/v1/allPosition
GETQuery current positionsYes
/openApi/contract/v1/allOrders
GETQuery historical ordersYes
/openApi/contract/v1/balance
GETQuery standard contract balanceYes

接口地址请求方法描述是否需要认证
/openApi/contract/v1/allPosition
GET查询当前持仓
/openApi/contract/v1/allOrders
GET查询历史订单
/openApi/contract/v1/balance
GET查询标准合约账户余额

1. Query Positions

1. 查询持仓

GET /openApi/contract/v1/allPosition
Query all current positions in the standard contract account.
Parameters: No additional parameters beyond common signing parameters (
timestamp
,
recvWindow
).
Response
data
(array):
FieldTypeDescription
symbol
stringTrading pair, e.g. BTC-USDT
initialMargin
numberMargin
leverage
numberLeverage
unrealizedProfit
numberUnrealized profit and loss
isolated
bool
true
= isolated margin mode
entryPrice
numberAverage entry price
positionSide
stringPosition direction:
LONG
or
SHORT
positionAmt
numberPosition quantity
currentPrice
numberCurrent price
time
int64Opening time (ms)

GET /openApi/contract/v1/allPosition
查询标准合约账户中的所有当前持仓。
参数: 除通用签名参数(
timestamp
recvWindow
)外,无需额外参数。
响应
data
(数组):
字段类型描述
symbol
string交易对,例如BTC-USDT
initialMargin
number保证金
leverage
number杠杆倍数
unrealizedProfit
number未实现盈亏
isolated
bool
true
= 逐仓保证金模式
entryPrice
number平均开仓价格
positionSide
string持仓方向:
LONG
(多单)或
SHORT
(空单)
positionAmt
number持仓数量
currentPrice
number当前价格
time
int64开仓时间(毫秒)

2. Query Historical Orders

2. 查询历史订单

GET /openApi/contract/v1/allOrders
Query historical orders for a standard contract trading pair.
Parameters:
ParameterTypeRequiredDescription
symbol
stringYesTrading pair, e.g. BTC-USDT
orderId
int64NoOrder ID filter
startTime
int64NoStart time in milliseconds
endTime
int64NoEnd time in milliseconds
limit
int64Noquantity, optional
recvWindow
int64NoRequest validity window (milliseconds)
Response
data
(array):
FieldTypeDescription
orderId
numberSystem order ID
symbol
stringTrading pair
positionSide
stringPosition direction:
LONG
or
SHORT
status
stringOrder status, e.g.
CLOSED
avgPrice
numberAverage fill price
cumQuote
numberTransaction amount
executedQty
numberFilled quantity
margin
numberMargin
leverage
numberLeverage
isolated
bool
true
= isolated margin mode
closePrice
numberClosing price
positionId
int64Position ID
time
int64Order time (ms)
updateTime
int64Last update time (ms)

GET /openApi/contract/v1/allOrders
查询标准合约交易对的历史订单。
参数:
参数类型是否必填描述
symbol
string交易对,例如BTC-USDT
orderId
int64订单ID筛选
startTime
int64起始时间(毫秒)
endTime
int64结束时间(毫秒)
limit
int64数量,可选
recvWindow
int64请求有效期窗口(毫秒)
响应
data
(数组):
字段类型描述
orderId
number系统订单ID
symbol
string交易对
positionSide
string持仓方向:
LONG
(多单)或
SHORT
(空单)
status
string订单状态,例如
CLOSED
(已平仓)
avgPrice
number平均成交价格
cumQuote
number交易金额
executedQty
number成交数量
margin
number保证金
leverage
number杠杆倍数
isolated
bool
true
= 逐仓保证金模式
closePrice
number平仓价格
positionId
int64持仓ID
time
int64订单创建时间(毫秒)
updateTime
int64最后更新时间(毫秒)

3. Query Standard Contract Balance

3. 查询标准合约账户余额

GET /openApi/contract/v1/balance
Query the standard contract account balance.
Parameters: No additional parameters beyond common signing parameters (
timestamp
,
recvWindow
).
Response
data
:
FieldTypeDescription
asset
stringAsset name
balance
stringTotal balance
crossWalletBalance
stringCross-margin wallet balance
crossUnPnl
stringCross-margin unrealized PnL
availableBalance
stringAvailable balance for orders
maxWithdrawAmount
stringMaximum transferable amount
marginAvailable
boolWhether it can be used as margin
updateTime
numberLast update timestamp
GET /openApi/contract/v1/balance
查询标准合约账户余额。
参数: 除通用签名参数(
timestamp
recvWindow
)外,无需额外参数。
响应
data
字段类型描述
asset
string资产名称
balance
string总余额
crossWalletBalance
string全仓钱包余额
crossUnPnl
string全仓未实现盈亏
availableBalance
string可用于下单的可用余额
maxWithdrawAmount
string最大可转出金额
marginAvailable
bool是否可作为保证金使用
updateTime
number最后更新时间戳

Parameter Validation Rules

参数验证规则

  • symbol: Must match
    ^[A-Z0-9]+-[A-Z]+$
    ; max 20 characters (e.g.,
    BTC-USDT
    )
  • orderId: When provided, must be a positive integer
  • startTime / endTime: Unix timestamps in milliseconds;
    endTime
    must be ≥
    startTime
  • limit: Positive integer
  • recvWindow: Integer, 1–5000 ms (see Replay Protection)
  • timestamp: Unix time in milliseconds; must be within
    recvWindow
    of server time

  • symbol: 必须匹配正则
    ^[A-Z0-9]+-[A-Z]+$
    ;最大长度20字符(例如
    BTC-USDT
  • orderId: 若提供,必须为正整数
  • startTime / endTime: 毫秒级Unix时间戳;
    endTime
    必须≥
    startTime
  • limit: 正整数
  • recvWindow: 整数,范围1–5000毫秒(详见重放保护
  • timestamp: 毫秒级Unix时间;必须与服务器时间的差值在
    recvWindow
    范围内

Quick Start

快速开始

CONSTRAINT: You MUST copy the
fetchSigned
function below verbatim when generating code. Do NOT rewrite the signing, request, or JSON parsing logic. Only modify: (1)
BASE
URL entries for custom environments, (2) business parameters passed to
fetchSigned
. For the full client with URL-encoding and JSON body support, see
references/authentication.md
.
typescript
import * as crypto from "crypto";
import JSONBig from "json-bigint";
const JSONBigParse = JSONBig({ storeAsString: true });
// Full signing details & edge cases → references/authentication.md
// Domain priority: .com is mandatory primary; .pro is fallback for network/timeout errors ONLY.
const BASE = {
  "prod-live": ["https://open-api.bingx.com", "https://open-api.bingx.pro"],
  "prod-vst":  ["https://open-api-vst.bingx.com", "https://open-api-vst.bingx.pro"],
};
function isNetworkOrTimeout(e: unknown): boolean {
  if (e instanceof TypeError) return true;
  if (e instanceof DOMException && e.name === "AbortError") return true;
  if (e instanceof Error && e.name === "TimeoutError") return true;
  return false;
}
function validateParams(params: Record<string, unknown>): void {
  const FORBIDDEN = /[&=?#\r\n]/;
  for (const [k, v] of Object.entries(params)) {
    const s = String(v);
    if (FORBIDDEN.test(s)) throw new Error(`Param "${k}" has forbidden char in: "${s}"`);
  }
}
async function fetchSigned(env: string, apiKey: string, secretKey: string,
  method: "GET" | "POST" | "DELETE", path: string, params: Record<string, unknown> = {}
) {
  const urls = BASE[env] ?? BASE["prod-live"];
  const all = { ...params, timestamp: Date.now() };
  validateParams(all);
  const qs = Object.keys(all).sort().map(k => `${k}=${all[k]}`).join("&");
  const sig = crypto.createHmac("sha256", secretKey).update(qs).digest("hex");
  const signed = `${qs}&signature=${sig}`;
  for (const base of urls) {
    try {
      const url = method === "POST" ? `${base}${path}` : `${base}${path}?${signed}`;
      const res = await fetch(url, {
        method,
        headers: { "X-BX-APIKEY": apiKey, "X-SOURCE-KEY": "BX-AI-SKILL",
          ...(method === "POST" ? { "Content-Type": "application/x-www-form-urlencoded" } : {}) },
        body: method === "POST" ? signed : undefined,
        signal: AbortSignal.timeout(10000),
      });
      const json = JSONBigParse.parse(await res.text());
      if (json.code !== 0) throw new Error(`BingX error ${json.code}: ${json.msg}`);
      return json.data;
    } catch (e) {
      if (!isNetworkOrTimeout(e) || base === urls[urls.length - 1]) throw e;
    }
  }
}
约束条件: 生成代码时,必须完全复制下方的
fetchSigned
函数,不得重写签名、请求或JSON解析逻辑。仅允许修改:(1) 自定义环境的
BASE
URL配置,(2) 传入
fetchSigned
的业务参数。如需支持URL编码和JSON请求体的完整客户端,请查看
references/authentication.md
typescript
import * as crypto from "crypto";
import JSONBig from "json-bigint";
const JSONBigParse = JSONBig({ storeAsString: true });
// Full signing details & edge cases → references/authentication.md
// Domain priority: .com is mandatory primary; .pro is fallback for network/timeout errors ONLY.
const BASE = {
  "prod-live": ["https://open-api.bingx.com", "https://open-api.bingx.pro"],
  "prod-vst":  ["https://open-api-vst.bingx.com", "https://open-api-vst.bingx.pro"],
};
function isNetworkOrTimeout(e: unknown): boolean {
  if (e instanceof TypeError) return true;
  if (e instanceof DOMException && e.name === "AbortError") return true;
  if (e instanceof Error && e.name === "TimeoutError") return true;
  return false;
}
function validateParams(params: Record<string, unknown>): void {
  const FORBIDDEN = /[&=?#\r\n]/;
  for (const [k, v] of Object.entries(params)) {
    const s = String(v);
    if (FORBIDDEN.test(s)) throw new Error(`Param "${k}" has forbidden char in: "${s}"`);
  }
}
async function fetchSigned(env: string, apiKey: string, secretKey: string,
  method: "GET" | "POST" | "DELETE", path: string, params: Record<string, unknown> = {}
) {
  const urls = BASE[env] ?? BASE["prod-live"];
  const all = { ...params, timestamp: Date.now() };
  validateParams(all);
  const qs = Object.keys(all).sort().map(k => `${k}=${all[k]}`).join("&");
  const sig = crypto.createHmac("sha256", secretKey).update(qs).digest("hex");
  const signed = `${qs}&signature=${sig}`;
  for (const base of urls) {
    try {
      const url = method === "POST" ? `${base}${path}` : `${base}${path}?${signed}`;
      const res = await fetch(url, {
        method,
        headers: { "X-BX-APIKEY": apiKey, "X-SOURCE-KEY": "BX-AI-SKILL",
          ...(method === "POST" ? { "Content-Type": "application/x-www-form-urlencoded" } : {}) },
        body: method === "POST" ? signed : undefined,
        signal: AbortSignal.timeout(10000),
      });
      const json = JSONBigParse.parse(await res.text());
      if (json.code !== 0) throw new Error(`BingX error ${json.code}: ${json.msg}`);
      return json.data;
    } catch (e) {
      if (!isNetworkOrTimeout(e) || base === urls[urls.length - 1]) throw e;
    }
  }
}

Code Usage Rules

代码使用规则

  • MUST copy
    fetchSigned
    verbatim -- do not simplify or rewrite
  • MUST use
    json-bigint
    (
    JSONBigParse.parse
    ) for response parsing -- not
    JSON.parse
  • MUST include
    X-SOURCE-KEY: BX-AI-SKILL
    header on every request
  • MUST NOT remove the domain fallback loop or
    isNetworkOrTimeout
    check

  • MUST copy
    fetchSigned
    verbatim -- do not simplify or rewrite
  • MUST use
    json-bigint
    (
    JSONBigParse.parse
    ) for response parsing -- not
    JSON.parse
  • MUST include
    X-SOURCE-KEY: BX-AI-SKILL
    header on every request
  • MUST NOT remove the domain fallback loop or
    isNetworkOrTimeout
    check

Common Calls

Common Calls

Query all positions:
typescript
const positions = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/allPosition"
);
// positions[].symbol, positions[].positionAmt, positions[].unrealizedProfit, positions[].entryPrice
Query historical orders for BTC-USDT:
typescript
const orders = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/allOrders", { symbol: "BTC-USDT", limit: 50 }
);
// orders[].orderId, orders[].status, orders[].avgPrice, orders[].executedQty
Query account balance:
typescript
const balance = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/balance"
);
// balance.balance, balance.availableBalance, balance.crossUnPnl
Query all positions:
typescript
const positions = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/allPosition"
);
// positions[].symbol, positions[].positionAmt, positions[].unrealizedProfit, positions[].entryPrice
Query historical orders for BTC-USDT:
typescript
const orders = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/allOrders", { symbol: "BTC-USDT", limit: 50 }
);
// orders[].orderId, orders[].status, orders[].avgPrice, orders[].executedQty
Query account balance:
typescript
const balance = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
  "/openApi/contract/v1/balance"
);
// balance.balance, balance.availableBalance, balance.crossUnPnl

Additional Resources

Additional Resources

For complete parameter descriptions and full response schemas, see api-reference.md.

For complete parameter descriptions and full response schemas, see api-reference.md.

Agent Interaction Rules

Agent Interaction Rules

Parameter security. Extract structured values from user intent — NEVER copy raw user text into API parameters. Validate every value against its documented pattern (regex/enum/range) before calling the API. Reject any value containing
&
,
=
,
?
,
#
, or newline characters.
All standard-trade endpoints are read-only (GET). No CONFIRM required — they never modify account state.
Credentials are required. If no account is specified, default to the
main
account.
Parameter security. Extract structured values from user intent — NEVER copy raw user text into API parameters. Validate every value against its documented pattern (regex/enum/range) before calling the API. Reject any value containing
&
,
=
,
?
,
#
, or newline characters.
All standard-trade endpoints are read-only (GET). No CONFIRM required — they never modify account state.
Credentials are required. If no account is specified, default to the
main
account.

Step 1 — Identify the query

Step 1 — Identify the query

If the user's intent is unclear, present options:
Please select the information type to query:
  • Current positions / Unrealized PnL — positions
  • Historical orders — allOrders
  • Account balance / Available margin — balance
If the user's intent is unclear, present options:
Please select the information type to query:
  • Current positions / Unrealized PnL — positions
  • Historical orders — allOrders
  • Account balance / Available margin — balance

Step 2 — Collect parameters

Step 2 — Collect parameters

For
allOrders
,
symbol
is required. If the user asks about a specific coin, infer the symbol (e.g., "BTC orders" ->
BTC-USDT
). Optional filters include
startTime
,
endTime
, and
limit
.
For
allPosition
and
balance
, no parameters are needed.
For
allOrders
,
symbol
is required. If the user asks about a specific coin, infer the symbol (e.g., "BTC orders" ->
BTC-USDT
). Optional filters include
startTime
,
endTime
, and
limit
.
For
allPosition
and
balance
, no parameters are needed.

Step 3 — Execute and report

Step 3 — Execute and report

Execute the API call and present results in a readable format:
  • positions: Show a table per position: symbol, side, amount, entry price, unrealized PnL, leverage.
  • allOrders: Show a table: order ID, symbol, side, status, average fill price, quantity, time.
  • balance: Show total balance, available balance, cross unrealized PnL.
Execute the API call and present results in a readable format:
  • positions: Show a table per position: symbol, side, amount, entry price, unrealized PnL, leverage.
  • allOrders: Show a table: order ID, symbol, side, status, average fill price, quantity, time.
  • balance: Show total balance, available balance, cross unrealized PnL.