### Example: Starting XtQuantTrader (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Demonstrates calling the start() method on the xt_trader instance. This action launches the background thread required for the API to function correctly. It is a prerequisite for establishing a connection and executing trading commands. ```python # 启动交易线程 #xt_trader为XtQuant API实例对象 xt_trader.start() ``` -------------------------------- ### Starting Trading Thread (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Initiates the internal trading thread and prepares the necessary environment for trading operations. This method must be called after creating the API instance and registering callbacks, but before attempting to connect or perform trading actions. ```python start() ``` -------------------------------- ### Initializing and Using XTQuant Trader - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Demonstrates the main execution flow for using the XTQuant Trader SDK. It initializes the trader with the terminal path and a session ID, creates a stock account object, registers the custom callback class, starts the trading thread, connects to the terminal, subscribes to account updates, places and cancels a stock order, places an asynchronous order, and queries various account data like assets, orders, trades, and positions. ```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:") ``` -------------------------------- ### Example: Initializing XtQuantTrader (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Demonstrates how to create an XtQuantTrader instance. Sets the path variable to the MiniQMT userdata directory and defines a unique session_id. The created instance is assigned to the xt_trader variable for later use. ```python path = 'D:\\迅投极速交易终端 睿智融科版\\userdata_mini' # session_id为会话编号,策略使用方对于不同的Python策略需要使用不同的会话编号 session_id = 123456 #后续的所有示例将使用该实例对象 xt_trader = XtQuantTrader(path, session_id) ``` -------------------------------- ### Example: Connecting XtQuantTrader (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Illustrates how to call the connect() method on the xt_trader instance to establish a connection to the MiniQMT client. The return value, indicating success (0) or failure (non-zero), is captured in connect_result and printed. ```python # 建立交易连接,返回0表示连接成功 #xt_trader为XtQuant API实例对象 connect_result = xt_trader.connect() print(connect_result) ``` -------------------------------- ### Example: Subscribing to Account (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Demonstrates how to subscribe to account information. An account object is created for the account ID '1000000365'. The subscribe() method is then called on the xt_trader instance with this account object to initiate the subscription. ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 subscribe_result = xt_trader.subscribe(account) ``` -------------------------------- ### Exporting Generic Data (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Exports generic data (like deal records) to a specified CSV file path. Requires a StockAccount object, the export file path, and the data type. Optional parameters include start time, end time, and user-defined parameters. Returns a dictionary indicating the success or failure of the export operation. ```python export_data(account, result_path, data_type, start_time = None, end_time = None, user_param = {}) ``` ```python resp = xt_trader.export_data(acc, 'C:\\Users\\Desktop\\test\\deal.csv', 'deal') print(resp) #成功输出示例:{'msg': 'export success'} #失败输出示例:{'error': {'errorMsg': 'can not find account info, accountID:2000449 accountType:2'}} ``` -------------------------------- ### Querying All Account Information - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries all funding accounts. Parameters: None. Returns: list Account information list. [ XtAccountInfo ] Remarks: None. ```python query_account_infos() ``` -------------------------------- ### Example: Registering Custom Callback (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Shows how to define a custom callback class MyXtQuantTraderCallback inheriting from XtQuantTraderCallback. An instance of this class is created and then registered with the xt_trader API instance using the register_callback method. This enables the strategy to receive asynchronous API events. ```python # 创建交易回调类对象,并声明接收回调 class MyXtQuantTraderCallback(XtQuantTraderCallback): ... pass callback = MyXtQuantTraderCallback() #xt_trader为XtQuant API实例对象 xt_trader.register_callback(callback) ``` -------------------------------- ### Querying SMT Compact Contracts - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the list of SMT compact contracts for a given account. Requires a StockAccount object as input and returns a list of dictionaries, each representing a contract with detailed information. ```python smt_query_compact(account) ``` -------------------------------- ### Connecting to MiniQMT (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Establishes a connection to the MiniQMT client. This is a one-time connection; if the connection is lost, it will not automatically reconnect and must be explicitly called again. Returns 0 on successful connection and a non-zero value on failure. ```python connect() ``` -------------------------------- ### Creating XtQuant API Instance (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Creates an instance of the XtQuant API for trading operations. Requires the full path to the MiniQMT userdata directory and a unique session ID for communication. This instance is necessary for all subsequent API calls. ```python XtQuantTrader(path, session_id) ``` -------------------------------- ### Example: Running XtQuantTrader Forever (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Demonstrates calling run_forever() on the xt_trader instance. This puts the main thread into a blocking state, allowing the API's background threads and registered callbacks to handle incoming data and events until stop() is explicitly invoked. ```python #xt_trader为XtQuant API实例对象 xt_trader.run_forever() ``` -------------------------------- ### Example: Stopping XtQuantTrader (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Shows a simple call to the stop() method on the xt_trader instance. This action terminates the API's background processes and should be performed before the application exits to ensure a clean shutdown. ```python #xt_trader为XtQuant API实例对象 xt_trader.stop() ``` -------------------------------- ### XtQuant Account Status (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Enumerated constants indicating the operational status of a trading account connected through the XtQuant library. These constants reflect the connection and initialization state of the account. ```Python # Account Status Constants 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: 用户停用(总线使用) ``` -------------------------------- ### Example: Unsubscribing from Account (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Shows how to unsubscribe from account information. An account object is created for the account ID '1000000365'. The unsubscribe() method is then called on the xt_trader instance with this account object to stop receiving updates for that account. ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 unsubscribe_result = xt_trader.unsubscribe(account) ``` -------------------------------- ### Registering Callback Class (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Registers an instance of a callback class with the API instance. This allows the API to deliver messages and push notifications to the strategy. The provided callback object must be an instance of a class inheriting from XtQuantTraderCallback. ```python register_callback(callback) ``` -------------------------------- ### Querying Today's New Stock/Bond Information - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries today's new stock and bond information. Parameters: None. Returns: dict New stock and bond information dataset. { stock1: info1, stock2: info2, ... } where stock - str variety code (e.g., '301208.SZ'), info - dict new stock information with name - str variety name, type - str variety type ('STOCK' - stock, 'BOND' - bond), minPurchaseNum / maxPurchaseNum - int minimum / maximum subscription limit (unit is shares (stock) / sheets (bond)), purchaseDate - str subscription date, issuePrice - float issue price. Returns example: {'754810.SH': {'name': '丰山发债', 'type': 'BOND', 'maxPurchaseNum': 10000, 'minPurchaseNum': 10, 'purchaseDate': '20220627', 'issuePrice': 100.0}, '301208.SZ': {'name': '中亦科技', 'type': 'STOCK', 'maxPurchaseNum': 16500, 'minPurchaseNum': 500, 'purchaseDate': '20220627', 'issuePrice': 46.06}} Remarks: None. ```python query_ipo_data() ``` -------------------------------- ### Getting Sector List - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xtdata.md 获取板块列表. Parameters: None. Returns: - list 板块列表,[ sector1, sector2, ... ] Remarks: - 需要下载板块分类信息. ```python get_sector_list() ``` -------------------------------- ### Getting Index Weights - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xtdata.md 获取指数成分权重信息. Parameters: - index_code - string 指数代码 Returns: - dict 数据字典,{ stock1 : weight1, stock2 : weight2, ... } Remarks: - 需要下载指数成分权重信息. ```python get_index_weight(index_code) ``` -------------------------------- ### Subscribing to Account Info (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Subscribes to information for a specific trading account, including fund details, order information, trade execution details, and position information. The account parameter should be a StockAccount object representing the target account. Returns 0 on success and -1 on failure. ```python subscribe(account) ``` -------------------------------- ### Asynchronous Order Response (XtOrderResponse) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Represents the feedback received after submitting an asynchronous order request. It contains identifiers for the account, order, and strategy, along with a sequence number to link the response back to the original request. ```Python class XtOrderResponse: """异步下单委托反馈""" account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 order_id: int # 订单编号 strategy_name: str # 策略名称 order_remark: str # 委托备注 seq: int # 异步下单的请求序号 ``` -------------------------------- ### Placing Stock Order Synchronously - XtQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Performs a synchronous stock order placement operation. Requires account, stock code, order type, volume, price type, price, strategy name, and remark. Returns the system-generated order ID, which is a positive integer on success or -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') ``` -------------------------------- ### XtQuant Order Data Structure (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Describes the `XtOrder` object structure, containing detailed information about a placed order. This includes identifiers, timestamps, order parameters (volume, price, type), execution details (traded volume, price), and the current status of the order. ```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 # 委托状态,参见数据字典 status_msg: str # 委托状态描述,如废单原因 strategy_name: str # 策略名称 order_remark: str # 委托备注 direction: int # 多空方向,股票不需要;参见数据字典 offset_flag: int # 交易操作,用此字段区分股票买卖,期货开、平仓,期权买卖等;参见数据字典 stock_code1: str # 证券代码,例如"600000.SH" ``` -------------------------------- ### Querying Generic Data (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries generic data by first exporting it using export_data to a temporary file, reading the data, and then deleting the file. Parameters are the same as export_data. Returns a dictionary containing the queried data, typically in a pandas DataFrame-like structure, or an error dictionary. ```python query_data(account, result_path, data_type, start_time = None, end_time = None, user_param = {}) ``` ```python data = xt_trader.query_data(acc, 'C:\\Users\\Desktop\\test\\deal.csv', 'deal') print(data) #成功输出示例: # account_id account_Type stock_code order_type ... #0 2003695 2 688488.SH 23 ... #1 2003695 2 000096.SZ 23 ... #失败输出示例:{'error': {'errorMsg': 'can not find account info, accountID:2000449 accountType:2'}} ``` -------------------------------- ### Querying Stock Trades - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries all trades for the current day corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: A list of XtTrade objects for all trades of the day corresponding to the account or None. Remarks: None indicates query failure or an empty trade list for the day. ```python query_stock_trades(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 trades = xt_trader.query_stock_trades(account) ``` -------------------------------- ### XtQuant Offset Flag (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Constants defining the type of trading operation being performed, such as opening or closing a position. This is crucial for distinguishing between buying/selling stocks and opening/closing positions in futures or options. ```Python # Offset Flag Constants xtconstant.OFFSET_FLAG_OPEN # 48: 买入,开仓 xtconstant.OFFSET_FLAG_CLOSE # 49: 卖出,平仓 xtconstant.OFFSET_FLAG_FORCECLOSE # 50: 强平 xtconstant.OFFSET_FLAG_CLOSETODAY # 51: 平今 xtconstant.OFFSET_FLAG_ClOSEYESTERDAY # 52: 平昨 xtconstant.OFFSET_FLAG_FORCEOFF # 53: 强减 xtconstant.OFFSET_FLAG_LOCALFORCECLOSE # 54: 本地强平 ``` -------------------------------- ### Query Specific Stock Position - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the stock position for a given account and stock code using the 'xt_trader' object. If a position is found, it prints its account ID, stock code, and volume. ```Python print("query position:") position = xt_trader.query_stock_position(acc, stock_code) if position: print("position:") print("{0} {1} {2}".format(position.account_id, position.stock_code, position.volume)) ``` -------------------------------- ### Print Last Position Details - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Prints the account ID, stock code, and volume for the last position object in a list named 'positions'. This assumes 'positions' is a list containing objects with these attributes. ```Python print("{0} {1} {2}".format(positions[-1].account_id, positions[-1].stock_code, positions[-1].volume)) ``` -------------------------------- ### Getting Stocks in Sector - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xtdata.md 获取板块成分股列表. Parameters: - sector_name - string 版块名称 - real_timetag 时间:1512748800000或'20171209',可缺省,缺省时获取最新的成分,不缺省时获取对应时间的历史成分 Returns: - list 成分股列表,[ stock1, stock2, ... ] Remarks: - 需要板块分类信息. ```python get_stock_list_in_sector(sector_name, real_timetag) ``` -------------------------------- ### Performing Fund Transfer - XtQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Performs a fund transfer operation. Requires the account, transfer direction, and amount. Returns a tuple (success, msg) indicating whether the transfer operation was successful and a feedback message. ```Python fund_transfer(account, transfer_direction, price) ``` -------------------------------- ### Implementing XtQuantTrader Callback - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Defines a custom callback class `MyXtQuantTraderCallback` that inherits from `XtQuantTraderCallback`. This class provides methods to handle various asynchronous trading events such as connection status, account status, asset updates, order status changes, trade confirmations, position updates, and order/cancel errors. ```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) ``` -------------------------------- ### Querying Futures Position Statistics - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the position statistics for the futures account. Parameters: account - StockAccount stock account. Returns: A list of the latest XtPositionStatistics objects corresponding to the account or None. Remarks: None indicates query failure or an empty position list for the day. ```python query_position_statistics(account) ``` ```python account = StockAccount('1000000365', 'FUTURE') #xt_trader为XtQuant API实例对象 positions = xt_trader.query_position_statistics(account) ``` -------------------------------- ### Querying Common Account Funds (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the fund details for a common trading account. Requires a StockAccount object as input. Returns a dictionary containing fund information like current balance, available balance, total assets, etc., along with success/error status. ```python query_com_fund(account) ``` -------------------------------- ### Querying SMT Quoter (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the SMT (Securities Margin Trading) quoter information. Requires a StockAccount object. Returns a list of dictionaries, where each dictionary represents a quoter entry with details like financial type, security type, term days, stock code, rates (occupancy, fine, early return, usage), dates, available quantities, source group ID, and application mode. ```python smt_query_quoter(account) ``` -------------------------------- ### Querying Stock Positions - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the positions corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: A list of the latest XtPosition objects corresponding to the account or None. Remarks: None indicates query failure or an empty position list for the day. ```python query_stock_positions(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 positions = xt_trader.query_stock_positions(account) ``` -------------------------------- ### Order Failure Error (XtOrderError) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Details the information when an asynchronous order submission fails. It includes account and order identifiers, the specific error code and message explaining the failure reason, and the strategy name and remark associated with the order. ```Python class XtOrderError: """下单失败错误""" account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 order_id: int # 订单编号 error_id: int # 下单失败错误码 error_msg: str # 下单失败具体信息 strategy_name: str # 策略名称 order_remark: str # 委托备注 ``` -------------------------------- ### Querying Stock Assets - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the asset corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: The asset object XtAsset corresponding to the account or None. Remarks: Returning None indicates query failure. ```python query_stock_asset(account) ``` ```python account = StockAccount('1000000365') #xt_trader为XtQuant API实例对象 asset = xt_trader.query_stock_asset(account) ``` -------------------------------- ### Submitting SMT Negotiated Order Async (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Submits an asynchronous application for a negotiated SMT order (inventory securities). Requires a StockAccount object, source group ID, stock code, term days, order amount, and application rate. Additional parameters like early return rate and fine rate can be passed in an optional dictionary. Returns a request sequence number (seq); a positive integer indicates successful initiation, -1 indicates failure. A successful request will trigger an on_smt_appointment_async_response callback. ```python smt_negotiate_order_async(self, account, src_group_id, order_code, date, amount, apply_rate, dict_param={}) ``` ```python account = StockAccount('1000008', 'CREDIT') dict_param = {'subFareRate':0.1, 'fineRate':0.1} #xt_trader为XtQuant API实例对象 seq = xt_trader.smt_negotiate_order_async(account, '', '000001.SZ', 7, 100, 0.2, dict_param) ``` -------------------------------- ### Placing Stock Order Asynchronously - XtQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Performs an asynchronous stock order placement operation. If the request sequence number (seq) is returned successfully, an order feedback will be received via the on_order_stock_async_response callback. Returns the request sequence number (seq), a positive integer on success or -1 on failure. Failure information is pushed via the order failure 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') ``` -------------------------------- ### XtQuant Transfer Direction (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Constants used to specify the direction for fund transfers between different account types or nodes within the trading system. These are relevant for managing capital across various account configurations. ```Python # Transfer Direction Constants 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: 节点资金划拨-深圳节点到上海节点 ``` -------------------------------- ### Querying Credit Account Securities Available for Lending - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the securities available for lending data corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: A list of CreditSloCode objects corresponding to the account or None. Remarks: None indicates query failure or an empty list of securities. ```python query_credit_slo_code(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_slo_code(account) ``` -------------------------------- ### XtQuant Price Types (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Defines constants representing various price types available for placing orders across different exchanges and instrument types (stocks, futures, options). These constants are used in the `price_type` field of order placement functions. ```Python # Common Price Types xtconstant.LATEST_PRICE # 最新价 xtconstant.FIX_PRICE # 指定价 # Zhengzhou Commodity Exchange (ZCE) Futures xtconstant.MARKET_BEST # 市价最优价 # Dalian Commodity Exchange (DCE) Futures xtconstant.MARKET_CANCEL # 市价即成剩撤 xtconstant.MARKET_CANCEL_ALL # 市价全额成交或撤 # China Financial Futures Exchange (CFFEX) Futures xtconstant.MARKET_CANCEL_1 # 市价最优一档即成剩撤 xtconstant.MARKET_CANCEL_5 # 市价最优五档即成剩撤 xtconstant.MARKET_CONVERT_1 # 市价最优一档即成剩转 xtconstant.MARKET_CONVERT_5 # 市价最优五档即成剩转 # Shanghai Stock Exchange (SSE) Stocks xtconstant.MARKET_SH_CONVERT_5_CANCEL # 最优五档即时成交剩余撤销 xtconstant.MARKET_SH_CONVERT_5_LIMIT # 最优五档即时成交剩转限价 xtconstant.MARKET_PEER_PRICE_FIRST # 对手方最优价格委托 xtconstant.MARKET_MINE_PRICE_FIRST # 本方最优价格委托 # Shenzhen Stock Exchange (SZSE) Stocks & Options 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 # 全额成交或撤销委托 ``` -------------------------------- ### Synchronizing External Transaction Data - XtQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Synchronizes external transaction data. Supports operations like UPDATE, REPLACE, ADD, DELETE for data type DEAL. Requires the operation type, data type, account, and a list of deal parameters. Returns a dictionary with 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], '}} ``` -------------------------------- ### Credit Account Details (XtCreditDetail) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Provides a comprehensive overview of the assets and liabilities within a credit trading account. It includes status, update time, various balance types (total, available, fetchable), market values (total, stock, fund), total debt, margin details, and specific breakdowns for financing (融資) and securities lending (融券) activities. ```Python class XtCreditDetail: """信用账号资产""" account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 m_nStatus: int # 账号状态 m_nUpdateTime: int # 更新时间 m_nCalcConfig: int # 计算参数 m_dFrozenCash: float # 冻结金额 m_dBalance: float # 总资产 m_dAvailable: float # 可用金额 m_dPositionProfit: float # 持仓盈亏 m_dMarketValue: float # 总市值 m_dFetchBalance: float # 可取金额 m_dStockValue: float # 股票市值 m_dFundValue: float # 基金市值 m_dTotalDebt: float # 总负债 m_dEnableBailBalance: float # 可用保证金 m_dPerAssurescaleValue: float # 维持担保比例 m_dAssureAsset: float # 净资产 m_dFinDebt: float # 融资负债 m_dFinDealAvl: float # 融资本金 m_dFinFee: float # 融资息费 m_dSloDebt: float # 融券负债 m_dSloMarketValue: float # 融券市值 m_dSloFee: float # 融券息费 m_dOtherFare: float # 其它费用 m_dFinMaxQuota: float # 融资授信额度 m_dFinEnableQuota: float # 融资可用额度 m_dFinUsedQuota: float # 融资冻结额度 m_dSloMaxQuota: float # 融券授信额度 m_dSloEnableQuota: float # 融券可用额度 m_dSloUsedQuota: float # 融券冻结额度 m_dSloSellBalance: float # 融券卖出资金 m_dUsedSloSellBalance: float # 已用融券卖出资金 m_dSurplusSloSellBalance: float # 剩余融券卖出资金 ``` -------------------------------- ### Configuring Relaxed Response Order (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Controls whether responses from synchronous request interfaces are returned from a dedicated thread, enabling relaxed data timing. Setting enabled to True (default is False) prevents synchronous queries within push callbacks from blocking, but may result in query data being newer than preceding push data. Use asynchronous query methods like query_stock_orders_async within callbacks for better practice. ```python set_relaxed_response_order_enabled(enabled) ``` -------------------------------- ### XtQuant Order Status (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Enumerated constants representing the possible states of an order within the XtQuant system. These constants are used in the `order_status` field of the `XtOrder` data structure to indicate the current processing state of an order. ```Python # Order Status Constants 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: 未知 ``` -------------------------------- ### XtQuant Trade Data Structure (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Details the `XtTrade` object, which provides information about a completed trade execution. It includes trade identifiers, timestamps, executed price and volume, associated order details, and transaction costs like commission. ```Python class XtTrade: account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 stock_code: str # 证券代码 order_type: int # 委托类型,参见数据字典 traded_id: str # 成交编号 traded_time: int # 成交时间 traded_price: float # 成交均价 traded_volume: int # 成交数量 traded_amount: float # 成交金额 order_id: int # 订单编号 order_sysid: str # 柜台合同编号 strategy_name: str # 策略名称 order_remark: str # 委托备注 direction: int # 多空方向,股票不需要;参见数据字典 offset_flag: int # 交易操作,用此字段区分股票买卖,期货开、平仓,期权买卖等;参见数据字典 stock_code1: str # 证券代码,例如"600000.SH" commission: float # 手续费 ``` -------------------------------- ### Querying Credit Account Details - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the assets corresponding to the credit stock account. Parameters: account - StockAccount stock account. Returns: A list of XtCreditDetail objects corresponding to the credit account or None. Remarks: None indicates query failure. Usually, a single account has only one detailed data entry. ```python query_credit_detail(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_detail(account) ``` -------------------------------- ### Run Trader Forever for Push Notifications - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Calls the 'run_forever' method on the 'xt_trader' object. This blocks the current thread indefinitely to receive real-time push notifications for trading events such as fund, order, trade, and position changes. ```Python xt_trader.run_forever() ``` -------------------------------- ### Asynchronous Cancel Order Response (XtCancelOrderResponse) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Provides feedback after submitting an asynchronous order cancellation request. It includes account and order identifiers, the counter's order system ID, the result of the cancellation attempt, and the sequence number from the original request. ```Python class XtCancelOrderResponse: """异步撤单委托反馈""" account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 order_id: int # 订单编号 order_sysid: str # 柜台委托编号 cancel_result: int # 撤单结果 seq: int # 异步撤单的请求序号 ``` -------------------------------- ### Querying Credit Account Liability Contracts - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the liability contracts corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: A list of StkCompacts objects corresponding to the account or None. Remarks: None indicates query failure or an empty liability contract list. ```python query_stk_compacts(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_stk_compacts(account) ``` -------------------------------- ### Cancel Failure Error (XtCancelError) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Details the information when an asynchronous order cancellation fails. It includes account and order identifiers, the trading market, the counter's order system ID, and the specific error code and message explaining why the cancellation failed. ```Python class XtCancelError: """撤单失败错误""" account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 order_id: int # 订单编号 market: int # 交易市场 0:上海 1:深圳 order_sysid: str # 柜台委托编号 error_id: int # 下单失败错误码 error_msg: str # 下单失败具体信息 ``` -------------------------------- ### Getting Trading Dates - Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xtdata.md 获取交易日列表. Parameters: - market - string 市场代码 - start_time - string 起始时间 - end_time - string 结束时间 - count - int 数据个数 Returns: - list 时间戳列表,[ date1, date2, ... ] Remarks: None. ```python get_trading_dates(market, start_time='', end_time='', count=-1) ``` -------------------------------- ### XtQuant Position Data Structure (Python) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Describes the `XtPosition` object, which holds information about current holdings in a specific security. It includes details like the number of shares/contracts held, available quantity, cost basis, market value, and frozen or on-road volumes. ```Python class XtPosition: account_type: int # 账号类型,参见数据字典 account_id: str # 资金账号 stock_code: str # 证券代码 volume: int # 持仓数量 can_use_volume: int # 可用数量 open_price: float # 开仓价 market_value: float # 市值 frozen_volume: int # 冻结数量 on_road_volume: int # 在途股份 yesterday_volume: int # 昨夜拥股 avg_price: float # 成本价 direction: int # 多空方向,股票不需要;参见数据字典 stock_code1: str # 证券代码,例如"600000.SH" ``` -------------------------------- ### Futures Position Statistics (XtPositionStatistics) Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Describes the detailed statistics for a specific futures position held in an account. It includes information like contract details, direction (long/short), quantity (total, yesterday, today, available to close), costs, profits (position, float), margin usage, and various calculated metrics like average price and profit ratios. ```Python class XtPositionStatistics: """期货持仓统计""" account_id: str # 账户 exchange_id: str # 市场代码 exchange_name: str # 市场名称 product_id: str # 品种代码 instrument_id: str # 合约代码 instrument_name: str # 合约名称 direction: int # 多空 hedge_flag: int # 投保 position: int # 持仓 yesterday_position: int # 昨仓 today_position: int # 今仓 can_close_vol: int # 可平 position_cost: float # 持仓成本 avg_price: float # 持仓均价 position_profit: float # 持仓盈亏 float_profit: float # 浮动盈亏 open_price: float # 开仓均价 used_margin: float # 已使用保证金 used_commission: float # 已使用的手续费 frozen_margin: float # 冻结保证金 frozen_commission: float # 冻结手续费 instrument_value: float # 市值,合约价值 open_times: int # 开仓次数 open_volume: int # 总开仓量 中间平仓不减 cancel_times: int # 撤单次数 last_price: float # 最新价 rise_ratio: float # 当日涨幅 product_name: str # 产品名称 royalty: float # 权利金市值 expire_date: str # 到期日 assest_weight: float # 资产占比 increase_by_settlement: float # 当日涨幅(结) margin_ratio: float # 保证金占比 float_profit_divide_by_used_margin: float # 浮盈比例(保证金) float_profit_divide_by_balance: float # 浮盈比例(动态权益) today_profit_loss: float # 当日盈亏(结) yesterday_init_position: int # 昨日持仓 frozen_royalty: float # 冻结权利金 today_close_profit_loss: float # 当日盈亏(收) close_profit: float # 平仓盈亏 ft_product_name: str # 品种名称 open_cost: float # 开仓成本 ``` -------------------------------- ### Querying Credit Account Margin/Lending Subjects - XTQuant Python Source: https://github.com/xuntou/xtquant-doc/blob/main/version_241014/doc/xttrader.md Queries the margin trading and securities lending subjects corresponding to the stock account. Parameters: account - StockAccount stock account. Returns: A list of CreditSubjects objects corresponding to the account or None. Remarks: None indicates query failure or an empty list of subjects. ```python query_credit_subjects(account) ``` ```python account = StockAccount('1208970161', 'CREDIT') #xt_trader为XtQuant API实例对象 datas = xt_trader.query_credit_subjects(account) ```