### Create and Connect XtQuantTrader Instance Source: https://dict.thinktrader.net/nativeApi/code_examples.html This function initializes and starts the XtQuantTrader, then attempts to connect to the trading server. It subscribes to a given stock account. Returns the trader instance on successful connection, otherwise None. ```python def create_trader(xt_acc,path, session_id): trader = XtQuantTrader(path, session_id,callback=MyXtQuantTraderCallback()) trader.start() connect_result = trader.connect() trader.subscribe(xt_acc) return trader if connect_result == 0 else None ``` -------------------------------- ### Subscribe Full Push Data / Download Historical Data Source: https://dict.thinktrader.net/nativeApi/code_examples.html This example demonstrates how to subscribe to full push data, download historical data, and retrieve market data using the xtdata module. ```APIDOC ## Subscribe Full Push Data / Download Historical Data ### Description This code snippet shows how to fetch real-time full tick data, download historical data for a specified period, subscribe to real-time quotes with a callback function, and retrieve historical market data. ### Method Python script ### Code Example ```python # coding:utf-8 import time from xtquant import xtdata code = '600000.SH' # Get full tick data full_tick = xtdata.get_full_tick([code]) print('Full tick data Daily latest value', full_tick) # Download historical data (the interface itself does not return data) xtdata.download_history_data(code, period='1m', start_time='20230701') # Subscribe to latest quotes def callback_func(data): print('Callback triggered', data) xtdata.subscribe_quote(code, period='1m', count=-1, callback= callback_func) data = xtdata.get_market_data(['close'], [code], period='1m', start_time='20230701') print('One-time data retrieval', data) # Infinite loop to block the main thread from exiting xtdata.run() ``` ``` -------------------------------- ### Subscribe to Real-time Market Data and Place Orders Source: https://dict.thinktrader.net/nativeApi/code_examples.html This example shows how to subscribe to full real-time data for Shanghai and Shenzhen markets. It includes logic to buy 200 shares of A-shares if their current gain exceeds 9%. Ensure to update the client path and account number before running. ```python #coding:utf-8 import time, datetime, traceback, sys from xtquant import xtdata from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback from xtquant.xttype import StockAccount from xtquant import xtconstant #定义一个类 创建类的实例 作为状态的容器 class _a(): pass A = _a() A.bought_list = [] A.hsa = xtdata.get_stock_list_in_sector('沪深A股') def interact(): """执行后进入repl模式""" import code code.InteractiveConsole(locals=globals()).interact() xtdata.download_sector_data() def f(data): now = datetime.datetime.now() for stock in data: if stock not in A.hsa: continue cuurent_price = data[stock][0]['lastPrice'] pre_price = data[stock][0]['lastClose'] ratio = cuurent_price / pre_price - 1 if pre_price > 0 else 0 if ratio > 0.09 and stock not in A.bought_list: print(f"{now} 最新价 买入 {stock} 200股") async_seq = xt_trader.order_stock_async(acc, stock, xtconstant.STOCK_BUY, 200, xtconstant.LATEST_PRICE, -1, 'strategy_name', stock) A.bought_list.append(stock) class MyXtQuantTraderCallback(XtQuantTraderCallback): def on_disconnected(self): """ 连接断开 :return: """ print(datetime.datetime.now(),'连接断开回调') def on_stock_order(self, order): """ 委托回报推送 :param order: XtOrder对象 :return: """ print(datetime.datetime.now(), '委托回调', order.order_remark) def on_stock_trade(self, trade): """ 成交变动推送 :param trade: XtTrade对象 :return: """ print(datetime.datetime.now(), '成交回调', trade.order_remark) def on_order_error(self, order_error): """ 委托失败推送 :param order_error:XtOrderError 对象 :return: """ # print("on order_error callback") # print(order_error.order_id, order_error.error_id, order_error.error_msg) print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}") def on_cancel_error(self, cancel_error): """ 撤单失败推送 :param cancel_error: XtCancelError 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) def on_order_stock_async_response(self, response): """ 异步下单回报推送 :param response: XtOrderResponse 对象 :return: """ print(f"异步委托回调 {response.order_remark}") def on_cancel_order_stock_async_response(self, response): """ :param response: XtCancelOrderResponse 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) def on_account_status(self, status): """ :param response: XtAccountStatus 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) if __name__ == '__main__': print("start") #指定客户端所在路径, # 注意:如果是连接投研端进行交易,文件目录需要指定到f"{安装目录}\userdata" path = r'D:\qmt\sp3\迅投极速交易终端 睿智融科版\userdata_mini' # 生成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 的证券账号对象 acc = StockAccount('800068', '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) #这一行是注册全推回调函数 包括下单判断 安全起见处于注释状态 确认理解效果后再放开 # xtdata.subscribe_whole_quote(["SH", "SZ"], callback=f) # 阻塞主线程退出 xt_trader.run_forever() # 如果使用vscode pycharm等本地编辑器 可以进入交互模式 方便调试 (把上一行的run_forever注释掉 否则不会执行到这里) interact() ``` -------------------------------- ### Scheduled Real-time Judgment Example Source: https://dict.thinktrader.net/nativeApi/code_examples.html This snippet is a placeholder for a scheduled real-time judgment example. It imports necessary libraries for trading and data handling. ```python # coding:utf-8 import time, datetime, traceback, sys from xtquant import xtdata from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback from xtquant.xttype import StockAccount from xtquant import xtconstant ``` -------------------------------- ### Initialize Market Data Center Source: https://dict.thinktrader.net/nativeApi/code_examples.html Configure and initialize the data center for market data. This includes setting data directories, authentication tokens, preferred server addresses, and specifying which markets and data types to initialize. Use `xtdc.init()` to start the data center service. ```python if 1: 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()) ``` -------------------------------- ### Subscribe to Full Push Data and Download Historical Data Source: https://dict.thinktrader.net/nativeApi/code_examples.html?id=7zqjlm Demonstrates how to get full tick data, download historical data for a specified code and period, subscribe to real-time quotes, and retrieve market data. ```python # coding:utf-8 import time from xtquant import xtdata code = '600000.SH' #取全推数据 full_tick = xtdata.get_full_tick([code]) print('全推数据 日线最新值', full_tick) #下载历史数据 下载接口本身不返回数据 xtdata.download_history_data(code, period='1m', start_time='20230701') #订阅最新行情 def callback_func(data): print('回调触发', data) xtdata.subscribe_quote(code, period='1m', count=-1, callback= callback_func) data = xtdata.get_market_data(['close'], [code], period='1m', start_time='20230701') print('一次性取数据', data) #死循环 阻塞主线程退出 xtdata.run() ``` -------------------------------- ### Get Opposite Price Source: https://dict.thinktrader.net/nativeApi/code_examples.html This example demonstrates how to retrieve the opposite price (bid price) for a given stock code and handle cases where the bid price is zero by using the last price. ```APIDOC ## Get Opposite Price ### Description This snippet retrieves the full tick data for a list of stocks and calculates the opposite price. It uses the bid price as the opposite price, and if the bid price is 0 (indicating a limit-down situation), it defaults to the last traded price. ### Method Python script ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # For selling, take the bid price as the opposite price. If the bid price is 0, it means it has hit the limit down, so use the last price. import pandas as pd import numpy as np from xtquant import xtdata to_do_trade_list = ["000001.SZ"] tick = xtdata.get_full_tick(to_do_trade_list) # Take the bid price as the opposite price, if the bid price is 0, it means it has hit the limit down, so take the last price for i in tick: fix_price = tick[i]["bidPrice"][0] if tick[i]["bidPrice"][0] != 0 else tick[i]["lastPrice"] print(fix_price) ``` ### Response #### Success Response (200) - **fix_price** (float) - The calculated opposite price. #### Response Example ``` 10.01 ``` ``` -------------------------------- ### Get Opponent Price Source: https://dict.thinktrader.net/nativeApi/code_examples.html?id=7zqjlm Calculates the opponent price by taking the first bid price. If the first bid price is 0 (indicating a limit down), it uses the last price instead. ```python # 以卖出为例 import pandas as pd import numpy as np from xtquant import xtdata to_do_trade_list = ["000001.SZ"] tick = xtdata.get_full_tick(to_do_trade_list) # 取买一价为对手价,若买一价为0,说明已经跌停,则取最新价 for i in tick: fix_price = tick[i]["bidPrice"][0] if tick[i]["bidPrice"][0] != 0 else tick[i]["lastPrice"] print(fix_price) ``` -------------------------------- ### Test File Write Permissions Source: https://dict.thinktrader.net/nativeApi/question_function.html Use this code to verify if your system has the necessary file write permissions. If a 'PermissionError' occurs, it indicates a potential issue with running the client as an administrator, especially when installed on the C: drive. ```python file_path = r"d:\\qmt\\userdata_mini\\example.txt" # 设置文件路径和名称 # 使用open函数创建文件,并指定写入模式("w"表示写入模式) with open(file_path, "w") as file: file.write("123") # 向文件写入内容 ``` -------------------------------- ### Trading Strategy with MA Crossover and Reconnection Logic Source: https://dict.thinktrader.net/nativeApi/code_examples.html This example demonstrates a trading strategy based on moving average crossovers. It includes logic to ensure a persistent connection to the trading server by periodically checking and re-establishing the connection if lost. It also prevents duplicate orders. ```python if __name__ == "__main__": # 注意实际连接XtQuantTrader时不要写类似while True 这种无限循环的尝试,因为每次连接都会用session_id创建一个对接文件,这样就会占满硬盘导致电脑运行异常 # 要控制session_id在有限的范围内尝试,这里提供10个session_id供重连尝试 # 当所有session_id都尝试后,程序会抛出异常。实际使用过程中当session_id用完时,可以增加邮件等通知方式提醒人工处理 #指定客户端所在路径 path = 'E:\\qmt\\userdata_mini' xt_trader = None xt_acc = StockAccount('2000204') xt_trader = get_xttrader(xt_acc,path) if not xt_trader: raise Exception('交易接口连接失败') print('交易接口连接成功, 策略开始') stock = '513050.SH' xtdata.subscribe_quote(stock, '5m','','',count=-1) time.sleep(1) order_record = [] while '093000'<=time.strftime('%H%M%S')<'150000': time.sleep(3) xt_trader = get_xttrader(xt_acc,path) price = xtdata.get_market_data_ex(['close'],[stock],period='5m',)[stock] #计算均线 ma5 = price['close'].rolling(5).mean() ma10 = price['close'].rolling(10).mean() if ma5.iloc[-1]>ma5.iloc[-10]: t = price.index[-1] order_flag = (t, '买') if order_flag not in order_record: #防止重复下单 print(f'发起买入 {stock} k线时间:{t}') # 用最新价买100股 xt_trader.order_stock_async(xt_acc, stock, xtconstant.STOCK_BUY,100,xtconstant.LATEST_PRICE,0) order_record.append(order_flag) elif ma5.iloc[-1] 0 else 0 if ratio > 0.09 and stock not in A.bought_list: print(f"{now} 最新价 买入 {stock} 100股") async_seq = xt_trader.order_stock_async(acc, stock, xtconstant.STOCK_BUY, 100, xtconstant.LATEST_PRICE, -1, 'strategy_name', stock) A.bought_list.append(stock) class MyXtQuantTraderCallback(XtQuantTraderCallback): def on_disconnected(self): """ 连接断开 :return: """ print(datetime.datetime.now(), '连接断开回调') def on_stock_order(self, order): """ 委托回报推送 :param order: XtOrder对象 :return: """ print(datetime.datetime.now(), '委托回调', order.order_remark) def on_stock_trade(self, trade): """ 成交变动推送 :param trade: XtTrade对象 :return: """ print(datetime.datetime.now(), '成交回调', trade.order_remark) def on_order_error(self, order_error): """ 委托失败推送 :param order_error:XtOrderError 对象 :return: """ # print("on order_error callback") # print(order_error.order_id, order_error.error_id, order_error.error_msg) print(f"委托报错回调 {order_error.order_remark} {order_error.error_msg}") def on_cancel_error(self, cancel_error): """ 撤单失败推送 :param cancel_error: XtCancelError 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) def on_order_stock_async_response(self, response): """ 异步下单回报推送 :param response: XtOrderResponse 对象 :return: """ print(f"异步委托回调 {response.order_remark}") def on_cancel_order_stock_async_response(self, response): """ :param response: XtCancelOrderResponse 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) def on_account_status(self, status): """ :param response: XtAccountStatus 对象 :return: """ print(datetime.datetime.now(), sys._getframe().f_code.co_name) 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) #订阅的品种列表 code_list = ['600000.SH', '000001.SZ'] for code in code_list: xtdata.subscribe_quote(code, '1d', callback = f) # 阻塞主线程退出 xt_trader.run_forever() # 如果使用vscode pycharm等本地编辑器 可以进入交互模式 方便调试 (把上一行的run_forever注释掉 否则不会执行到这里) interact() ``` -------------------------------- ### Apply for Inventory Stock Lending (Async) Source: https://dict.thinktrader.net/nativeApi/xttrader.html Asynchronously applies for stock lending from inventory. Returns a sequence number (seq) for tracking the request. Use this when you need to initiate a lending request and receive a response later via `on_smt_appointment_async_response`. ```python smt_negotiate_order_async(self, account, src_group_id, order_code, date, amount, apply_rate, dict_param={}) ``` ```python account = StockAccount('1000008', 'CREDIT') dict_param = {'subFareRate':0.1, 'fineRate':0.1} #xt_trader为XtQuant API实例对象 seq = xt_trader.smt_negotiate_order_async(account, '', '000001.SZ', 7, 100, 0.2, dict_param) ``` -------------------------------- ### Get Financial Futures Contracts from Index Code Source: https://dict.thinktrader.net/nativeApi/code_examples.html Returns a list of corresponding financial futures contracts for a given index code. This function queries the available instruments in the "中金所" (CFFEX) sector. ```python from xtquant import xtdata import re def get_financial_futures_code_from_index(index_code:str) -> list: """ ToDo:传入指数代码,返回对应的期货合约(当前) Args: index_code:指数代码,如"000300.SH","000905.SH" Retuen: list: 对应期货合约列表 """ financial_futures = xtdata.get_stock_list_in_sector("中金所") future_list = [] pattern = r'^[a-zA-Z]{1,2}\d{3,4}\.[A-Z]{2}$' for i in financial_futures: if re.match(pattern,i): future_list.append(i) ls = [] for i in future_list: _info = xtdata._get_instrument_detail(i) _index_code = _info["ExtendInfo"]['OptUndlCode'] + "." + _info["ExtendInfo"]['OptUndlMarket'] if _index_code == index_code: ls.append(i) return ls if __name__ == "__main__": ls = get_financial_futures_code_from_index("000905.SH") print(ls) ``` ```text ['IC2402.IF', 'IC2403.IF', 'IC2406.IF', 'IC2409.IF'] ``` -------------------------------- ### Initialize Market Data Center Source: https://dict.thinktrader.net/nativeApi/code_examples.html?id=7zqjlm This snippet shows how to initialize the xtdatacenter module, including setting data directories, tokens, optimizing server addresses, and specifying markets for K-line data. ```APIDOC ## Initialize Market Data Center ### Description Initializes the `xtdatacenter` module, configuring data paths, authentication tokens, preferred server addresses, and K-line data markets. ### Method `xtdc.set_data_home_dir(path: str)` `xtdc.set_token(token: str)` `xtdc.set_allow_optmize_address(address_list: list[str])` `xtdc.set_kline_mirror_markets(market_list: list[str])` `xtdc.set_init_markets(market_list: list[str])` `xtdc.init(start_local_service: bool = True)` `xtdc.listen(port: tuple[int, int] | int)` ### Parameters - `data_home_dir`: The directory to store data. - `token`: The authentication token. - `opt_list`: A list of preferred server addresses. - `init_markets`: A list of markets to initialize. - `start_local_service`: Whether to start a local service. - `port`: The port or range of ports to listen on. ### Code Example ```python from xtquant import xtdatacenter as xtdc # Set data directory xtdc.set_data_home_dir('data') # Set token token = "your_token" xtdc.set_token(token) # Set preferred server addresses 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) # Enable full K-line push for specified markets xtdc.set_kline_mirror_markets(['SH', 'SZ', 'BJ']) # Set markets to initialize init_markets = [ 'SH', 'SZ', 'BJ', ] xtdc.set_init_markets(init_markets) # Initialize xtdc module xtdc.init(start_local_service = False) # Listen on a port listen_port = xtdc.listen(port = (58620, 58650)) import xtquant.xtdata as xtdata xtdata.connect(port = listen_port) ``` ``` -------------------------------- ### Get Full Tick Data Source: https://dict.thinktrader.net/nativeApi/xtdata.html Subscribes to and retrieves full tick data. Can subscribe to an entire market by providing market codes (e.g., 'SH', 'SZ') or specific contracts by providing contract codes (e.g., '600000.SH'). ```python get_full_tick(code_list) ``` -------------------------------- ### Get Underlying Futures Contract Code from Option Code Source: https://dict.thinktrader.net/nativeApi/code_examples.html Retrieves the corresponding futures contract code for a given commodity options contract code. Note: This function is not applicable to index futures options or ETF options. ```python from xtquant import xtdata def get_option_underline_code(code:str) -> str: """ 注意:该函数不适用于股指期货期权与ETF期权 Todo: 根据商品期权代码获取对应的具体商品期货合约 Args: code:str 期权代码 Return: 对应的期货合约代码 """ Exchange_dict = { "SHFE":"SF", "CZCE":"ZF", "DCE":"DF", "INE":"INE", "GFEX":"GF" } if code.split(".")[-1] not in [v for k,v in Exchange_dict.items()]: raise KeyError("此函数不支持该交易所合约") info = xtdata.get_option_detail_data(code) underline_code = info["OptUndlCode"] + "." + Exchange_dict[info["OptUndlMarket"]] return underline_code if __name__ == "__main__": symbol_code = get_option_underline_code('sc2403C465.INE') # 获取期权合约'sc2403C465.INE'对应的期货合约代码 print(symbol_code) ``` ```text 'sc2403.INE' ```