Order management
Use RestClient to place, amend and cancel a BTC-USDT Spot order. The example uses the live global service, so running place can spend real funds. To use simulated funds, configure demo trading on every client with demo credentials before running the commands.
Before submitting
- Configure authenticated account access with read and trading permissions.
- Check
BTC-USDTinstrument metadata usinggetInstruments(). Choose price and size strings satisfying its increments, minimums and current exchange limits. This example usestdMode: 'cash', so it buys Spot without changing leverage or position mode. - Start the private stream with the same account, region and environment. Wait for authentication and a successful
orderssubscription acknowledgement before submitting. - Record a unique alphanumeric
clOrdIdof at most 32 characters before sending. Keep it for recovery even if the command never returns an exchange order ID.
Add your own values to .env:
OKX_CLIENT_ORDER_ID=spotExample20261111001
OKX_LIMIT_PRICE=60000
OKX_ORDER_SIZE=0.0001
OKX_NEW_PRICE=59000Replace the example prices and size with values that meet the current instrument rules. Choose a buy price below the current best bid. A post_only order that would immediately take liquidity is rejected or cancelled according to the exchange's rules; a resting order can still fill before you cancel it.
Place and observe
Save first-order.ts beside the credential helper, follow the compile instructions with first-order.ts as the entry file, then run the emitted file:
import { client } from './authenticated-client.js';
function requiredEnv(name: string): string {
const value = process.env[name];
if (!value) {
throw new Error(`Set ${name} before running this command.`);
}
return value;
}
function reportResults(results: { sCode: string; sMsg: string; ordId: string }[]) {
for (const result of results) {
console.log(result);
if (result.sCode !== '0') {
throw new Error(`Order request rejected: ${result.sCode} ${result.sMsg}`);
}
}
}
async function main() {
const command = process.argv[2];
const instId = 'BTC-USDT';
const clOrdId = requiredEnv('OKX_CLIENT_ORDER_ID');
switch (command) {
case 'place': {
// Save this ID before sending. Check the order status before retrying a timed-out request.
console.log('Submitting client order ID:', clOrdId);
reportResults(await client.submitOrder({
instId,
clOrdId,
tdMode: 'cash',
side: 'buy',
ordType: 'post_only',
px: requiredEnv('OKX_LIMIT_PRICE'),
sz: requiredEnv('OKX_ORDER_SIZE'),
}));
break;
}
case 'status': {
console.log(await client.getOrderDetails({ instId, clOrdId }));
break;
}
case 'amend': {
reportResults(await client.amendOrder({
instId,
clOrdId,
newPx: requiredEnv('OKX_NEW_PRICE'),
cxlOnFail: false,
}));
break;
}
case 'cancel': {
reportResults(await client.cancelOrder({ instId, clOrdId }));
break;
}
default: {
throw new Error('Choose place, status, amend or cancel. These commands use live funds.');
}
}
}
main().catch((error) => {
console.error('Order command failed; resolve the outcome before retrying:', error);
process.exitCode = 1;
});node --env-file=.env dist/first-order.js placeSave the returned ordId. REST removes the top-level response envelope, but each result still has sCode and sMsg. Only sCode: '0' indicates that item was accepted. The sample checks each returned result.
Follow the matching ordId or clOrdId on the private orders channel. Typical states include live, partially_filled, filled and canceled. Read accFillSz for cumulative filled quantity; use fill identifiers and trade history when recording individual executions. An accepted order may still be unfilled.
Amend an open order
node --env-file=.env dist/first-order.js amendThis changes the price using newPx and explicitly sets cxlOnFail: false. It does not request cancellation if the amendment fails. Check the item response and subsequent order events; orders can fill while an amendment is in flight. If amending size with newSz, it is the new total size, not an additional quantity.
Cancel remaining quantity
node --env-file=.env dist/first-order.js cancelCancellation requests do not reverse fills. Follow the order stream until the resulting state is known, including fills received while the cancellation was being processed. A filled Spot buy leaves an asset balance even if any remainder is cancelled.
Recover an uncertain outcome
The sample never retries order commands automatically. A timeout can occur after OKX accepts a request. Check matching private events first, then query the order if its status is still unknown:
node --env-file=.env dist/first-order.js statusThis uses getOrderDetails() with the saved client ID. For records beyond that endpoint's scope, use getOrderHistory(), getOrderHistoryArchive() and getFills(), with pagination and appropriate filters. Empty results or delayed history are not proof the order failed.
Use the client ID to match requests with order events and status queries. Give each new order a unique ID. Reusing an ID does not guarantee duplicate requests will be ignored indefinitely, so resolve a timed-out request before resubmitting it. Use REST for recovery rather than querying after every successful command.
Closing a process or WebSocket does not cancel open orders.