FXCM API Update sgcWebSockets

FXCM Forex Trading API Integration in Delphi

The FXCM API provides programmatic access to one of the world's largest retail forex brokers, enabling real-time market data streaming, order execution, and historical candle retrieval. The TsgcWSAPI_FXCM component for Delphi wraps FXCM's WebSocket (socket.io) and HTTP interfaces into a single, easy-to-use class, letting you build automated trading systems, market scanners, and portfolio dashboards without dealing with low-level protocol details.

Overview and Architecture

FXCM exposes its trading platform through a hybrid protocol that combines a persistent WebSocket connection (built on socket.io) for real-time streaming with standard HTTP endpoints for request/response operations. The TsgcWSAPI_FXCM component abstracts both transport layers behind a unified Delphi interface, so you interact with a single component regardless of whether the underlying call uses WebSocket or HTTP.

The API supports three major functional areas:

Area Description Transport
Market Data Real-time price streaming and symbol discovery WebSocket + HTTP
Trading Tables Account state, positions, orders, and offers WebSocket + HTTP
Order Execution Place, modify, and close trading orders HTTP

Configuration

Before connecting to the FXCM API, you must configure two essential properties on the TsgcWSAPI_FXCM component:

Property Type Description
FXCM.AccessToken String Your API access token, obtained from FXCM Trading Station Web
FXCM.Demo Boolean Set to True for the demo environment, False for live trading
Note: To obtain your Access Token, log in to FXCM Trading Station Web, navigate to your account settings, and generate a new API token. Always start development with FXCM.Demo := True to avoid placing real trades.

Getting Started

Setting up the FXCM component requires just three steps: create a WebSocket client, attach the API component, and configure your credentials. Once the client is activated, the component handles the socket.io handshake and HTTP bearer-token authentication automatically.

var
  oClient: TsgcWebSocketClient;
  oFXCM: TsgcWSAPI_FXCM;
begin
  oClient := TsgcWebSocketClient.Create(nil);
  oFXCM := TsgcWSAPI_FXCM.Create(nil);
  oFXCM.Client := oClient;
  oFXCM.FXCM.AccessToken := 'your_access_token';
  oFXCM.FXCM.Demo := True;
  oClient.Active := True;
end;

Market Data Methods

The market data methods allow you to discover available instruments, subscribe to real-time price updates, and manage your active subscriptions.

Method Description
GetSymbols Returns a list of all available trading symbols (currency pairs, CFDs, etc.)
SubscribeMarketData Subscribes to real-time price updates for a given symbol
UnSubscribeMarketData Stops receiving real-time price updates for a given symbol
UpdateSubscriptions Filters the offer table to display only the symbols you are currently subscribed to

Subscribing to Market Data

Once connected, call GetSymbols to discover available instruments, then subscribe to any symbol for streaming bid/ask prices:

// Retrieve all available trading symbols
ShowMessage(oFXCM.GetSymbols);

// Subscribe to real-time EUR/USD price updates
oFXCM.SubscribeMarketData('EUR/USD');

// Subscribe to additional pairs
oFXCM.SubscribeMarketData('GBP/USD');
oFXCM.SubscribeMarketData('USD/JPY');

// Filter the offer table to show only subscribed symbols
oFXCM.UpdateSubscriptions;

Trading Table Methods

FXCM organizes account data into trading tables. You can subscribe to receive continuous updates as the state changes, or request a one-time snapshot of the current state.

Available Trading Tables

Table Name Description
Offer Current bid/ask prices, high/low, and trading session info for each instrument
OpenPosition All currently open positions with P&L, margin, and entry prices
ClosedPosition Recently closed positions with realized P&L
Order Pending entry orders and their parameters
Summary Aggregated position summary per instrument
LeverageProfile Leverage settings per instrument and account
Account Account balance, equity, used margin, and usable margin
Properties Account-level settings and trading properties

Subscription and Snapshot Methods

