Skip to content

API Reference

Igor Sazonov edited this page Mar 15, 2026 · 1 revision

Complete method reference for the OKX PHP SDK.

Client

The main class for interacting with the OKX API.

Constructor

public function __construct(
    string $apiKey,
    string $secretKey,
    string $passphrase,
    bool $isDemo = false,
    string $baseUrl = 'https://www.okx.com',
    ?HttpClient $httpClient = null,
    ?LoggerInterface $logger = null
)

Parameters:

  • $apiKey — OKX API key
  • $secretKey — Secret key
  • $passphrase — Passphrase
  • $isDemo — Enable demo trading mode
  • $baseUrl — Base API URL
  • $httpClient — Optional HTTP client (Guzzle)
  • $logger — Optional PSR-3 logger

Factory Methods

$client->account()      // Account API
$client->trade()        // Trade API
$client->market()       // Market API
$client->publicData()   // Public Data API
$client->asset()        // Asset API
$client->finance()      // Finance API
$client->copyTrading()  // Copy Trading API
$client->tradingBot()   // Trading Bot API
$client->rfq()          // RFQ API
$client->sprd()         // Spread Trading API
$client->rubik()        // Trading Statistics API
$client->fiat()         // Fiat API
$client->users()        // Users API
$client->support()      // Support API
$client->systemStatus() // System Status API
$client->affiliate()    // Affiliate API

Account API

getBalance

Get account balance.

public function getBalance(?string $ccy = null): array

Parameters:

  • $ccy — Currency (optional)

Returns: Array with balance data

Example:

$balance = $client->account()->getBalance();
$btcBalance = $client->account()->getBalance('BTC');

getPositions

Get open positions.

public function getPositions(
    ?string $instType = null,
    ?string $instId = null,
    ?string $posId = null
): array

Parameters:

  • $instType — Instrument type (SPOT, SWAP, FUTURES, OPTION)
  • $instId — Instrument ID
  • $posId — Position ID

setLeverage

Set leverage.

public function setLeverage(
    string $lever,
    ?string $mgnMode = null,
    ?string $instId = null,
    ?string $ccy = null,
    ?string $posSide = null
): array

Parameters:

  • $lever — Leverage value (e.g., "10")
  • $mgnMode — Margin mode (cross, isolated)
  • $instId — Instrument ID
  • $ccy — Currency
  • $posSide — Position side (long, short)

Trade API

placeOrder

Place an order.

public function placeOrder(
    string $instId,
    string $tdMode,
    string $side,
    string $ordType,
    string $sz,
    ?string $px = null,
    ?string $ccy = null,
    ?string $clOrdId = null,
    ?string $tag = null,
    ?string $posSide = null,
    ?bool $reduceOnly = null,
    ?string $tgtCcy = null,
    ?bool $banAmend = null,
    ?string $tpTriggerPx = null,
    ?string $tpOrdPx = null,
    ?string $slTriggerPx = null,
    ?string $slOrdPx = null,
    ?string $tpTriggerPxType = null,
    ?string $slTriggerPxType = null,
    ?string $quickMgnType = null,
    ?string $stpId = null,
    ?string $stpMode = null,
    ?array $attachAlgoOrds = null
): array

Required parameters:

  • $instId — Instrument ID (e.g., "BTC-USDT")
  • $tdMode — Trade mode (cash, cross, isolated)
  • $side — Side (buy, sell)
  • $ordType — Order type (market, limit, post_only, fok, ioc)
  • $sz — Order size

Optional parameters:

  • $px — Price (required for limit orders)
  • $tgtCcy — Target currency (base_ccy, quote_ccy)
  • $tpTriggerPx — Take Profit trigger price
  • $slTriggerPx — Stop Loss trigger price

Example:

// Market order
$order = $client->trade()->placeOrder(
    instId: 'BTC-USDT',
    tdMode: 'cash',
    side: 'buy',
    ordType: 'market',
    sz: '100',
    tgtCcy: 'quote_ccy'
);

