XTB API Update sgcWebSockets

XTB xStation5 Trading API Integration in Delphi

XTB is one of Europe's leading online trading platforms, offering access to forex, indices, commodities, stocks, and cryptocurrencies through its xStation5 platform. The TsgcWSAPI_XTB component provides a complete Delphi integration with the xStation5 API over a single WebSocket connection — covering authentication, market data retrieval, account management, trade execution, and real-time streaming subscriptions. This article walks through every method available and demonstrates how to get started in minutes.

Architecture Overview

Unlike many crypto exchanges that split functionality between REST endpoints and WebSocket channels, the XTB xStation5 API operates entirely over a single WebSocket connection. Every request — from pulling a list of symbols to placing a trade — is sent and received as a JSON message on the same socket. A second streaming socket is automatically managed for real-time subscriptions (balance, candles, ticks, trades, and more).

The TsgcWSAPI_XTB component abstracts all of this for you. You simply assign a TsgcWebSocketClient, configure your credentials, activate the client, and call high-level methods such as GetAllSymbols or SubscribeTickPrices.

Authentication

Authentication is handled automatically when the WebSocket client connects, using the credentials you set in the XTB property group. You can also call these methods explicitly if needed.

Method Description
Login Authenticates with the xStation5 server using UserId and Password. Called automatically on connect.
Logout Terminates the authenticated session and disconnects from the server.

Market Data Methods

These methods retrieve instrument information, pricing, charts, news, and trading hours from the xStation5 server. All calls are request/response over the WebSocket connection.

Method Description
GetAllSymbols Returns a list of all instruments available on the platform.
GetSymbol Returns detailed information for a specific symbol.
GetTickPrices Returns the current tick prices (bid/ask) for the specified symbols.
GetTradingHours Returns trading hours for the given instruments.
GetCalendar Returns the economic calendar of upcoming events.
GetChartLastRequest Returns chart candle data starting from a given timestamp to the present.
GetChartRangeRequest Returns chart candle data for a specific date range.
GetNews Returns news topics from the XTB trading platform.
GetStepRules Returns step rules for volume calculations.
GetServerTime Returns the current server time.
GetVersion Returns the API version number.

Account Methods

Account methods let you inspect your user profile, margin levels, and profit calculations without leaving the WebSocket session.

Method Description
GetCurrentUserData Returns information about the currently logged-in user (name, currency, leverage, etc.).
GetMarginLevel Returns the current account margin level, equity, and balance.
GetMarginTrade Calculates the expected margin for a given instrument and volume.
GetIbsHistory Returns the Introducing Broker (IB) commission history.
GetProfitCalculation Calculates the estimated profit for a given trade scenario.

Trading Methods

These methods cover everything from reading open and historical positions to placing and monitoring trade transactions.

Method Description
GetTrades Returns a list of currently open trades. Pass True to include only opened positions.
GetTradesHistory Returns closed trades within a specified time range.
GetTradeRecords Returns trade records for specified order numbers.
TradeTransaction Executes a trade transaction (open, close, modify, or delete an order).
TradeTransactionStatus Checks the current status of a previously submitted trade transaction.

Streaming Subscriptions

Streaming methods open real-time data channels on a dedicated streaming connection. Each subscription has a corresponding unsubscribe method to stop receiving updates.

Subscribe Unsubscribe Description
SubscribeBalance UnSubscribeBalance Real-time balance and equity updates.
SubscribeCandles UnSubscribeCandles Live candle/chart updates for a symbol.
SubscribeKeepAlive UnSubscribeKeepAlive Periodic keep-alive heartbeat messages.
SubscribeNews UnSubscribeNews Real-time news feed from the platform.
SubscribeProfits UnSubscribeProfits Real-time profit/loss updates on open positions.
SubscribeTickPrices UnSubscribeTickPrices Live bid/ask tick prices for a symbol.
SubscribeTrades UnSubscribeTrades Real-time updates when trades are opened, closed, or modified.
SubscribeTradeStatus UnSubscribeTradeStatus Real-time trade transaction status changes.
SubscribePing Subscribes to streaming ping to keep the connection alive (no unsubscribe needed).
Note: Streaming subscriptions require a successful login first. The streaming session ID is obtained automatically during authentication.

Utility Methods

Method Description
Ping Sends a ping to the server to verify the connection is alive and prevent timeouts.

Getting Started — Code Example

The following example creates a connection to the XTB demo server, authenticates, retrieves symbols and user data, subscribes to live tick prices and balance updates, and fetches open trades.

var
  oClient: TsgcWebSocketClient;
  oXTB: TsgcWSAPI_XTB;
begin
  // Create the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  // Create the XTB API component
  oXTB := TsgcWSAPI_XTB.Create(nil);
  oXTB.Client := oClient;

  // Configure credentials
  oXTB.XTB.UserId := 'your_user_id';
  oXTB.XTB.Password := 'your_password';
  oXTB.XTB.Demo := True;

  // Connect and authenticate
  oClient.Active := True;

  // After the login event fires, call API methods:
  oXTB.GetAllSymbols;
  oXTB.GetCurrentUserData;

  // Subscribe to real-time tick prices for EURUSD
  oXTB.SubscribeTickPrices('EURUSD', 0, 0);

  // Subscribe to balance updates
  oXTB.SubscribeBalance;

  // Get all open trades
  oXTB.GetTrades(False);
end;

Handling Responses

All responses arrive asynchronously through the component's events. Assign handlers to events such as OnXTBResponse and OnXTBStreamingResponse to process the returned JSON data. Each response includes a command identifier so you can route it to the appropriate processing logic.

Configuration Reference

All configuration is grouped under the XTB property of the TsgcWSAPI_XTB component.

Property Type Description
XTB.UserId String Your XTB account user ID.
XTB.Password String Your XTB account password.
XTB.Demo Boolean Set to True to connect to the demo server; False for the live production server.

Tips and Notes

Demo vs. Live

Always develop and test with XTB.Demo := True. The demo server uses the same API surface as production but connects to a sandbox environment with virtual funds. Switch to False only when you are ready for live trading.

Connection Keep-Alive

The XTB server disconnects idle sessions after a timeout period. Use SubscribePing or call Ping periodically to keep the connection alive. The SubscribeKeepAlive method on the streaming connection serves a similar purpose.

Single Connection Architecture

Unlike exchanges with separate REST endpoints, XTB routes every command through WebSocket messages. This simplifies the component architecture: you only need a TsgcWebSocketClient and a TsgcWSAPI_XTB — no additional HTTP components are required.

Error Handling

If a request fails, the server returns a JSON error response with an error code and description. Handle these in your response event by checking the status field. Common issues include invalid credentials, expired sessions, and rate-limiting on excessive requests.

Rate limits: The XTB API enforces request limits per second. Avoid sending bursts of requests in tight loops. Space out your calls or use streaming subscriptions for data that updates frequently.
×
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.

OKX API Update sgcWebSockets

Related Posts