### Complete Strategy Template Example Source: https://context7.com/fisher188/qmtpython_api/llms.txt Provides a full working example for strategy development, demonstrating initialization, data handling, and trading logic. This template serves as a starting point for building trading strategies within the QMT Python API. ```python #coding=utf-8 ``` -------------------------------- ### Example: Monitor Market Status and Get Minute K-line Source: https://github.com/fisher188/qmtpython_api/blob/main/数据字典.MD A practical example demonstrating how to monitor market status and retrieve the latest minute K-line data. ```APIDOC ## EXAMPLE: Monitor Market Status and Get Minute K-line ### Description This example shows how to subscribe to real-time market data, monitor the market time, and retrieve minute K-line data when the minute is about to end. ### Code ```python import pandas as pd from xtquant import xtdata market = 'SH' # Specify the market, e.g., 'SH' for Shanghai # Get the list of instrument codes in the specified market sector sl = xtdata.get_stock_list_in_sector(market) def on_data(datas): # Determine the current market time from the received data market_time = max([datas[i]["time"] for i in datas]) # Check if the time is near the end of the minute (e.g., >= 57 seconds) if market_time % 60 >= 57: print(f'Reached {market_time % 60} seconds, market_time: {market_time}') # Retrieve the minute K-line data for the instruments in the sector data = xtdata.get_full_kline([], sl, '1m') print(data) return # Subscribe to the whole quote for the specified market xtdata.subscribe_whole_quote([market], callback = on_data) # Keep the program running to receive data xtdata.run() ``` ``` -------------------------------- ### ContextInfo.get_financial_data() - Get Financial Data Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves financial data. This requires downloading financial data locally through the QMT client first. ```APIDOC ## GET /api/financial_data ### Description Retrieves financial data. Prior to using this function, ensure that financial data has been downloaded via the 'Interface Data Management - Financial Data' section in the QMT client. ### Method GET ### Endpoint `ContextInfo.get_financial_data()` ### Parameters This endpoint has two usage patterns with different parameters and return values. Please refer to the QMT documentation for specific parameter details for each usage. ### Request Example ```python # Example usage (specific parameters depend on the intended data) # C.get_financial_data(parameters_for_usage_1) # C.get_financial_data(parameters_for_usage_2) ``` ### Response #### Success Response (200) - Returns financial data. The structure and content depend on the specific parameters used for the call. Data includes Balance Sheet, Income Statement, Cash Flow Statement, Capital Structure, and per-share index data. Dates are in millisecond timestamp format, while other values are in currency units or percentages. ``` -------------------------------- ### XtQuant API Initialization and Setup Source: https://github.com/fisher188/qmtpython_api/blob/main/XtQuant文档.md This section covers the essential steps for initializing and setting up the XtQuant API, including creating an API instance, registering callbacks, starting the API environment, establishing a connection, and managing the API's lifecycle. ```APIDOC ## XtQuant API Setup ### Create API Instance ```python XtQuantTrader(path, session_id) ``` #### Description Creates an instance of the XtQuant API. #### Parameters - **path** (str) - Required - The full path to the MiniQMT client's `userdata_mini` directory. - **session_id** (int) - Required - The session ID for communication with MiniQMT. Ensure unique IDs for different sessions. #### Returns - An XtQuant API instance object. #### Notes - Subsequent operations on the XtQuant API require this instance. - Typically, only one XtQuant API instance needs to be created. #### Example ```python path = 'D:\\迅投极速交易终端 睿智融科版\\userdata_mini' # session_id is the session number, policy users should use different session numbers for different Python policies session_id = 123456 # The following examples will use this instance object xt_trader = XtQuantTrader(path, session_id) ``` ### Register Callback Class ```python register_callback(callback) ``` #### Description Registers a callback class instance with the API instance for message callbacks and real-time pushes. #### Parameters - **callback** (XtQuantTraderCallback) - Required - An instance of the callback class. #### Returns - None #### Notes - None #### Example ```python # Create a trading callback class object and declare to receive callbacks class MyXtQuantTraderCallback(XtQuantTraderCallback): ... pass callback = MyXtQuantTraderCallback() # xt_trader is the XtQuant API instance object xt_trader.register_callback(callback) ``` ### Prepare API Environment ```python start() ``` #### Description Starts the trading thread and prepares the environment required for trading. #### Parameters - None #### Returns - None #### Notes - None #### Example ```python # Start the trading thread # xt_trader is the XtQuant API instance object xt_trader.start() ``` ### Connect to MiniQMT ```python connect() ``` #### Description Connects to MiniQMT. #### Parameters - None #### Returns - Connection result information. Returns 0 on successful connection, non-zero otherwise. #### Notes - This connection is a one-time connection. It will not automatically reconnect after disconnection; you need to call this method again. #### Example ```python # Establish a trading connection, returning 0 indicates a successful connection # xt_trader is the XtQuant API instance object connect_result = xt_trader.connect() print(connect_result) ``` ### Stop API ```python stop() ``` #### Description Stops the API interface. #### Parameters - None #### Returns - None #### Notes - None #### Example ```python # xt_trader is the XtQuant API instance object xt_trader.stop() ``` ### Block Current Thread ```python run_forever() ``` #### Description Blocks the current thread, entering a waiting state until the `stop` function is called to end the blocking. #### Parameters - None #### Returns - None #### Notes - None #### Example ```python # xt_trader is the XtQuant API instance object xt_trader.run_forever() ``` ### Enable Relaxed Response Order ```python set_relaxed_response_order_enabled(enabled) ``` #### Description Controls whether the responses from actively requested interfaces are returned from a separate dedicated thread to achieve relaxed data timing. #### Parameters - **enabled** (bool) - Required - Whether to enable it. Defaults to `False` (disabled). #### Returns - None #### Notes - If enabled, calling synchronous request interfaces within push callbacks like `on_stock_order` will not block execution. However, the timing of queried and pushed data becomes uncertain. Example Scenario: ``` timeline t1 t2 t3 t4 callback push1 push2 push3 resp4 do query4 ------------------^ ``` For instance, if three order data arrive at times t1, t2, and t3, and a synchronous order query `query_orders()` is called within `on_push1`: - Without relaxed timing enabled, the query response `resp4` is processed at time t4, after `push3` completes. This blocks synchronous waiting queries. - With relaxed timing enabled, `resp4` is returned by a dedicated thread, allowing normal program execution. However, `resp4` reflects the state after `push3`, meaning the orders in `resp4` are newer than the data pushed at `push2` and `push3`. The processing starts earlier, around t1. - Use this feature based on your strategy's actual needs. It is generally recommended to use asynchronous versions of query interfaces (e.g., `query_stock_orders_async`) within push callbacks like `on_stock_order`. ``` -------------------------------- ### Get History Data Example Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md This Python example shows how to retrieve historical market data using the `get_history_data` function. It specifies the number of data points, the period (daily in this case), and the field (closing price). The function requires setting a universe of stocks first. The code assumes GBK encoding. ```python # coding = gbk def init(C): C.stock_list = ["000001.SZ","600519.SH", "510050.SH"] C.set_universe(C.stock_list) def handlebar(C): data = C.get_history_data(2, '1d', 'close') print(data) ``` -------------------------------- ### ContextInfo.get_open_date - Get stock listing date Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the listing date of a stock given its code. ```APIDOC ## ContextInfo.get_open_date ### Description Retrieves the listing date of a stock given its code. ### Method Various (contextual) ### Endpoint N/A (Method within ContextInfo) ### Parameters - **stockcode** (string) - Optional - The stock code (e.g., '000001.SZ'). Defaults to the current chart's stock code. ### Request Example ```python def init(ContextInfo): print(ContextInfo.get_open_date('000001.SZ')) ``` ### Response #### Success Response (number) - **listing_date** (number) - The listing date of the stock. #### Response Example ``` 20000101 ``` ``` -------------------------------- ### ContextInfo.get_option_detail_data - Get Option Detail Data Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves detailed information for a specified option contract. ```APIDOC ## ContextInfo.get_option_detail_data ### Description Retrieves detailed information for a specified option contract. If an empty string is provided for `optioncode`, it defaults to the option contract of the current main chart. ### Method Builtin Python function ### Endpoint `ContextInfo.get_option_detail_data(optioncode)` ### Parameters #### Path Parameters - **optioncode** (string) - Required - The option contract code, e.g., '10001506.SHO'. ### Request Example ```python #encoding:gbk def init(ContextInfo): pass def after_init(ContextInfo): print(ContextInfo.get_option_detail_data('10002235.SHO')) ``` ### Response #### Success Response (200) - **Return Value** (dict) - A dictionary containing detailed information about the option contract, including: - **ExchangeID** (str) - Option market code. - **InstrumentID** (str) - Option code. - **ProductID** (str) - Underlying product ID of the option. - **OpenDate** (int) - Issuance date. - **ExpireDate** (int) - Expiry date. - **PreClose** (float) - Previous closing price. - **SettlementPrice** (float) - Previous settlement price. - **UpStopPrice** (float) - Daily upper limit price. - **DownStopPrice** (float) - Daily lower limit price. - **LongMarginRatio** (float) - Long margin ratio. - **ShortMarginRatio** (float) - Short margin ratio. - **PriceTick** (float) - Minimum price fluctuation unit. - **VolumeMultiple** (int) - Contract multiplier. - **MaxMarketOrderVolume** (int) - Maximum order volume at daily limit price. - **MinMarketOrderVolume** (int) - Minimum order volume at daily limit price. - **MaxLimitOrderVolume** (int) - Maximum limit order volume. - **MinLimitOrderVolume** (int) - Minimum limit order volume. - **OptUnit** (int) - Option contract unit. - **MarginUnit** (float) - Option unit margin. - **OptUndlCode** (str) - Underlying security code of the option. - **OptUndlMarket** (str) - Underlying security market of the option. - **OptExercisePrice** (float) - Option strike price. - **NeeqExeType** (str) - NEEQ transfer type. - **OptUndlRiskFreeRate** (float) - Risk-free rate of the option underlying. - **OptUndlHistoryRate** (float) - Historical volatility of the option underlying. - **EndDelivDate** (int) - Option exercise termination date. - **optType** (str) - Option type. ``` -------------------------------- ### Get Local Data Example Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md This Python code snippet demonstrates how to fetch local data for a specific stock code within a given time range and period. It uses the `get_local_data` function and prints the retrieved data. The code assumes a GBK encoding. ```python # coding:gbk def init(C): pass def handlebar(C): data = C.get_local_data(stock_code='600000.SH',start_time='20220101',end_time='20220131',period='1d',divid_type='none') print(data) ``` -------------------------------- ### get_sector_list - Get sector directory information Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves a list of sectors and folders within a specified node. ```APIDOC ## get_sector_list ### Description Retrieves a list of sectors and folders within a specified node. ### Method GET (conceptual) ### Endpoint N/A (Function call) ### Parameters - **node** (string) - Optional - The name of the sector node. Defaults to the top-level directory (''). ### Request Example ```python get_sector_list('我的') ``` ### Response #### Success Response (list) - **info_list** (list of lists) - A list where the first inner list contains sector names and the second inner list contains folder names. Example: `[['我的自选'],['新建分类1']]`. #### Response Example ``` [['我的自选'], ['新建分类1']] ``` ``` -------------------------------- ### get_ipo_data - Get Daily IPO Information Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves daily new stock and bond subscription information. Can be filtered to return only stock or bond information. ```APIDOC ## GET /api/ipo_data ### Description Fetches daily information on new stock and bond subscriptions. The result is a dictionary containing details like subscription codes, names, and quantities. ### Method GET ### Endpoint /api/ipo_data ### Parameters #### Query Parameters - **type** (string) - Optional - Filters the results. If empty, returns both new stocks and bonds. If 'STOCK', returns only new stock information. If 'BOND', returns only new bond information. ### Response #### Success Response (200) - **dict** - A dictionary containing IPO data. #### Response Example ```json { "new_stocks": [...], "new_bonds": [...] } ``` ### Request Example ```python get_ipo_data() # Returns both new stocks and bonds get_ipo_data("STOCK") # Returns only new stock information get_ipo_data("BOND") # Returns only new bond information ``` ``` -------------------------------- ### ContextInfo.get_main_contract - Get Main Futures Contract Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the main contract for a given futures market. Supports real-time and backtesting modes. Requires downloading historical main contract data for historical queries. ```APIDOC ## ContextInfo.get_main_contract ### Description Retrieves the main contract for a given futures market. Supports real-time and backtesting modes. Requires downloading historical main contract data for historical queries. ### Method Builtin Python function ### Endpoint `ContextInfo.get_main_contract(codemarket, [date], [startDate], [endDate])` ### Parameters #### Path Parameters - **codemarket** (string) - Required - The contract and market, e.g., 'IF00.IF', 'zn00.SF'. - **date** (string) - Optional - The specific date to retrieve the main contract for (format: YYYYMMDD). - **startDate** (string) - Optional - The start date for retrieving main contracts (format: YYYYMMDD). - **endDate** (string) - Optional - The end date for retrieving main contracts (format: YYYYMMDD). ### Request Example ```python # coding:gbk def init(C): pass def handlebar(C): symbol1 = C.get_main_contract('IF00.IF') # Get current main contract symbol2 = C.get_main_contract('IF00.IF', '20190101') # Get main contract for a specific date symbol3 = C.get_main_contract('IF00.IF', '20181101', '20190101') # Get all main contracts within a date range print(symbol1, symbol2) print("="*10) print(symbol3) ``` ### Response #### Success Response (200) - **Return Value** (string) - The contract code of the main contract. ``` -------------------------------- ### Get Current Bar Index in Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Demonstrates how to get the current K-line index (bar position) in a backtest using ContextInfo.barpos in Python. This is a read-only integer value starting from 0. ```Python # coding:gbk def init(ContextInfo): pass def handlebar(ContextInfo): print(ContextInfo.barpos) ``` -------------------------------- ### Initialize and Execute Smart Algo with Parameters (Python) Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Demonstrates how to initialize algorithm parameters and then execute a smart trading order using these parameters. This example shows setting up `algoParam` dictionary with specific values for the 'VWAP' algorithm and subsequently calling `smart_algo_passorder`. It highlights the structure of `algoParam` and its role in automated trading execution. ```python #coding:gbk def init(ContextInfo): pass # Method 2: Using algoParam and smart_algo_passorder # Note: This method might not be supported by some older clients # Retrieve algorithm parameters print(get_smart_algo_param(['VWAP'])) # Define algorithm parameters algoParam={ 'm_dLimitOverRate': 0.25, # Volume Ratio 25% 'm_dMinAmountPerOrder':0, # Minimum Order Amount 'm_dMaxAmountPerOrder':10000, # Maximum Order Amount 'm_nStopTradeForOwnHiLow': 1, # Stop Trading on High/Low 'm_dMulitAccountRate':0.30, # Multi-Account Volume Ratio 'm_strCmdRemark': 'Investment Remark 1' # Investment Remark } # Execute the smart trading order smart_algo_passorder( 23, 1101, account, # Assuming 'account' is defined elsewhere '600000.SH', 12, 0, 10000, '', 2, # quickTrade 'Investment Remark', 'VWAP', "10:25:00", # Start Time "14:50:00", # End Time algoParam, # Algorithm Parameters ContextInfo ) ``` -------------------------------- ### Get Extended Data Rank Range with ext_data_rank_range in Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md The ext_data_rank_range function calculates the rank of an extended data value within a specified time range across all stocks. It requires the extended data name, stock code, start time, end time, and ContextInfo object. The function returns a Python dictionary. ```Python #coding:gbk def init(ContextInfo): print(ext_data_rank_range('mycci', '600000.SH','2022-08-02 12:12:30', '2023-08-02 12:12:30', ContextInfo)) ``` -------------------------------- ### Initialize QMT Data Center and Connect Source: https://github.com/fisher188/qmtpython_api/blob/main/XtQuant文档.md This snippet demonstrates how to initialize the QMT data center, set a data directory and token, configure market data options, and connect to the QMT data service. It includes setting preferred market data servers and K-line push settings. Dependencies include the 'xtquant' library. ```python from xtquant import xtdatacenter as xtdc ## 设置数据目录 xtdc.set_data_home_dir('data') ## 设置token token = "你的token" xtdc.set_token(token) ## 限定行情站点的优选范围 opt_list = [ '115.231.218.73:55310', '115.231.218.79:55310', '42.228.16.210:55300', '42.228.16.211:55300', '36.99.48.20:55300', '36.99.48.21:55300', ] xtdc.set_allow_optmize_address(opt_list) ## 开启指定市场的K线全推 xtdc.set_kline_mirror_markets(['SH', 'SZ', 'BJ']) ## 设置要初始化的市场列表 init_markets = [ 'SH', 'SZ', 'BJ', #'DF', 'GF', 'IF', 'SF', 'ZF', 'INE', #'SHO', 'SZO', ] xtdc.set_init_markets(init_markets) ## 初始化xtdc模块 xtdc.init(start_local_service = False) ## 监听端口 #xtdc.listen(port = 58620) listen_port = xtdc.listen(port = (58620, 58650)) #import code; code.interact(local = locals()) import xtquant.xtdata as xtdata xtdata.connect(port = listen_port) import code; code.interact(local = locals()) ``` -------------------------------- ### Get Local Market Data - Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves local historical market data. This function requires historical data to be pre-downloaded using download_history_data. It accepts parameters for stock code, start and end times, K-line period, dividend adjustment type, and the number of data points. The function returns a dictionary of market data. ```python ContextInfo.get_local_data( stock_code, start_time='', end_time='', period='1d', divid_type='none', count=-1) ``` -------------------------------- ### Initialize Trading Account - Python Source: https://context7.com/fisher188/qmtpython_api/llms.txt Sets up the connection to the trading account with credentials and defines the initial trading universe and benchmark. It configures the account ID, type, stock universe, and a benchmark for performance tracking. ```python def init(ContextInfo): """Initialize function called once at strategy startup""" # Set the trading account (replace with actual account info) ContextInfo.accountid = '8000000123' # Account ID from broker ContextInfo.accounttype = 'STOCK' # Options: 'STOCK', 'CREDIT', 'FUTURE' # Initialize stock universe for the strategy ContextInfo.universe = ['600000.SH', '000001.SZ', '000002.SZ'] # Set benchmark for performance comparison ContextInfo.set_benchmark('000300.SH') # CSI 300 Index # Initialize global variables ContextInfo.position_target = {} print("Strategy initialized successfully") ``` -------------------------------- ### POST /buy_open Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Places a futures order to buy and open a new position. Supports various pricing strategies. ```APIDOC ## POST /buy_open ### Description Places a futures order to buy and open a new position. Supports various pricing strategies. ### Method POST ### Endpoint /buy_open ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stockcode** (string) - Required - The futures contract code, e.g., 'IF1805.IF'. - **amount** (int) - Required - The number of lots to trade. - **style** (string) - Optional - The order pricing style. Defaults to 'LATEST'. Possible values: 'LATEST', 'FIX', 'HANG', 'COMPETE', 'MARKET', 'SALE1', 'BUY1'. - **price** (double) - Optional - The specific price for the order, used when style is 'FIX'. - **ContextInfo** (PythonObj) - Required - A Python object of type ContextInfo. - **accId** (string) - Optional - The account ID. ### Request Example ```python buy_open('IF1805.IF', 1, ContextInfo, '110476') buy_open('IF1805.IF', 1, 'COMPETE', ContextInfo, '110476') buy_open('IF1805.IF', 2, 'fix', 3750, ContextInfo, '110476') ``` ### Response #### Success Response (200) This endpoint does not return any specific data upon success. #### Response Example None ``` -------------------------------- ### GET /get_closed_compacts Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves a detailed list of closed liability contracts for a given account. ```APIDOC ## GET /get_closed_compacts ### Description Retrieves a detailed list of closed liability contracts for a given account. ### Method GET ### Endpoint /get_closed_compacts ### Parameters #### Query Parameters - **accountID** (string) - Required - The account ID for which to retrieve closed compacts. - **accountType** (string) - Required - The type of account, should be 'CREDIT'. ### Request Example ```json { "accountID": "6000000248", "accountType": "CREDIT" } ``` ### Response #### Success Response (200) - **list** (array) - A list of CStkUnclosedCompacts objects, each containing details of a closed liability contract. ##### CStkUnclosedCompacts Object - **m_strAccountID** (string) - Account ID. - **m_nBrokerType** (int) - Broker type (e.g., 1-Futures, 2-Stocks, 3-Credit). - **m_strExchangeID** (string) - Market exchange ID. - **m_strInstrumentID** (string) - Security code. - **m_eCompactType** (int) - Compact type (e.g., 32-Unlimited, 48-Financing, 49-Securities Lending). - **m_eCashgroupProp** (int) - Position source (e.g., 32-Unlimited, 48-Normal, 49-Special). - **m_nOpenDate** (int) - Open date in YYYYMMDD format. - **m_nBusinessVol** (int) - Volume of securities in the contract. - **m_nRetEndDate** (int) - Expiry date in YYYYMMDD format. - **m_nDateClear** (int) - Clearance date in YYYYMMDD format. - **m_nEntrustVol** (int) - Entrusted volume. - **m_dEntrustBalance** (float) - Entrusted balance. - **m_dBusinessBalance** (float) - Contract balance. - **m_dBusinessFare** (float) - Contract fee. - **m_dRepaidFare** (float) - Repaid fee. - **m_dRepaidBalance** (float) - Repaid balance. - **m_strCompactId** (string) - Compact ID. - **m_strEntrustNo** (string) - Entrustment number. - **m_strPositionStr** (string) - Position string. #### Response Example ```json [ { "m_strAccountID": "6000000248", "m_nBrokerType": 3, "m_strExchangeID": "SZ", "m_strInstrumentID": "000002.SZ", "m_eCompactType": 48, "m_eCashgroupProp": 48, "m_nOpenDate": 20230101, "m_nBusinessVol": 100, "m_nRetEndDate": 20231231, "m_nDateClear": 20231231, "m_nEntrustVol": 0, "m_dEntrustBalance": 0.0, "m_dBusinessBalance": 10000.0, "m_dBusinessFare": 5.0, "m_dRepaidFare": 0.0, "m_dRepaidBalance": 0.0, "m_strCompactId": "C12345", "m_strEntrustNo": "E67890", "m_strPositionStr": "POS1" } ] ``` ``` -------------------------------- ### Event-Driven Trading - Subscribe Example Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Demonstrates an event-driven trading strategy using the `subscribe_quote` function. This example sets up real-time quote subscriptions for specified stocks and defines a callback function to process incoming market data. The callback calculates the stock's percentage change and places a buy order if the change is positive and the stock hasn't been bought yet. Note that the order placement function (`passorder`) is commented out for safety and requires actual testing. ```python #coding:gbk class a():pass A = a() A.bought_list = [] account = 'testaccount' def init(C): #下单函数的参数需要 ContextInfo对象 在init中定义行情回调函数 可以用到init函数的入参 不用手动传入 def callback_func(data): #print(data) for stock in data: current_price = data[stock]['close'] pre_price = data[stock]['preClose'] ratio = current_price / pre_price - 1 print(stock, C.get_stock_name(stock), '当前涨幅', ratio) if ratio > 0 and stock not in A.bought_list: msg = f"当前涨幅 {ratio} 大于0 买入100股" print(msg) #下单函数passorder 安全起见处于注释状态 需要实际测试下单交易时再放开 #passorder(23, 1101, account, stock, 5, -1, 100, '订阅下单示例', 2, msg, C) A.bought_list.append(stock) stock_list = ['600000.SH', '000001.SZ'] for stock in stock_list: C.subscribe_quote(stock, period = '1d', callback = callback_func) ``` -------------------------------- ### Live Trading Example (Python - Placeholder) Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md This is a placeholder for a live trading example using the handlebar function in Python. The actual implementation would involve real-time market data handling and order execution. Further details and specific API calls for live trading would be required. ```python #coding:gbk ``` -------------------------------- ### ContextInfo.get_contract_multiplier - Get Contract Multiplier Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the multiplier for a given futures contract code. ```APIDOC ## ContextInfo.get_contract_multiplier ### Description Retrieves the multiplier for a given futures contract code. ### Method Builtin Python function ### Endpoint `ContextInfo.get_contract_multiplier(contractcode)` ### Parameters #### Path Parameters - **contractcode** (string) - Required - The contract code, format: 'code.market', e.g., 'IF1707.IF'. ### Request Example ```python # coding:gbk def init(C): pass def handlebar(C): multiplier = C.get_contract_multiplier("rb2401.SF") print(multiplier) ``` ### Response #### Success Response (200) - **Return Value** (int) - The contract multiplier. ``` -------------------------------- ### Symbol Examples Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Provides examples of symbol formats for various exchanges and instrument types, including futures and options. ```APIDOC ## Symbol Examples This section provides examples of symbol formats for different markets and instrument types. | Market Name (Chinese) | Market Code | Example Symbol | Display Suffix | Security Abbreviation | |-----------------------|-------------|----------------|----------------|-----------------------| | Shanghai Stock Exchange | SH | 600000.SH | SH | Pudong Development Bank | | Shenzhen Stock Exchange | SZ | 000001.SZ | SZ | Ping An Bank | | Beijing Stock Exchange | BJ | 830779.BJ | BJ | Wuhan Blue Electric | | China Financial Futures Exchange | IF | IC2311.IF | CFFEX | CSI 500 Index November 2023 Futures Contract | | Shanghai Futures Exchange | SF | rb2311.SF | SHFE | Rebar November 2023 Futures Contract | | Dalian Commodity Exchange | DF | m2311.DF | DCE | Soybean Meal November 2023 Futures Contract | | Zhengzhou Commodity Exchange | ZF | FG305.ZF | CZCE | Glass May 2023 Futures Contract | | Shanghai International Energy Exchange | INE | sc2311.INE | INE | Crude Oil November 2023 Futures Contract | | Guangzhou Futures Exchange | GF | lc2405.GF | GFEX | Lithium Carbonate May 2024 Futures Contract | | SSE Options | SHO | 10005334.SHO | SH | 50ETF Call December 2650 | | SZSE Options | SZO | 90002114.SZO | SZ | SZSE 100 ETF Put December 2700 | | Sector Index | BKZS | 290001.BKZS | BKZS | Industrial Futures Sector Index | ``` -------------------------------- ### POST /sell_open Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Places a futures order to sell and open a new position. Supports various pricing strategies. ```APIDOC ## POST /sell_open ### Description Places a futures order to sell and open a new position. Supports various pricing strategies. ### Method POST ### Endpoint /sell_open ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **stockcode** (string) - Required - The futures contract code, e.g., 'IF1805.IF'. - **amount** (int) - Required - The number of lots to trade. - **style** (string) - Optional - The order pricing style. Defaults to 'LATEST'. Possible values: 'LATEST', 'FIX', 'HANG', 'COMPETE', 'MARKET', 'SALE1', 'BUY1'. - **price** (double) - Optional - The specific price for the order, used when style is 'FIX'. - **ContextInfo** (PythonObj) - Required - A Python object of type ContextInfo. - **accId** (string) - Optional - The account ID. ### Request Example ```python sell_open('IF1805.IF', 1, ContextInfo, '110476') sell_open('IF1805.IF', 1, 'COMPETE', ContextInfo, '110476') sell_open('IF1805.IF', 2, 'fix', 3750, ContextInfo, '110476') ``` ### Response #### Success Response (200) This endpoint does not return any specific data upon success. #### Response Example None ``` -------------------------------- ### Set Backtest Start and End Times in Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Demonstrates how to set the start and end times for a backtest using the ContextInfo object in Python. This is crucial for defining the data range for strategy evaluation. The format required is 'YYYY-MM-DD HH:MM:SS'. ```Python # coding:gbk def init(ContextInfo): ContextInfo.start = "2017-01-01 00:00:00"# 回测开始时间为 2017-01-01 ContextInfo.end = "2020-01-01 00:00:00"# 回测结束时间为 2020-01-01 def handlebar(ContextInfo): # 打印输出当前回测时间 print(timetag_to_datetime(ContextInfo.get_bar_timetag(ContextInfo.barpos), "%Y-%m-%d %H%M%S")) ``` -------------------------------- ### get_comb_option - Get Option Combination Position Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the holdings of option combination positions for a given account. ```APIDOC ## get_comb_option ### Description Retrieves the holdings of option combination positions for a given account. ### Method `get_comb_option(accountID)` ### Parameters - `accountID` (string) - Required - The account ID. ### Response - Returns a list of `CStkOptCombPositionDetail` objects. ### Request Example ```python obj_list = get_comb_option('880399990383') print(len(obj_list)) for obj in obj_list: print(obj.m_strCombCodeName, obj.m_strCombID, obj.m_nVolume, obj.m_nFrozenVolume) ``` ``` -------------------------------- ### Initialize and Connect QMT Trader in Python Source: https://github.com/fisher188/qmtpython_api/blob/main/XtQuant文档.md This code snippet demonstrates the initialization of the XtQuantTrader, setting up the path to the user data directory, and establishing a connection to the trading system. It also includes subscribing to account updates and querying stock assets. ```python if __name__ == '__main__': print("start") # 指定客户端所在路径, 券商端指定到 userdata_mini文件夹 # 注意:如果是连接投研端进行交易,文件目录需要指定到f""安装目录"\userdata" path = r'D:\qmt\投研\迅投极速交易终端睿智融科版\userdata' # 生成session id 整数类型 同时运行的策略不能重复 session_id = int(time.time()) xt_trader = XtQuantTrader(path, session_id) # 开启主动请求接口的专用线程 开启后在on_stock_xxx回调函数里调用XtQuantTrader.query_xxx函数不会卡住回调线程,但是查询和推送的数据在时序上会变得不确定 # 详见: http://docs.thinktrader.net/vip/pages/ee0e9b/#开启主动请求接口的专用线程 # xt_trader.set_relaxed_response_order_enabled(True) # 创建资金账号为 800068 的证券账号对象 股票账号为STOCK 信用CREDIT 期货FUTURE acc = StockAccount('2000128', 'STOCK') # 创建交易回调类对象,并声明接收回调 callback = MyXtQuantTraderCallback() xt_trader.register_callback(callback) # 启动交易线程 xt_trader.start() # 建立交易连接,返回0表示连接成功 connect_result = xt_trader.connect() print('建立交易连接,返回0表示连接成功', connect_result) # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功 subscribe_result = xt_trader.subscribe(acc) print('对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功', subscribe_result) #取账号信息 account_info = xt_trader.query_stock_asset(acc) #取可用资金 available_cash = account_info.m_dCash print(acc.account_id, '可用资金', available_cash) #查账号持仓 positions = xt_trader.query_stock_positions(acc) #取各品种 总持仓 可用持仓 position_total_dict = {i.stock_code : i.m_nVolume for i in positions} position_available_dict = {i.stock_code : i.m_nCanUseVolume for i in positions} print(acc.account_id, '持仓字典', position_total_dict) print(acc.account_id, '可用持仓字典', position_available_dict) ``` -------------------------------- ### get_option_subject_position - Get Option Underlying Position Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the holdings of option underlying assets for a given account. ```APIDOC ## get_option_subject_position ### Description Retrieves the holdings of option underlying assets for a given account. ### Method `get_option_subject_position(accountID)` ### Parameters - `accountID` (string) - Required - The account ID. ### Response - Returns a list of `CLockPosition` objects. ### Request Example ```python data = get_option_subject_position('880399990383') print(len(data)) for obj in data: print(obj.m_strInstrumentName, obj.m_lockVol, obj.m_coveredVol) ``` ``` -------------------------------- ### Initialize QMT API with ContextInfo Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md The `init` function is called once at the beginning of a strategy's execution. It's used for initial setup tasks such as subscribing to market data and account information. Any operations before `init` completes, like fetching trading dates, may not be available. The `ContextInfo` object passed to `init` can be used to store global variables for the strategy. ```python #coding:gbk def init(C): #init函数入参为ContextInfo对象 定义时可以选择更简短的形参名 如C #在init函数中 可以进行 订阅行情的操作 #如需在行情回调函数中下单 下单函数需要传入ContextInfo对象 可以通过在init中定义回调函数 来使用外层的ContextInfo def my_callback_function(data): #自定义行情回调函数 入参为指数据字典 print(data) stock = '600000.SH' C.subscribe_quote(stock, period = '5m', callback = my_callback_function) #init函数执行完成后 print('init函数执行完成') ``` -------------------------------- ### ContextInfo.get_contract_expire_date - Get Futures Contract Expiry Date Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the expiry date for a given futures contract. ```APIDOC ## ContextInfo.get_contract_expire_date ### Description Retrieves the expiry date for a given futures contract. ### Method Builtin Python function ### Endpoint `ContextInfo.get_contract_expire_date(codemarket)` ### Parameters #### Path Parameters - **Codemarket** (string) - Required - The contract and market, e.g., 'IF00.IF', 'zn00.SF'. ### Request Example ```python # coding:gbk def init(C): pass def handlebar(C): data = C.get_contract_expire_date("IF2311.IF") print(data) ``` ### Response #### Success Response (200) - **Return Value** (string) - The expiry date of the contract. ``` -------------------------------- ### Subscribe to 1-Minute K-Line Data for All Stocks in Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Subscribes to real-time 1-minute K-line data for all stocks in the '沪深A股' sector. Requires VIP privileges and the `qmtpython` API. The `call_back` function is used to process incoming data. ```python #coding:gbk import pandas as pd import numpy as np def init(C): stock_list = C.get_stock_list_in_sector("沪深A股") sub_num_dict = {i:C.subscribe_quote( stock_code = i, period = '1m', dividend_type = 'none', result_type = 'dict', # 回调函数的行情数据格式 callback = call_back # 指定一个自定义的函数接收行情,自定义的函数只能有一个位置参数 ) for i in stock_list} def call_back(data): print(data) ``` -------------------------------- ### Create Option Combination Source: https://github.com/fisher188/qmtpython_api/blob/main/迅投QMT极速策略交易系统_模型资料_Python_API_说明文档_Python3.md Creates an option combination strategy. It takes parameters like quantity, option details, direction, account ID, strategy name, remark, and context information. The example demonstrates setting up a bull spread strategy. ```python 1 ContextInfo.accid='880399990383' 2 make_option_combination(50, {'10003006.SHO':48,'10003259.SHO':49},1,ContextInfo.accid,'stragegyName','str Remark',ContextInfo); ``` -------------------------------- ### Get Backtest Benchmark - Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md Retrieves the code of the backtesting benchmark. This attribute is only available in backtesting mode and is read-only. ```python # coding:gbk def init(ContextInfo): pass def handlebar(ContextInfo): print(ContextInfo.benchmark) ``` -------------------------------- ### Place Orders Immediately or After Bar Close using Python Source: https://github.com/fisher188/qmtpython_api/blob/main/内置Python.md This Python snippet demonstrates how to place orders using the `passorder` function, differentiating between immediate execution (using the latest price or a limit price) and execution after the current bar closes. It also shows how to place an order based on a monetary amount. ```python #coding:gbk c = 0 s = '000001.SZ' def init(ContextInfo): # 立即下单 用最新价买入股票s 100股,且指定投资备注 passorder(23,1101,account,s,5,0,100,'1',2,'tzbz',ContextInfo) pass def handlebar(ContextInfo): if not ContextInfo.is_last_bar(): #历史k线不应该发出实盘信号 跳过 return if ContextInfo.is_last_bar(): global c c +=1 if c ==1: # 用14.00元限价买入股票s 100股 passorder(23,1101,account,s,11,14.00,100,1,ContextInfo) # 当前k线为最新k线 则立即下单 # 用最新价限价买入股票s 100股 passorder(23,1101,account,s,5,-1,100,0,ContextInfo) # K线走完下单 # 用最新价限价买入股票s 1000元 passorder(23, 1102, account, s, 5, 0,1000, 2, ContextInfo) # 不管是不是最新K线,立即下单 ```