-
Notifications
You must be signed in to change notification settings - Fork 0
WebSocket API
Igor Sazonov edited this page Mar 15, 2026
·
1 revision
A guide to working with the OKX WebSocket API for real-time data streaming.
The SDK supports all 53 OKX WebSocket channels:
- Public channels β Market data (no authentication required)
- Private channels β Account data (authentication required)
- Business channels β Deposits, withdrawals, and related events
use Tigusigalpa\OKX\WebsocketClient;
$ws = new WebsocketClient(
apiKey: 'your-api-key',
secretKey: 'your-secret-key',
passphrase: 'your-passphrase',
isDemo: false
);$ws->connectPublic();$ws->subscribe('tickers', ['instId' => 'BTC-USDT'], function ($data) {
$ticker = $data['data'][0];
echo "BTC-USDT: {$ticker['last']}\n";
echo "24h Volume: {$ticker['vol24h']}\n";
echo "24h Change: {$ticker['sodUtc0']}\n";
});// Full order book
$ws->subscribe('books', ['instId' => 'BTC-USDT'], function ($data) {
$book = $data['data'][0];
echo "Asks: " . count($book['asks']) . "\n";
echo "Bids: " . count($book['bids']) . "\n";
});
// Top 5 levels
$ws->subscribe('books5', ['instId' => 'BTC-USDT'], function ($data) {
$book = $data['data'][0];
$bestAsk = $book['asks'][0];
$bestBid = $book['bids'][0];
echo "Best Ask: {$bestAsk[0]} @ {$bestAsk[1]}\n";
echo "Best Bid: {$bestBid[0]} @ {$bestBid[1]}\n";
});$ws->subscribe('trades', ['instId' => 'BTC-USDT'], function ($data) {
foreach ($data['data'] as $trade) {
echo "Trade: {$trade['side']} {$trade['sz']} @ {$trade['px']}\n";
}
});// Available intervals: 1m, 3m, 5m, 15m, 30m, 1H, 2H, 4H, 6H, 12H, 1D, 1W, 1M
$ws->subscribe('candle1H', ['instId' => 'BTC-USDT'], function ($data) {
foreach ($data['data'] as $candle) {
[$ts, $open, $high, $low, $close, $vol, $volCcy] = $candle;
echo "Candle: O:{$open} H:{$high} L:{$low} C:{$close}\n";
}
});$ws->subscribe('index-tickers', ['instId' => 'BTC-USDT'], function ($data) {
$index = $data['data'][0];
echo "Index Price: {$index['idxPx']}\n";
});$ws->subscribe('funding-rate', ['instId' => 'BTC-USDT-SWAP'], function ($data) {
$funding = $data['data'][0];
echo "Funding Rate: {$funding['fundingRate']}\n";
echo "Next Funding Time: {$funding['nextFundingTime']}\n";
});$ws->subscribe('mark-price', ['instId' => 'BTC-USDT-SWAP'], function ($data) {
$mark = $data['data'][0];
echo "Mark Price: {$mark['markPx']}\n";
});$ws->subscribe('open-interest', ['instId' => 'BTC-USDT-SWAP'], function ($data) {
$oi = $data['data'][0];
echo "Open Interest: {$oi['oi']}\n";
});$ws->connectPrivate();$ws->subscribe('account', ['ccy' => 'BTC'], function ($data) {
foreach ($data['data'] as $account) {
echo "Currency: {$account['ccy']}\n";
echo "Balance: {$account['bal']}\n";
echo "Available: {$account['availBal']}\n";
echo "Frozen: {$account['frozenBal']}\n";
}
});$ws->subscribe('positions', [
'instType' => 'SWAP',
'instId' => 'BTC-USDT-SWAP'
], function ($data) {
foreach ($data['data'] as $position) {
echo "Position: {$position['instId']}\n";
echo "Size: {$position['pos']}\n";
echo "PnL: {$position['upl']}\n";
echo "Margin: {$position['margin']}\n";
}
});$ws->subscribe('orders', ['instType' => 'SPOT'], function ($data) {
foreach ($data['data'] as $order) {
echo "Order {$order['ordId']}: {$order['state']}\n";
echo "Instrument: {$order['instId']}\n";
echo "Side: {$order['side']}\n";
echo "Price: {$order['px']}\n";
echo "Size: {$order['sz']}\n";
echo "Filled: {$order['accFillSz']}\n";
}
});$ws->subscribe('orders-algo', ['instType' => 'SPOT'], function ($data) {
foreach ($data['data'] as $algoOrder) {
echo "Algo Order {$algoOrder['algoId']}: {$algoOrder['state']}\n";
echo "Type: {$algoOrder['ordType']}\n";
echo "Trigger Price: {$algoOrder['triggerPx']}\n";
}
});$ws->subscribe('fills', ['instType' => 'SPOT'], function ($data) {
foreach ($data['data'] as $fill) {
echo "Fill: {$fill['side']} {$fill['fillSz']} @ {$fill['fillPx']}\n";
echo "Fee: {$fill['fee']} {$fill['feeCcy']}\n";
}
});$ws->subscribe('balance_and_position', [], function ($data) {
$balData = $data['data'][0]['balData'] ?? [];
$posData = $data['data'][0]['posData'] ?? [];
echo "Balances:\n";
foreach ($balData as $bal) {
echo " {$bal['ccy']}: {$bal['cashBal']}\n";
}
echo "Positions:\n";
foreach ($posData as $pos) {
echo " {$pos['instId']}: {$pos['pos']}\n";
}
});$ws->subscribe('liquidation-warning', ['instType' => 'SWAP'], function ($data) {
foreach ($data['data'] as $warning) {
echo "β οΈ Liquidation Warning!\n";
echo "Position: {$warning['instId']}\n";
echo "Margin Ratio: {$warning['mgnRatio']}\n";
}
});$ws->connectBusiness();$ws->subscribe('deposit-info', [], function ($data) {
foreach ($data['data'] as $deposit) {
echo "Deposit: {$deposit['ccy']} {$deposit['amt']}\n";
echo "Status: {$deposit['state']}\n";
echo "TxId: {$deposit['txId']}\n";
}
});$ws->subscribe('withdrawal-info', [], function ($data) {
foreach ($data['data'] as $withdrawal) {
echo "Withdrawal: {$withdrawal['ccy']} {$withdrawal['amt']}\n";
echo "Status: {$withdrawal['state']}\n";
echo "TxId: {$withdrawal['txId']}\n";
}
});$ws->unsubscribe('tickers', ['instId' => 'BTC-USDT']);$instruments = ['BTC-USDT', 'ETH-USDT', 'SOL-USDT'];
foreach ($instruments as $instId) {
$ws->subscribe('tickers', ['instId' => $instId], function ($data) use ($instId) {
$ticker = $data['data'][0];
echo "{$instId}: {$ticker['last']}\n";
});
}// Start listening (blocking call)
$ws->run();
// Stop the client
$ws->stop();The client automatically reconnects if the connection drops:
$ws->connectPublic();
$ws->subscribe('tickers', ['instId' => 'BTC-USDT'], function ($data) {
// Subscriptions are automatically restored after reconnection
echo "Price: {$data['data'][0]['last']}\n";
});
$ws->run(); // Reconnects automatically on errorsThe client sends a ping every 25 seconds automatically β no manual configuration needed.
use Tigusigalpa\OKX\WebsocketClient;
$ws = new WebsocketClient(
apiKey: 'your-api-key',
secretKey: 'your-secret-key',
passphrase: 'your-passphrase'
);
// Public data
$ws->connectPublic();
// Monitor price
$ws->subscribe('tickers', ['instId' => 'BTC-USDT'], function ($data) {
$ticker = $data['data'][0];
$price = (float) $ticker['last'];
// Alert when price crosses a threshold
if ($price > 60000) {
echo "π BTC above $60,000!\n";
}
});
// Monitor trades
$ws->subscribe('trades', ['instId' => 'BTC-USDT'], function ($data) {
foreach ($data['data'] as $trade) {
$size = (float) $trade['sz'];
// Alert on large trades
if ($size > 10) {
echo "π Large trade: {$trade['side']} {$size} BTC\n";
}
}
});
// Start
$ws->run();-
tickersβ Ticker data -
booksβ Full order book -
books5β Top 5 levels -
books-l2-tbtβ L2 order book (tick-by-tick) -
bbo-tbtβ Best bid/offer (tick-by-tick) -
tradesβ Trade stream -
candle1m,candle3m,candle5m,candle15m,candle30mβ Minute candles -
candle1H,candle2H,candle4H,candle6H,candle12Hβ Hourly candles -
candle1D,candle1W,candle1Mβ Daily / weekly / monthly candles -
index-tickersβ Index tickers -
index-candle1Dβ Index candles -
mark-priceβ Mark price -
mark-price-candle1Dβ Mark price candles -
price-limitβ Price limits -
funding-rateβ Funding rate -
open-interestβ Open interest -
estimated-priceβ Estimated delivery price -
opt-summaryβ Options summary -
liquidation-ordersβ Liquidation orders -
public-block-tradesβ Public block trades -
block-tickersβ Block tickers
-
accountβ Account updates -
positionsβ Position updates -
balance_and_positionβ Combined balance and position updates -
ordersβ Order updates -
orders-algoβ Algo order updates -
fillsβ Fill notifications -
liquidation-warningβ Liquidation warnings -
account-greeksβ Greeks (options) -
rfqsβ RFQ updates -
quotesβ Quote updates -
grid-orders-spotβ Grid orders (spot) -
grid-orders-contractβ Grid orders (contracts) -
grid-positionsβ Grid positions -
grid-sub-ordersβ Grid sub-orders -
algo-advanceβ Advanced algo orders -
algo-recurring-buyβ Recurring buy -
copytrading-lead-notificationβ Copy trading notifications -
adl-warningβ ADL warnings
-
deposit-infoβ Deposit events -
withdrawal-infoβ Withdrawal events -
sprd-ordersβ Spread orders -
sprd-tradesβ Spread trades
Back: β REST API | Next: Laravel Integration β