### init(ContextInfo) Source: http://docs.thinktrader.net/pages/91d44f Initialization function called once at the start of the strategy. Used for setting up trading commissions, slippage, benchmarks, and other global parameters. ```APIDOC ## init(ContextInfo) ### Description Initialization function, called only once when the strategy starts. ### Parameters - **ContextInfo** (Object) - Required - The strategy runtime environment object used to store custom global variables. ### Example ```python def init(ContextInfo): ContextInfo.initProfit = 0 ``` ``` -------------------------------- ### Get All Market Subscriptions Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves information about all currently active market data subscriptions. ```python data=ContextInfo.get_all_subscription() ``` -------------------------------- ### Get Market Data (Version 2) Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves market data with advanced configuration options. Note that historical data must be downloaded manually. ```python data=ContextInfo.get_market_data_ex(['open','high','low','close'],['000300.SH'],period='1d',start_time='',end_time='',count=-1,dividend_type='follow',fill_data=True,subscribe=True) ``` -------------------------------- ### 设定回测起止时间 ContextInfo.start / ContextInfo.end Source: http://docs.thinktrader.net/pages/91d44f 仅在 init() 中设置生效,用于定义回测的时间范围。 ```python def init(ContextInfo): ContextInfo.start = '2012-06-06 10:00:00' ContextInfo.end = '2013-08-08 14:30:00' ``` -------------------------------- ### Get Current K-Line Index Source: http://docs.thinktrader.net/pages/91d44f Returns the current K-line index, starting from 0. ```python def handlebar(ContextInfo): print(ContextInfo.barpos) __ ``` -------------------------------- ### connect() Source: http://docs.thinktrader.net/pages/ee0e9b Establishes a connection to the MiniQMT terminal. ```APIDOC ## connect() ### Description Establishes a connection to the MiniQMT terminal. This is a one-time connection; if disconnected, it must be called again. ### Returns - **int** - Returns 0 on success, non-zero on failure. ``` -------------------------------- ### Get Backtest Benchmark Source: http://docs.thinktrader.net/pages/91d44f Retrieves the benchmark used for backtesting. ```python def handlebar(ContextInfo): print(ContextInfo.benchmark) ``` -------------------------------- ### 实现初始化函数 init() Source: http://docs.thinktrader.net/pages/91d44f 策略启动时执行一次,用于设置交易佣金、滑点、基准等参数。 ```python def init(ContextInfo): ContextInfo.initProfit = 0 ``` -------------------------------- ### Get Market Time Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the latest time for a specified market. ```python get_market_time("SH") ``` -------------------------------- ### Get Stock Name Source: http://docs.thinktrader.net/pages/91d44f Retrieves the name of a stock based on its code. ```python def handlebar(ContextInfo): print(ContextInfo.get_stock_name('000001.SZ')) ``` -------------------------------- ### 实现后置初始化函数 after_init() Source: http://docs.thinktrader.net/pages/91d44f 在 init() 执行后、handlebar() 执行前调用,适用于调用 init() 中不支持的特定函数。 ```python #coding:gbk def init(ContextInfo): print('init') def after_init(ContextInfo): print('系统会在init函数执行完后和执行handlebar之前调用after_init') def handlebar(ContextInfo): if ContextInfo.is_last_bar(): print('handlebar') ``` -------------------------------- ### 设定交易账号 ContextInfo.set_account() Source: http://docs.thinktrader.net/pages/91d44f 在 init() 中设定交易账号,用于后续的交易主推订阅。 ```python def init(ContextInfo): account = '6000000223' ContextInfo.set_account(account) ``` -------------------------------- ### Get Winner Chips Ratio Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the ratio of chips at a specified price. ```python data = get_winner_chips('000001.SZ', '1d', '20210730', 18.93) ``` -------------------------------- ### 双均线实盘交易策略 Source: http://docs.thinktrader.net/pages/c8bccc 该策略通过init函数初始化交易环境,并在handlebar函数中根据均线交叉情况执行买卖操作。注意ContextInfo对象在盘中会被深拷贝,不建议用于记录交易信号。 ```python #encoding:gbk import pandas as pd import numpy as np import datetime """ 示例说明:双均线实盘策略,通过计算快慢双均线,在金叉时买入,死叉时做卖出 """ class a(): pass A = a() #创建空的类的实例 用来保存委托状态 #ContextInfo对象在盘中每次handlebar调用前都会被深拷贝, 如果调用handlebar的分笔不是k线最后分笔 ContextInfo会被回退到深拷贝的内容 所以ContextInfo不能用来记录快速交易的信号 def init(C): A.stock= C.stockcode + '.' + C.market #品种为模型交易界面选择品种 A.acct= account #账号为模型交易界面选择账号 A.acct_type= accountType #账号类型为模型交易界面选择账号 A.amount = 10000 #单笔买入金额 触发买入信号后买入指定金额 A.line1=17 #快线周期 A.line2=27 #慢线周期 A.waiting_list = [] #未查到委托列表 存在未查到委托情况暂停后续报单 防止超单 A.buy_code = 23 if A.acct_type == 'STOCK' else 33 #买卖代码 区分股票 与 两融账号 A.sell_code = 24 if A.acct_type == 'STOCK' else 34 #设置股票池 订阅品种行情 C.set_universe([A.stock]) print(f'双均线实盘示例{A.stock} {A.acct} {A.acct_type} 单笔买入金额{A.amount}') def handlebar(C): #跳过历史k线 if not C.is_last_bar(): return now = datetime.datetime.now() now_time = now.strftime('%H%M%S') #跳过非交易时间 if now_time < '093000' or now_time > "150000": return account = get_trade_detail_data(A.acct, A.acct_type, 'account') if len(account)==0: print(f'账号{A.acct} 未登录 请检查') return account = account[0] available_cash = int(account.m_dAvailable) #如果有未查到委托 查询委托 if A.waiting_list: found_list = [] orders = get_trade_detail_data(A.acct, A.acct_type, 'order') for order in orders: if order.m_strRemark in A.waiting_list: found_list.append(order.m_strRemark) A.waiting_list = [i for i in A.waiting_list if i not in found_list] if A.waiting_list: print(f"当前有未查到委托 {A.waiting_list} 暂停后续报单") return holdings = get_trade_detail_data(A.acct, A.acct_type, 'position') holdings = {i.m_strInstrumentID + '.' + i.m_strExchangeID : i.m_nCanUseVolume for i in holdings} #获取行情数据 data = C.get_history_data(max(A.line1, A.line2)+1, '1d', 'close',dividend_type='front_ratio') close_list = data[A.stock] if len(close_list) < max(A.line1, A.line2)+1: print('行情长度不足(新上市或最近有停牌) 跳过运行') return pre_line1 = np.mean(close_list[-A.line1-1: -1]) pre_line2 = np.mean(close_list[-A.line2-1: -1]) current_line1 = np.mean(close_list[-A.line1:]) current_line2 = np.mean(close_list[-A.line2:]) #如果快线穿过慢线,则买入委托 当前无持仓 买入 vol = int(A.amount / close_list[-1] / 100) * 100 #买入数量 向下取整到100的整数倍 if A.amount < available_cash and vol >= 100 and A.stock not in holdings and pre_line1 < pre_line2 and current_line1 > current_line2: #下单开仓 ,参数说明可搜索PY交易函数 passorder msg = f"双均线实盘 {A.stock} 上穿均线 买入 {vol}股" passorder(A.buy_code, 1101, A.acct, A.stock, 14, -1, vol, '双均线实盘', 2 , msg, C) print(msg) A.waiting_list.append(msg) #如果快线下穿慢线,则卖出委托 if A.stock in holdings and holdings[A.stock] > 0 and pre_line1 > pre_line2 and current_line1 < current_line2: msg = f"双均线实盘 {A.stock} 下穿均线 卖出 {holdings[A.stock]}股" passorder(A.sell_code, 1101, A.acct, A.stock, 14, -1, holdings[A.stock], '双均线实盘', 2 , msg, C) print(msg) A.waiting_list.append(msg) ``` -------------------------------- ### Get Delisted Contracts Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves a list of delisted contracts for a specific market. ```python def handlebar(ContextInfo): print( ContextInfo.get_his_contract_list('IF')) def handlebar(ContextInfo): print( ContextInfo.get_his_contract_list('SHO')) ``` -------------------------------- ### Get Sector List Source: http://docs.thinktrader.net/pages/91d44f Retrieves the list of sectors and folders in a specific node. ```python get_sector_list('我的') ``` -------------------------------- ### 设定股票池 ContextInfo.set_universe() Source: http://docs.thinktrader.net/pages/91d44f 在 init() 中调用以设定策略运行的股票池。 ```python def init(ContextInfo): stocklist = ['000300.SH','000004.SZ'] ContextInfo.set_universe(stocklist) ``` -------------------------------- ### Get Market Information Source: http://docs.thinktrader.net/pages/91d44f Retrieves the market identifier for the current main chart. ```python def handlebar(ContextInfo): print(ContextInfo.market) ``` -------------------------------- ### 获取LV1行情数据 Source: http://docs.thinktrader.net/pages/6f0df0 演示了在init和handlebar函数中使用get_market_data_ex获取K线数据的方法。订阅模式受数量限制,非订阅模式需提前下载本地数据。 ```python #coding:gbk # get_market_data_ex(subscribe=True)有订阅股票数量限制 # 即stock_list参数的数量不能超过500 # get_market_data_ex(subscribe=False) 该模式下(非订阅模式),接口会从本地行情文件里获取数据,不会获取动态行情数,且不受订阅数限制,但需要提前下载数据 # 下载数据在 操作/数据管理/补充数据选项卡里,按照页面提示下载数据 # get_market_data_ex(subscribe=True) 该模式下(订阅模式),受订阅数量上限限制,可以取到动态行情 # 建议每天盘后增量补充对应周期的行情 import time def init(C): C.stock = C.stockcode + '.' + C.market # 获取指定时间的k线 price = C.get_market_data_ex(['open','high','low','close'], [C.stock], start_time='', end_time='',period='1d', subscribe=False) print(price[C.stock].head()) def handlebar(C): bar_timetag = C.get_bar_timetag(C.barpos) bar_date = timetag_to_datetime(bar_timetag, '%Y%m%d%H%M%S') print('获取截至到%s为止前5根k线的开高低收等字段:'%(bar_date)) # 获取截至今天为止前30根k线 price = C.get_market_data_ex( [], [C.stock], end_time=bar_date, period=C.period, subscribe=True, count=5, ) print(price[C.stock].to_dict('dict')) ``` -------------------------------- ### PRINTOUT(X, Y) Source: http://docs.thinktrader.net/pages/9247e2 Outputs variables to a file in the BIN subdirectory of the installation directory. ```APIDOC ## PRINTOUT(X, Y) ### Description Outputs the values of variables X and Y to a file named after the current model in the BIN subdirectory. ### Parameters - **X** (variable) - Required - The first variable to output. - **Y** (variable) - Required - The second variable to output. ``` -------------------------------- ### Get Stock Holding Statistics Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves holding statistics for a specific stock code. ```python def handlebar(ContextInfo): ContextInfo.get_hkt_statistics('600000.SH') ``` -------------------------------- ### 聚宽策略结构示例 Source: http://docs.thinktrader.net/pages/164778 聚宽策略使用initialize进行初始化,并配合run_daily或handle_data进行周期性逻辑执行。 ```python def initialize(context): # 定义一个全局变量, 保存要操作的股票,如000001平安银行 g.security = '000001.XSHE' # 运行函数 run_daily(market_open, time='every_bar') # 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次 def market_open(context): if g.security not in context.portfolio.positions: order(g.security, 1000) else: order(g.security, -800) ``` -------------------------------- ### QMT策略结构示例 Source: http://docs.thinktrader.net/pages/164778 QMT策略通过init进行初始化,handlebar函数在回测周期的每根bar或实时行情更新时被调用。 ```python #示例说明:本策略,在回测的每个周期买入主图标的 def init(C): #init handlebar函数的入参是ContextInfo对象 可以缩写为C #设置测试标的为主图品种 C.stock= C.stockcode + '.' +C.market #accountid为测试的ID 回测模式资金账号可以填任意字符串 C.accountid = "testS" def handlebar(C): # handlebar在回测时,会在回测周期的每根bar被执行一次 # handlebar在实时行情下,会随着主图tick的更新被调用 # passorder是QMT的综合下单函数,具体参数字段参考官方文档 passorder(23, 1101,C.accountid, C.stock, 5, -1, 1, C) ``` -------------------------------- ### Retrieve Option Detail Data Source: http://docs.thinktrader.net/pages/fd9cbd Gets detailed information for a specific option contract. ```python def handlebar(ContextInfo): print ContextInfo.get_option_detail_data('10001506.SHO') ``` -------------------------------- ### account_callback(ContextInfo, accountInfo) Source: http://docs.thinktrader.net/pages/84f157 当资金账号状态发生变化时,客户端会自动调用此函数。仅在实盘模式下生效,且需先调用ContextInfo.set_account。 ```APIDOC ## account_callback(ContextInfo, accountInfo) ### Description 当资金账号状态有变化时,这个函数被客户端调用。仅在实盘运行模式下生效,且需要先在init里调用ContextInfo.set_account后生效。 ### Parameters - **ContextInfo** (Object) - 特定对象 - **accountInfo** (Object) - 账号对象或信用账号对象 ### Returns - 无 ``` -------------------------------- ### Get Stock Open Date Source: http://docs.thinktrader.net/pages/91d44f Retrieves the listing date of a stock based on its code. ```python def handlebar(ContextInfo): print(ContextInfo.get_open_date('000001.SZ')) ``` -------------------------------- ### 资金账号状态变化回调 Source: http://docs.thinktrader.net/pages/84f157 在实盘模式下,需先调用ContextInfo.set_account设置账号,当资金账号状态变化时触发此回调。 ```python def init(ContextInfo): # 设置对应的资金账号 ContextInfo.set_account('6000000058') def handlebar(ContextInfo): pass def account_callback(ContextInfo, accountInfo): print('accountInfo') print(accountInfo.m_strStatus) # m_strStatus 为资金账号的属性之一,表示资金账号的状态 __ ``` -------------------------------- ### Get Dividend Type Source: http://docs.thinktrader.net/pages/91d44f Retrieves the current dividend adjustment method for the main chart. ```python def handlebar(ContextInfo): print(ContextInfo.dividend_type) ``` -------------------------------- ### ContextInfo Configuration Methods Source: http://docs.thinktrader.net/pages/91d44f Methods for configuring the strategy environment, including stock pools, accounts, and backtesting parameters. ```APIDOC ## ContextInfo.set_universe(stocklist) Sets the stock pool for the strategy. ## ContextInfo.set_account(account) Sets the trading account for order execution. ## ContextInfo.start / ContextInfo.end Sets the backtest start and end time (e.g., "2009-07-14 01:13:30"). ## ContextInfo.capital Sets the initial capital for backtesting (default: 1000000). ## ContextInfo.set_slippage(slippageType, slippage) Sets backtest slippage. slippageType: 0 (tick), 1 (fixed price), 2 (price ratio). ``` -------------------------------- ### Place Algorithm Order with algo_passorder Source: http://docs.thinktrader.net/pages/c8bccc Demonstrates how to configure algorithm parameters and execute an order using the algo_passorder function. ```python #coding:gbk import time def init(C): userparam={ 'OrderType':1, #表示要下算法 'PriceType':0, # 卖5价下单 'MaxOrderCount':12, # 最大委托次数 'SuperPriceType':0, # 超价类型,0表示按比例 'SuperPriceRate':0.02, # 超价2%下单 'VolumeRate':0.1, # 单笔下单比率 每次拆10% 'VolumeType': 10, # 单笔基准量类型 'SingleNumMax':1000000, # 单笔拆单最大值 'PriceRangeType':0, # 波动区间类型 'PriceRangeRate':1, # 波动区间值 'ValidTimeType':1, # 有效时间类型 1 表示按执行时间 'ValidTimeStart':int(time.time()), # 算法开始时间 'ValidTimeEnd':int(time.time()+60*60), # 算法结束时间 'PlaceOrderInterval':10, # 报撤间隔 'UndealtEntrustRule':0, # 未成委托处理数值 用卖5加挂单 } target_vol = 2000000 # 股, 算法目标总量 algo_passorder(23, 1101, account, '600000.SH', -1, -1, target_vol, '', 2, '普通算法', userparam, C) print('finish') def handlebar(C): pass ``` -------------------------------- ### Get Total K-Line Count Source: http://docs.thinktrader.net/pages/91d44f Returns the total number of K-lines in the current chart. ```python def handlebar(ContextInfo): print(ContextInfo.time_tick_size) __ ``` -------------------------------- ### Get Current Period Source: http://docs.thinktrader.net/pages/91d44f Returns the current timeframe period set in the strategy configuration. ```python def handlebar(ContextInfo): print(ContextInfo.period) __ ``` -------------------------------- ### ordering(AccountID, MarketID, StockID, Direction, [strategyName]) Source: http://docs.thinktrader.net/pages/9247e2 执行下单操作,返回委托结果。 ```APIDOC ## ordering(AccountID, MarketID, StockID, Direction, [strategyName]) ### Description 执行下单操作。 ### Parameters - **AccountID** (string) - Required - 资金账号 - **MarketID** (string) - Required - 市场代码 - **StockID** (string) - Required - 证券/合约代码 - **Direction** (int) - Required - 1: 买入, 2: 卖出 - **strategyName** (string) - Optional - 自定义策略名 ``` -------------------------------- ### Execute Orders with passorder Source: http://docs.thinktrader.net/pages/c8bccc Demonstrates the difference between immediate order placement and order placement upon bar completion using the passorder function. ```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线,立即下单 ``` -------------------------------- ### Get Chips Price by Ratio Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the price level corresponding to a specified chip ratio. ```python data = get_chips_price('000001.SZ', '1d', '20210730', 0.5) ``` -------------------------------- ### 创建连接 Source: http://docs.thinktrader.net/pages/ee0e9b 与MiniQMT建立连接,返回0表示成功。该连接为一次性,断开后需重新调用。 ```python # 建立交易连接,返回0表示连接成功 #xt_trader为XtQuant API实例对象 connect_result = xt_trader.connect() print(connect_result) ``` -------------------------------- ### Get Stock Holding Details Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves detailed holding information for a specific stock code. ```python def handlebar(ContextInfo): ContextInfo.get_hkt_details('600000.SH') ``` -------------------------------- ### Get Northbound Finance Data Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves Northbound and Southbound finance data for a specified period. ```python def handlebar(ContextInfo): ContextInfo.get_north_finance_change('1d') ``` -------------------------------- ### 股票异步报单 Source: http://docs.thinktrader.net/pages/ee0e9b 使用order_stock_async进行异步下单。成功后会收到on_order_stock_async_response反馈,返回下单请求序号。 ```python order_stock_async(account, stock_code, order_type, order_volume, price_type, price, strategy_name, order_remark) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 seq = xt_trader.order_stock_async(account, '600000.SH', xtconstant.STOCK_BUY, 1000, xtconstant.FIX_PRICE, 10.5, 'strategy1', 'order_test') ``` -------------------------------- ### Get Option Implied Volatility Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the real-time implied volatility for a specific stock option. ```python def handlebar(ContextInfo): print( ContextInfo.get_option_iv('10003280.SHO')) ``` -------------------------------- ### buy_open(stockcode, amount[, style, price], ContextInfo[, accId]) Source: http://docs.thinktrader.net/pages/d0dd26 Executes a futures buy order to open a position. ```APIDOC ## buy_open ### Description Opens a long position in futures trading. ### Parameters - **stockcode** (string) - Required - Futures code (e.g., 'IF1805.IF') - **amount** (int) - Required - Number of lots - **style** (string) - Optional - Order pricing type (default: 'LATEST') - **price** (double) - Optional - Specific price - **ContextInfo** (PythonObj) - Required - Context object - **accId** (string) - Optional - Account ID ### Example ```python # 按最新价 1 手买入开仓 buy_open('IF1805.IF', 1, ContextInfo, '110476') ``` ``` -------------------------------- ### after_init(ContextInfo) Source: http://docs.thinktrader.net/pages/91d44f Initialization function called after init() and before the first handlebar() execution. Useful for functions not supported within init(). ```APIDOC ## after_init(ContextInfo) ### Description System calls this function after init() finishes and before handlebar() starts. Suitable for calling functions like ContextInfo.get_trading_dates that are not supported in init(). ### Parameters - **ContextInfo** (Object) - Required - The strategy runtime environment object. ``` -------------------------------- ### Retrieve Inner Volume Source: http://docs.thinktrader.net/pages/fd9cbd Gets the inner volume (sell volume) for a specific stock code. ```python def handlebar(ContextInfo): print(ContextInfo.get_svol('000001.SZ')) ``` -------------------------------- ### ContextInfo.get_market_data_ex(...) Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves market data with advanced configuration options. ```APIDOC ## ContextInfo.get_market_data_ex(fields, stock_code, period, start_time, end_time, count, dividend_type, fill_data, subscribe) ### Description Retrieves market data. Note: Historical data must be downloaded manually. ### Parameters - **fields** (list) - Optional - Data fields to retrieve. - **stock_code** (list) - Required - List of stock codes. - **period** (string) - Optional - Data period (e.g., 'tick', '1d', '1m', '5m', 'l2quote'). - **start_time** (string) - Optional - Start time. - **end_time** (string) - Optional - End time. - **count** (int) - Optional - Max number of records. - **dividend_type** (string) - Optional - 'none', 'front', 'back', 'front_ratio', 'back_ratio'. - **fill_data** (bool) - Optional - Whether to fill data for suspended stocks. - **subscribe** (bool) - Optional - Whether to subscribe to data. ### Response - **Returns** (dict) - {code1: data1, code2: data2, ...}. ``` -------------------------------- ### Get Current Chart Stock Code Source: http://docs.thinktrader.net/pages/91d44f Returns the stock code of the current main chart. ```python def handlebar(ContextInfo): print(ContextInfo.stockcode) __ ``` -------------------------------- ### 语句块 BEGIN...END Source: http://docs.thinktrader.net/pages/9247e2 将多条语句组合成一个逻辑块。 ```ThinkTrader IF CLOSE>OPEN THEN BEGIN AA:=1; END//若该周期收盘,将AA赋值为1 ``` -------------------------------- ### Get Chip Distribution Data Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the complete chip distribution data for a stock at a specific time. ```python data = get_chip_distribution('000001.SZ', '1d', '20210730') ``` -------------------------------- ### 获取历史行情数据 Source: http://docs.thinktrader.net/pages/fd9cbd 获取股票池中历史行情数据,需先通过ContextInfo.set_universe()设定股票池。该接口已不推荐使用,建议改用ContextInfo.get_market_data_ex。 ```python def init(ContextInfo): ContextInfo.set_universe(['000300.SH', '000004.SZ']) def handlebar(ContextInfo): # 获取股票池中所有股票的最近两日的收盘价 hisdict = ContextInfo.get_history_data(2, '1d', 'close') for k, v in hisdict.items(): if len(v) > 1: # 今日涨幅 print(k, ':', v[1] - v[0]) __ ``` -------------------------------- ### Get Option Variety List Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the list of option varieties corresponding to a specific underlying asset. ```python data=ContextInfo.get_option_undl_data('510300.SH') ``` -------------------------------- ### Create Sector Source: http://docs.thinktrader.net/pages/91d44f Creates a new stock sector. ```python sector=create_sector('我的','新建板块',False) ``` -------------------------------- ### Get Result Records Source: http://docs.thinktrader.net/pages/91d44f Retrieves historical trade or holding records for a specific type and time index. ```python def handlebar(ContextInfo): index = ContextInfo.barpos print(get_result_records('buys', index, ContextInfo)) ``` -------------------------------- ### 使用快速交易参数委托 Source: http://docs.thinktrader.net/pages/c8bccc 通过设置quickTrade参数为2,使passorder函数在执行后立即下单,无需等待K线结束。 ```python #coding:gbk def after_init(C): #account变量是模型交易界面 添加策略时选择的资金账号 不需要手动填写 #快速交易参数(quickTrade )填2 passorder函数执行后立刻下单 不会等待k线走完再委托。 可以在after_init函数 run_time函数注册的回调函数里进行委托 msg = f"投资备注字符串 用来区分不同委托" passorder(23, 1101, account, '600000.SH', 5, -1, 200, '测试下单', 2, msg, C) ``` -------------------------------- ### Get Financial Data Source: http://docs.thinktrader.net/pages/36f5df Retrieves financial data tables. Requires prior download using download_financial_data. ```python get_financial_data(stock_list, table_list=[], start_time='', end_time='', report_type='report_time') __ ``` ```python 'Balance' #资产负债表 'Income' #利润表 'CashFlow' #现金流量表 __ ``` ```python 'report_time' #截止日期 'announce_time' #披露日期 __ ``` -------------------------------- ### Get Option List Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves a list of option contracts based on underlying code, date, type, and availability. ```python # 获取到期月份为202101的上交所510300ETF认购合约 data=ContextInfo.get_option_list('510300.SH','202101',"CALL") # 获取20210104当天上交所510300ETF可交易的认购合约 data=ContextInfo.get_option_list('510300.SH','20210104',"CALL",True) # 获取20210104当天上交所510300ETF已经上市的认购合约(包括退市) data=ContextInfo.get_option_list('510300.SH','20210104',"CALL",False) ``` -------------------------------- ### deal_callback(ContextInfo, dealInfo) Source: http://docs.thinktrader.net/pages/84f157 当账号成交状态发生变化时,客户端会自动调用此函数。仅在实盘模式下生效。 ```APIDOC ## deal_callback(ContextInfo, dealInfo) ### Description 当账号成交状态有变化时,这个函数被客户端调用。仅在实盘运行模式下生效。 ### Parameters - **ContextInfo** (Object) - 特定对象 - **dealInfo** (Object) - 成交对象 ### Returns - 无 ``` -------------------------------- ### Get Historical ST Data via ContextInfo Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves historical ST data for a specific stock as a dictionary. ```python def handlebar(ContextInfo): print( ContextInfo.get_his_st_data('000004.SZ')) ``` -------------------------------- ### 使用 ContextInfo.paint 绘制指标曲线 Source: http://docs.thinktrader.net/pages/b92bef 在指定索引位置绘制指标曲线,支持自定义线型和颜色。 ```python def handlebar(ContextInfo): realtimetag = ContextInfo.get_bar_timetag(ContextInfo.barpos) value = ContextInfo.get_close_price('', '', realtimetag) ContextInfo.paint('close', value, -1, 0, 'white','noaxis') ``` -------------------------------- ### Get Stock Industry Name Source: http://docs.thinktrader.net/pages/91d44f Retrieves the industry name for a stock based on the specified industry classification standard. ```python def handlebar(ContextInfo): print(get_industry_name_of_stock('SW','600000.SH')) __ ``` -------------------------------- ### 获取最新流通股本 Source: http://docs.thinktrader.net/pages/fd9cbd 通过股票代码获取最新的流通股本数据。 ```python def handlebar(ContextInfo): print(ContextInfo.get_last_volume('000002.SZ')) ``` -------------------------------- ### Get Shareholder Count Data Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves shareholder count data for a list of stocks within a specified time range. ```python def handlebar(ContextInfo): print(ContextInfo.get_holder_num(['000002.SZ'],'20100101','20180101')) ``` -------------------------------- ### Execute Futures Buy Close Orders (Yesterday First) Source: http://docs.thinktrader.net/pages/d0dd26 Use buy_close_ydayfirst to close a short position with priority given to yesterday's positions. ```python def handlebar(ContextInfo): # 按最新价 1 手买入平仓,平昨优先 buy_close_ydayfirst('IF1805.IF', 1, ContextInfo, '110476') # 用对手价 1 手买入平仓,平昨优先 buy_close_ydayfirst('IF1805.IF', 1, 'COMPETE', ContextInfo, '110476') # 用指定价 3750 元 2 手买入平仓,平昨优先 buy_close_ydayfirst('IF1805.IF', 2, 'fix', 3750, ContextInfo, '110476') ``` -------------------------------- ### Get Raw Financial Data Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves raw financial data for specified stocks and fields without daily interpolation. ```python fieldList = ['ASHAREBALANCESHEET.fix_assets','ASHAREINCOME.net_profit_incl_min_int_inc'] stockList = ['600000.SH','000001.SZ'] startDate = '20200101' endDate = '20210101' ContextInfo.get_raw_financial_data(fieldList,stockList,startDate,endDate) ``` -------------------------------- ### Create Sector Folder Source: http://docs.thinktrader.net/pages/91d44f Creates a new folder node for sectors. ```python folder=create_sector_folder('我的','新建分类',False) ``` -------------------------------- ### Get Order or Deal Information by ID Source: http://docs.thinktrader.net/pages/d0dd26 Retrieves specific order or deal details using a provided order ID. ```python def init(ContextInfo): ContextInfo.accid = '6000000248' def handlebar(ContextInfo): orderid = get_last_order_id(ContextInfo.accid, 'stock', 'order') print(orderid) obj = get_value_by_order_id(orderid,ContextInfo.accid, 'stock', 'order') print(obj.m_strInstrumentID) __ ``` -------------------------------- ### order_callback(ContextInfo, orderInfo) Source: http://docs.thinktrader.net/pages/84f157 当账号委托状态发生变化时,客户端会自动调用此函数。仅在实盘模式下生效。 ```APIDOC ## order_callback(ContextInfo, orderInfo) ### Description 当账号委托状态有变化时,这个函数被客户端调用。仅在实盘运行模式下生效。 ### Parameters - **ContextInfo** (Object) - 特定对象 - **orderInfo** (Object) - 委托对象 ### Returns - 无 ``` -------------------------------- ### XtQuantTrader(path, session_id) Source: http://docs.thinktrader.net/pages/ee0e9b Creates an instance of the XtQuant API. This instance is required for all subsequent API operations. ```APIDOC ## XtQuantTrader(path, session_id) ### Description Creates an instance of the XtQuant API. This instance is required for all subsequent API operations. ### Parameters - **path** (str) - Required - The full path to the MiniQMT client's userdata_mini directory. - **session_id** (int) - Required - A unique session ID for communication with MiniQMT. ### Returns - **XtQuant API instance object** ``` -------------------------------- ### Get Historical Index Component List Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves the list of index components at historical adjustment dates. Requires historical data to be downloaded. ```python def handlebar(ContextInfo): print( ContextInfo.get_his_index_data('000300.SH'))#获取沪深300函数历次调整时的指数成分列表,计算对应权重可以进一步取历史股本进行计算 ``` -------------------------------- ### 资产信息推送回调 Source: http://docs.thinktrader.net/pages/ee0e9b 接收资产信息变动推送,注意该回调函数目前不生效。 ```python on_stock_asset(data) ``` -------------------------------- ### Get Level 2 Market Data Source: http://docs.thinktrader.net/pages/36f5df Methods to retrieve Level 2 market data. Requires prior subscription via subscribe_quote. ```python get_l2_quote(field_list=[], stock_code='', start_time='', end_time='', count=-1) __ ``` ```python get_l2_order(field_list=[], stock_code='', start_time='', end_time='', count=-1) __ ``` ```python get_l2_transaction(field_list=[], stock_code='', start_time='', end_time='', count=-1) __ ``` -------------------------------- ### 持仓信息推送回调 Source: http://docs.thinktrader.net/pages/ee0e9b 接收持仓信息变动推送,注意该回调函数目前不生效。 ```python on_stock_position(data) ``` -------------------------------- ### do_order(ContextInfo) Source: http://docs.thinktrader.net/pages/d0dd26 Triggers the order signal from the previous bar in real-time. ```APIDOC ## do_order(ContextInfo) ### Description Triggers the order signal generated in the previous bar. This is useful for strategies running on daily K-lines or higher periods to ensure signals are sent at specific times. ### Parameters - **ContextInfo** (pythonobj) - Required - The context object. ### Returns - **None** ``` -------------------------------- ### Get Historical ST Status Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves historical ST status for a given stock code. Requires historical ST data to be downloaded first. ```python get_st_status('600599.SH'); ``` -------------------------------- ### ContextInfo.get_option_list() Source: http://docs.thinktrader.net/pages/fd9cbd Retrieves a list of options based on the underlying asset, expiration date, and type. ```APIDOC ## ContextInfo.get_option_list(undl_code, dedate, opttype, isavailable) ### Description Retrieves a list of options for a specified underlying asset. For historical options, ensure the expired contract list is downloaded first. ### Parameters - **undl_code** (string) - Required - The underlying asset code (e.g., '510300.SH'). - **dedate** (string) - Required - Expiration month ('YYYYMM') or specific date ('YYYYMMDD'). - **opttype** (string) - Optional - Option type: 'CALL', 'PUT', or empty for both. - **isavailable** (boolean) - Optional - Whether to filter by availability when using 'YYYYMMDD' format. ``` -------------------------------- ### 获取扩展数据 Source: http://docs.thinktrader.net/pages/8da043 使用ext_data函数获取指定扩展数据的值。 ```python def handlebar(ContextInfo): print(ext_data('mycci', '600000.SH', 0, ContextInfo)) ``` -------------------------------- ### 异步下单回报推送回调 Source: http://docs.thinktrader.net/pages/ee0e9b 接收异步下单委托反馈。 ```python on_order_stock_async_response(data) ``` -------------------------------- ### 获取账户新股申购额度 Source: http://docs.thinktrader.net/pages/d0dd26 使用 get_new_purchase_limit 查询指定资金账号的新股申购额度。 ```python def init(ContextInfo): ContextInfo.accid="10000001"# 返回新股新债信息 purchase_limit=get_new_purchase_limit(ContextInfo.accid) ``` -------------------------------- ### 使用xtquant获取行情数据示例 Source: http://docs.thinktrader.net/pages/5e493a 演示了全推数据获取、历史数据下载、行情订阅及数据查询的基本流程。需注意xtdata.run()会阻塞主线程。 ```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_data2([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() ``` -------------------------------- ### 循环语句 FOR Source: http://docs.thinktrader.net/pages/9247e2 执行指定次数的循环。注意在逐K线模式下避免在循环内使用序列统计函数。 ```ThinkTrader FOR VAR=N1 TO N2 DO EXPR; 从 VAR=N1 开始到 VAR=N2 开始循环执行 EXPR 语句,每执行一次 VAR 加 1 FOR VAR=N1 DOWNTO N2 DO EXPR2; 从 VAR=N1 开始到 VAR=N2 开始循环执行 EXPR 语句,每执行一次 VAR 减 1 ``` -------------------------------- ### handlebar(ContextInfo) Source: http://docs.thinktrader.net/pages/91d44f Market event function executed for each K-line. In real-time mode, it runs for each historical K-line and then for each incoming tick. ```APIDOC ## handlebar(ContextInfo) ### Description Market event function, executed once per K-line. In real-time mode, it processes historical data first, then triggers on every tick. ### Parameters - **ContextInfo** (Object) - Required - The strategy runtime environment object. ### Example ```python def handlebar(ContextInfo): print(ContextInfo.barpos) ``` ``` -------------------------------- ### ContextInfo.get_financial_data (用法1) Source: http://docs.thinktrader.net/pages/0e9cf0 通过字段列表、股票列表和时间范围批量获取财务数据。 ```APIDOC ## ContextInfo.get_financial_data(fieldList, stockList, startDate, endDate, report_type = 'announce_time') ### Description 根据指定的字段列表、股票列表和时间范围获取财务数据。返回类型根据请求的股票数量和时间范围动态变化(Series, DataFrame 或 Panel)。 ### Parameters - **fieldList** (List) - Required - 财报字段列表,例如 ['ASHAREBALANCESHEET.fix_assets', '利润表.净利润'] - **stockList** (List) - Required - 股票代码列表,例如 ['600000.SH', '000001.SZ'] - **startDate** (Str) - Required - 开始时间,格式 'YYYYMMDD' - **endDate** (Str) - Required - 结束时间,格式 'YYYYMMDD' - **report_type** (Str) - Optional - 报表时间类型,'report_time' 为报告期,'announce_time' 为公告日期,默认为公告日期。 ### Request Example ```python def handlebar(ContextInfo): fieldList = ['CAPITALSTRUCTURE.total_capital', '利润表.净利润'] stockList = ['600000.SH','000001.SZ'] startDate = '20171209' endDate = '20171212' ContextInfo.get_financial_data(fieldList, stockList, startDate, endDate, report_type = 'report_time') ``` ``` -------------------------------- ### 账号异常下单回调 Source: http://docs.thinktrader.net/pages/84f157 实盘模式下,当账号下单出现异常时由客户端调用。 ```python def init(ContextInfo): # 设置对应的资金账号 ContextInfo.set_account('6000000058') def handlebar(ContextInfo): pass def orderError_callback(ContextInfo,orderArgs,errMsg): print('orderArgs') print(errMsg) __ ``` -------------------------------- ### 处理异步请求响应回调 Source: http://docs.thinktrader.net/pages/ee0e9b 用于处理异步下单和约券请求的响应数据。 ```python print("on_order_stock_async_response") print(response.account_id, response.order_id, response.seq) def on_smt_appointment_async_response(self, response): """ :param response: XtAppointmentResponse 对象 :return: """ print("on_smt_appointment_async_response") print(response.account_id, response.order_sysid, response.error_id, response.error_msg, response.seq) ```