USD-M futures order management
Use USDMClient for Binance's USD-M futures markets. This walkthrough reads starting account state, follows private WebSocket updates, and uses REST to place and cancel a BTCUSDT perpetual order.
The order script makes one REST request per command. In a persistent application, keep the user data stream connected and track account and order state locally. Use REST reads to initialize state, recover missed updates or resolve uncertain outcomes, not after every order.
The examples use production USD-M Futures. The place command submits a real order.
Set up
Use Node.js 24 and install the binance npm package in a server-side project:
npm install binanceUse production Futures API credentials with permissions to read account state and trade.
For Futures Demo Trading, set demoTrading: true on the REST and WebSocket clients and use Demo credentials. Leave testnet false or omitted; the flags select different environments.
Create a private .env file and exclude it from version control. Keep API credentials in a secure server-side environment:
BINANCE_API_KEY=example_key # Illustrative; use your Futures key
BINANCE_API_SECRET=example_secret # Illustrative; use its secret
BINANCE_USDM_PRICE=60000 # USDT per BTC; choose for the current market
BINANCE_USDM_QUANTITY=0.002 # BTC; adjust for your available marginChoose a buy price below the current best ask. Use getExchangeInfo() to inspect the symbol's current price increment, quantity increment and minimum notional. The SDK accepts numeric price and quantity values for this method; the exchange validates the order.
Read account state
Save this as usdm-account.ts:
import { USDMClient } from 'binance';
async function main() {
const api_key = process.env.BINANCE_API_KEY;
const api_secret = process.env.BINANCE_API_SECRET;
if (!api_key || !api_secret) {
throw new Error('Set BINANCE_API_KEY and BINANCE_API_SECRET.');
}
const client = new USDMClient({ api_key, api_secret });
const account = await client.getAccountInformationV3();
console.log('Account:', {
canTrade: account.canTrade,
walletBalance: account.totalWalletBalance,
availableBalance: account.availableBalance,
});
console.log('Balances:', await client.getBalanceV3());
console.log(
'BTCUSDT positions:',
await client.getPositionsV3({ symbol: 'BTCUSDT' }),
);
const positionMode = await client.getCurrentPositionMode();
console.log(
'Position mode:',
positionMode.dualSidePosition ? 'Hedge' : 'One-way',
);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});node --env-file=.env usdm-account.tsThis prints the account's trading permission and margin balances, balance records, BTCUSDT positions and position mode. It uses the current V3 account methods and makes no account changes. The positions list may be empty if there is no open BTCUSDT position.
Follow account changes
Save the following as usdm-private-stream.ts and run it in another terminal with the same Futures credentials:
import { WebsocketClient } from 'binance';
async function main() {
const api_key = process.env.BINANCE_API_KEY;
const api_secret = process.env.BINANCE_API_SECRET;
if (!api_key || !api_secret) {
throw new Error(
'Set USD-M Futures credentials in BINANCE_API_KEY and BINANCE_API_SECRET.',
);
}
const ws = new WebsocketClient({
api_key,
api_secret,
beautify: false,
});
let stopped = false;
// Stop after 60 seconds, including listen-key and connection setup.
const timer = setTimeout(stop, 60_000);
function stop() {
if (stopped) return;
stopped = true;
clearTimeout(timer);
process.removeListener('SIGINT', stop);
process.removeListener('SIGTERM', stop);
ws.closeAll(true);
console.log('USD-M user data stream closed. This does not cancel orders.');
}
process.once('SIGINT', stop);
process.once('SIGTERM', stop);
// Install listeners before connecting. This stream passively receives changes;
// it does not submit orders or query state after each REST submission.
ws.on('message', (message) => {
if (stopped || Array.isArray(message)) return;
if (message.e === 'ORDER_TRADE_UPDATE') {
console.log('Order update:', {
symbol: message.o.s,
orderId: message.o.i,
executionType: message.o.x,
status: message.o.X,
lastExecutedQuantity: message.o.l,
cumulativeExecutedQuantity: message.o.z,
});
} else if (message.e === 'ACCOUNT_UPDATE') {
console.log('Balance and position updates:', message.a);
} else if (message.e === 'listenKeyExpired') {
console.error('User data listen key expired. Account updates may have a gap.');
}
});
ws.on('open', () => {
if (stopped) {
ws.closeAll(true);
return;
}
console.log('USD-M Futures user data connected. Waiting for account events.');
});
ws.on('exception', (error) => {
console.error('USD-M user data stream exception:', error);
});
// The SDK manages listen-key renewal and reconnecting.
ws.on('reconnecting', () => console.log('USD-M user data reconnecting.'));
ws.on('reconnected', () => {
if (stopped) {
ws.closeAll(true);
return;
}
console.log('USD-M user data reconnected.');
// If missed events leave state unresolved, use a targeted REST recovery query.
});
try {
// This opens a dedicated listen-key connection, not a topic subscription.
// Setup can return undefined after emitting an exception; awaiting it alone
// is not proof that the stream connected. Observe the open event above.
await ws.subscribeUsdFuturesUserDataStream();
} catch (error) {
console.error('Could not start the USD-M user data stream:', error);
process.exitCode = 1;
stop();
} finally {
// A stop can occur while listen-key/connection setup is pending.
if (stopped) ws.closeAll(true);
}
}
main().catch((error: unknown) => {
console.error(error);
process.exitCode = 1;
});node --env-file=.env usdm-private-stream.tsWait for the user data connection to open before placing an order. ORDER_TRADE_UPDATE reports order changes and fills; ACCOUNT_UPDATE reports balance and position changes. Apply these events to local state instead of repeatedly reading the account through REST. The demonstration prints events for 60 seconds and does not maintain a complete state store.
In a persistent application, subscribe before loading the initial account data, account for events received during that read, and recover missed state after a connection gap. See account state.
The position changes in ACCOUNT_UPDATE can trigger follow-up logic, such as placing or resizing SL/TP orders when a position opens or increases. Merge the reported positions into local state rather than treating each event as a full account snapshot. Compare position size by symbol and position side, then use a throttled debounce with a maximum wait so partial fills do not cause a burst of API calls or delay adjustments indefinitely.
The stream emits reconnecting when connection recovery starts and reconnected when the socket reopens. Use the latter to trigger REST reconciliation of missed account and order state before making dependent order adjustments; see stream recovery.
Place a post-only order
The order example assumes one-way mode, using positionSide: 'BOTH'. Check the account output before using it. The program does not change position mode, margin mode or leverage.
Save this as usdm-order.ts:
import { USDMClient } from 'binance';
// Subscribe to account WebSocket updates before submitting orders.
// Use the status command only when those updates leave an outcome unclear.
function requiredEnvVar(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name} in .env.`);
}
return value;
}
function getPositiveNumberEnvVar(name: string): number {
const value = Number(requiredEnvVar(name));
if (!Number.isFinite(value) || value <= 0) {
throw new Error(`${name} must be a positive number.`);
}
return value;
}
async function main() {
const action = process.argv[2];
if (!['place', 'status', 'cancel'].includes(action)) {
throw new Error('Usage: usdm-order.ts place|status|cancel');
}
const client = new USDMClient(
{
api_key: requiredEnvVar('BINANCE_API_KEY'),
api_secret: requiredEnvVar('BINANCE_API_SECRET'),
},
{ timeout: 10_000 },
);
const symbol = 'BTCUSDT';
if (action === 'place') {
// LIMIT + GTX is post-only. BOTH is for an account already in one-way mode.
const order = await client.submitNewOrder({
symbol,
side: 'BUY',
positionSide: 'BOTH',
type: 'LIMIT',
timeInForce: 'GTX',
price: getPositiveNumberEnvVar('BINANCE_USDM_PRICE'),
quantity: getPositiveNumberEnvVar('BINANCE_USDM_QUANTITY'),
});
console.log(
'Submission acknowledged. Save BINANCE_USDM_ORDER_ID:',
order.orderId,
);
return;
}
const orderId = getPositiveNumberEnvVar('BINANCE_USDM_ORDER_ID');
if (action === 'cancel') {
const order = await client.cancelOrder({ symbol, orderId });
console.log('Cancellation response:', {
orderId: order.orderId,
status: order.status,
executedQuantity: order.executedQty,
});
return;
}
const order = await client.getOrder({ symbol, orderId });
console.log({
orderId: order.orderId,
status: order.status,
executedQuantity: order.executedQty,
originalQuantity: order.origQty,
});
}
main().catch((error) => {
console.error(error);
console.error(
'Use account WebSocket updates to resolve the outcome. If still unknown, make a targeted REST query before another order action.',
);
process.exitCode = 1;
});node --env-file=.env usdm-order.ts placeFor futures, type: 'LIMIT' with timeInForce: 'GTX' is post-only. It will not take liquidity immediately; an accepted resting order can still fill before you cancel it. The response acknowledges submission, not a fill.
Save the returned exchange order ID in .env:
BINANCE_USDM_ORDER_ID=123456789 # Use the orderId printed by your submissionCancel remaining quantity
Follow matching ORDER_TRADE_UPDATE events for the saved order ID. If the order still has open quantity, request cancellation:
node --env-file=.env usdm-order.ts cancelThe cancellation response can include executed quantity from partial fills. Continue following user data events for the resulting order and position state. Cancelling an order does not undo fills or close a position.
Position mode and fills
In one-way mode, a buy can increase a long position or reduce an existing short. It can cross through zero into a long if its filled quantity exceeds the short. This example is not a reduce-only closing order.
Hedge mode uses positionSide: 'LONG' or 'SHORT' explicitly. Choose both side and positionSide for the intended position effect rather than copying the one-way parameters. For a one-way closing order, the API supports reduceOnly: 'true'; it cannot be sent in Hedge Mode. See the futures order parameters.
Recover an uncertain outcome
The example logs the actual error and does not retry automatically. A timeout or ambiguous server error does not prove that an order failed.
Check matching user data events first. If the outcome remains unclear, use getOrder() through the one-shot status command:
node --env-file=.env usdm-order.ts statusUse this for diagnosis or recovery, not after every order. If no ID is available, reconcile getAllOpenOrders(), getAllOrders(), getAccountTrades() and getPositionsV3() using the symbol, request time, side, price and quantity. Resolve the outcome before sending another order. An order missing from the open list may already have filled or been cancelled.