Method Description
SubscribeTradingTables Subscribes to continuous updates for a specified trading table
UnSubscribeTradingTables Stops receiving updates for a specified trading table
SnapshotTradingTables Retrieves a one-time snapshot of the current state of a trading table
// Subscribe to real-time updates for open positions
oFXCM.SubscribeTradingTables('OpenPosition');

// Subscribe to account balance updates
oFXCM.SubscribeTradingTables('Account');

// Get a one-time snapshot of all pending orders
ShowMessage(oFXCM.SnapshotTradingTables('Order'));

// Stop receiving position updates
oFXCM.UnSubscribeTradingTables('OpenPosition');

Trading Orders

The TradingOrder method provides a unified interface for placing, modifying, and closing orders through the FXCM HTTP API. All order operations are performed via this single method, with different parameters controlling the action taken.

Method Description
TradingOrder Places a new order, modifies an existing order, or closes an open position depending on the parameters provided
Note: The TradingOrder method sends requests via HTTP. Always confirm execution results by checking the trading tables (OpenPosition, Order) for updated state after submitting an order.

Historical Data

The GetHistoricalData method retrieves OHLC (Open, High, Low, Close) candle data for any available instrument at a specified time frame. This is essential for backtesting strategies, building charts, and performing technical analysis.

Method Parameters Description
GetHistoricalData Symbol, TimeFrame, NumPeriods Retrieves candle data for a given instrument at the specified time frame and number of periods

Supported Time Frames

Value Description
m1 1-minute candles
m5 5-minute candles
m15 15-minute candles
m30 30-minute candles
H1 1-hour candles
H4 4-hour candles
D1 Daily candles
W1 Weekly candles
M1 Monthly candles
// Get the last 100 five-minute candles for EUR/USD
ShowMessage(oFXCM.GetHistoricalData('EUR/USD', 'm5', 100));

// Get the last 50 daily candles for GBP/USD
ShowMessage(oFXCM.GetHistoricalData('GBP/USD', 'D1', 50));

Complete Code Example

The following example demonstrates a complete workflow: connecting to the FXCM demo environment, retrieving available symbols, subscribing to real-time market data, and fetching historical candle data.

var
  oClient: TsgcWebSocketClient;
  oFXCM: TsgcWSAPI_FXCM;
begin
  // Create and configure the WebSocket client
  oClient := TsgcWebSocketClient.Create(nil);
  oFXCM := TsgcWSAPI_FXCM.Create(nil);
  oFXCM.Client := oClient;

  // Configure FXCM credentials
  oFXCM.FXCM.AccessToken := 'your_access_token';
  oFXCM.FXCM.Demo := True;

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

  // Get all available symbols
  ShowMessage(oFXCM.GetSymbols);

  // Subscribe to real-time market data for EUR/USD
  oFXCM.SubscribeMarketData('EUR/USD');

  // Get the last 100 five-minute candles
  ShowMessage(oFXCM.GetHistoricalData('EUR/USD', 'm5', 100));
end;

Notes and Best Practices

Demo vs. Live Environment

Always develop and test with FXCM.Demo := True. The demo environment provides the same API surface and data format as the live environment, but uses virtual funds. Switch to FXCM.Demo := False only after thorough testing.

Connection Management

The underlying socket.io connection sends periodic heartbeats to keep the session alive. If the connection drops, the component will attempt to reconnect automatically. Monitor the WebSocket client's OnDisconnect and OnError events to handle network interruptions gracefully.

Rate Limits

FXCM enforces rate limits on HTTP requests. Avoid calling methods like GetHistoricalData or TradingOrder in tight loops. For real-time data, prefer WebSocket subscriptions over polling with HTTP.

Tip: Combine SubscribeMarketData for live prices with SubscribeTradingTables('OpenPosition') and SubscribeTradingTables('Account') to build a complete real-time trading dashboard that shows both market conditions and your portfolio state.
×
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.

Coinbase API Update sgcWebSockets

Related Posts