// Limit order with TP/SL
$order = $client->trade()->placeOrder(
    instId: 'BTC-USDT',
    tdMode: 'cross',
    side: 'buy',
    ordType: 'limit',
    sz: '0.1',
    px: '50000',
    tpTriggerPx: '55000',
    slTriggerPx: '48000'
);

cancelOrder

Cancel an order.

public function cancelOrder(
    string $instId,
    ?string $ordId = null,
    ?string $clOrdId = null
): array

Parameters:

  • $instId — Instrument ID
  • $ordId — Order ID (either ordId or clOrdId is required)
  • $clOrdId — Client Order ID

getOrdersPending

Get open orders.

public function getOrdersPending(
    ?string $instType = null,
    ?string $uly = null,
    ?string $instId = null,
    ?string $ordType = null,
    ?string $state = null,
    ?string $after = null,
    ?string $before = null,
    ?int $limit = null,
    ?string $instFamily = null
): array

getFills

Get trade fills.

public function getFills(
    ?string $instType = null,
    ?string $uly = null,
    ?string $instId = null,
    ?string $ordId = null,
    ?string $after = null,
    ?string $before = null,
    ?string $begin = null,
    ?string $end = null,
    ?int $limit = null,
    ?string $instFamily = null
): array

Market API

getTicker

Get ticker data.

public function getTicker(string $instId): array

Parameters:

  • $instId — Instrument ID

Returns:

[
    [
        'instId' => 'BTC-USDT',
        'last' => '50000',
        'lastSz' => '0.1',
        'askPx' => '50001',
        'bidPx' => '49999',
        'open24h' => '49000',
        'high24h' => '51000',
        'low24h' => '48000',
        'vol24h' => '1000',
        'volCcy24h' => '50000000'
    ]
]

getBooks

Get the order book.

public function getBooks(
    string $instId,
    ?string $sz = null
): array

Parameters:

  • $instId — Instrument ID
  • $sz — Order book depth (1–400)

getCandles

Get candlestick data.

public function getCandles(
    string $instId,
    ?string $bar = null,
    ?string $after = null,
    ?string $before = null,
    ?int $limit = null
): array

Parameters:

  • $instId — Instrument ID
  • $bar — Interval (1m, 3m, 5m, 15m, 30m, 1H, 2H, 4H, 6H, 12H, 1D, 1W, 1M)
  • $after — Timestamp (after)
  • $before — Timestamp (before)
  • $limit — Number of candles (max 300)

Returns:

[
    [timestamp, open, high, low, close, volume, volumeCcy],
    ...
]

getTrades

Get recent trades.

public function getTrades(
    string $instId,
    ?int $limit = null
): array

Asset API

transfer

Transfer funds between accounts.

public function transfer(
    string $ccy,
    string $amt,
    string $from,
    string $to,
    ?string $type = null,
    ?string $subAcct = null,
    ?string $instId = null,
    ?string $toInstId = null,
    ?bool $loanTrans = null,
    ?string $clientId = null,
    ?bool $omitPosRisk = null
): array

Parameters:

  • $ccy — Currency
  • $amt — Amount
  • $from — Source account (6: Funding, 18: Trading)
  • $to — Destination account (6: Funding, 18: Trading)

withdrawal

Withdraw funds.

public function withdrawal(
    string $ccy,
    string $amt,
    string $dest,
    string $toAddr,
    string $fee,
    ?string $chain = null,
    ?string $areaCode = null,
    ?string $clientId = null
): array

Parameters:

  • $ccy — Currency
  • $amt — Amount
  • $dest — Destination type (3: internal transfer, 4: on-chain)
  • $toAddr — Recipient address
  • $fee — Transaction fee
  • $chain — Network (e.g., "USDT-TRC20")

WebSocket Client

Constructor

public function __construct(
    string $apiKey,
    string $secretKey,
    string $passphrase,
    bool $isDemo = false,
    ?LoggerInterface $logger = null
)

