XTQuant Quantitative Trading Platform Documentation

website·Indexed 32 days ago

http://dict.thinktrader.net/

Documentation for the XTQuant quantitative trading platform, featuring the XtData module for real-time and historical market data, the ContextInfo environment object, and API references for trading functions. It includes guides on factor data downloading, opType enumeration constants for transaction operations, and Python environment troubleshooting for quantitative strategies.

Tokens
43.8K
Snippets
194
Records
253
Agent score
58%

What's inside XTQuant

  1. Overview of XtQuant.XtData Market Data Module

    The xtdata module in the xtquant library provides a streamlined interface for quantitative traders to access market data, including historical and real-time K-lines, tick data, financial statements, contract basic information, and sector/industry classifications. It operates by establishing a connection with MiniQmt, which handles the data requests and returns results to the Python layer. Users should ensure MiniQmt has the required data (using download/supplement interfaces) before calling data retrieval interfaces.
  2. Overview of XTQuant AI Intelligent Assistant

    The XTQuant AI Intelligent Assistant integrates the XTQuant quantitative trading platform with AI capabilities, allowing the AI to directly access and operate quantitative trading data and functions. It supports various trading strategies including Grid strategies, ETF Rotation strategies, Single Stock Trend strategies, and Multi-factor strategies. The platform supports Built-in Python (PY), Native Python (PY), and VBA.
  3. Understand QMT trading interface and data synchronization

    QMT trading interfaces (such as passorder) are asynchronous to ensure high-speed execution. When a trade is requested, the function returns immediately without waiting for the order report or blocking the Python thread.

    Account information, positions, and order updates are managed by the client background and cached locally. Functions like get_trade_detail_data and trading callback functions read from this local cache, not directly from the broker's server. Cache refresh rates vary by broker (from 50ms for push-enabled brokers to 1-6 seconds for others). Consequently, there may be a delay between sending an order and seeing the updated status in the local cache.

  4. Retrieve instrument details and listing dates

    Retrieve basic information about a stock or instrument using the following methods:

    • ContextInfo.get_open_date('stockcode'): Returns the listing date of the stock as a number (e.g., 19910403).
    • ContextInfo.get_stock_name('stockcode'): Returns the name of the stock. Note: This function is deprecated. Use ContextInfo.get_instrument_detail("stockcode")["InstrumentName"] instead.

    For both methods, if stockcode is an empty string ' ', it defaults to the current chart's instrument.

    def init(ContextInfo):
        # Get listing date
        open_date = ContextInfo.get_open_date('000001.SZ')
        # Recommended way to get stock name
        name = ContextInfo.get_instrument_detail('000001.SZ')['InstrumentName']
  5. Understand the ContextInfo object

    ContextInfo is the strategy execution environment object passed as an argument to core methods like init, after_init, and handlebar. It contains built-in attributes and methods provided by the terminal.

    Important Caveat: It is generally not recommended to add custom attributes directly to the ContextInfo object because it is reset to the end-state of the previous bar whenever the bar switches. Use separate global variables for persistent storage instead.

  6. Download historical market data

    Historical data is required for strategy execution and indicator calculation. Data can be downloaded via three methods:

    1. Manual Download:

    • Go to the 'Market' (行情) interface $\rightarrow$ 'Historical Data Download' (历史数据下载) tab.
    • Select the data type (e.g., K-line, Tick, or Financial data) from the dropdown.
    • Define the data range and period, then click 'Supplement' (补充).

    2. Automated Scheduled Download:

    • Go to 'Market' (行情) $\rightarrow$ 'Scheduling Tasks' (调度任务) $\rightarrow$ 'New Plan' (新增方案).
    • Define the data category, select the target sectors/plates, and set the date range.
    • Set the execution time (recommended: after market close, e.g., 16:00) and click 'Apply'.

    3. Python API:

    • Use the download_history_data function to programmatically retrieve historical data.
  7. Manage trading calendars and holidays

    The module provides tools to handle trading days and holidays. You must call download_holiday_data() before attempting to retrieve future trading days via the calendar API.
    # 1. Download holiday data first
    xtdata.download_holiday_data()
    
    # 2. Get list of holiday dates (8-digit strings)
    holidays = xtdata.get_holidays()
    
    # 3. Get trading calendar for a specific market
    trading_days = xtdata.get_trading_calendar('SH', start_time='20230101', end_time='20231231')
  8. Download factor data using xtquant

    To download factor data, first update the factor list using download_metatable_data(). You can then retrieve the mapping of English table names to Chinese names via get_metatable_list(). Use download_history_data to download the specific factor data for a given instrument.
    from xtquant import xtdata
    
    # Update the factor list
    xtdata.download_metatable_data()
    
    # Get the factor mapping dictionary {English Name: Chinese Name}
    metainfo = xtdata.get_metatable_list()
    
    # Reverse the dictionary to {Chinese Name: English Name}
    metainfo_rev = {v:k for k,v in metainfo.items()}
    
    zn_factor_name = "质量类因子" 
    
    # Download data for a specific instrument (e.g., 'XXXXXX.XX')
    xtdata.download_history_data('XXXXXX.XX', metainfo_rev[zn_factor_name], '', '', incrementally=False)
  9. Use the handlebar function for event-driven logic

    The handlebar function is the primary event handler. It triggers once for every historical K-line (in chronological order) and once for every new tick received during real-time trading. It is used for calculating indicators, backtesting, and executing real-time orders. This is a system function and cannot be called manually.
    def handlebar(ContextInfo):
        # Output the current K-line position
        print(ContextInfo.barpos)
  10. Connect to a specific market data server

    You can connect to a specific server by providing a configuration dictionary containing the IP, port, username, and password. You can monitor the connection status using watch_quote_server_status.
    from xtquant import xtdata
    
    # Connection info (username/pwd optional for token-based connection)
    info = {"ip": '115.231.218.73', "port": 55300, "username": '', "pwd": ''}
    
    # Callback to monitor connection status
    def status_callback(d):
        print(f"Server {d.get('ip')} status: {d.get('status')}")
    
    xtdata.watch_quote_server_status(status_callback)
    
    # Establish connection
    qs = xtdata.QuoteServer(info)
    qs.connect()
  11. Install Xuntou Research platform

    Download the Xuntou Research (投研端) installer from the User Center after purchasing permissions. Two versions are available: the Stable version (recommended for reliability) and the Pioneer version (contains latest features but may be unstable).

    Installation Steps:

    1. Run the installer and follow the prompts.
    2. Crucial: Do not install the software on the C: drive to avoid permission issues. Select a different directory.
    3. If installation to the C: drive is mandatory, you must launch the application with Administrator privileges.

    File Location: The software executable and Python libraries are located in {Installation Directory}/bin.x64.

  12. Use the init function for strategy initialization

    The init function is called exactly once at the start of the strategy. It is primarily used for subscribing to market quotes and account information. Note that some interfaces, such as get_trading_dates, are unavailable until init has finished executing. This is a system function and cannot be called manually.
    # Example: Initializing a variable and subscribing to quotes
    def init(C):
        # C is the ContextInfo object
        C.initProfit = 0
        
        def my_callback_function(data):
            print(data)
            
        stock = '600000.SH'
        C.subscribe_quote(stock, period = '5m', callback = my_callback_function)
        print('init function execution complete')