Skip to content

PHP wrapper for the X-Trade Brokers (XTB) xStation5 Trading API, supporting real-time streaming and simple commands via socket.

License

Notifications You must be signed in to change notification settings

timirey/xapi-php

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

XTB Online Investing

Tests Latest Stable Version Total Downloads License

This PHP library provides a comprehensive and user-friendly interface for interacting with the X-Trade Brokers (XTB) xStation5 Trading API. It supports a wide range of functionalities, including account management, trade execution, market data retrieval, and real-time streaming commands via socket, making it an ideal tool for developers looking to integrate advanced trading features and live market data into their applications.

Table of contents

Installation

Install the package via Composer.

composer require timirey/xapi-php

Usage

Basic usage example.

use Timirey\XApi\Client;
use Timirey\XApi\Enums\Host;
use Timirey\XApi\Responses\GetCalendarResponse;
use Timirey\XApi\Responses\LoginResponse;
use Timirey\XApi\Responses\LogoutResponse;

/**
 * @var Client
 */
$client = new Client(
    host: Host::DEMO
);

/**
 * @var LoginResponse $loginResponse
 */
$loginResponse = $client->login(
    userId: 123456789, 
    password: 'password'
);

/**
 * @var GetCalendarResponse $getCalendarResponse
 */
$getCalendarResponse = $client->getCalendar();

/**
 * @var LogoutResponse $logoutResponse
 */
$logoutResponse = $client->logout();

Subscribe to a stream channel.

use Timirey\XApi\Responses\GetTickPricesStreamResponse;
use Timirey\XApi\Responses\Data\TickStreamRecord;
use Timirey\XApi\Responses\LoginResponse;
use Timirey\XApi\Enums\StreamHost;
use Timirey\XApi\StreamClient;
use Timirey\XApi\Enums\Host;
use Timirey\XApi\Client;

/**
 * @var Client
 */
$client = new Client(
    host: Host::DEMO
);

/**
 * @var LoginResponse $loginResponse
 */
$loginResponse = $client->login(
    userId: 123456789, 
    password: 'password'
);

/**
 * @var string $streamSessionId
 */
$streamSessionId = $loginResponse->streamSessionId;

/**
 * @var $streamClient StreamClient
 */
$streamClient = new StreamClient(
    streamSessionId: $streamSessionId,
    host: StreamHost::DEMO
);

// Meant to be a daemon, run as separate process.
$streamClient->getTickPrices(
    symbol: 'EURUSD',
    callback: static function (GetTickPricesStreamResponse $tickPricesStreamResponse): void {
        /**
         * @var TickStreamRecord $tickStreamRecord
         */
        $record = $tickPricesStreamResponse->tickStreamRecord;
    }
);

// Unreachable code.

Available commands

Request-Reply commands are performed on main connection socket. The reply is sent by main connection socket.

Logs in to the xStation5 API.

use Timirey\XApi\Responses\LoginResponse;
use Timirey\XApi\Client;

/** 
 * @var LoginResponse $response 
 * @var Client $client
 */
$response = $client->login(
    userId: 123456789, 
    password: 'password'
);

Logs out from the xStation5 API.

use Timirey\XApi\Responses\LogoutResponse;
use Timirey\XApi\Client;

/** 
 * @var LogoutResponse $response
 * @var Client $client
 */
$response = $client->logout();

Available streaming commands

Allows to get actual account indicators values in real-time, as soon as they are available in the system.

use Timirey\XApi\Responses\Data\BalanceStreamRecord;
use Timirey\XApi\Responses\GetBalanceStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getBalance(
    callback: static function (GetBalanceStreamResponse $response): void {
        /**
         * @var BalanceStreamRecord $record
         */
        $record = $response->balanceStreamRecord;
    }
);

Subscribes for and unsubscribes from API chart candles. The interval of every candle is 1 minute. A new candle arrives every minute.

use Timirey\XApi\Responses\Data\CandleStreamRecord;
use Timirey\XApi\Responses\GetCandlesStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getCandles(
    symbol: 'EURUSD',
    callback: static function (GetCandlesStreamResponse $response): void {
        /**
         * @var CandleStreamRecord $record
         */
        $record = $response->candleStreamRecord;
    }
);

Subscribes for and unsubscribes from 'keep alive' messages. A new 'keep alive' message is sent by the API every 3 seconds.

