### Starting XtQuantTrader API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Starts the trading thread and prepares the environment required for trading operations using the XtQuant API instance. ```python start() ``` ```python # 启动交易线程 #xt_trader为XtQuant API实例对象 xt_trader.start() ``` -------------------------------- ### Initialize XTQuant Trader and Perform Operations - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Demonstrates the main workflow for using XtQuantTrader. It initializes the trader with a path and session ID, creates a stock account object, registers the custom callback, starts the trading thread, connects to the terminal, subscribes to account updates, places and cancels a stock order, and queries asset, order, trade, and position data. ```Python if __name__ == "__main__": print("demo test") # path为mini qmt客户端安装目录下userdata_mini路径 path = 'D:\\迅投极速交易终端 睿智融科版\\userdata_mini' # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号 session_id = 123456 xt_trader = XtQuantTrader(path, session_id) # 创建资金账号为1000000365的证券账号对象 acc = StockAccount('1000000365') # StockAccount可以用第二个参数指定账号类型,如沪港通传'HUGANGTONG',深港通传'SHENGANGTONG' # acc = StockAccount('1000000365','STOCK') # 创建交易回调类对象,并声明接收回调 callback = MyXtQuantTraderCallback() xt_trader.register_callback(callback) # 启动交易线程 xt_trader.start() # 建立交易连接,返回0表示连接成功 connect_result = xt_trader.connect() print(connect_result) # 对交易回调进行订阅,订阅后可以收到交易主推,返回0表示订阅成功 subscribe_result = xt_trader.subscribe(acc) print(subscribe_result) stock_code = '600000.SH' # 使用指定价下单,接口返回订单编号,后续可以用于撤单操作以及查询委托状态 print("order using the fix price:") fix_result_order_id = xt_trader.order_stock(acc, stock_code, xtconstant.STOCK_BUY, 200, xtconstant.FIX_PRICE, 10.5, 'strategy_name', 'remark') print(fix_result_order_id) # 使用订单编号撤单 print("cancel order:") cancel_order_result = xt_trader.cancel_order_stock(acc, fix_result_order_id) print(cancel_order_result) # 使用异步下单接口,接口返回下单请求序号seq,seq可以和on_order_stock_async_response的委托反馈response对应起来 print("order using async api:") async_seq = xt_trader.order_stock(acc, stock_code, xtconstant.STOCK_BUY, 200, xtconstant.FIX_PRICE, 10.5, 'strategy_name', 'remark') print(async_seq) # 查询证券资产 print("query asset:") asset = xt_trader.query_stock_asset(acc) if asset: print("asset:") print("cash {0}".format(asset.cash)) # 根据订单编号查询委托 print("query order:") order = xt_trader.query_stock_order(acc, fix_result_order_id) if order: print("order:") print("order {0}".format(order.order_id)) # 查询当日所有的委托 print("query orders:") orders = xt_trader.query_stock_orders(acc) print("orders:", len(orders)) if len(orders) != 0: print("last order:") print("{0} {1} {2}".format(orders[-1].stock_code, orders[-1].order_volume, orders[-1].price)) # 查询当日所有的成交 print("query trade:") trades = xt_trader.query_stock_trades(acc) print("trades:", len(trades)) if len(trades) != 0: print("last trade:") print("{0} {1} {2}".format(trades[-1].stock_code, trades[-1].traded_volume, trades[-1].traded_price)) # 查询当日所有的持仓 print("query positions:") positions = xt_trader.query_stock_positions(acc) print("positions:", len(positions)) if len(positions) != 0: print("last position:") ``` -------------------------------- ### Get IPO Info Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Returns new stock subscription information within the selected time range. Parameters: - start_time: Start date (e.g., '20230327'). - end_time: End date (e.g., '20230327'). - If start_time and end_time are empty, returns all data. Returns: list[dict], new stock subscription information. ```python securityCode - string 证券代码 codeName - string 代码简称 market - string 所属市场 actIssueQty - int 发行总量,单位:股 onlineIssueQty - int 网上发行量, 单位:股 onlineSubCode - string 申购代码 onlineSubMaxQty - int 申购上限, 单位:股 publishPrice - float 发行价格 isProfit - int 是否已盈利 0:上市时尚未盈利 1:上市时已盈利 industryPe - float 行业市盈率 afterPE - float 发行后市盈率 ``` ```python get_ipo_info(start_time, end_time) ``` -------------------------------- ### Creating XtQuantTrader Instance - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Creates an instance of the XtQuant API. Requires the full path to the MiniQMT client's userdata_mini directory and a unique session ID. This instance is used for all subsequent API operations. ```python XtQuantTrader(path, session_id) ``` ```python path = 'D:\\迅投极速交易终端 睿智融科版\\userdata_mini' # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号 session_id = 123456 #后续的所有示例将使用该实例对象 xt_trader = XtQuantTrader(path, session_id) ``` -------------------------------- ### Get Financial Data Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Gets financial data. Parameters: - stock_list (list): List of contract codes. - table_list (list): List of financial data table names. ```python 'Balance' #资产负债表 'Income' #利润表 'CashFlow' #现金流量表 'Capital' #股本表 'Holdernum' #股东数 'Top10holder' #十大股东 'Top10flowholder' #十大流通股东 'Pershareindex' #每股指标 ``` - start_time (string): Start time. - end_time (string): End time. - report_type (string): Report filtering method. ```python 'report_time' #截止日期 'announce_time' #披露日期 ``` Returns: dict, dataset { stock1 : datas1, stock2 : data2, ... } - stock1, stock2, ... : Contract code. - datas1, datas2, ... : dict dataset { table1 : table_data1, table2 : table_data2, ... } - table1, table2, ... : Financial data table name. - table_data1, table_data2, ... : pd.DataFrame dataset, data fields detailed in Appendix - Financial Data Field List. Remarks: None. ```python get_financial_data(stock_list, table_list=[], start_time='', end_time='', report_type='report_time') ``` -------------------------------- ### Connecting to MiniQMT - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Establishes a connection to the MiniQMT client. Returns 0 on success and a non-zero value on failure. This is a one-time connection and does not automatically reconnect. ```python connect() ``` ```python # 建立交易连接,返回0表示连接成功 #xt_trader为XtQuant API实例对象 connect_result = xt_trader.connect() print(connect_result) ``` -------------------------------- ### Query All Account Information - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries details for all funding accounts accessible via the API. It takes no parameters. The function returns a list of XtAccountInfo objects. ```python query_account_infos() ``` -------------------------------- ### Get ETF Info Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Gets information for all ETF creation/redemption lists. Parameters: None. Returns: dict, all creation/redemption data. ```python get_etf_info() ``` -------------------------------- ### Subscribing to Account Information - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Subscribes to information for a specific account, including fund details, order information, trade information, and position information. Requires a `StockAccount` object. Returns 0 on success, -1 on failure. ```python subscribe(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 subscribe_result = xt_trader.subscribe(account) ``` -------------------------------- ### Get Trading Calendar Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Get the trading calendar for a specified market. Parameters: - market (str): Market. - start_time (str): Start time, 8-digit string. Empty means the first trading day of the current market. - end_time (str): End time, 8-digit string. Empty means the current time. Returns: Returns a list, the complete list of trading days. Remarks: The end time can be a future time to get future trading days. Requires downloading the holiday list. ```python get_trading_calendar(market, start_time = '', end_time = '') ``` -------------------------------- ### Get Quote Server Configuration - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the current connection configuration for the quote server. Returns a list of information dictionaries. ```python def get_quote_server_config() ``` -------------------------------- ### Get Formulas - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Queries and returns a list of all available trading strategy formulas. ```python def get_formulas() ``` -------------------------------- ### Query Securities Lending Contracts - XTQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries the securities lending contracts for a given account using the `smt_query_compact` function. It requires a `StockAccount` object as input and returns a list of dictionaries, each representing a contract with detailed information about the security, amounts, dates, rates, and status. ```python smt_query_compact(account) ``` -------------------------------- ### Get Markets - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves a dictionary of all available markets. ```python def get_markets() ``` -------------------------------- ### Getting Authorized Market List - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves a list of all authorized markets. Returns a list. ```python def get_authorized_market_list() ``` -------------------------------- ### Download Financial Data (Async) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Downloads financial data. Parameters: - stock_list (list): List of contract codes. - table_list (list): List of financial data table names. - start_time (string): Start time. - end_time (string): End time. - Filters by `m_anntime` disclosure date field within the `[start_time, end_time]` range. - callback (func): Callback function. - Parameter is a progress information dict. - total - Total number to download. - finished - Number completed. - stockcode - Contract code completed locally. - message - Current message. ```python def on_progress(data): print(data) # {'finished': 1, 'total': 50, 'stockcode': '000001.SZ', 'message': ''} ``` Returns: None. Remarks: Executes synchronously, returns after data supplementation is complete. ```python download_financial_data2(stock_list, table_list=[], start_time='', end_time='', callback=None) ``` -------------------------------- ### Get All K-Line Trading Periods - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves K-line trading period information for all markets. ```python def get_all_kline_trading_periods() ``` -------------------------------- ### Query Credit Collateral - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Fetches the collateral details for a credit account. It requires a StockAccount object. The function returns a list of CreditAssure objects representing the collateral, or None if the query fails or the list is empty. ```python query_credit_assure(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_assure(account) ``` -------------------------------- ### Get Available Quote Keys - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of data keys supported by the current quote server address. ```python def get_available_quote_key() ``` -------------------------------- ### Registering Callback Class - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Registers a callback class instance with the API instance to receive messages and push notifications. The callback class must inherit from `XtQuantTraderCallback`. ```python register_callback(callback) ``` ```python # 创建交易回调类对象,并声明接收回调 class MyXtQuantTraderCallback(XtQuantTraderCallback): ... pass callback = MyXtQuantTraderCallback() #xt_trader为XtQuant API实例对象 xt_trader.register_callback(callback) ``` -------------------------------- ### Get Authorized Market List - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of authorized markets. ```python def get_authorized_market_list() ``` -------------------------------- ### Get All Trading Periods - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves trading period information for all markets. ```python def get_all_trading_periods() ``` -------------------------------- ### Get Quote Server List - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of server groups available at the current address. ```python def get_server_list() ``` -------------------------------- ### Get Sector List (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves a list of all available sectors. Returns a list of strings, where each string is the name of a sector. ```python def get_sector_list() ``` -------------------------------- ### Unsubscribing from Account Information - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Unsubscribes from information for a specific account. Requires a `StockAccount` object. Returns 0 on success, -1 on failure. ```python unsubscribe(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 unsubscribe_result = xt_trader.unsubscribe(account) ``` -------------------------------- ### Download History Data (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Downloads historical data for a single stock code over a specified period. Allows setting start and end times and controlling incremental downloads. ```python def download_history_data(stock_code, period, start_time='', end_time='', incrementally=None) ``` -------------------------------- ### Query Today's New Stock/Bond Info - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Retrieves information about new stocks and bonds available for subscription today. It takes no parameters. The function returns a dictionary mapping instrument codes to detailed information like name, type, limits, date, and price. ```python query_ipo_data() ``` -------------------------------- ### Query Credit Securities Lending Data - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries data related to available securities for lending for a credit account. It takes a StockAccount object. The function returns a list of CreditSloCode objects or None if the query fails or the list is empty. ```python query_credit_slo_code(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_slo_code(account) ``` -------------------------------- ### Define Account Status Constants in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md These constants indicate the current operational status of a trading account within the XtQuant library, such as normal, connecting, logging in, or failed. ```Python xtconstant.ACCOUNT_STATUS_INVALID = -1 # 无效 xtconstant.ACCOUNT_STATUS_OK = 0 # 正常 xtconstant.ACCOUNT_STATUS_WAITING_LOGIN = 1 # 连接中 xtconstant.ACCOUNT_STATUSING = 2 # 登陆中 xtconstant.ACCOUNT_STATUS_FAIL = 3 # 失败 xtconstant.ACCOUNT_STATUS_INITING = 4 # 初始化中 xtconstant.ACCOUNT_STATUS_CORRECTING = 5 # 数据刷新校正中 xtconstant.ACCOUNT_STATUS_CLOSED = 6 # 收盘后 xtconstant.ACCOUNT_STATUS_ASSIS_FAIL = 7 # 穿透副链接断开 xtconstant.ACCOUNT_STATUS_DISABLEBYSYS = 8 # 系统停用(总线使用-密码错误超限) xtconstant.ACCOUNT_STATUS_DISABLEBYUSER = 9 # 用户停用(总线使用) ``` -------------------------------- ### Define Price Types in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md These constants define the various price types that can be used when placing orders in the XtQuant library, covering different exchanges and instrument types like stocks and futures. ```Python xtconstant.LATEST_PRICE # 最新价 xtconstant.FIX_PRICE # 指定价 # 郑商所 期货 xtconstant.MARKET_BEST # 市价最优价 # 大商所 期货 xtconstant.MARKET_CANCEL # 市价即成剩撤 xtconstant.MARKET_CANCEL_ALL # 市价全额成交或撤 # 中金所 期货 xtconstant.MARKET_CANCEL_1 # 市价最优一档即成剩撤 xtconstant.MARKET_CANCEL_5 # 市价最优五档即成剩撤 xtconstant.MARKET_CONVERT_1 # 市价最优一档即成剩转 xtconstant.MARKET_CONVERT_5 # 市价最优五档即成剩转 # 上交所 股票 xtconstant.MARKET_SH_CONVERT_5_CANCEL # 最优五档即时成交剩余撤销 xtconstant.MARKET_SH_CONVERT_5_LIMIT # 最优五档即时成交剩转限价 xtconstant.MARKET_PEER_PRICE_FIRST # 对手方最优价格委托 xtconstant.MARKET_MINE_PRICE_FIRST # 本方最优价格委托 # 深交所 股票 期权 xtconstant.MARKET_PEER_PRICE_FIRST # 对手方最优价格委托 xtconstant.MARKET_MINE_PRICE_FIRST # 本方最优价格委托 xtconstant.MARKET_SZ_INSTBUSI_RESTCANCEL # 即时成交剩余撤销委托 xtconstant.MARKET_SZ_CONVERT_5_CANCEL # 最优五档即时成交剩余撤销 xtconstant.MARKET_SZ_FULL_OR_CANCEL # 全额成交或撤销委托 ``` -------------------------------- ### Query Credit Asset Details - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries detailed asset information for a credit funding account. It requires a StockAccount object configured for credit. The function returns a list containing XtCreditDetail objects (usually one) or None if the query fails. ```python query_credit_detail(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_detail(account) ``` -------------------------------- ### Placing Stock Order Synchronously - XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md This function places a stock order synchronously. It requires account details, stock code, order type, volume, price type, price, strategy name, and remark. It returns the system-generated order ID, which is a positive integer on success and -1 on failure. ```python order_stock(account, stock_code, order_type, order_volume, price_type, price, strategy_name, order_remark) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 order_id = xt_trader.order_stock(account, '600000.SH', xtconstant.STOCK_BUY, 1000, xtconstant.FIX_PRICE, 10.5, 'strategy1', 'order_test') ``` -------------------------------- ### Initialize QuoteServer - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Initializes a QuoteServer instance with connection information. ```python def __init__(info={}) ``` -------------------------------- ### Get Trading Calendar - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Fetches the trading calendar for a specified market within a given start and end time range. ```python def get_trading_calendar(market, start_time='', end_time='') ``` -------------------------------- ### Placing Stock Order Asynchronously - XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md This function places a stock order asynchronously. If the request is successful, it returns a request sequence number (seq) and triggers the on_order_stock_async_response callback upon receiving feedback. It requires account details, stock code, order type, volume, price type, price, strategy name, and remark. It returns a positive integer sequence number on success and -1 on failure, with failure details provided via a push interface. ```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') ``` -------------------------------- ### Initializing XtQuantTrader (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Initializes the XtQuantTrader instance. Requires the path to the userdata folder, a session ID, and an optional callback object for handling events. ```python def __init__(path, session, callback=None) ``` -------------------------------- ### Define Order Status Constants in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md These constants represent the possible states of an order within the XtQuant library, indicating its lifecycle from unreported to fully succeeded or canceled. ```Python xtconstant.ORDER_UNREPORTED = 48 # 未报 xtconstant.ORDER_WAIT_REPORTING = 49 # 待报 xtconstant.ORDER_REPORTED = 50 # 已报 xtconstant.ORDER_REPORTED_CANCEL = 51 # 已报待撤 xtconstant.ORDER_PARTSUCC_CANCEL = 52 # 部成待撤 xtconstant.ORDER_PART_CANCEL = 53 # 部撤 xtconstant.ORDER_CANCELED = 54 # 已撤 xtconstant.ORDER_PART_SUCC = 55 # 部成 xtconstant.ORDER_SUCCEEDED = 56 # 已成 xtconstant.ORDER_JUNK = 57 # 废单 xtconstant.ORDER_UNKNOWN = 255 # 未知 ``` -------------------------------- ### Query Credit Liability Contracts - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Fetches liability contracts associated with a credit funding account. It takes a StockAccount object. The function returns a list of StkCompacts objects representing the contracts, or None if the query fails or the list is empty. ```python query_stk_compacts(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_stk_compacts(account) ``` -------------------------------- ### Query Stock Orders - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Retrieves all daily orders for a given stock funding account. It takes a StockAccount object and an optional boolean cancelable_only to filter for cancelable orders. The result is a list of XtOrder objects or None if the query fails or the list is empty. ```python query_stock_orders(account, cancelable_only = False) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 orders = xt_trader.query_stock_orders(account, False) ``` -------------------------------- ### Get Trading Time Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Returns the trading periods for the specified code. Parameters: - stockcode (str): Contract code (e.g., `600000.SH`). Returns: list, returns a list of trading periods. The first element is the start time, the second is the end time, and the third is the trading type (2 - Call Auction, 3 - Continuous Trading, 8 - Closing Auction, 9 - After-hours Fixed Price Trading). Time unit is "seconds". Remarks: - Returns an empty list if the stock code is incorrect. - For cross-day periods, 0:00 of the current day is the start, the previous day is negative, and the next day is +86400. - To convert to datetime, you can use the following method: ```python #需要转换为datetime时,可以用以下方法转换 import datetime as dt dt.datetime.combine(dt.date.today(), dt.time()) + dt.timedelta(seconds = 34200) ``` ```python get_trading_time(stockcode) ``` -------------------------------- ### Initializing Order Structure (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Describes the parameters required to initialize a structure representing a trading order, including account details, security code, order specifics, price, volume, status, and remarks. ```python def __init__(account_id, stock_code, order_id, order_time, order_type, order_volume, price_type, price, traded_volume, traded_price, order_status, status_msg, order_remark, contract_no, stock_code1) ``` -------------------------------- ### Query Stock Positions - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries the latest positions held in a stock funding account. It requires a StockAccount object. The function returns a list of XtPosition objects detailing the holdings, or None if the query fails or there are no positions. ```python query_stock_positions(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 positions = xt_trader.query_stock_positions(account) ``` -------------------------------- ### Query New Stock Subscription Limit - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries the new stock subscription limits for a funding account. It takes a StockAccount object. The function returns a dictionary detailing limits for different types (KCB, SH, SZ), noting that bond limits are fixed. ```python query_new_purchase_limit(account) ``` -------------------------------- ### Query Stock Trades - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Fetches all daily trades executed for a specific stock funding account. It accepts a StockAccount object. The function returns a list of XtTrade objects representing the trades, or None if the query fails or no trades are found. ```python query_stock_trades(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 trades = xt_trader.query_stock_trades(account) ``` -------------------------------- ### Initializing StockAccount Instance (__init__) - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md The `__init__` method for the `StockAccount` class, used to initialize an instance with the provided fund account ID. ```Python def __init__(account_id, account_type='STOCK') ``` -------------------------------- ### Get Full Kline Data Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Gets full push k-line data for the latest trading day. Parameters: Refer to the `get_market_data` function. Returns: dict - {field: DataFrame}. ```python get_full_kline(field_list = [], stock_list = [], period = '1m' , start_time = '', end_time = '', count = 1 , dividend_type = 'none', fill_data = True) ``` -------------------------------- ### XtOrder Data Structure in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md The XtOrder structure represents a trading order within the XtQuant library, containing details such as security code, order ID, price, volume, status, and related timestamps. ```Python class XtOrder: account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 stock_code: str # 证券代码,例如\"600000.SH\" order_id: int # 订单编号 order_sysid: str # 柜台合同编号 order_time: int # 报单时间 order_type: int # 委托类型,参见数据字典 order_volume: int # 委托数量 price_type: int # 报价类型,参见数据字典 price: float # 委托价格 traded_volume: int # 成交数量 traded_price: float # 成交均价 order_status: int # 委托状态,参见数据字典 ``` -------------------------------- ### Query Stock Asset - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Queries the asset details for a specified stock funding account. It requires a StockAccount object as input. The function returns an XtAsset object representing the account's assets upon success, or None if the query fails. ```python query_stock_asset(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 asset = xt_trader.query_stock_asset(account) ``` -------------------------------- ### Download Index Weight Data (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Initiates the download of index weight data. This function does not take any arguments. ```python def download_index_weight() ``` -------------------------------- ### Query Credit Subjects - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Retrieves the list of margin trading and securities lending subjects available for a credit account. It requires a StockAccount object. The function returns a list of CreditSubjects objects or None if the query fails or the list is empty. ```python query_credit_subjects(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_subjects(account) ``` -------------------------------- ### Query Futures Position Statistics - XtQuant API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Retrieves position statistics specifically for a futures account. It takes a StockAccount object configured for futures. The function returns a list of XtPositionStatistics objects or None if the query fails or the list is empty. ```python query_position_statistics(account) ``` ```python account = StockAccount('1000000365', 'FUTURE') #xt_trader为XtQuant API实例对象 positions = xt_trader.query_position_statistics(account) ``` -------------------------------- ### Initializing XtCreditDeal Structure (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Describes the parameters required to initialize an XtCreditDeal structure, including account details, security code, trade specifics, price, volume, order ID, and contract number. ```python def __init__(account_id, stock_code, traded_id, traded_time, traded_price, traded_volume, order_id, contract_no, stock_code1) ``` -------------------------------- ### Get Sector Constituent Stock List - xtquant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Retrieves the list of stocks belonging to a specific sector. Takes the sector name and an optional time tag (timestamp or 'YYYYMMDD') to get historical constituents; defaults to the latest if omitted. Requires sector classification data to be downloaded. Returns a list of strings, where each string is a stock code. ```Python get_stock_list_in_sector(sector_name, real_timetag) ``` -------------------------------- ### Download ETF Info Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Downloads information for all ETF creation/redemption lists. Parameters: None. Returns: None. ```python download_etf_info() ``` -------------------------------- ### Initializing XtSmtAppointmentResponse Structure (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Describes the parameters required to initialize an XtSmtAppointmentResponse structure, including the sequence number of the request, success status, a message, and the application ID if successful. ```python def __init__(seq, success, msg, apply_id) ``` -------------------------------- ### Get Holidays - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves a list of public holidays. ```python def get_holidays() ``` -------------------------------- ### Placing Stock Order - xtquant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Places a stock order with specified parameters. Requires account, stock code, order type (buy/sell), volume, price type, and price. Optionally includes strategy name and remark. Returns the order request sequence number; a positive integer indicates success, -1 indicates failure. ```python def order_stock(account, stock_code, order_type, order_volume, price_type, price, strategy_name='', order_remark='') ``` -------------------------------- ### Download Financial Data (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Downloads financial data for a list of stocks. Allows specifying which financial tables to download and a time range. Supports incremental downloads. ```python def download_financial_data(stock_list, table_list=[], start_time='', end_time='', incrementally=None) ``` -------------------------------- ### Define XTQuant Trader Callback Class - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Defines a custom callback class `MyXtQuantTraderCallback` inheriting from `XtQuantTraderCallback`. This class implements various methods to handle real-time trading events such as connection status, order updates, asset changes, trade executions, position changes, and order/cancel errors. ```Python #coding=utf-8 from xtquant.xttrader import XtQuantTrader, XtQuantTraderCallback from xtquant.xttype import StockAccount from xtquant import xtconstant class MyXtQuantTraderCallback(XtQuantTraderCallback): def on_disconnected(self): """ 连接断开 :return: """ print("connection lost") def on_stock_order(self, order): """ 委托回报推送 :param order: XtOrder对象 :return: """ print("on order callback:") print(order.stock_code, order.order_status, order.order_sysid) def on_stock_asset(self, asset): """ 资金变动推送 :param asset: XtAsset对象 :return: """ print("on asset callback") print(asset.account_id, asset.cash, asset.total_asset) def on_stock_trade(self, trade): """ 成交变动推送 :param trade: XtTrade对象 :return: """ print("on trade callback") print(trade.account_id, trade.stock_code, trade.order_id) def on_stock_position(self, position): """ 持仓变动推送 :param position: XtPosition对象 :return: """ print("on position callback") print(position.stock_code, position.volume) 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) def on_cancel_error(self, cancel_error): """ 撤单失败推送 :param cancel_error: XtCancelError 对象 :return: """ print("on cancel_error callback") print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg) def on_order_stock_async_response(self, response): """ 异步下单回报推送 :param response: XtOrderResponse 对象 :return: """ print("on_order_stock_async_response") print(response.account_id, response.order_id, response.seq) def on_account_status(self, status): """ :param response: XtAccountStatus 对象 :return: """ print("on_account_status") print(status.account_id, status.account_type, status.status) ``` -------------------------------- ### Querying IPO Data - XTQuant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Queries the new stock and new bond information. Requires no arguments. Returns the new stock and new bond information. ```python def query_ipo_data() ``` -------------------------------- ### Setting Relaxed Response Order - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Controls whether responses from active request interfaces are returned from an additional dedicated thread for relaxed data timing. Enabling this allows synchronous calls in callbacks without blocking but makes data timing uncertain. Defaults to False. ```python set_relaxed_response_order_enabled(enabled) ``` -------------------------------- ### Placing Stock Order (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Method signature for placing a stock order. (Details not provided in snippet). ```python def order_stock( ``` -------------------------------- ### Implement XTQuant Trader Callback Class - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Defines a custom callback class `MyXtQuantTraderCallback` by inheriting from `XtQuantTraderCallback`. This class overrides methods to handle various asynchronous events from the XTQuant trading API, including connection status changes, account status updates, asset/position/order/trade pushes, and error notifications for orders and cancellations. ```python class MyXtQuantTraderCallback(XtQuantTraderCallback): def on_disconnected(self): """ 连接状态回调 :return: """ print("connection lost") def on_account_status(self, status): """ 账号状态信息推送 :param response: XtAccountStatus 对象 :return: """ print("on_account_status") print(status.account_id, status.account_type, status.status) def on_stock_asset(self, asset): """ 资金信息推送 :param asset: XtAsset对象 :return: """ print("on asset callback") print(asset.account_id, asset.cash, asset.total_asset) def on_stock_order(self, order): """ 委托信息推送 :param order: XtOrder对象 :return: """ print("on order callback:") print(order.stock_code, order.order_status, order.order_sysid) def on_stock_trade(self, trade): """ 成交信息推送 :param trade: XtTrade对象 :return: """ print("on trade callback") print(trade.account_id, trade.stock_code, trade.order_id) def on_stock_position(self, position): """ 持仓信息推送 :param position: XtPosition对象 :return: """ print("on position callback") print(position.stock_code, position.volume) 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) def on_cancel_error(self, cancel_error): """ 撤单失败信息推送 :param cancel_error: XtCancelError 对象 :return: """ print("on cancel_error callback") print(cancel_error.order_id, cancel_error.error_id, cancel_error.error_msg) def on_order_stock_async_response(self, response): """ 异步下单回报推送 :param response: XtOrderResponse 对象 :return: """ 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) ``` -------------------------------- ### Synchronizing External Transaction Data - XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md This function is used for importing external transaction data. It supports operations like "UPDATE", "REPLACE", "ADD", and "DELETE" for "DEAL" data type. It requires the operation type, data type, account, and a list of deal dictionaries. It returns a dictionary containing feedback information. ```python sync_transaction_from_external(operation, data_type, account, deal_list) ``` ```python deal_list = [ {'m_strExchangeID':'SF', 'm_strInstrumentID':'ag2407' , 'm_strTradeID':'123456', 'm_strOrderSysID':'1234566' , 'm_dPrice':7600, 'm_nVolume':1 , 'm_strTradeDate': '20240627' } ] resp = xt_trader.sync_transaction_from_external('ADD', 'DEAL', acc, deal_list) print(resp) #成功输出示例:{'msg': 'sync transaction from external success'} #失败输出示例:{'error': {'msg': '[0-0: invalid operation type: ADDD], '}} ``` -------------------------------- ### Querying IPO Data Async - XTQuant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Asynchronously queries the new stock and new bond information. Requires a `callback` function. Returns the new stock and new bond information via the callback. ```python def query_ipo_data_async(callback) ``` -------------------------------- ### Get Foreign Markets List - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves a list of all available foreign markets. ```python def get_wp_market_list() ``` -------------------------------- ### Get Trading Time - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Returns the trading periods for a specific stock code. ```python def get_trading_time(stockcode) ``` -------------------------------- ### Get Financial Data - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves financial data for a list of stocks. Requires a list of contract codes, an optional list of report table names, optional start/end times, and a report type ('announce_time' or 'report_time') for time filtering. Returns a dictionary containing fields, dates, stocks, and corresponding values. ```python def get_financial_data(stock_list, table_list=[], start_time='', end_time='', report_type='report_time') ``` -------------------------------- ### Connect QuoteServer - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Establishes a connection to the configured quote server address. ```python def connect() ``` -------------------------------- ### Get Quote Server Load - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the load status for the current quote server address. ```python def test_load() ``` -------------------------------- ### Stopping XtQuantTrader API - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Stops the XtQuant API interface, terminating the trading thread and releasing resources. ```python stop() ``` ```python #xt_trader为XtQuant API实例对象 xt_trader.stop() ``` -------------------------------- ### Initializing XtAccountStatus Structure (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Describes the parameters required to initialize an XtAccountStatus structure, including account ID, account type, and the status code. ```python def __init__(account_id, account_type, status) ``` -------------------------------- ### Initializing XtOrder Object in Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Defines the initialization method for the XtOrder class. It takes numerous arguments to populate the order details such as stock code, order ID, time, type, volume, price, status, and strategy information. ```python def __init__(account_id, stock_code, order_id, order_sysid, order_time, order_type, order_volume, price_type, price, traded_volume, traded_price, order_status, status_msg, strategy_name, order_remark, direction, offset_flag, stock_code1) ``` -------------------------------- ### Initializing Account/Asset Structure in Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Defines the initialization method for a data structure representing account assets, including cash, frozen cash, market value, and total asset. Requires account ID and asset details as arguments. ```python def __init__(account_id, cash, frozen_cash, market_value, total_asset) ``` -------------------------------- ### Placing Stock Order Asynchronously (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Places a stock order asynchronously. Returns a request sequence number; a positive number indicates success, -1 indicates failure. Requires account details, stock code, order type, volume, price type, price, and optional strategy name and remark. ```python def order_stock_async(account, stock_code, order_type, order_volume, price_type, price, strategy_name='', order_remark='') ``` -------------------------------- ### Get Historical Option List - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of options for a given underlying code on a specific historical date. ```python def get_his_option_list(undl_code, dedate) ``` -------------------------------- ### Querying Account Information - xtquant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Synchronously queries and returns a list of available trading accounts. ```python def query_account_infos() ``` -------------------------------- ### Get Available Period List Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Returns the list of available periods. Parameters: None. Returns: list, list of periods. ```python get_period_list() ``` -------------------------------- ### Download Convertible Bond Data Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtdata.md Description: Downloads all convertible bond information. Parameters: None. Returns: None. Remarks: None. ```python download_cb_data() ``` -------------------------------- ### Get Historical Option List Batch - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of options for a given underlying code over a historical date range. ```python def get_his_option_list_batch(undl_code, start_time='', end_time='') ``` -------------------------------- ### SMT Appointment Order Async - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Initiates an asynchronous securities lending/borrowing appointment order. Requires account details, security code, term in days, quantity, and application rate. Returns a request sequence number; a positive integer indicates success, -1 indicates failure. ```python def smt_appointment_order_async(account, order_code, date, amount, apply_rate) ``` -------------------------------- ### Get Instrument Type - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Determines the type of a given security based on its stock code. Optionally filters by a list of variety types. ```python def get_instrument_type(stock_code, variety_list=None) ``` -------------------------------- ### Initializing XtPosition Object in Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Defines the initialization method for the XtPosition class. It takes arguments for position details such as stock code, total volume, available volume, cost price, market value, frozen volume, and yesterday's volume. ```python def __init__(account_id, stock_code, volume, can_use_volume, open_price, market_value, frozen_volume, on_road_volume, yesterday_volume, avg_price, direction, stock_code1) ``` -------------------------------- ### Blocking Thread for API Wait - XtQuantTrader - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md Blocks the current thread, putting it into a waiting state until the `stop()` function is called to end the blocking. ```python run_forever() ``` ```python #xt_trader为XtQuant API实例对象 xt_trader.run_forever() ``` -------------------------------- ### Initializing XtTrade Object in Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Defines the initialization method for the XtTrade class. It includes arguments for trade details like stock code, trade ID, time, price, volume, amount, associated order information, strategy, and commission. ```python def __init__(account_id, stock_code, order_type, traded_id, traded_time, traded_price, traded_volume, traded_amount, order_id, order_sysid, strategy_name, order_remark, direction, offset_flag, stock_code1, commission) ``` -------------------------------- ### Define Trade Direction Constants in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md These constants define the direction of a trade, specifically for instruments like futures where 'long' and 'short' positions are relevant. ```Python xtconstant.DIRECTION_FLAG_LONG = 48 # 多 xtconstant.DIRECTION_FLAG_SHORT = 49 # 空 ``` -------------------------------- ### Download Financial Data - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Downloads financial data for a list of stocks and specified tables within a given time range. Allows for a callback function to process data asynchronously. ```python def download_financial_data2(stock_list, table_list=[], start_time='', end_time='', callback=None) ``` -------------------------------- ### Download Sector Data - xtquant.xtdata (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Downloads industry sector classification data. ```python def download_sector_data() ``` -------------------------------- ### Get Trading Contract List - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the list of tradable targets for a given main contract code. An optional date can be provided to query historical lists. ```python def get_trading_contract_list(stockcode, date=None) ``` -------------------------------- ### Get Quote Server Status - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Retrieves the current global connection status for quote servers. Returns a dictionary mapping quote keys to status information. ```python def get_quote_server_status() ``` -------------------------------- ### Placing SMT Negotiate Order Async - XTQuant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Asynchronously places an SMT (Securities Margin Trading) negotiate order. Requires `account` (证券账号), `src_group_id` (来源组编号), `order_code` (证券代码, e.g., '600000.SH'), `date` (期限天数), `amount` (委托数量), and `apply_rate` (资券申请利率). An optional `dict_param` can include `subFareRate` and `fineRate`. Returns the negotiation request sequence number; a positive integer indicates success, -1 indicates failure. ```python def smt_negotiate_order_async(account, src_group_id, order_code, date, amount, apply_rate, dict_param={}) ``` -------------------------------- ### Define Fund Transfer Direction Constants in XtQuant Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xttrader.md These constants specify the direction of fund transfers between different account types or nodes within the XtQuant library. ```Python xtconstant.FUNDS_TRANSFER_NORMAL_TO_SPEED = 510 # 资金划拨-普通柜台到极速柜台 xtconstant.FUNDS_TRANSFER_SPEED_TO_NORMAL = 511 # 资金划拨-极速柜台到普通柜台 xtconstant.NODE_FUNDS_TRANSFER_SH_TO_SZ = 512 # 节点资金划拨-上海节点到深圳节点 xtconstant.NODE_FUNDS_TRANSFER_SZ_TO_SH = 513 # 节点资金划拨-深圳节点到上海节点 ``` -------------------------------- ### Handling Connection Success (Python) Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Callback method triggered when the connection to the trading system is successfully established. ```python def on_connected() ``` -------------------------------- ### Querying Stock Compacts Async - XTQuant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Asynchronously queries the stock compacts (liability contracts) for a given account. Requires the `account` (证券账号) and a `callback` function. Returns the liability contracts via the callback. ```python def query_stk_compacts_async(account, callback) ``` -------------------------------- ### SMT Compact Return Async - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Initiates an asynchronous return for a securities lending/borrowing compact. Requires account details, source group ID, cash compact ID, security code, and return quantity. Returns a return request sequence number; a positive integer indicates success, -1 indicates failure. ```python def smt_compact_return_async(account, src_group_id, cash_compact_id, order_code, occur_amount) ``` -------------------------------- ### Querying SMT Quoter - XTQuant - Python Source: https://github.com/xuntou/xtquant/blob/main/version_241014/doc/xtquant.md Queries the SMT (Securities Margin Trading) quoter information for a given account. Requires the `account` (证券账号) as input. Returns the securities source market data. ```python def smt_query_quoter(account) ```