Private account updates
Private subscriptions keep account state current without polling after every order. The example below reads updates only: it does not place, modify or cancel orders.
Save it as private-stream.ts beside the credential helper, then use the compile instructions with private-stream.ts as the entry file. It runs until Ctrl+C.
import { WebsocketClient } from 'okx-api';
import { credentials } from './authenticated-client.js';
const ws = new WebsocketClient({ accounts: [credentials] });
ws.on('authenticated', () => {
console.log('Private connection authenticated.');
});
ws.on('response', (message) => {
console.log('Subscription response:', message);
});
ws.on('update', (message) => {
console.log('Account update:', message);
});
ws.on('exception', (error) => {
console.error('Private stream exception:', error);
});
ws.on('reconnect', () => {
console.log('Reconnecting; account state may be stale. Pause trading decisions until recovery completes.');
});
ws.on('reconnected', () => {
console.log('Connection restored; the SDK restores subscriptions automatically. Recover missed account updates through REST.');
});
Promise.all(ws.subscribe([
{ channel: 'orders', instType: 'SPOT' },
{ channel: 'account' },
{ channel: 'positions', instType: 'ANY' },
])).catch((error) => {
console.error('Private subscription failed:', error);
ws.closeAll();
process.exitCode = 1;
});
process.once('SIGINT', () => {
ws.closeAll();
});node --env-file=.env dist/private-stream.jsWhat each channel provides
orderswithinstType: 'SPOT'reports Spot order changes. It does not send an initial snapshot of all open orders.accountsupplies trading-account balance information. Apply currency updates to your existing store; do not discard currencies absent from a partial update.positionswithinstType: 'ANY'covers available position types for the account. Spot cash holdings live in balances, not derivative position rows.
For a derivatives workflow, subscribe to the corresponding order instrument type as well. Access and available channels depend on your account and region. Authentication success alone does not mean every requested channel was accepted: inspect each subscription acknowledgement.
The example prints events for inspection. It does not store account state or recover missed events. Keep private data out of shared logs.
Initialize without losing changes
Connect and confirm the needed subscriptions, buffering incoming updates while loading the initial account data through REST. Use getBalance(), getOrderList() and getPositions(). Paginate open orders where necessary. The account-state example shows these reads. You will need to merge updates received while they run.
Combine snapshots with buffered updates using order IDs, update times and execution identifiers. Preserve terminal orders and cumulative fills so that an older REST row cannot overwrite a newer event. Do not treat the separate REST responses as one atomic snapshot. Deduplicate repeated events before triggering downstream work.
Recover after a gap
The SDK reconnects, authenticates and restores subscriptions automatically. On reconnect, mark affected state stale and pause decisions that depend on it. Use reconnected to start recovery, buffer incoming events and reconcile:
- Refresh balances, positions and all relevant open orders.
- Query recent order history and fills covering the outage, with overlap and pagination. An order missing from the open-order list may have filled or been cancelled while disconnected.
- Resolve uncertain commands by saved IDs. Merge and deduplicate buffered events and history before marking state current.
- Resume stream-driven updates. Limit recovery requests to the affected account and time range, and respect rate limits.
If private streaming is temporarily unavailable, use temporary REST polling within the account's rate limits and mark the data as potentially delayed. Once streams are restored, reconcile before turning polling off. Wait until balances and positions are current before making trading decisions.