use Timirey\XApi\Responses\Data\KeepAliveStreamRecord;
use Timirey\XApi\Responses\GetKeepAliveStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getKeepAlive(
    callback: static function (GetKeepAliveStreamResponse $response): void {
        /**
         * @var KeepAliveStreamRecord $record
         */
        $record = $response->keepAliveStreamRecord;
    }
);

Subscribes for and unsubscribes from news.

use Timirey\XApi\Responses\Data\NewsStreamRecord;
use Timirey\XApi\Responses\GetNewsStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getNews(
    callback: static function (GetNewsStreamResponse $response): void {
        /**
         * @var NewsStreamRecord $record
         */
        $record = $response->newsStreamRecord;
    }
);

Subscribes for and unsubscribes from profits.

use Timirey\XApi\Responses\Data\ProfitStreamRecord;
use Timirey\XApi\Responses\GetProfitsStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getProfits(
    callback: static function (GetProfitsStreamResponse $response): void {
        /**
         * @var ProfitStreamRecord $record
         */
        $record = $response->profitStreamRecord;
    }
);

Establishes subscription for quotations and allows to obtain the relevant information in real-time, as soon as it is available in the system.

use Timirey\XApi\Responses\Data\TickStreamRecord;
use Timirey\XApi\Responses\GetTickPricesStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getTickPrices(
    symbol: 'EURUSD',
    callback: static function (GetTickPricesStreamResponse $response): void {
        /**
         * @var TickStreamRecord $record
         */
        $record = $response->tickStreamRecord;
    },
    maxLevel: 1,
    minArrivalTime: 200
);

Establishes subscription for user trade status data and allows to obtain the relevant information in real-time, as soon as it is available in the system.

use Timirey\XApi\Responses\Data\TradeStreamRecord;
use Timirey\XApi\Responses\GetTradesStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getTrades(
    callback: static function (GetTradesStreamResponse $response): void {
        /**
         * @var TradeStreamRecord $record
         */
        $record = $response->tradeStreamRecord;
    }
);

Allows to get status for sent trade requests in real-time, as soon as it is available in the system.

use Timirey\XApi\Responses\Data\TradeStatusStreamRecord;
use Timirey\XApi\Responses\GetTradeStatusStreamResponse;
use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->getTradeStatus(
    callback: static function (GetTradeStatusStreamResponse $response): void {
        /**
         * @var TradeStatusStreamRecord $record
         */
        $record = $response->tradeStatusStreamRecord;
    }
);

Regularly calling this function is enough to refresh the internal state of all the components in the system.

use Timirey\XApi\StreamClient;

/**
 * @var StreamClient $streamClient
 */
$streamClient->ping();

Retrieving trading data

Retrieves information about all symbols.

use Timirey\XApi\Responses\GetAllSymbolsResponse;
use Timirey\XApi\Client;

/** 
 * @var GetAllSymbolsResponse $response 
 * @var Client $client
 */
$response = $client->getAllSymbols();

Returns a calendar with market events.

use Timirey\XApi\Responses\GetCalendarResponse;
use Timirey\XApi\Client;

/** 
 * @var GetCalendarResponse $response 
 * @var Client $client
 */
$response = $client->getCalendar();

Returns chart info from the start date to the current time.

use Timirey\XApi\Responses\GetChartLastRequestResponse;
use Timirey\XApi\Client;
use Timirey\XApi\Payloads\Data\ChartLastInfoRecord;
use Timirey\XApi\Enums\Period;
use DateTime;

$chartLastInfoRecord = new ChartLastInfoRecord(
    period: Period::PERIOD_M1,
    start: new DateTime('-1 week'),
    symbol: 'EURUSD'
);

/** 
 * @var GetChartLastRequestResponse $response 
 * @var Client $client
 */
$response = $client->getChartLastRequest(
    chartLastInfoRecord: $chartLastInfoRecord
);

Returns chart info from the start date to the current time.

use Timirey\XApi\Responses\GetChartRangeRequestResponse;
use Timirey\XApi\Client;
use Timirey\XApi\Payloads\Data\ChartRangeInfoRecord;
use Timirey\XApi\Enums\Period;
use DateTime;

