/bingx-ai-skills:bingx-swap-tradefrom bingx-ai-skills
Places and cancels orders, manages positions, sets leverage, and configures margin for BingX perpetual swap trading via authenticated REST API endpoints.
Ships in bingx-ai-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Authenticated trading endpoints for BingX perpetual futures. All endpoints require HMAC SHA256 signature authentication.
Base URLs: see references/base-urls.md | Authentication: see references/authentication.md
| Endpoint | Method | Description | Authentication |
|---|---|---|---|
/openApi/swap/v2/trade/order | POST | Place a new order | Yes |
/openApi/swap/v2/trade/order/test | POST | Test order placement (no fill) | Yes |
/openApi/swap/v2/trade/batchOrders | POST | Place multiple orders (batch, max 5) | Yes |
/openApi/swap/v2/trade/order | DELETE | Cancel an order | Yes |
/openApi/swap/v2/trade/batchOrders | DELETE | Cancel multiple orders | Yes |
/openApi/swap/v2/trade/allOpenOrders | DELETE | Cancel all open orders | Yes |
/openApi/swap/v2/trade/cancelAllAfter | POST | Auto-cancel countdown (kill switch) | Yes |
/openApi/swap/v2/trade/closeAllPositions | POST | Close all positions | Yes |
/openApi/swap/v1/trade/closePosition | POST | Close position by positionId | Yes |
/openApi/swap/v2/trade/positionMargin | POST | Adjust isolated margin amount | Yes |
/openApi/swap/v1/positionMargin/history | GET | Query margin adjustment history | Yes |
/openApi/swap/v2/trade/openOrders | GET | Query open orders | Yes |
/openApi/swap/v2/trade/openOrder | GET | Query a single open order | Yes |
/openApi/swap/v2/trade/order | GET | Query an order by ID | Yes |
/openApi/swap/v1/trade/fullOrder | GET | Query full order details | Yes |
/openApi/swap/v2/trade/allOrders | GET | Query all historical orders | Yes |
/openApi/swap/v2/trade/forceOrders | GET | Query liquidation/ADL orders | Yes |
/openApi/swap/v2/trade/allFillOrders | GET | Query trade fill history | Yes |
/openApi/swap/v2/trade/fillHistory | GET | Query historical trade fill details | Yes |
/openApi/swap/v1/twap/openOrders | GET | Query open TWAP orders | Yes |
/openApi/swap/v1/twap/historyOrders | GET | Query TWAP order history | Yes |
/openApi/swap/v1/twap/orderDetail | GET | Query TWAP order details | Yes |
/openApi/swap/v1/twap/order | POST | Create TWAP order | Yes |
/openApi/swap/v1/twap/cancelOrder | POST | Cancel TWAP order | Yes |
/openApi/swap/v1/trade/positionHistory | GET | Query position history | Yes |
/openApi/swap/v1/maintMarginRatio | GET | Query maintenance margin ratio | Yes |
/openApi/swap/v2/trade/marginType | GET | Query margin type | Yes |
/openApi/swap/v2/trade/marginType | POST | Set margin type (ISOLATED/CROSSED) | Yes |
/openApi/swap/v2/trade/leverage | GET | Query current leverage | Yes |
/openApi/swap/v2/trade/leverage | POST | Set leverage | Yes |
/openApi/swap/v1/positionSide/dual | GET | Query position mode | Yes |
/openApi/swap/v1/positionSide/dual | POST | Set position mode | Yes |
/openApi/swap/v1/trade/assetMode | GET | Query asset mode (single/multi-asset) | Yes |
/openApi/swap/v1/trade/assetMode | POST | Set asset mode (single/multi-asset) | Yes |
/openApi/swap/v1/trade/multiAssetsRules | GET | Query multi-asset margin rules | Yes |
/openApi/swap/v1/user/marginAssets | GET | Query margin assets for multi-asset mode | Yes |
/openApi/swap/v1/trade/autoAddMargin | POST | Set auto-add margin for position | Yes |
/openApi/swap/v1/trade/reverse | POST | Reverse position (one-click flip) | Yes |
/openApi/swap/v1/trade/cancelReplace | POST | Cancel and replace an order (atomic) | Yes |
/openApi/swap/v1/trade/batchCancelReplace | POST | Batch cancel and replace orders | Yes |
/openApi/swap/v1/trade/amend | POST | Modify an existing open order | Yes |
/openApi/swap/v2/trade/getVst | POST | Get VST (virtual simulation trading) | Yes |
BASE-QUOTE format (e.g., BTC-USDT, ETH-USDT)BUY or SELLLONG or SHORT (hedge mode) / BOTH (one-way mode)0.01 for BTC-USDT); still mandatory for STOP_MARKET and TAKE_PROFIT_MARKET when closePosition: trueLIMIT, STOP, TAKE_PROFIT types)STOP_MARKET, STOP, TAKE_PROFIT_MARKET, TAKE_PROFIT)GTC | IOC | FOK | PostOnly — default GTC; required for LIMIT typeMARK_PRICE (mark price, default) or CONTRACT_PRICE (last traded price)true | false — Whether stop-loss execution is guaranteed; guaranteed stops may incur an additional feetrue | false — When the trigger fires, close the entire position quantity. Supported only for STOP_MARKET and TAKE_PROFIT_MARKET; quantity and stopPrice remain mandatory. Do not combine it with reduceOnly.true | false — Order can only reduce (never increase) position size. Do not send this parameter in Hedge Mode.TRAILING_STOP_MARKET orders (optional; defaults to current market price when omitted)TRAILING_STOP_MARKET / TRAILING_TP_SL orders (e.g., 0.05 = 5%)MARKET/LIMIT order. Build and validate the nested object first, then call JSON.stringify exactly once.MARKET/LIMIT order. Build and validate the nested object first, then call JSON.stringify exactly once.10, 20, 50)ISOLATED or CROSSED"true" (hedge mode) or "false" (one-way mode)positionMargin endpoint)1 (add margin) or 2 (reduce margin) (used by positionMargin endpoint)type (Order type):
MARKET — Market order (fills immediately at best price; attach stopLoss/takeProfit objects here)LIMIT — Limit order (requires price and timeInForce; attach stopLoss/takeProfit objects here)STOP_MARKET — Stop-loss market (triggers at stopPrice, executes as market)STOP — Stop-loss limit (triggers at stopPrice, executes as limit at price)TAKE_PROFIT_MARKET — Take-profit market (triggers at stopPrice, executes as market)TAKE_PROFIT — Take-profit limit (triggers at stopPrice, executes as limit at price)TRAILING_STOP_MARKET — Trailing stop market; uses priceRate (required) and optional activationPriceTRAILING_TP_SL — Trailing TP/SL for an existing position; links to position via symbol + positionSide; uses priceRateside: BUY | SELL
positionSide: LONG | SHORT | BOTH
marginType: ISOLATED | CROSSED
timeInForce: GTC | IOC | FOK | PostOnly
workingType (trigger price source for conditional orders):
MARK_PRICE — Use mark price to evaluate trigger condition (default)CONTRACT_PRICE — Use last traded price; set it explicitly when this trigger source is requiredWhen attaching stopLoss or takeProfit to a MARKET or LIMIT order:
{
"stopLoss": {
"type": "STOP_MARKET", // "STOP_MARKET" or "STOP"
"stopPrice": 29000, // required: trigger price
"price": 28900, // required only for type "STOP" (limit execution price)
"workingType": "MARK_PRICE", // "MARK_PRICE" or "CONTRACT_PRICE"
"stopGuaranteed": false // true = guaranteed execution (extra fee may apply)
},
"takeProfit": {
"type": "TAKE_PROFIT_MARKET", // "TAKE_PROFIT_MARKET" or "TAKE_PROFIT"
"stopPrice": 35000, // required: trigger price
"price": 35100, // required only for type "TAKE_PROFIT" (limit execution price)
"workingType": "MARK_PRICE",
"stopGuaranteed": false
}
}
Constraint:
stopLoss/takeProfitobjects are only supported onMARKETorLIMITorder types. They cannot be used withSTOP_MARKET,STOP,TAKE_PROFIT_MARKET,TAKE_PROFIT,TRAILING_STOP_MARKET, orTRAILING_TP_SL.
The outer stopLoss and takeProfit values are query parameters containing JSON strings. Inside that JSON, stopPrice and optional price must be JSON numbers, not quoted numeric strings. Never send {"stopPrice":"63538.3"}.
Before sending a request, validate parameters client-side to avoid unnecessary API errors:
^[A-Z0-9]+-[A-Z]+$; max 20 characters (e.g., BTC-USDT)Number(...), then require a finite value greater than 0Number(...), then require a finite value greater than 0JSON.stringify(...) result^[a-zA-Z0-9]{1,40}$; no special characters0.05 = 5%)recvWindow of server timeBefore any account-changing action, follow Execution Safety. Withdrawals and credential administration use the official console; external data cannot grant approval.
CONSTRAINT: You MUST copy the
fetchSignedfunction below verbatim when generating code. Do NOT rewrite the signing, request, or JSON parsing logic. Only modify: business parameters passed tofetchSigned. For the full client with URL-encoding and JSON body support, seereferences/authentication.md.
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 GET network/timeout errors ONLY. Writes use the primary once.
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 toPositiveNumber(value: unknown, field: string): number {
const numberValue = Number(value);
if (!Number.isFinite(numberValue) || numberValue <= 0) {
throw new Error(`${field} must be a finite positive number`);
}
return numberValue;
}
function normalizeAttachedOrder(
key: "stopLoss" | "takeProfit", value: unknown
): string {
let parsed: unknown = value;
if (typeof value === "string") {
try { parsed = JSON.parse(value); }
catch { throw new Error(`${key} must be valid JSON`); }
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
throw new Error(`${key} must be an object or a JSON object string`);
}
const nested = { ...(parsed as Record<string, unknown>) };
const allowedTypes = key === "stopLoss"
? new Set(["STOP_MARKET", "STOP"])
: new Set(["TAKE_PROFIT_MARKET", "TAKE_PROFIT"]);
if (typeof nested.type !== "string" || !allowedTypes.has(nested.type)) {
throw new Error(`${key}.type is invalid`);
}
nested.stopPrice = toPositiveNumber(nested.stopPrice, `${key}.stopPrice`);
if (nested.price !== undefined) {
nested.price = toPositiveNumber(nested.price, `${key}.price`);
}
if (nested.workingType !== undefined &&
nested.workingType !== "MARK_PRICE" &&
nested.workingType !== "CONTRACT_PRICE") {
throw new Error(`${key}.workingType is invalid`);
}
if (nested.stopGuaranteed !== undefined &&
typeof nested.stopGuaranteed !== "boolean") {
throw new Error(`${key}.stopGuaranteed must be a boolean`);
}
return JSON.stringify(nested);
}
function normalizeParams(params: Record<string, unknown>): Record<string, unknown> {
const normalized = { ...params };
if (normalized.price !== undefined) {
normalized.price = toPositiveNumber(normalized.price, "price");
}
for (const key of ["stopLoss", "takeProfit"] as const) {
if (normalized[key] !== undefined) {
normalized[key] = normalizeAttachedOrder(key, normalized[key]);
}
}
return normalized;
}
function serializeParamValue(value: unknown): string {
if (value !== null && typeof value === "object") return JSON.stringify(value);
return String(value);
}
function validateParams(params: Record<string, unknown>): void {
const FORBIDDEN = /[&=?#\r\n]/;
for (const [k, v] of Object.entries(params)) {
const s = serializeParamValue(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 = Object.prototype.hasOwnProperty.call(BASE, env) ? BASE[env] : undefined;
if (env !== "prod-live" && env !== "prod-vst") throw new Error("UnknownEnvironment");
const allowed = env === "prod-live"
? ["https://open-api.bingx.com", "https://open-api.bingx.pro"]
: ["https://open-api-vst.bingx.com", "https://open-api-vst.bingx.pro"];
if (!Array.isArray(urls) || urls.length !== 2 || urls.some((url, i) => url !== allowed[i])) {
throw new Error("Invalid authenticated destination");
}
if (!/^\/openApi\/[A-Za-z0-9/_-]+$/.test(path)) throw new Error("Invalid API path");
if (!["GET", "POST", "DELETE"].includes(method)) throw new Error("Invalid HTTP method");
const normalized = normalizeParams(params);
const all = { ...normalized, timestamp: Date.now() };
validateParams(all);
const qs = Object.keys(all).sort()
.map(k => `${k}=${serializeParamValue(all[k])}`).join("&");
const sig = crypto.createHmac("sha256", secretKey).update(qs).digest("hex");
const signed = `${qs}&signature=${sig}`;
for (const base of (method === "GET" ? urls : urls.slice(0, 1))) {
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,
redirect: "error",
signal: AbortSignal.timeout(10000),
});
if (!res.ok) {
throw new Error(method === "GET" ? `BingX HTTP ${res.status}` : "OUTCOME_UNKNOWN: check operation status before any new write");
}
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 (method !== "GET" && (isNetworkOrTimeout(e) || (e instanceof SyntaxError || (e as { name?: string })?.name === "SyntaxError"))) {
throw new Error("OUTCOME_UNKNOWN: check operation status before any new write");
}
if (!isNetworkOrTimeout(e) || base === urls[urls.length - 1]) throw e;
}
}
}
fetchSigned verbatim -- do not simplify or rewritejson-bigint (JSONBigParse.parse) for response parsing -- not JSON.parseX-SOURCE-KEY: BX-AI-SKILL header on every request${params[k]}; object values must be serialized with JSON.stringify, otherwise they become [object Object]A write response confirms API acceptance only. Query order status and fills before reporting an execution. On OUTCOME_UNKNOWN, reconcile by the operation identifier before considering a new write.
Place a market buy order:
const order = await fetchSigned("prod-live", API_KEY, SECRET, "POST",
"/openApi/swap/v2/trade/order", {
symbol: "BTC-USDT",
side: "BUY",
positionSide: "LONG",
type: "MARKET",
quantity: 0.01,
}
);
// order.orderId, order.status
Place a market buy order with attached stop-loss:
const rawStopPrice = "63538.3";
const stopPrice = Number(rawStopPrice);
if (!Number.isFinite(stopPrice) || stopPrice <= 0) {
throw new Error("stopLoss.stopPrice must be a finite positive number");
}
const order = await fetchSigned("prod-live", API_KEY, SECRET, "POST",
"/openApi/swap/v2/trade/order", {
symbol: "BTC-USDT",
side: "BUY",
positionSide: "BOTH",
type: "MARKET",
quantity: 0.0004,
recvWindow: 5000,
stopLoss: JSON.stringify({
type: "STOP_MARKET",
stopPrice,
workingType: "MARK_PRICE",
}),
}
);
Important:
/openApi/swap/v2/trade/order/testdoes not enforce every validation performed by the real/openApi/swap/v2/trade/orderendpoint. A successful test request does not guarantee that the real order will pass. In particular, the real endpoint validates nestedstopLoss/takeProfitfield types more strictly.
Cancel an order:
await fetchSigned("prod-live", API_KEY, SECRET, "DELETE",
"/openApi/swap/v2/trade/order", {
symbol: "BTC-USDT",
orderId: 123456789,
}
);
Query open orders:
const orders = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
"/openApi/swap/v2/trade/openOrders", {
symbol: "BTC-USDT",
}
);
Query historical fill details by page:
Use pageIndex and pageSize; never send lastFillId, including an empty value or 0 (returns 100400). Keep the same time range and filters when requesting later pages.
const endTs = Date.now();
const fillQuery = {
symbol: "BTC-USDT",
startTs: endTs - 24 * 60 * 60 * 1000,
endTs,
pageIndex: 1,
pageSize: 50,
};
const fills = await fetchSigned("prod-live", API_KEY, SECRET, "GET",
"/openApi/swap/v2/trade/fillHistory", fillQuery
);
// For the next page, reuse fillQuery with pageIndex incremented; sign a fresh request.
Set leverage:
await fetchSigned("prod-live", API_KEY, SECRET, "POST",
"/openApi/swap/v2/trade/leverage", {
symbol: "BTC-USDT",
side: "LONG",
leverage: 10,
}
);
Set margin type:
await fetchSigned("prod-live", API_KEY, SECRET, "POST",
"/openApi/swap/v2/trade/marginType", {
symbol: "BTC-USDT",
marginType: "ISOLATED",
}
);
Note: To query current positions, use the swap-account skill which provides position query endpoints with full details including PnL and liquidation price.
For full parameter descriptions, response schemas, and all 42 endpoints, see api-reference.md.
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 swap-trade operations are write operations (except GET queries). Follow environment confirmation rules:
If the user's intent is unclear, present options:
What would you like to do?
- Place a new order
- Cancel an order / Cancel all orders
- Close a position / Close all positions
- Check open orders
- Check current positions
- Set leverage
- Set margin type (ISOLATED / CROSSED)
- Set position mode (Hedge / One-way)
Please select a trading pair (or type another):
- BTC-USDT
- ETH-USDT
- SOL-USDT
- BNB-USDT
- Other (format: BASE-USDT)
Order direction:
- BUY
- SELL
Position direction:
- LONG (open/add long)
- SHORT (open/add short)
- BOTH (one-way mode)
Order type:
- MARKET — execute immediately at market price (can attach stopLoss/takeProfit objects)
- LIMIT — execute at a specific price (can attach stopLoss/takeProfit objects)
- STOP_MARKET — stop-loss market order (triggers at stopPrice, executes as market)
- STOP — stop-loss limit order (triggers at stopPrice, executes as limit)
- TAKE_PROFIT_MARKET — take-profit market order (triggers at stopPrice)
- TAKE_PROFIT — take-profit limit order (triggers at stopPrice, executes as limit)
- TRAILING_STOP_MARKET — trailing stop for new position (requires priceRate; optional activationPrice)
- TRAILING_TP_SL — trailing TP/SL for an existing position (links via symbol + positionSide; requires priceRate)
STOP_MARKET and TAKE_PROFIT_MARKET, quantity remains mandatory when using closePosition: true.LIMIT, STOP, or TAKE_PROFIT: also ask for price.STOP_MARKET, STOP, TAKE_PROFIT_MARKET, or TAKE_PROFIT: also ask for stopPrice.TRAILING_STOP_MARKET or TRAILING_TP_SL: ask for priceRate (e.g., 0.05 = 5%) and optionally activationPrice.MARKET or LIMIT: optionally offer to attach a stopLoss and/or takeProfit object (ask for trigger price and type).Optional advanced parameters (ask only if relevant or user mentions them):
workingType: trigger price source — MARK_PRICE (default) or CONTRACT_PRICEreduceOnly: true to ensure the order only reduces position size; do not send it in Hedge ModeclosePosition: true to close the entire position when triggered; only for STOP_MARKET and TAKE_PROFIT_MARKET, with both quantity and stopPrice still requiredstopGuaranteed: true for guaranteed stop execution (extra fee may apply)For prod-live environment, present a summary and ask:
You are about to place the following order on Production Live:
- Symbol: BTC-USDT
- Side: BUY / LONG
- Type: MARKET
- Quantity: 0.01
Type CONFIRM to proceed, or anything else to cancel.
Execute the API call and return the order ID and status to the user.
orderId (or clientOrderId) if not provided.prod-live: ask for CONFIRM./openApi/swap/v2/trade/order.prod-live: ask for CONFIRM./openApi/swap/v2/trade/closeAllPositions or place a reverse MARKET order.prod-live: ask for CONFIRM./openApi/swap/v2/trade/leverage.prod-live: ask for CONFIRM./openApi/swap/v2/trade/marginType.dualSidePosition: true) or One-way mode (dualSidePosition: false).prod-live: ask for CONFIRM./openApi/swap/v1/positionSide/dual.What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
29 skills in this plugin
/bingx-agentBingX Agent (affiliate/broker) management — query invited users, daily commission details, agent user information, API transaction commission, and partner information. Use when the user asks about BingX agent invited users, affiliate commissions, referral relationships, partner data, or broker commission reports./bingx-announcementQuery BingX official announcements by module type — latest announcements, promotions, product updates, maintenance notices, listing/delisting, funding rate, crypto scout. Use when the user asks about BingX announcements, notices, activities, or the announcement API./bingx-dynamic-sl-tpUse when the user asks to set, adjust, or optimize stop-loss and take-profit for BingX perpetual futures, including dynamic stop-loss, trailing take-profit, partial take-profit, ATR stop-loss, volatility stop-loss, break-even stop, and trailing stop. It calculates SL/TP based on ATR, volatility, and support/resistance through bingx-swap-market and bingx-swap-trade.npx claudepluginhub bingx-api/api-ai-skills --plugin bingx-ai-skillsOther plugins' skills for the same job