XTP API Documentation

website·Indexed 31 days ago

https://10000l.github.io/

Developer documentation and sample code for XTP trading and market data APIs. Includes guides for the Trader API (TraderApi, TraderSpi) and Quote API (QuoteApi), covering Level 2 tick-by-tick data, UDP configurations, order placement, fund transfers, and specific trading logics for new stock and bond subscriptions.

Tokens
104.3K
Snippets
372
Records
596
Agent score
75%

What's inside XTP

  1. Overview of QuoteApi for market data management

    The QuoteApi class is the primary interface for interacting with the XTP market data system. It provides methods for API initialization, session management (Login/Logout), and managing subscriptions for market data, order books, and tick-by-tick data across different exchanges and instrument types (including options).
  2. Overview of XTP Trader API Paginated Query Functions

    The XTP Trader API provides paginated query functions for scenarios where a single query would return a very large number of results. The available paginated query functions include:

    • QueryOrdersByPage: Query orders by page.
    • QueryOrdersByPageEx: Extended query orders by page.
    • QueryTradesByPage: Query trades by page.
    • QueryOptionCombinedOrdersByPage: Query combined option orders by page.
    • QueryOptionCombinedOrdersByPageEx: Extended query combined option orders by page.
    • QueryOptionCombinedTradesByPage: Query combined option trades by page.

    All these functions generally follow the same pattern: they require a request parameter structure, a session_id, and a user-defined request_id.

  3. Overview of the XTP Trading Platform

    XTP is a high-speed trading platform focused on ultra-low latency market data and execution. It provides a comprehensive trading ecosystem consisting of the following core service areas:

    • Client Access Services: Provides trading API interfaces for quantitative and strategy system integration, as well as dedicated trading clients such as XClient and SmartX.
    • Core Trading Services: Offers a 24/7 simulation environment for interface testing, automated deployment during onboarding, ultra-fast market data (XQuote), high-speed trading services, risk management (RiskX), and trading algorithms (AlgoX).
    • Trading Support & Monitoring: Includes XMS and XMonitor for real-time trade monitoring and machine optimization/deployment, as well as trading data analysis and historical data backfilling services.
    • Client Evaluation Services: Uses FundX to analyze trading risk and return performance, providing investors with comprehensive evaluation data to assess quantitative private equity managers.
  4. Overview of TraderApi functionality

    The TraderApi class provides the core set of functions required to interact with the XTP trading system. Its primary capabilities include:

    • Lifecycle Management: Initializing the API, logging in/out, and releasing resources.
    • Order Management: Placing orders (InsertOrder), canceling orders (CancelOrder), and querying order status and history.
    • Account & Asset Tracking: Querying positions, assets, fund transfers, and ETF information.
    • Credit & Debt Management: Handling credit cash repayments, querying debt information, and managing credit-related assets.
    • Option Trading: Specialized methods for combined option orders and strategy queries.
    • Algorithmic Trading: Dedicated functions for ALGO login, strategy querying, and inserting/modifying algorithmic orders.
    • System Utilities: Retrieving the current trading day, API version, and error handling via GetApiLastError.
  5. XTP Quote-API Library Overview

    The XTP Quote-API provides asynchronous market data notifications. It consists of two primary interface classes: QuoteApi for sending subscription requests and QuoteSpi for handling callbacks. The library only supports 64-bit architectures; ensure the project and compiler are configured for 64-bit.
  6. Perform margin trading and securities lending (融资融券) in XTP

    XTP supports a full suite of margin trading and securities lending operations:

    • Trading Operations: Collateral purchase (担保品买入), collateral sale (担保品卖出), margin buying (融资买入), short selling (融券卖出), selling securities to repay (卖券还款), and buying securities to return (买券还券).
    • Non-Trading Operations: Cash repayment (现金还款), returning securities (现券还券), collateral transfer-in (担保品转入), collateral transfer-out (担保品转出), surplus securities transfer (余券划转), fund transfer (资金划拨), and new share subscription.
  7. Execute spot trading operations in XTP

    XTP supports spot trading for stocks, funds, and bonds. Supported assets include:

    • Stocks: Main board, SME board, ChiNext (创业板), and STAR Market (科创板).
    • Funds: Single-market stock ETFs, cross-market stock ETFs, Shanghai money market funds, bond ETFs, gold ETFs, and T0-type cross-border ETFs.
    • Bonds: Convertible bonds, treasury bonds, corporate bonds, and enterprise bonds.

    Non-trading operations include new share subscriptions, rights issues (配股), and bond allocations (配债). Fund transfers (资金划拨) are supported to Goldenwind (金证) or between trading nodes in dual-center deployments. Subscription and redemption are supported for single-market and cross-market stock ETFs in the Shanghai and Shenzhen markets.

  8. Enhance Markdown with vuepress-plugin-md-enhance

    The vuepress-plugin-md-enhance plugin provides advanced Markdown syntax and writing functions beyond the standard VuePress extensions. Supported enhancements include:

    • Interactive Elements: Tabs, Code Tabs, and Spoilers.
    • Academic/Technical Writing: TeX (mathematical formulas), Footnotes, Superscript, and Subscript.
    • Visuals & Diagrams: Mermaid, PlantUML, ECharts, Chart.js, Flowcharts, and MarkMap.
    • Styling: Text alignment, custom attributes (Attrs), marking text, and stylized content.
    • Interactive Code: Code Demos and Playgrounds (Vue, Kotlin, Sandpack).
    • Containers: Hint boxes and GFM alerts.
  9. XTP Tick-by-Tick (TBT) Data Structure Overview

    The XTPTBT (XTPTickByTickStruct) is the primary container for tick-by-tick data. It includes common metadata and a union that holds specific data for entrustments, trades, or status updates based on the type field.
    typedef struct XTPTickByTickStruct {
        XTP_EXCHANGE_TYPE exchange_id; // Exchange code
        char ticker[XTP_TICKER_LEN];   // Contract code (null-terminated)
        int64_t seq;                   // SH: Business sequence number; SZ: Meaningless
        int64_t data_time;              // Entrustment or Trade time
        XTP_TBT_TYPE type;             // Type: Entrustment, Trade, or Status
    
        union {
            XTPTickByTickEntrust entrust;
            XTPTickByTickTrade     trade;
            XTPTickByTickStatus    state;
        };
    } XTPTBT;
  10. XTPTradeReport structure reference

    The XTPTradeReport structure contains detailed information about a trade execution.
    struct XTPTradeReport
    {
        uint64_t                 order_xtp_id;      // Unique XTP system order ID
        uint32_t                 order_client_id;   // Order reference
        char                     ticker[XTP_TICKER_LEN]; // Contract code
        XTP_MARKET_TYPE          market;            // Trading market
        uint64_t                 local_order_id;     // Local order ID (duplicates order_xtp_id)
        char                     exec_id[XTP_EXEC_ID_LEN]; // Execution ID
        double                   price;             // Execution price
        int64_t                  quantity;           // Execution quantity (not cumulative)
        int64_t                  trade_time;         // Time: YYYYMMDDHHMMSSsss
        double                   trade_amount;      // Total amount (price * quantity)
        uint64_t                 report_index;       // Report sequence number
        char                     order_exch_id[XTP_ORDER_EXCH_LEN]; // Exchange order ID
        TXTPTradeTypeType        trade_type;         // Execution type
        union {
            uint32_t            u32;
            struct {
                XTP_SIDE_TYPE               side;            // Buy/Sell direction
                XTP_POSITION_EFFECT_TYPE    position_effect; // Open/Close flag
                uint8_t                     reserved1;
                uint8_t                     reserved2;
            };
        };
        XTP_BUSINESS_TYPE        business_type;      // Business type
        char                     branch_pbu[XTP_BRANCH_PBU_LEN]; // Exchange trader code
    };
  11. XTP Market Data Service Overview

    XQuote is a proprietary market data decoding and push server supporting SHL1, SHL2, SZL1, SZL2, and Beijing Stock Exchange data. It provides real-time data for stocks, funds, bonds, indices, and options. Note that historical data is not provided. Data is delivered via TCP or UDP (multicast), with UDP being the standard for production environments. Supported data types include market snapshots, Buy1/Sell1 order queues, tick-by-tick data, and order books.
  12. Implement market data callbacks with QuoteSpi

    The QuoteSpi class in the XTP::API namespace provides a set of virtual callback methods that developers must override to receive real-time market data, subscription responses, and connection notifications.

    Critical Performance Note: Most callback methods (especially data notifications) must return quickly. Blocking these methods can obstruct subsequent messages and may lead to a connection disconnect if the blockage is severe.

    namespace XTP {
        namespace API {
            class MyQuoteSpi : public QuoteSpi {
                // Override methods here
            };
        }
    }