xtb-api-unofficial - v0.1.0
    Preparing search index...

    Class XTBClient

    High-level XTB trading client. Provides a unified API over Browser automation and WebSocket modes.

    ⚠️ Warning: This is an unofficial library. Use at your own risk. Always test thoroughly on demo accounts before using with real money.

    • WebSocket Mode: Direct CoreAPI protocol, no browser needed
    • Browser Mode: Controls xStation5 via Chrome DevTools Protocol
    • CAS Authentication: Full login flow (credentials → TGT → ST → session)
    • Real-time Data: Live quotes, positions, balance via push events
    • Trading: Buy/sell market orders with SL/TP
    • Instrument Search: Access to 11,888+ instruments
    const client = new XTBClient({
    mode: 'browser',
    browser: { cdpUrl: 'ws://127.0.0.1:9222' }
    });
    await client.connect();
    await client.buy('CIG.PL', 1);
    const client = new XTBClient({
    mode: 'websocket',
    websocket: {
    url: 'wss://api5demoa.x-station.eu/v1/xstation',
    accountNumber: 12345678
    },
    auth: {
    credentials: { email: 'user@example.com', password: 'password' }
    }
    });
    await client.connect();
    const positions = await client.getPositions();
    Index

    Constructors

    Accessors

    • get browser(): XTBBrowserClient | null

      Get the underlying Browser client (only available in browser mode).

      Useful for accessing browser-specific features and low-level page manipulation.

      Returns XTBBrowserClient | null

      Browser client instance or null if in WebSocket mode

    • get ws(): XTBWebSocketClient | null

      Get the underlying WebSocket client (only available in WebSocket mode).

      Useful for accessing WebSocket-specific features like event listeners, raw protocol methods, and real-time subscriptions.

      Returns XTBWebSocketClient | null

      WebSocket client instance or null if in browser mode

      const ws = client.ws;
      if (ws) {
      ws.on('tick', (tick) => console.log('Price update:', tick));
      ws.on('position', (pos) => console.log('Position update:', pos));
      }

    Methods

    • Execute a BUY order for the specified symbol.

      ⚠️ WARNING: This executes real trades. Use demo accounts for testing.

      Parameters

      • symbol: string

        Symbol name (e.g., 'CIG.PL', 'AAPL.US')

      • volume: number

        Volume to buy (number of units)

      • Optionaloptions: TradeOptions

        Optional trade parameters (stop loss, take profit, etc.)

      Returns Promise<TradeResult>

      Trade execution result

      const result = await client.buy('CIG.PL', 100, {
      stopLoss: 2.40,
      takeProfit: 2.80
      });
      console.log(result.success ? 'Trade executed' : 'Trade failed');
    • Connect to XTB and authenticate if needed.

      For browser mode, this connects to Chrome via CDP. For WebSocket mode, this establishes WebSocket connection and performs CAS authentication.

      Returns Promise<void>

      Error if connection or authentication fails

    • Disconnect from XTB.

      Cleanly closes the connection and cleans up resources.

      Returns Promise<void>

    • Get the account number associated with this session.

      Returns Promise<number>

      Account number

      const accountNumber = await client.getAccountNumber();
      console.log(`Connected to account: #${accountNumber}`);
    • Get account balance and equity information.

      Returns Promise<AccountBalance>

      Account balance with equity, free margin, and currency

      const balance = await client.getBalance();
      console.log(`Balance: ${balance.balance} ${balance.currency}`);
      console.log(`Equity: ${balance.equity} ${balance.currency}`);
      console.log(`Free Margin: ${balance.freeMargin} ${balance.currency}`);
    • Get all open positions.

      Returns Promise<Position[]>

      Array of open positions with current P&L, stop loss, take profit, etc.

      const positions = await client.getPositions();
      for (const position of positions) {
      console.log(`${position.symbol}: ${position.volume} @ ${position.openPrice}`);
      }
    • Get current quote (bid/ask prices) for a symbol.

      Parameters

      Returns Promise<Quote | null>

      Current quote with bid, ask, spread, and optional high/low/time

      const quote = await client.getQuote('CIG.PL');
      if (quote) {
      console.log(`Bid: ${quote.bid}, Ask: ${quote.ask}, Spread: ${quote.spread}`);
      }
    • Search for financial instruments.

      Searches across 11,888+ available instruments by name or description.

      Parameters

      • query: string

        Search query (e.g., 'Apple', 'CIG', 'EUR/USD')

      Returns Promise<InstrumentSearchResult[]>

      Array of matching instruments with symbol keys, IDs, and descriptions

      const results = await client.searchInstrument('Apple');
      for (const instrument of results) {
      console.log(`${instrument.symbol} - ${instrument.description}`);
      }
    • Execute a SELL order for the specified symbol.

      ⚠️ WARNING: This executes real trades. Use demo accounts for testing.

      Parameters

      • symbol: string

        Symbol name (e.g., 'CIG.PL', 'AAPL.US')

      • volume: number

        Volume to sell (number of units)

      • Optionaloptions: TradeOptions

        Optional trade parameters (stop loss, take profit, etc.)

      Returns Promise<TradeResult>

      Trade execution result

      const result = await client.sell('CIG.PL', 100, {
      stopLoss: 2.80,
      takeProfit: 2.40
      });
      console.log(result.success ? 'Trade executed' : 'Trade failed');
    • Create a browser mode client instance.

      Parameters

      • cdpUrl: string

        Chrome DevTools Protocol WebSocket URL (e.g., 'ws://127.0.0.1:9222')

      • Optionaloptions: Omit<BrowserClientConfig, "cdpUrl">

        Additional browser client options

      Returns XTBClient

      New XTB client configured for browser mode

      const client = XTBClient.browser('ws://127.0.0.1:9222');
      await client.connect();
    • Create a WebSocket mode client instance.

      Parameters

      Returns XTBClient

      New XTB client configured for WebSocket mode

      const client = XTBClient.websocket({
      url: 'wss://api5demoa.x-station.eu/v1/xstation',
      accountNumber: 12345678,
      auth: {
      credentials: { email: 'user@example.com', password: 'password' }
      }
      });
      await client.connect();