connectPublic

Connect to public channels.

public function connectPublic(): void

connectPrivate

Connect to private channels.

public function connectPrivate(): void

connectBusiness

Connect to business channels.

public function connectBusiness(): void

subscribe

Subscribe to a channel.

public function subscribe(
    string $channel,
    array $args,
    callable $callback
): void

Parameters:

  • $channel — Channel name
  • $args — Channel arguments
  • $callback — Callback function to handle incoming data

Example:

$ws->subscribe('tickers', ['instId' => 'BTC-USDT'], function ($data) {
    echo "Price: " . $data['data'][0]['last'];
});

unsubscribe

Unsubscribe from a channel.

public function unsubscribe(string $channel, array $args): void

run

Start listening for messages.

public function run(): void

stop

Stop the client.

public function stop(): void

Exceptions

OKXException

Base exception class.

Properties:

  • $okxCode — OKX error code
  • $rawResponse — Raw response from the API

AuthenticationException

Authentication errors (50111, 50113).

RateLimitException

Rate limit exceeded (50011).

InvalidParameterException

Invalid request parameters (51000–51099).

InsufficientFundsException

Insufficient funds (54000–54099).

Constants

Instrument Types

  • SPOT — Spot trading
  • MARGIN — Margin trading
  • SWAP — Perpetual swaps
  • FUTURES — Futures
  • OPTION — Options

Trade Modes

  • cash — Spot (cash)
  • cross — Cross margin
  • isolated — Isolated margin

Order Types

  • market — Market order
  • limit — Limit order
  • post_only — Post-only
  • fok — Fill-or-Kill
  • ioc — Immediate-or-Cancel
  • optimal_limit_ioc — Optimal limit IOC

Sides

  • buy — Buy
  • sell — Sell

Position Sides

  • long — Long position
  • short — Short position
  • net — Net (one-way mode)

Candlestick Intervals

  • 1m, 3m, 5m, 15m, 30m — Minutes
  • 1H, 2H, 4H, 6H, 12H — Hours
  • 1D — Day
  • 1W — Week
  • 1M — Month

Full Method List

Account (53 methods)

  • getAccountLevel()
  • getBalance(?string $ccy)
  • getBills(...)
  • getConfig()
  • getPositions(...)
  • setLeverage(...)
  • setPositionMode(string $posMode)
  • increaseDecreaseMargin(...)
  • And more...

Trade (32 methods)

  • placeOrder(...)
  • batchOrders(array $orders)
  • cancelOrder(...)
  • cancelBatchOrders(...)
  • amendOrder(...)
  • getOrder(...)
  • getOrdersPending(...)
  • getOrdersHistory(...)
  • getFills(...)
  • placeAlgoOrder(...)
  • And more...

Market (24 methods)

  • getTicker(string $instId)
  • getTickers(...)
  • getBooks(...)
  • getCandles(...)
  • getTrades(...)
  • getHistoryCandles(...)
  • And more...

Asset (26 methods)

  • getBalances(?string $ccy)
  • transfer(...)
  • withdrawal(...)
  • getDepositAddress(string $ccy)
  • getDepositHistory(...)
  • getWithdrawalHistory(...)
  • And more...

Public Data (24 methods)

  • getInstruments(...)
  • getTime()
  • getFundingRate(string $instId)
  • getOpenInterest(...)
  • getPositionTiers(...)
  • And more...

Return Types

All methods return arrays containing the data from the OKX API. The general response structure is:

[
    [
        // First item data
    ],
    [
        // Second item data
    ],
    ...
]

For typed access, you can use DTOs:

use Tigusigalpa\OKX\DTO\Trade\PlaceOrderResponse;

$order = $client->trade()->placeOrder(...);
$orderDto = PlaceOrderResponse::fromArray($order[0]);

echo $orderDto->ordId;
echo $orderDto->sCode;

Back: ← Testing | Home: Home

Clone this wiki locally