OKX API Update sgcWebSockets

OKX WebSocket Trading API Integration in Delphi

The TsgcWSAPI_OKX component provides comprehensive Delphi access to the OKX exchange through a unified WebSocket interface. It supports public market data streams, private account channels, and direct trading operations including market and limit orders, all through a single component. This guide details every available method, configuration property, and includes working code examples to get you trading on OKX from Delphi.

WebSocket Public Channels

Public channels stream market data to all connected clients without requiring authentication. These channels cover instruments, tickers, order books, trades, candlesticks, funding rates, and more. Each subscribe method has a corresponding unsubscribe method.

Market Data Channels

Method Description
SubscribeInstruments Subscribes to instrument updates (new listings, delistings, status changes).
SubscribeTicker Subscribes to real-time ticker data for a specific instrument.
SubscribeOpenInterest Subscribes to open interest updates for futures and perpetual contracts.
SubscribeCandlestick Subscribes to candlestick/kline data at the specified interval.
SubscribeTrades Subscribes to real-time trade execution data for a specific instrument.
SubscribeOrderBook Subscribes to order book updates with configurable depth.

Price & Index Channels

Method Description
SubscribeEstimatedPrices Subscribes to estimated delivery/exercise price for options and futures.
SubscribeMarkPrice Subscribes to mark price updates used for margin and PnL calculations.
SubscribeMarkPriceCandlestick Subscribes to candlestick data based on the mark price.
SubscribePriceLimit Subscribes to price limit (price band) updates for an instrument.
SubscribeIndexCandlestick Subscribes to candlestick data based on the index price.
SubscribeIndexTicker Subscribes to index ticker updates for a given index.
SubscribeFundingRate Subscribes to funding rate updates for perpetual contracts.

Options & System Channels

Method Description
SubscribeOptionSummary Subscribes to options summary data (greeks, volatility, open interest).
SubscribeStatus Subscribes to system status updates (maintenance, disruptions).
SubscribePublicStructureBlockTrades Subscribes to public structure block trade data.
SubscribeBlockTickers Subscribes to block trade ticker updates.
Note: Every Subscribe method listed above has a corresponding UnSubscribe counterpart (e.g., UnSubscribeTicker) to stop receiving updates for that channel.

WebSocket Private Channels

Private channels require authentication and deliver real-time updates on your account state, positions, orders, and algorithmic trading activity. Set OKX.IsPrivate := True and provide valid API credentials before subscribing to these channels.

Account & Position Channels

Method Description
SubscribeAccount Subscribes to account balance and equity updates in real time.
SubscribePositions Subscribes to position updates (open, close, size changes).
SubscribeBalanceAndPosition Subscribes to combined balance and position updates in a single stream.
SubscribePositionRisk Subscribes to position risk warning updates (liquidation proximity).
SubscribeAccountGreeks Subscribes to account-level greeks updates for options positions.

Order & Algo Channels

Method Description
SubscribeOrders Subscribes to order status updates (placed, filled, cancelled, partially filled).
SubscribeOrdersAlgo Subscribes to algorithmic order updates (trigger, TP/SL, trailing stop).
SubscribeAdvanceAlgo Subscribes to advanced algorithmic order updates (iceberg, TWAP).

RFQ & Block Trade Channels

Method Description
SubscribeRfqs Subscribes to request-for-quote (RFQ) updates for block trading.
SubscribeQuotes Subscribes to quote updates in response to RFQs.
SubscribePrivateStructureBlockTrades Subscribes to private structure block trade updates.

Grid Trading Channels

Method Description
SubscribeSpotGridAlgoOrders Subscribes to spot grid algo order updates.
SubscribeContactGridAlgoOrders Subscribes to contract grid algo order updates.
SubscribeGridPositions Subscribes to grid trading position updates.
SubscribeGridSubOrders Subscribes to individual sub-order updates within a grid strategy.

WebSocket Trading Operations

OKX supports placing and managing orders directly over the WebSocket connection, which provides lower latency compared to REST API calls. These methods require authentication.