$chartRangeInfoRecord = new ChartRangeInfoRecord(
    period: Period::PERIOD_H1,
    start: new DateTime('-1 month'),
    end: new DateTime(),
    symbol: 'EURUSD',
    ticks: 1000
);

/** 
 * @var GetChartRangeRequestResponse $response 
 * @var Client $client
 */
$response = $client->getChartRangeRequest(
    chartRangeInfoRecord: $chartRangeInfoRecord
);

Returns the calculation of commission and rate of exchange.

use Timirey\XApi\Responses\GetCommissionDefResponse;
use Timirey\XApi\Client;

/** 
 * @var GetCommissionDefResponse $response 
 * @var Client $client
 */
$response = $client->getCommissionDef(
    symbol: 'EURUSD',
    volume: 1.0
);

Returns information about account currency and leverage.

use Timirey\XApi\Responses\GetCurrentUserDataResponse;
use Timirey\XApi\Client;

/** 
 * @var GetCurrentUserDataResponse $response 
 * @var Client $client
 */
$response = $client->getCurrentUserData();

Returns IBs data from the given time range.

use Timirey\XApi\Responses\GetIbsHistoryResponse;
use Timirey\XApi\Client;
use DateTime;

/** 
 * @var GetIbsHistoryResponse $response 
 * @var Client $client
 */
$response = $client->getIbsHistory(
    start: new DateTime('-1 month'),
    end: new DateTime()
);

Returns various account indicators.

use Timirey\XApi\Responses\GetMarginLevelResponse;
use Timirey\XApi\Client;

/** 
 * @var GetMarginLevelResponse $response 
 * @var Client $client
 */
$response = $client->getMarginLevel();

Returns expected margin for a given instrument and volume.

use Timirey\XApi\Responses\GetMarginTradeResponse;
use Timirey\XApi\Client;

/** 
 * @var GetMarginTradeResponse $response 
 * @var Client $client
 */
$response = $client->getMarginTrade(
    symbol: 'EURPLN', 
    volume: 1.0
);

Returns news from the trading server which were sent within a specified period.

use Timirey\XApi\Responses\GetNewsResponse;
use Timirey\XApi\Client;
use DateTime;

/** 
 * @var GetNewsResponse $response 
 * @var Client $client
 */
$response = $client->getNews(
    start: new DateTime('-1 month'), 
    end: new DateTime()
);

Calculates estimated profit for given deal data.

use Timirey\XApi\Responses\GetProfitCalculationResponse;
use Timirey\XApi\Client;
use Timirey\XApi\Enums\Cmd;

/** 
 * @var GetProfitCalculationResponse $response 
 * @var Client $client
 */
$response = $client->getProfitCalculation(
  closePrice: 1.3000, 
  cmd: Cmd::BUY, 
  openPrice: 1.2233, 
  symbol: 'EURPLN', 
  volume: 1.0
);

Returns the current time on the trading server.

use Timirey\XApi\Responses\GetServerTimeResponse;
use Timirey\XApi\Client;

/** 
 * @var GetServerTimeResponse $response 
 * @var Client $client
 */
$response = $client->getServerTime();

Returns a list of step rules for DMAs.

use Timirey\XApi\Responses\GetStepRulesResponse;
use Timirey\XApi\Client;

/** 
 * @var GetStepRulesResponse $response 
 * @var Client $client
 */
$response = $client->getStepRules();

Retrieves information about a specific symbol.

use Timirey\XApi\Responses\GetSymbolResponse;
use Timirey\XApi\Client;

/** 
 * @var GetSymbolResponse $response 
 * @var Client $client
 */
$response = $client->getSymbol(
    symbol: EURUSD
);

Returns an array of current quotations for given symbols.

use Timirey\XApi\Responses\GetTickPricesResponse;
use Timirey\XApi\Enums\Level;
use Timirey\XApi\Client;
use DateTime;

/**
 * @var GetTickPricesResponse $response
 * @var Client $client
 */
$response = $client->getTickPrices(
    level: Level::BASE, 
    symbols: ['EURPLN', 'AGO.PL'], 
    timestamp: new DateTime()
);

Returns an array of trades listed in orders argument.

use Timirey\XApi\Responses\GetTradeRecordsResponse;
use Timirey\XApi\Client;

/** 
 * @var GetTradeRecordsResponse $response 
 * @var Client $client
 */
