### Installing Third-Party Python Libraries Source: http://dict.thinktrader.net/innerApi/question_answer.html Example command for installing a third-party library to a specific directory within the QMT installation. ```bash pip install openpyxl -t E:\QMT交易端20962\bin.x64\Lib\site-packages ``` -------------------------------- ### QMT Code Structure Example Source: http://dict.thinktrader.net/strategy/JoinQuant2QMT.html Example of a basic strategy structure in QMT, including initialization and handlebar logic. ```python # Example description: This strategy buys the main chart symbol at each backtest period def init(C): # The input parameter of the init handlebar function is the ContextInfo object, which can be abbreviated as C # Set the test target to the main chart variety C.stock= C.stockcode + '.' +C.market # accountid is the test ID. In backtest mode, the fund account can be filled with any string C.accountid = "testS" def handlebar(C): # handlebar is executed once per bar in the backtest period # handlebar is called with the update of the main chart tick in real-time market data # passorder is QMT's comprehensive order placement function. For specific parameter fields, refer to the official documentation passorder(23, 1101,C.accountid, C.stock, 5, -1, 1, C) ``` -------------------------------- ### JoinQuant Code Structure Example Source: http://dict.thinktrader.net/strategy/JoinQuant2QMT.html Example of a basic strategy structure in JoinQuant, including initialization and daily market open logic. ```python def initialize(context): # Define a global variable to store the stock to be operated, such as 000001 Ping An Bank g.security = '000001.XSHE' # Run function run_daily(market_open, time='every_bar') # Called once per unit of time (called once a day if backtesting by day, once a minute if by minute) def market_open(context): if g.security not in context.portfolio.positions: order(g.security, 1000) else: order(g.security, -800) ``` -------------------------------- ### Get Table Names Example Source: http://dict.thinktrader.net/dictionary/data_browser_barra_factor.html This is an example of the return structure for getting table names, showing Chinese names corresponding to the interface. ```python {'cne1d_100_asset_data': '残差风险表', 'cne1d_100_asset_dlyspecret': '资产残差收益表', 'cne1d_100_asset_exposure_wide': '资产对每个因子的暴露度(宽表)', 'cne1d_100_covariance': '因子协方差矩阵', 'cne1d_100_dlyfacret_wide': '因子日度收益', 'cne1_daily_asset_price': '每日资产收益、收盘价和流通市值', 'cne1_rates': '汇率和无风险收益率'} ``` -------------------------------- ### Get ETF Info Example Source: http://dict.thinktrader.net/dictionary/floorfunds.html This example demonstrates how to retrieve and print ETF information, including the first 20 keys of the main dictionary, the keys of a specific ETF's information, and the first 10 component stock details. ```python from xtquant import xtdata xtdata.download_etf_info() all_etf_info = xtdata.get_etf_info() print(list(all_etf_info.keys())[:20]) # 打印第一层key target_etf_info = all_etf_info["510050.SH"] print(target_etf_info.keys()) # 打印第二层key data = target_etf_info["成份股信息"] print(data[:10]) # 打印成份股信息 ``` -------------------------------- ### Get ETF IOPV Example Source: http://dict.thinktrader.net/dictionary/floorfunds.html Example of how to use the get_etf_iopv function to retrieve and print the IOPV for a specific ETF. ```python # coding:gbk def init(C): pass def handlebar(C): print(get_etf_iopv("510050.SH")) ``` -------------------------------- ### smart_algo_passorder Example (VWAP) Source: http://dict.thinktrader.net/innerApi/trading_function.html This example demonstrates using smart_algo_passorder to place a buy order with VWAP strategy. It specifies the order details, account, instrument, price type (market order), volume, and smart algorithm parameters such as volume ratio, minimum order amount, target price level, start and end times, and price limit control. ```python #coding:gbk def init(ContextInfo): pass def after_init(ContextInfo): # # 使用smart_algo_passorder 下单 smart_algo_passorder( 23, # 买入 1101, # 表示volume的单位是股 account, # 资金账号 '000001.SZ', 12, # 11限价,12市价 0, # 限价时,价格填任意数量占位 50000, # 5000股 '', 2, # quickTrade '', 'VWAP', 25, # 量比25% 0, # 智能算法最小委托金额 1, # 智能算法目标价格 本项只针对冰山算法,其他算法可缺省。 "10:25:00", # 开始时间 "14:50:00", # 结束时间 1, # 涨跌停控制 1为涨停不卖跌停不卖 0 为无限制 ContextInfo ) ``` -------------------------------- ### Example Usage for ETF Statistics Source: http://dict.thinktrader.net/dictionary/floorfunds.html?id=7zqjlm A comprehensive example showing how to download ETF statistics data for multiple stocks, print the last 5 entries for a specific stock, and subscribe to real-time quotes with a callback function. ```python import datetime from xtquant import xtdata from datetime import datetime start_time = datetime.now().strftime("%Y%m%d") end_time = '' print('start_time:', start_time, ' end_time:', end_time) stock_list = ['159001.SZ', '159003.SZ', '159005.SZ', '159150.SZ', '159306.SZ', '159309.SZ', '159502.SZ'] for stock in stock_list: '''下载etf实时申赎信息''' xtdata.download_history_data(stock, 'etfstatistics', start_time, end_time, incrementally = True) print('download finished ' + stock) data = xtdata.get_market_data_ex([], stock_list, 'etfstatistics', start_time, end_time, -1) # 打印"159001.SZ"最后5条数据 print(data["159001.SZ"].iloc[-5:]) def f(data): print(data) for i in stock_list: xtdata.subscribe_quote(i,period="etfstatistics",callback=f) ``` -------------------------------- ### Example - gmd return value Source: http://dict.thinktrader.net/dictionary/floorfunds.html This example demonstrates downloading ETF real-time subscription/redemption information and printing the last 5 data points for a specific stock. ```python import datetime from xtquant import xtdata from datetime import datetime start_time = datetime.now().strftime("%Y%m%d") end_time = '' print('start_time:', start_time, ' end_time:', end_time) stock_list = ['159001.SZ', '159003.SZ', '159005.SZ', '159150.SZ', '159306.SZ', '159309.SZ', '159502.SZ'] for stock in stock_list: '''下载etf实时申赎信息''' xtdata.download_history_data(stock, 'etfstatistics', start_time, end_time, incrementally = True) print('download finished ' + stock) data = xtdata.get_market_data_ex([], stock_list, 'etfstatistics', start_time, end_time, -1) # 打印"159001.SZ"最后5条数据 print(data["159001.SZ"].iloc[-5:]) def f(data): print(data) for i in stock_list: xtdata.subscribe_quote(i,period="etfstatistics",callback=f) ``` -------------------------------- ### Example: Subscribe to a Specific Contract's Tick Data Source: http://dict.thinktrader.net/dictionary/floorfunds.html?id=7zqjlm An example demonstrating how to subscribe to the tick data of a specific stock code with a specified end time and count. ```python # coding=utf-8 from xtquant import xtdata # 订阅指定合约最新行情 xtdata.subscribe_quote('513330.SH', period='tick', start_time='', end_time='20231026150000', count=1, callback=None) ``` -------------------------------- ### Example Return Value Source: http://dict.thinktrader.net/dictionary/floorfunds.html?id=7zqjlm This snippet demonstrates how to use xtdata.download_etf_info() and xtdata.get_etf_info() to retrieve and print ETF information, including the first 20 keys, keys for a specific ETF, and its constituent stock information. ```python from xtquant import xtdata xtdata.download_etf_info() all_etf_info = xtdata.get_etf_info() print(list(all_etf_info.keys())[:20]) # 打印第一层key target_etf_info = all_etf_info["510050.SH"] print(target_etf_info.keys()) # 打印第二层key data = target_etf_info["成份股信息"] print(data[:10]) # 打印成份股信息 ``` -------------------------------- ### Local Data Example Source: http://dict.thinktrader.net/innerApi/question_answer.html Python interface for getting local market data, suitable for backtesting. ```python get_market_data_ex(subscribe=False) ``` -------------------------------- ### Trader Initialization and Connection Source: http://dict.thinktrader.net/nativeApi/code_examples.html Initializes the `XtQuantTrader` with a specified path and session ID, sets up a custom callback, starts the trading thread, and establishes a connection to the trading server. ```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) ``` -------------------------------- ### Example return value for getting fund list Source: http://dict.thinktrader.net/dictionary/floorfunds.html?id=7zqjlm This example demonstrates the expected return format when retrieving a list of funds in a sector. ```python # coding=utf-8 from xtquant import xtdata ret_sector_data = get_stock_list_in_sector('沪深基金') [:10] print(ret_sector_data) ``` -------------------------------- ### Example Return Value Source: http://dict.thinktrader.net/dictionary/floorfunds.html?id=7zqjlm This is an example of the return value for the get_instrument_detail function. ```python # coding=utf-8 from xtquant import xtdata code_detail = xtdata.get_instrument_detail('159733.SZ') print(code_detail) ``` -------------------------------- ### Strategy Execution Example Source: http://dict.thinktrader.net/videos/touyan/ty_native_python.html Demonstrates how to run a trading strategy using `run_strategy_file` from `xtquant.qmttools`. It includes defining strategy parameters and executing backtesting. ```python if __name__ == '__main__': import sys from xtquant.qmttools import run_strategy_file # 参数定义方法一,如果使用方法二定义参数,run_strategy_file的param参数可不传 param = { 'stock_code': '000300.SH', # 驱动handlebar的代码, 'period': '1d', # 策略执行周期 即主图周期 'start_time': '2022-01-01 00:00:00', # 注意格式,不要写错 'end_time': '2024-03-01 00:00:00', # 注意格式,不要写错 'trade_mode': 'backtest', # 'backtest':回测 'quote_mode': 'history', # handlebar模式,'realtime':仅实时行情(不调用历史行情的handlebar),'history':仅历史行情, 'all':所有,即history+realtime } # user_script = os.path.basename(__file__) # 当前脚本路径,相对路径,绝对路径均可,此处为相对路径的方法 user_script = sys.argv[0] # 当前脚本路径,相对路径,绝对路径均可,此处为绝对路径的方法 print(user_script) result = run_strategy_file(user_script, param=param) if result: print(result.get_backtest_index()) print(result.get_group_result()) xtdata.run() ``` -------------------------------- ### Example Return Value Source: http://dict.thinktrader.net/dictionary/floorfunds.html Example of subscribing to the latest quote for a specified contract. ```python # coding=utf-8 from xtquant import xtdata # 订阅指定合约最新行情 xtdata.subscribe_quote('513330.SH', period='tick', start_time='', end_time='20231026150000', count=1, callback=None) ``` -------------------------------- ### Market Example Source: http://dict.thinktrader.net/innerApi/variable_convention.html Example of how to print the current main chart market using ContextInfo.market. ```python # coding:gbk def init(ContextInfo): pass def handlebar(ContextInfo): print(ContextInfo.market) ``` -------------------------------- ### Get Full Tick Data and Place Order Source: http://dict.thinktrader.net/nativeApi/code_examples.html This example shows how to retrieve full tick data for a stock, get instrument details, and place an order at the lower limit price. ```python code = "000001.SZ" tick = xtdata.get_full_tick([code])[code] last_price = tick["lastPrice"] # 最新价 ask_price = round(tick["askPrice"][0],3) # 卖方1档价 bid_price = round(tick["bidPrice"][4],3) # 买方5档价 symbol_info = xtdata.get_instrument_detail(code) up_limit = symbol_info["UpStopPrice"] down_limit = symbol_info["DownStopPrice"] lots = 1 res_id = xt_trade.order_stock_async(account, code, xtconstant.FUTURE_OPEN_LONG, lots, xtconstant.FIX_PRICE, down_limit, strategy_name, "跌停价/固定手数") # lots = 100 # res_id = xt_trade.order_stock_async(account, code, xtconstant.STOCK_BUY, lots, xtconstant.FIX_PRICE, bid_price, strategy_name, "跌停价/固定手数") xtdata.run() ``` -------------------------------- ### Data Initialization and Parameter Setup Source: http://dict.thinktrader.net/videos/touyan/ty_native_python.html Initializes global variables and sets up parameters for a trading strategy, including stock selection, initial capital, and trading rules. ```python class G(): pass g = G() def init(C): # ------------------------参数设定----------------------------- g.his_st = {} # g.s = C.get_stock_list_in_sector("沪深A股") # 获取沪深A股股票列表 g.s = C.get_stock_list_in_sector("沪深300") # 获取沪深300股票列表 # g.s = ['000001.SZ'] g.day = 0 g.holdings = {i: 0 for i in g.s} g.weight = [0.1] * 10 g.buypoint = {} g.money = 1000000 # C.capital g.accid = 'test' g.profit = 0 # 因子权重 g.buy_num = 10 # 买排名前5的股票,在过滤中会用到 g.per_money = g.money / g.buy_num * 0.95 ``` -------------------------------- ### Full Push Data Examples Source: http://dict.thinktrader.net/innerApi/question_answer.html Python interfaces for retrieving the latest full push market data. ```python get_full_tick ``` ```python subscribe_whole_quote ``` -------------------------------- ### Progress Callback Function Example Source: http://dict.thinktrader.net/nativeApi/xtdata.html Example of a callback function to process download progress information. ```python def on_progress(data): print(data) # {'finished': 1, 'total': 50, 'stockcode': '000001.SZ', 'message': ''} ``` -------------------------------- ### Subscription Data Examples Source: http://dict.thinktrader.net/innerApi/question_answer.html Python interfaces for subscribing to specific instrument market data with different periods. ```python subscribe_quote ``` ```python get_market_data_ex(subscribe=True,) ``` -------------------------------- ### Get Full Tick Data Source: http://dict.thinktrader.net/dictionary/indexes.html Example of retrieving full tick data for a stock code. ```python # coding=utf-8 from xtquant import xtdata # 获取迅投板块指数代码列表 xt_sector_index_list = xtdata.get_stock_list_in_sector("迅投一级行业板块加权指数") # 获取迅投板块指数信息 xt_sector_index_info = xtdata.get_instrument_detail(xt_sector_index_list[0]) # 获取迅投板块指数tick数据 ret_full_tick = xtdata.get_full_tick([xt_sector_index]) print(ret_full_tick) ``` -------------------------------- ### Process 1: Start xtdatacenter Listener Source: http://dict.thinktrader.net/dictionary This snippet shows how to initialize the行情 module, load contract data, and start a data service listener in Process 1. ```python from xtquant import xtdatacenter as xtdc xtdc.set_token('这里输入token') print('xtdc.init') xtdc.init() # 初始化行情模块,加载合约数据,会需要大约十几秒的时间 print('done') # 为其他进程的xtdata提供服务时启动server,单进程使用不需要 print('xtdc.listen') listen_addr = xtdc.listen(port = 58610) print(f'done, listen_addr:{listen_addr}') from xtquant import xtdata print('running') xtdata.run() #循环,维持程序运行 ``` -------------------------------- ### Get Historical Market Data Source: http://dict.thinktrader.net/dictionary/future.html Example of retrieving historical market data for a future contract. ```python from xtquant import xtdata xtdata.get_market_data_ex([],['rb2401.SF'],period='tick') ``` -------------------------------- ### Get Opponent Price Source: http://dict.thinktrader.net/nativeApi/code_examples.html This Python example demonstrates how to get the opponent price, specifically for a sell order. It retrieves the full tick data for a given stock code and then determines the opponent price. If the best bid price is 0 (indicating a lower limit), it uses the last price as the opponent price; otherwise, it uses the best bid price. ```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) ``` -------------------------------- ### Process 1: Start xtdatacenter listener Source: http://dict.thinktrader.net/dictionary?id=null This Python code snippet demonstrates how to initialize the xtdatacenter, set the access token, and start a listening service for other processes to connect to. ```python from xtquant import xtdatacenter as xtdc xtdc.set_token('这里输入token') print('xtdc.init') xtdc.init() # 初始化行情模块,加载合约数据,会需要大约十几秒的时间 print('done') # 为其他进程的xtdata提供服务时启动server,单进程使用不需要 print('xtdc.listen') listen_addr = xtdc.listen(port = 58610) print(f'done, listen_addr:{listen_addr}') from xtquant import xtdata print('running') xtdata.run() #循环,维持程序运行 ``` -------------------------------- ### Import necessary libraries and initialize xtquant Source: http://dict.thinktrader.net/videos/touyan/ty_native_python.html This code snippet demonstrates how to import essential libraries for strategy backtesting and initialize the xtquant library, including specifying the path to xtquant and printing its directory. ```python # Set the xtquant path as needed import sys import numpy as np import pandas as pd from xtquant import xtdata import xtquant print(xtquant) print(xtdata.data_dir) # Specify to get data from the investment research terminal (optional, defaults to prioritizing connection to investment research) # xtdata.reconnect(port=58613) ``` -------------------------------- ### Get Market Data Ex (Daily) Source: http://dict.thinktrader.net/dictionary/indexes.html Example of retrieving daily market data for a specific stock index. ```python # coding=utf-8 from xtquant import xtdata day_data = xtdata.get_market_data_ex(field_list=[], stock_list=[xt_sector_index], period='1d', start_time='',end_time='20231026', count=5, dividend_type='none', fill_data=True) print(day_data) ``` -------------------------------- ### Create Sector Folder Source: http://dict.thinktrader.net/nativeApi/xtdata.html Creates a directory node for sectors. ```python create_sector_folder(parent_node, folder_name, overwrite) ``` -------------------------------- ### Example - callback return value Source: http://dict.thinktrader.net/dictionary/floorfunds.html This shows the expected output format when using a callback function for ETF statistics. ```text # 打印"159001.SZ"最后5条数据 time 申购笔数 申购数量 申购金额 赎回笔数 赎回数量 赎回金额 17628 1721629992000 417 647341.0 0.0 84 890490.0 0.0 17629 1721629995000 417 647341.0 0.0 84 890490.0 0.0 17630 1721630001000 417 647341.0 0.0 84 890490.0 0.0 17631 1721630007000 417 647341.0 0.0 84 890490.0 0.0 17632 1721630019000 417 647341.0 0.0 84 890490.0 0.0 ``` -------------------------------- ### Download All Table Information (Metatable) Source: http://dict.thinktrader.net/dictionary/data_browser_barra_factor.html This code snippet shows how to download all table information (metatable) and then retrieve the list of table names. ```python from xtquant import xtdata # First step: Download all table information (metatable) from the Data Browser xtdata.download_metatable_data() # Second step: Get the table names metainfo = xtdata.get_metatable_list() print(metainfo) ```