Method Description
PlaceOrder Places a new order with full control over all order parameters.
PlaceMarketOrder Places a market order that executes immediately at the best available price.
PlaceLimitOrder Places a limit order at a specified price, executed only when the market reaches that price.
CancelOrder Cancels an existing order by its order ID.
AmendOrder Amends an existing order (modify price or size without cancelling and replacing).
Note: WebSocket-based trading provides significantly lower latency than REST-based order placement. OKX processes WebSocket orders with higher priority, making this the preferred method for latency-sensitive strategies.

Code Example

The following example demonstrates how to create and configure the TsgcWSAPI_OKX component, authenticate with the API, subscribe to ticker data, monitor orders, and place both market and limit orders directly over the WebSocket connection.

var
  oClient: TsgcWebSocketClient;
  oOKX: TsgcWSAPI_OKX;
begin
  // Create the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  oOKX := TsgcWSAPI_OKX.Create(nil);
  oOKX.Client := oClient;

  // Configure API credentials
  oOKX.OKX.ApiKey := 'your_api_key';
  oOKX.OKX.ApiSecret := 'your_api_secret';
  oOKX.OKX.Passphrase := 'your_passphrase';
  oOKX.OKX.IsPrivate := True;

  // Connect to OKX
  oClient.Active := True;

  // Subscribe to BTC-USDT ticker
  oOKX.SubscribeTicker('BTC-USDT');

  // Subscribe to order updates for spot trading
  oOKX.SubscribeOrders(okxitSpot);

  // Place a market buy order
  oOKX.PlaceMarketOrder(okxosBuy, 'BTC-USDT', 0.001);

  // Place a limit buy order
  oOKX.PlaceLimitOrder(okxosBuy, 'BTC-USDT', 0.001, 30000);
end;

Handling WebSocket Events

Assign an event handler to process incoming WebSocket messages. The event provides the channel name and the JSON payload for each update.

procedure TForm1.OnOKXEvent(Sender: TObject;
  const aChannel, aData: string);
begin
  // aChannel identifies the subscription (e.g., 'tickers', 'orders')
  // aData contains the JSON payload
  Memo1.Lines.Add(aChannel + ': ' + aData);
end;

Using Demo Trading Mode

OKX provides a demo trading environment for testing. Enable it by setting OKX.IsDemo := True before connecting. Demo mode connects to a separate endpoint with simulated balances, allowing you to test your trading logic without risking real funds.

// Enable demo trading mode
oOKX.OKX.IsDemo := True;
oOKX.OKX.IsPrivate := True;
oClient.Active := True;

Configuration & Notes

Configuration Properties

All configuration is accessed through the OKX property of the component.

Property Type Description
OKX.ApiKey String Your OKX API key. Generate this from the OKX API Management page.
OKX.ApiSecret String Your OKX API secret. Keep this value secure and never expose it in client-side code.
OKX.Passphrase String The passphrase you set when creating the API key. Required for all authenticated requests.
OKX.IsDemo Boolean When set to True, connects to the OKX demo trading environment with simulated funds. Defaults to False.
OKX.IsPrivate Boolean When set to True, enables authentication on the WebSocket connection. Required for private channels and trading operations. Defaults to False.

Important Notes

Security: Never hard-code your API key, secret, or passphrase directly in production code. Use a secure configuration file or environment variable to store credentials.
  • Set OKX.IsPrivate := True before connecting if you need private channels or trading operations. Public channels work without authentication.
  • Use OKX.IsDemo := True to test against the OKX demo environment before going live. Demo mode uses separate API credentials generated specifically for the demo platform.
  • The SubscribeOrders method accepts an instrument type parameter (e.g., okxitSpot, okxitFutures, okxitSwap, okxitOption) to filter order updates by trading type.
  • The PlaceMarketOrder and PlaceLimitOrder convenience methods accept an order side parameter (e.g., okxosBuy, okxosSell), instrument ID, size, and (for limit orders) price.
  • The AmendOrder method allows you to modify price or size of an active order without cancelling and re-placing it, reducing latency and avoiding lost queue position.
  • OKX enforces rate limits on WebSocket messages. Refer to the official OKX documentation for current limits on subscriptions and trading requests per second.
  • WebSocket subscriptions are persistent for the lifetime of the connection. If the connection drops, you will need to resubscribe after reconnecting.
×
Stay Informed

When you subscribe to the blog, we will send you an e-mail when there are new updates on the site so you wouldn't miss them.

MEXC API Update sgcWebSockets

Related Posts