$response = $client->getTradeRecords(
    orders: [7489839, 7489841]
);

Returns an array of user's trades.

use Timirey\XApi\Responses\GetTradesResponse;
use Timirey\XApi\Client;

/** 
 * @var GetTradesResponse $response 
 * @var Client $client
 */
$response = $client->getTrades(
    openedOnly: true
);

Returns an array of user's trades which were closed within a specified period.

use Timirey\XApi\Responses\GetTradesHistoryResponse;
use Timirey\XApi\Client;
use DateTime;

/** 
 * @var GetTradesHistoryResponse $response 
 * @var Client $client
 */
$response = $client->getTradesHistory(
    start: new DateTime('last month'), 
    end: new DateTime()
);

Returns quotes and trading times.

use Timirey\XApi\Responses\GetTradingHoursResponse;
use Timirey\XApi\Client;

/** 
 * @var GetTradingHoursResponse $response 
 * @var Client $client
 */
$response = $client->getTradingHours(
    symbols: ['EURPLN', 'AGO.PL']
);

Returns the current API version.

use Timirey\XApi\Responses\GetVersionResponse;
use Timirey\XApi\Client;

/** 
 * @var GetVersionResponse $response 
 * @var Client $client
 */
$response = $client->getVersion();

Regularly calling this function is enough to refresh the internal state of all the components in the system.

use Timirey\XApi\Responses\PingResponse;
use Timirey\XApi\Client;

/** 
 * @var PingResponse $response 
 * @var Client $client
 */
$response = $client->ping();

Starts a trade transaction.

use Timirey\XApi\Responses\TradeTransactionResponse;
use Timirey\XApi\Payloads\Data\TradeTransInfo;
use Timirey\XApi\Client;

$tradeTransInfo = new TradeTransInfo(
    cmd: Cmd::BUY,
    customComment: 'Test trade',
    expiration: new DateTime(),
    offset: 0,
    order: 0,
    price: 1.12345,
    sl: 1.12000,
    symbol: 'EURUSD',
    tp: 1.12500,
    type: Type::OPEN,
    volume: 1.0
);

/** 
 * @var TradeTransactionResponse $response 
 * @var Client $client
 */
$response = $client->tradeTransaction(
    tradeTransInfo: $tradeTransInfo
);

Returns the current transaction status.

use Timirey\XApi\Responses\TradeTransactionStatusResponse;
use Timirey\XApi\Client;

/** 
 * @var TradeTransactionStatusResponse $response 
 * @var Client $client
 */
$response = $client->tradeTransactionStatus(
    order: 123456
);

Error handling

Custom exceptions for handling request errors.

ErrorResponseException

Thrown when the API returns an error (e.g., invalid password). Provides error code and description.

use Timirey\XApi\Exceptions\ResponseException;
use Timirey\XApi\Enums\Host;
use Timirey\XApi\Client;

/** 
 * @var Client $client 
 */
$client = new Client(
    userId: 123456789, 
    password: 'invalidPassword', 
    host: Host::DEMO
);

try {
    $client->login();
} catch (ErrorResponseException $e) {
    echo ($e->getErrorCode()); // 'BE005'
    echo ($e->getErrorDescr()); // 'userPasswordCheck: Invalid login or password.'
}

All error codes and descriptions can be found in the official documentation.

InvalidResponseException

Thrown when a request fails and the API does not return a proper error response (e.g., invalid or incomplete response).

use \Timirey\XApi\Exceptions\InvalidResponseException;
use Timirey\XApi\Enums\Host;
use Timirey\XApi\Client;

/** 
 * @var Client $client 
 */
$client = new Client(
    userId: 123456789, 
    password: 'password', 
    host: Host::DEMO
);

try {
    $client->login();
} catch (InvalidResponseException $e) {
    echo ($e->getMessage()); // 'The response did not include a status.'
}

Testing

This package uses the PestPHP framework for testing.

./vendor/bin/pest

License

This library is open-sourced software licensed under the MIT license.

Reference

For more detailed documentation, please refer to the XTB xStation5 Trading API Documentation.

About

PHP wrapper for the X-Trade Brokers (XTB) xStation5 Trading API, supporting real-time streaming and simple commands via socket.

Topics

Resources

License

Stars

Watchers

Forks

Languages