bingx-standard-trade
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseBingX Standard Contract Trading
BingX标准合约交易
Authenticated endpoints for BingX standard contract (standard futures) data. All endpoints require HMAC SHA256 signature authentication.
Base URLs: see | Authentication: see
references/base-urls.mdreferences/authentication.md用于获取BingX标准合约(标准期货)数据的认证接口。所有接口均需HMAC SHA256签名认证。
基础URL: 查看 | 认证方式: 查看
references/base-urls.mdreferences/authentication.mdQuick Reference
快速参考
| Endpoint | Method | Description | Authentication |
|---|---|---|---|
| GET | Query current positions | Yes |
| GET | Query historical orders | Yes |
| GET | Query standard contract balance | Yes |
| 接口地址 | 请求方法 | 描述 | 是否需要认证 |
|---|---|---|---|
| GET | 查询当前持仓 | 是 |
| GET | 查询历史订单 | 是 |
| GET | 查询标准合约账户余额 | 是 |
1. Query Positions
1. 查询持仓
GET /openApi/contract/v1/allPositionQuery all current positions in the standard contract account.
Parameters: No additional parameters beyond common signing parameters (, ).
timestamprecvWindowResponse (array):
data| Field | Type | Description |
|---|---|---|
| string | Trading pair, e.g. BTC-USDT |
| number | Margin |
| number | Leverage |
| number | Unrealized profit and loss |
| bool | |
| number | Average entry price |
| string | Position direction: |
| number | Position quantity |
| number | Current price |
| int64 | Opening time (ms) |
GET /openApi/contract/v1/allPosition查询标准合约账户中的所有当前持仓。
参数: 除通用签名参数(、)外,无需额外参数。
timestamprecvWindow响应(数组):
data| 字段 | 类型 | 描述 |
|---|---|---|
| string | 交易对,例如BTC-USDT |
| number | 保证金 |
| number | 杠杆倍数 |
| number | 未实现盈亏 |
| bool | |
| number | 平均开仓价格 |
| string | 持仓方向: |
| number | 持仓数量 |
| number | 当前价格 |
| int64 | 开仓时间(毫秒) |
2. Query Historical Orders
2. 查询历史订单
GET /openApi/contract/v1/allOrdersQuery historical orders for a standard contract trading pair.
Parameters:
| Parameter | Type | Required | Description |
|---|---|---|---|
| string | Yes | Trading pair, e.g. BTC-USDT |
| int64 | No | Order ID filter |
| int64 | No | Start time in milliseconds |
| int64 | No | End time in milliseconds |
| int64 | No | quantity, optional |
| int64 | No | Request validity window (milliseconds) |
Response (array):
data| Field | Type | Description |
|---|---|---|
| number | System order ID |
| string | Trading pair |
| string | Position direction: |
| string | Order status, e.g. |
| number | Average fill price |
| number | Transaction amount |
| number | Filled quantity |
| number | Margin |
| number | Leverage |
| bool | |
| number | Closing price |
| int64 | Position ID |
| int64 | Order time (ms) |
| int64 | Last update time (ms) |
GET /openApi/contract/v1/allOrders查询标准合约交易对的历史订单。
参数:
| 参数 | 类型 | 是否必填 | 描述 |
|---|---|---|---|
| string | 是 | 交易对,例如BTC-USDT |
| int64 | 否 | 订单ID筛选 |
| int64 | 否 | 起始时间(毫秒) |
| int64 | 否 | 结束时间(毫秒) |
| int64 | 否 | 数量,可选 |
| int64 | 否 | 请求有效期窗口(毫秒) |
响应(数组):
data| 字段 | 类型 | 描述 |
|---|---|---|
| number | 系统订单ID |
| string | 交易对 |
| string | 持仓方向: |
| string | 订单状态,例如 |
| number | 平均成交价格 |
| number | 交易金额 |
| number | 成交数量 |
| number | 保证金 |
| number | 杠杆倍数 |
| bool | |
| number | 平仓价格 |
| int64 | 持仓ID |
| int64 | 订单创建时间(毫秒) |
| int64 | 最后更新时间(毫秒) |
3. Query Standard Contract Balance
3. 查询标准合约账户余额
GET /openApi/contract/v1/balanceQuery the standard contract account balance.
Parameters: No additional parameters beyond common signing parameters (, ).
timestamprecvWindowResponse :
data| Field | Type | Description |
|---|---|---|
| string | Asset name |
| string | Total balance |
| string | Cross-margin wallet balance |
| string | Cross-margin unrealized PnL |
| string | Available balance for orders |
| string | Maximum transferable amount |
| bool | Whether it can be used as margin |
| number | Last update timestamp |
GET /openApi/contract/v1/balance查询标准合约账户余额。
参数: 除通用签名参数(、)外,无需额外参数。
timestamprecvWindow响应:
data| 字段 | 类型 | 描述 |
|---|---|---|
| string | 资产名称 |
| string | 总余额 |
| string | 全仓钱包余额 |
| string | 全仓未实现盈亏 |
| string | 可用于下单的可用余额 |
| string | 最大可转出金额 |
| bool | 是否可作为保证金使用 |
| number | 最后更新时间戳 |
Parameter Validation Rules
参数验证规则
- symbol: Must match ; max 20 characters (e.g.,
^[A-Z0-9]+-[A-Z]+$)BTC-USDT - orderId: When provided, must be a positive integer
- startTime / endTime: Unix timestamps in milliseconds; must be ≥
endTimestartTime - limit: Positive integer
- recvWindow: Integer, 1–5000 ms (see Replay Protection)
- timestamp: Unix time in milliseconds; must be within of server time
recvWindow
- symbol: 必须匹配正则;最大长度20字符(例如
^[A-Z0-9]+-[A-Z]+$)BTC-USDT - orderId: 若提供,必须为正整数
- startTime / endTime: 毫秒级Unix时间戳;必须≥
endTimestartTime - limit: 正整数
- recvWindow: 整数,范围1–5000毫秒(详见重放保护)
- timestamp: 毫秒级Unix时间;必须与服务器时间的差值在范围内
recvWindow
Quick Start
快速开始
CONSTRAINT: You MUST copy thefunction below verbatim when generating code. Do NOT rewrite the signing, request, or JSON parsing logic. Only modify: (1)fetchSignedURL entries for custom environments, (2) business parameters passed toBASE. For the full client with URL-encoding and JSON body support, seefetchSigned.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;
}
}
}约束条件: 生成代码时,必须完全复制下方的函数,不得重写签名、请求或JSON解析逻辑。仅允许修改:(1) 自定义环境的fetchSignedURL配置,(2) 传入BASE的业务参数。如需支持URL编码和JSON请求体的完整客户端,请查看fetchSigned。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 verbatim -- do not simplify or rewrite
fetchSigned - MUST use (
json-bigint) for response parsing -- notJSONBigParse.parseJSON.parse - MUST include header on every request
X-SOURCE-KEY: BX-AI-SKILL - MUST NOT remove the domain fallback loop or check
isNetworkOrTimeout
- MUST copy verbatim -- do not simplify or rewrite
fetchSigned - MUST use (
json-bigint) for response parsing -- notJSONBigParse.parseJSON.parse - MUST include header on every request
X-SOURCE-KEY: BX-AI-SKILL - MUST NOT remove the domain fallback loop or check
isNetworkOrTimeout
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[].entryPriceQuery 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[].executedQtyQuery account balance:
typescript
const balance = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
"/openApi/contract/v1/balance"
);
// balance.balance, balance.availableBalance, balance.crossUnPnlQuery all positions:
typescript
const positions = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
"/openApi/contract/v1/allPosition"
);
// positions[].symbol, positions[].positionAmt, positions[].unrealizedProfit, positions[].entryPriceQuery 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[].executedQtyQuery account balance:
typescript
const balance = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
"/openApi/contract/v1/balance"
);
// balance.balance, balance.availableBalance, balance.crossUnPnlAdditional 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 account.
mainParameter 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 account.
mainStep 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 , is required. If the user asks about a specific coin, infer the symbol (e.g., "BTC orders" -> ). Optional filters include , , and .
allOrderssymbolBTC-USDTstartTimeendTimelimitFor and , no parameters are needed.
allPositionbalanceFor , is required. If the user asks about a specific coin, infer the symbol (e.g., "BTC orders" -> ). Optional filters include , , and .
allOrderssymbolBTC-USDTstartTimeendTimelimitFor and , no parameters are needed.
allPositionbalanceStep 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.