### APIDOC: Message Push - `start` Function Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Starts the event loop to receive trading events and trigger callback functions. It returns an integer value, where 0 indicates success and any non-zero value indicates failure. It is crucial to keep the process active for callbacks to function correctly. ```python start(filename=None, token=None, endpoint=None) ``` ```APIDOC Parameters: filename: str - File containing the callback function. The special variable `__file__` can be used for the current file. token: str - Token for identity authentication, obtainable from the simulated trading official website after login. endpoint: str - Simulation service address. If not filled, defaults to the local terminal service address. Note: Requires the process to remain active, e.g.: # Keep the process from exiting, otherwise callbacks will no longer be effective info = input("Enter any character to exit")) ``` -------------------------------- ### Python Example: Query Unfinished Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Demonstrates how to use the `get_unfinished_orders` function in Python to retrieve and display all unfinished orders for the current day. ```python get_unfinished_orders() ``` -------------------------------- ### DataArray Usage Example: Querying and Iterating with at() Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Demonstrates how to query historical tick data using `history_ticks`, check the `DataArray` status, iterate through the results using the `at()` method, and release the data. ```cpp //查询一段tick行情 DataArray *da = history_ticks("SHSE.600000", "2018-07-16 09:30:00", "2018-07-16 10:30:00"); if (da->status() == 0) //判断查询是否成功 { //遍历行情数组 for (int i = 0; i < da->count(); i++) { cout << da->at(i).symbol << " " << da->at(i).price << endl; } } //释放数组 da->release(); ``` -------------------------------- ### C++ API Query and Order Placement Example Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md This C++ snippet demonstrates direct API calls for querying trading data and placing orders. It covers fetching positions, placing market orders, canceling orders, retrieving execution reports, listing all orders, and checking account cash balance. It requires token authentication and account login to the MyQuant trading server. ```cpp #include #include "gmtrade.h" #include "gmtrade_def.h" //引入命名空间 using namespace gmtrade; using namespace std; int main () { //token身份认证 //不关注交易事件, 可以直接使用Trade类对象调用交易函数进行交易 Trade mt ("token"); //设置仿真服务地址api.myquant.cn:9000 mt.set_endpoint ("api.myquant.cn:9000"); //登录账户ID mt.login ("account_id"); //查持仓 DataArray *ps = mt.get_position (); if (ps->status () == 0) { //遍历持仓 for (int i = 0; i < ps->count (); i++) { Position &p = ps->at (i); cout << "account_id: " << p.account_id << endl; cout << "available: " << p.available << endl; cout << "symbol: " << p.symbol << endl; cout << "fpnl: " << p.fpnl << endl; cout << "volume: " << p.volume << endl; cout << "vwap: " << p.vwap << endl; } //内存释放 ps->release (); } //下单, 以市场价买入1000股浦发银行 Order order = mt.order_volume ("SHSE.600000", 1000, OrderSide_Buy, OrderType_Market, PositionEffect_Open); //撤单 mt.order_cancel (order.cl_ord_id); //获取执行回报 DataArray* rpts = mt.get_execution_reports (); if (rpts->status () == 0) { //遍历执行回报 // ... //释放内存 rpts->release (); } //查委托 DataArray* orders = mt.get_orders (); if (orders->status () == 0) { //遍历委托 // ... //释放内存 orders->release (); } //查资金 Cash cash{}; int res = mt.get_cash (cash); if (res == 0) { cout << "account_id: "<< cash.account_id; cout << "available: " << cash.available; cout << "balance: " << cash.balance; cout << "fpnl: " << cash.fpnl; } cout << "程序结束" << endl; getchar(); } ``` -------------------------------- ### Python Example: Place Batch Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Demonstrates how to use the `order_batch` function in Python to place multiple orders as a combined batch. It initializes two order dictionaries with symbol, volume, price, side, order type, and position effect, then calls `order_batch` with these orders, and iterates to print the results. ```python order_1 = {'symbol': 'SHSE.600000', 'volume': 100, 'price': 11, 'side': 1, 'order_type': 2, 'position_effect':1} order_2 = {'symbol': 'SHSE.600004', 'volume': 100, 'price': 11, 'side': 1, 'order_type': 2, 'position_effect':1} orders = [order_1, order_2] batch_orders = order_batch(orders, combine=True) for order in batch_orders: print(order) ``` -------------------------------- ### Python Example: Cancel All Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Demonstrates how to use the `order_cancel_all` function in Python to cancel all pending orders with a single call. ```python order_cancel_all() ``` -------------------------------- ### Python Example: Close All Positions Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Demonstrates how to use the `order_close_all` function in Python to close all current open positions with a single call. ```python order_close_all() ``` -------------------------------- ### DataArray Usage Example: Querying and Iterating with data() Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Illustrates an alternative way to iterate through `DataArray` results by obtaining the raw array pointer using `data()` and then accessing elements directly. Always remember to release the data. ```cpp //查询一段tick行情 DataArray *da = history_ticks("SHSE.600000", "2018-07-16 09:30:00", "2018-07-16 10:30:00"); if (da->status() == 0) //判断查询是否成功 { //获得原始数组指针 Tick *ticks = da->data(); //遍历行情数组 for (int i = 0; i < da->count(); i++) { cout << ticks[i].symbol << " " << ticks[i].price << endl; } } //释放数组 da->release(); ``` -------------------------------- ### C++ Event-Driven Trading Information Reception Example Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md This C++ snippet illustrates an event-driven approach to receive real-time trading updates. By inheriting the `Trade` class and overriding methods like `on_order_status`, `on_execution_report`, `on_trade_data_connected`, `on_trade_data_disconnected`, and `on_account_status`, users can process order status changes, execution reports, and connection/account status events. This method provides more timely updates compared to polling. ```cpp #include #include "gmtrade.h" //引入命名空间 using namespace gmtrade; using namespace std; //定义交易类, 继承Trade, 通过重写方法关注交易时间, 如 on_order_status, on_execution_report 等, 具体事件说明参考"交易事件类型" class MyTrade:public Trade { public: MyTrade (const std::string& token) :Trade (token.c_str()) { } //关注委托状态变化 void on_order_status(Order* order) override { cout << "symbol: " << order->symbol << endl; cout << "cl_ord_id" << order->cl_ord_id << endl; cout << "status: " << order->status << endl; cout << "volume: " << order->volume << endl; cout << "filled_amount: " << order->filled_amount << endl; cout << "filled_commission: " << order->filled_commission << endl; cout << "filled_volume: " << order->filled_volume << endl; cout << "filled_vwap: " << order->filled_vwap << endl; cout << "created_at: " << order->created_at << endl; } //关注执行回报, 如成交, 撤单拒绝等 void on_execution_report(ExecRpt* rpt) override { cout << "price: " << rpt->price << endl; cout << "volume: " << rpt->volume << endl; cout << "amount: " << rpt->amount << endl; cout << "commission: " << rpt->commission << endl; cout << "cost: " << rpt->cost << endl; cout << "created_at: " << rpt->created_at<< endl; } void on_trade_data_connected () override { cout << "连接上交易服务器 .........." << endl; } void on_trade_data_disconnected () override { cout << "断开交易服务器 ........." << endl; } void on_account_status (AccountStatus *account_status) override { cout << "账户状态变化 : " << account_status->state << endl; } }; int main() { //token身份认证 MyTrade mt ("token"); // 设置服务地址api.myquant.cn:9000 mt.set_endpoint ("api.myquant.cn:9000"); //登录账户id mt.login("account_id"); //开始接收事件 int status = mt.start (); //判断状态 if (status == 0) { cout << "连接成功, 开始运行" << endl; } else { cout << "连接失败" << endl; } // 保持进程不退出,否则回调不再生效 getchar(); } ``` -------------------------------- ### Python Example: Cancel Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Demonstrates how to use the `order_cancel` function in Python to cancel multiple specific orders. It initializes two order dictionaries with `cl_ord_id` and then calls `order_cancel` with these orders. ```python order_1 = {'symbol': 'SHSE.600000', 'cl_ord_id': 'cl_ord_id_1', 'price': 11, 'side': 1, 'order_type':1 } order_2 = {'symbol': 'SHSE.600004', 'cl_ord_id': 'cl_ord_id_2', 'price': 11, 'side': 1, 'order_type':1 } orders = [order_1, order_2] order_cancel(wait_cancel_orders=orders) ``` -------------------------------- ### DataArray::at(int i) Method API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Returns a reference to the element at the specified index `i`, starting from 0. If status indicates failure, the array should not be traversed. ```APIDOC DataArray::at(int i) Function Prototype: T& at(int i) Parameters: i (int): Array index, starting from 0 返回值 (T&): Reference to the data element, specific to the template parameter T Notes: 1. If status indicates failure, the array should not be traversed; it should be released directly. ``` -------------------------------- ### DataArray Class Template Definition Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the `DataArray` template class, a standard return type for market and trading data queries. It provides methods to check status, access data, get count, access elements by index, and release resources. ```cpp template class DataArray { public: //获取api调用结果, 0: 成功, 非0: 错误码 virtual int status() = 0; //返回结构数组的指针 virtual T* data() = 0; //返回数据的长度 virtual int count() = 0; //返回下标为i的结构引用,从0开始 virtual T& at(int i) = 0; //释放数据集合 virtual void release() = 0; }; ``` -------------------------------- ### get_orders - Query All Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Queries all orders. ```C++ DataArray* get_orders(const char *account = NULL); ``` ```APIDOC get_orders API Details: Parameters: account (const char *): Account ID `account_id`. If NULL is entered, orders for all accounts are returned. Returns: DataArray*: An array of Order structures. ``` -------------------------------- ### order_batch API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Detailed API documentation for the `order_batch` function, used for placing multiple orders. It supports combining orders and specifying an account. Includes parameter definitions, return structure, and important notes regarding symbol validation, volume constraints, position sufficiency, and order type precedence (market vs. limit price behavior). Invalid parameters result in NameError, while missing parameters may lead to rejected orders. ```APIDOC Function Prototype: order_batch(orders, combine=False, account='') Parameters: orders: list[order] - List of order objects, each containing at least the required parameters for the trading interface. Refer to [Order Object](e#Order - 委托对象). combine: bool - Whether it's a combined order (default is False). account: account id or account name or None - Account ID or name. Return Value Sample: status volume account_id created_at position_side symbol target_percent percent value side position_effect target_volume filled_amount filled_volume order_style filled_vwap price strategy_id target_value order_type -------- -------- ------------ ------------------- --------------- ----------- ---------------- --------- ------- ------ ----------------- --------------- --------------- --------------- ------------- ------------- ------- ------------- -------------- ------------ 3 9000 strategy_id 2017-07-06 07:00:01 1 SHSE.600000 0.099 0.1 100000 1 1 9000 99000 9000 3 11 11 strategy_id 99000 1 ``` -------------------------------- ### C++ gmtrade::Trade Class API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Detailed API reference for the `gmtrade::Trade` class, including its public constructors, basic functions for connection management, trading functions for various order types and queries, and virtual event callback functions for real-time updates. ```cpp namespace gmtrade { class GM_TRADE_API Trade { public: Trade(const char *token); Trade(); virtual ~Trade(); public: //基础函数 //开始接收事件 int start(); //停止接收事件 void stop(); //设置用户token void set_token(const char *token); //设置服务地址 void set_endpoint(const char *serv_addr); public: //交易函数 int login(const char *account_ids); //按指定量委托 Order order_volume(const char *symbol, int volume, int side, int order_type, int position_effect, double price = 0, const char *account = NULL); //按指定价值委托 Order order_value(const char *symbol, double value, int side, int order_type, int position_effect, double price = 0, const char *account = NULL); //按总资产指定比例委托 Order order_percent(const char *symbol, double percent, int side, int order_type, int position_effect, double price = 0, const char *account = NULL); //调仓到目标持仓量 Order order_target_volume(const char *symbol, int volume, int position_side, int order_type, double price = 0, const char *account = NULL); //调仓到目标持仓额 Order order_target_value(const char *symbol, double value, int position_side, int order_type, double price = 0, const char *account = NULL); //调仓到目标持仓比例(总资产的比例) Order order_target_percent(const char *symbol, double percent, int position_side, int order_type, double price = 0, const char *account = NULL); //平当前所有可平持仓 DataArray* order_close_all(); //委托撤单 int order_cancel(const char *cl_ord_id, const char *account = NULL); //撤销所有委托 int order_cancel_all(); //委托下单 Order place_order(const char *symbol, int volume, int side, int order_type, int position_effect, double price = 0, int order_duration = 0, int order_qualifier = 0, double stop_price = 0, const char *account = NULL); //查询资金 int get_cash(Cash &cash, const char *accounts = NULL); //查询委托 DataArray* get_orders(const char *account = NULL); //查询未结委托 DataArray* get_unfinished_orders(const char *account = NULL); //查询成交 DataArray* get_execution_reports(const char *account = NULL); //查询持仓 DataArray* get_position(const char *account = NULL); public: //事件函数 //委托变化 virtual void on_order_status(Order *order); //执行回报 virtual void on_execution_report(ExecRpt *rpt); //实盘账号状态变化 virtual void on ``` -------------------------------- ### get_execution_reports - Query Execution Reports Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Queries all execution reports. ```C++ DataArray* get_execution_reports(const char *account = NULL); ``` ```APIDOC get_execution_reports API Details: Parameters: account (const char *): Account ID `account_id`. If NULL is entered, execution reports for all accounts are returned. Returns: DataArray*: An array of ExecRpt structures. ``` -------------------------------- ### get_unfinished_orders - Query Unfinished Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Queries all unfinished orders. ```C++ DataArray* get_unfinished_orders(const char *account = NULL); ``` ```APIDOC get_unfinished_orders API Details: Parameters: account (const char *): Account ID `account_id`. If NULL is entered, orders for all accounts are returned. Returns: DataArray*: An array of Order structures. ``` -------------------------------- ### order_volume - Place Order by Specified Volume Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Places an order by specified volume. If the call is successful, subsequent order status changes will trigger the on_order_status callback. ```C++ Order order_volume(const char *symbol, int volume, int side, int order_type, int position_effect, double price = 0, const char *account = NULL); ``` ```APIDOC order_volume API Details: Parameters: symbol (const char *): Instrument code, only single instrument. volume (int): Order quantity. side (int): Order direction, see `enum OrderSide`. order_type (int): Order type, see `enum OrderType`. position_effect (int): Open/Close type, see `enum PositionSide`. price (double): Order price. account (const char *): Real account ID, fill in when associating multiple real accounts, can be obtained from `get_accounts` or copied from terminal real account configuration. If the strategy is only associated with one account, it can be set to NULL. Returns: Order: An Order structure. If the function call fails, `Order.status` will be `OrderStatus_Rejected`, and `Order.ord_rej_reason_detail` will be the error reason description. Otherwise, it indicates the function call was successful, and `Order.cl_ord_id` is the identifier for this order, which can be used to track order status or cancel the order. Notes: 1. Only one instrument code is supported. If the trading code is incorrect, the terminal will reject the order and display `Incorrect order code`. 2. If the order quantity is incorrect, the terminal will reject the order and display `Incorrect order quantity`. The minimum unit for stock buying is `100`, and for selling is `1`. If there are holdings less than 100 shares, they can be sold at once; the minimum unit for futures buying and selling is `1`, `rounded down`. 3. If the position is insufficient, the terminal will reject the order and display `Insufficient position`. When closing positions, stocks default to `closing yesterday's positions`, and futures default to `closing today's positions`. For research needs, `stock short selling is also supported`. 4. `Order_type` has higher priority than `price`. If `OrderType_Market` is specified for a market order, the price used will be the latest price from the latest tick, and the `price` parameter will be invalid. If `OrderType_Limit` is specified for a limit order, and the price is incorrect in simulation mode, the terminal will reject the order and display `Incorrect order price`. `In backtesting mode, there is no price restriction`. 5. A successful function call does not mean the order has been successful; it only means the order has been successfully sent. Whether the order is successful should be judged based on `on_order_status` or `get_order`. ``` ```C++ //以11块的价格限价买入10000股浦发银行 Order o = order_volume("SHSE.600000", 10000, OrderSide_Buy, OrderType_Limit, PositionEffect_Open, 11); ``` -------------------------------- ### OrderRejectReason Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the various reasons why an order might be rejected, such as insufficient funds, invalid parameters, or account issues. ```cpp OrderRejectReason_Unknown = 0 ## 未知原因 OrderRejectReason_RiskRuleCheckFailed = 1 ## 不符合风控规则 OrderRejectReason_NoEnoughCash = 2 ## 资金不足 OrderRejectReason_NoEnoughPosition = 3 ## 仓位不足 OrderRejectReason_IllegalAccountId = 4 ## 非法账户ID OrderRejectReason_IllegalStrategyId = 5 ## 非法策略ID OrderRejectReason_IllegalSymbol = 6 ## 非法交易标的 OrderRejectReason_IllegalVolume = 7 ## 非法委托量 OrderRejectReason_IllegalPrice = 8 ## 非法委托价 OrderRejectReason_AccountDisabled = 10 ## 交易账号被禁止交易 OrderRejectReason_AccountDisconnected = 11 ## 交易账号未连接 OrderRejectReason_AccountLoggedout = 12 ## 交易账号未登录 OrderRejectReason_NotInTradingSession = 13 ## 非交易时段 OrderRejectReason_OrderTypeNotSupported = 14 ## 委托类型不支持 OrderRejectReason_Throttle = 15 ## 流控限制 ``` -------------------------------- ### OrderStyle Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines different styles for placing orders, such as by specified volume, value, or percentage, or for adjusting to target positions. ```cpp OrderStyle_Unknown = 0 OrderStyle_Volume = 1 ## 按指定量委托 OrderStyle_Value = 2 ## 按指定价值委托 OrderStyle_Percent = 3 ## 按指定比例委托 OrderStyle_TargetVolume = 4 ## 调仓到目标持仓量 OrderStyle_TargetValue = 5 ## 调仓到目标持仓额 OrderStyle_TargetPercent = 6 ## 调仓到目标持仓比例 ``` -------------------------------- ### order_cancel_all API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Detailed API documentation for the `order_cancel_all` function, used for canceling all pending orders for the current account. ```APIDOC Function Prototype: order_cancel_all() ``` -------------------------------- ### order_close_all API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Detailed API documentation for the `order_close_all` function, used for closing all current open positions that are available to be closed. ```APIDOC Function Prototype: order_close_all() ``` -------------------------------- ### Define Order Styles in Python Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Defines different styles or types of orders that can be placed in the trading system, including volume-based, value-based, and target-based orders. This allows for flexible order placement strategies. ```Python OrderStyle_Unknown = 0 OrderStyle_Volume = 1 ## 按指定量委托 OrderStyle_Value = 2 ## 按指定价值委托 OrderStyle_Percent = 3 ## 按指定比例委托 OrderStyle_TargetVolume = 4 ## 调仓到目标持仓量 OrderStyle_TargetValue = 5 ## 调仓到目标持仓额 OrderStyle_TargetPercent = 6 ## 调仓到目标持仓比例 ``` -------------------------------- ### get_unfinished_orders API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Detailed API documentation for the `get_unfinished_orders` function, used for querying all unfinished orders for the current trading day. It returns a list of order objects. ```APIDOC Function Prototype: get_unfinished_orders() Return Value: Type: list[order] - List of order objects. Refer to [Order Object](#order---委托对象). Return Value Sample: status volume account_id created_at position_side symbol target_percent percent value side position_effect target_volume filled_amount filled_volume order_style filled_vwap price strategy_id target_value order_type -------- -------- ------------ ------------------- --------------- ----------- ---------------- --------- ------- ------ ----------------- --------------- --------------- --------------- ------------- ------------- ------- ------------- -------------- ------------ 3 9000 strategy_id 2017-07-06 07:00:01 1 SHSE.600000 0.099 0.1 100000 1 1 9000 99000 9000 3 11 11 strategy_id 99000 1 ``` -------------------------------- ### Define Trading Account Status States in C++ Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Enumerates the possible connection and login states of a trading account, ranging from unknown and connecting to connected, logged in, disconnected, and error states. This helps in monitoring the account's operational status. ```C++ State_UNKNOWN = 0; //未知 State_CONNECTING = 1; //连接中 State_CONNECTED = 2; //已连接 State_LOGGEDIN = 3; //已登录 State_DISCONNECTING = 4; //断开中 State_DISCONNECTED = 5; //已断开 State_ERROR = 6; //错误 ``` -------------------------------- ### Common Error Codes API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md A list of common error codes returned by API calls, along with their descriptions. A code of 0 indicates success. ```APIDOC Error Codes: 0: Success 1000: Error or invalid token 1010: Failed to get Gujin server address list 1011: Message packet parsing error 1012: Network message packet parsing error 1013: Trading service call error 1019: Trading gateway service call error 1020: Invalid ACCOUNT_ID 1022: Execution timeout 1100: Trading message service connection failed 1101: Trading message service disconnected ``` -------------------------------- ### APIDOC: Account Login - `login` Function Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Function to log in with a collection of account objects. The first successfully logged-in account is set as the default. Specific accounts can be designated for transactions. ```python login(accounts) ``` ```APIDOC Parameters: accounts: iterable[account] - Collection of funding accounts ``` -------------------------------- ### on_trade_data_connected - Trade Data Connected Callback Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Triggered when trade data is connected. ```C++ virtual void on_trade_data_connected(); ``` -------------------------------- ### CancelOrderRejectReason Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the reasons why an order cancellation request might be rejected, such as the order already being finalized or unknown. ```cpp CancelOrderRejectReason_OrderFinalized = 101 ## 委托已完成 CancelOrderRejectReason_UnknownOrder = 102 ## 未知委托 CancelOrderRejectReason_BrokerOption = 103 ## 柜台设置 CancelOrderRejectReason_AlreadyInPendingCancel = 104 ## 委托撤销中 ``` -------------------------------- ### Define Order Reject Reasons in Python Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Enumerates the various reasons why an order might be rejected by the trading system, including risk rule failures, insufficient funds, or invalid parameters. These codes help in diagnosing order placement issues. ```Python OrderRejectReason_Unknown = 0 ## 未知原因 OrderRejectReason_RiskRuleCheckFailed = 1 ## 不符合风控规则 OrderRejectReason_NoEnoughCash = 2 ## 资金不足 OrderRejectReason_NoEnoughPosition = 3 ## 仓位不足 OrderRejectReason_IllegalAccountId = 4 ## 非法账户ID OrderRejectReason_IllegalStrategyId = 5 ## 非法策略ID OrderRejectReason_IllegalSymbol = 6 ## 非法交易标的 OrderRejectReason_IllegalVolume = 7 ## 非法委托量 OrderRejectReason_IllegalPrice = 8 ## 非法委托价 OrderRejectReason_AccountDisabled = 10 ## 交易账号被禁止交易 OrderRejectReason_AccountDisconnected = 11 ## 交易账号未连接 OrderRejectReason_AccountLoggedout = 12 ## 交易账号未登录 OrderRejectReason_NotInTradingSession = 13 ## 非交易时段 OrderRejectReason_OrderTypeNotSupported = 14 ## 委托类型不支持 OrderRejectReason_Throttle = 15 ## 流控限制 ``` -------------------------------- ### Query All Intraday Orders - get_orders API Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Retrieves a list of all intraday orders. This function takes no parameters and returns a list of order objects, providing comprehensive details such as status, volume, price, and timestamps for each order. ```APIDOC get_orders() Returns: list[order]: List of order objects. See Order object documentation for details. ``` ```python get_orders() ``` ```python status volume account_id created_at position_side symbol target_percent percent value side position_effect target_volume filled_amount filled_volume order_style filled_vwap price strategy_id target_value order_type -------- -------- ------------ ------------------- --------------- ----------- ---------------- --------- ------- ------ ----------------- --------------- --------------- --------------- ------------- ------------- ------- ------------- -------------- ------------ 3 9000 strategy_id 2017-07-06 07:00:01 1 SHSE.600000 0.099 0.1 100000 1 1 9000 99000 9000 3 11 11 strategy_id 99000 1 ``` -------------------------------- ### API Error Codes Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Provides a comprehensive list of common API error codes and their corresponding descriptions, which are returned by the trading system to indicate reasons for failed API calls or operations. This reference is crucial for debugging and error handling. ```APIDOC Error Code | Description -----------|------------ 0 | 成功 1000 | 错误或无效的token 1010 | 无法获取掘金服务器地址列表 1011 | 消息包解析错误 1012 | 网络消息包解析错误 1013 | 交易服务调用错误 1019 | 交易网关服务调用错误 1020 | 无效的ACCOUNT_ID 1021 | 非法日期格式 1100 | 交易消息服务连接失败 1101 | 交易消息服务断开 ``` -------------------------------- ### APIDOC: Account Login - `account` Function Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Function to construct an account object. It takes an optional account ID and alias, returning an `Account` object. This object is used for subsequent login operations. ```python account(account_id='', account_alias='') ``` ```APIDOC Parameters: account_id: str - Account ID account_alias: str - Account Alias, optional Returns: Account object Note: Pass a collection of account objects as parameters. The first successfully logged-in account object is designated as the default account. If you need to specify another account for trading, you must specify the account in the function. ``` -------------------------------- ### AccountStatus Enum Definition Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the possible states for a trading account, ranging from unknown to connected, logged in, disconnecting, disconnected, and error states. ```cpp State_UNKNOWN = 0; //未知 State_CONNECTING = 1; //连接中 State_CONNECTED = 2; //已连接 State_LOGGEDIN = 3; //已登录 State_DISCONNECTING = 4; //断开中 State_DISCONNECTED = 5; //已断开 State_ERROR = 6; //错误 ``` -------------------------------- ### DataArray::data() Method API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Returns a pointer to the raw data array. This pointer can be used for iteration and copying data. If status indicates failure, the array should not be traversed. ```APIDOC DataArray::data() Function Prototype: T* data() Parameters: 返回值 (结构指针): Specific to the template parameter T Notes: 1. If status indicates failure, the array should not be traversed; it should be released directly. ``` -------------------------------- ### OrderStatus Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the possible states of an order within the trading system, including new, partially filled, filled, canceled, and various pending or rejected states. ```cpp OrderStatus_Unknown = 0 OrderStatus_New = 1 ## 已报 OrderStatus_PartiallyFilled = 2 ## 部成 OrderStatus_Filled = 3 ## 已成 OrderStatus_Canceled = 5 ## 已撤 OrderStatus_PendingCancel = 6 ## 待撤 OrderStatus_Rejected = 8 ## 已拒绝 OrderStatus_Suspended = 9 ## 挂起 OrderStatus_PendingNew = 10 ## 待报 OrderStatus_Expired = 12 ## 已过期 ``` -------------------------------- ### Define Cancel Order Reject Reasons in Python Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Enumerates the reasons why an order cancellation request might be rejected, such as the order already being finalized, an unknown order ID, or broker-specific settings. These codes assist in understanding cancellation failures. ```Python CancelOrderRejectReason_OrderFinalized = 101 ## 委托已完成 CancelOrderRejectReason_UnknownOrder = 102 ## 未知委托 CancelOrderRejectReason_BrokerOption = 103 ## 柜台设置 CancelOrderRejectReason_AlreadyInPendingCancel = 104 ## 委托撤销中 ``` -------------------------------- ### Enumeration Constant: ExecType - Execution Report Type Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Defines the types of execution reports, indicating various stages of an order's lifecycle. These include statuses like new, canceled, trade, and other updates, providing a detailed audit trail for order execution. ```python ExecType_Unknown = 0 ExecType_New = 1 ## 已报 ExecType_Canceled = 5 ## 已撤销 ExecType_PendingCancel = 6 ## 待撤销 ExecType_Rejected = 8 ## 已拒绝 ExecType_Suspended = 9 ## 挂起 ExecType_PendingNew = 10 ## 待报 ExecType_Expired = 12 ## 已过期 ExecType_Trade = 15 ## 成交 ExecType_OrderStatus = 18 ## 委托状态 ExecType_CancelRejected = 19 ## 撤单被拒绝 ``` -------------------------------- ### on_account_status - Real Account Status Change Callback Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Triggered when the real account status changes, such as real account login or logout. ```C++ virtual void on_account_status(AccountStatus *account_status); ``` ```APIDOC on_account_status API Details: Parameters: account_status (AccountStatus *): Corresponding changed account. ``` -------------------------------- ### OrderSide Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the direction of an order, specifying whether it is a buy or sell order. ```cpp OrderSide_Unknown = 0 OrderSide_Buy = 1 ## 买入 OrderSide_Sell = 2 ## 卖出 ``` -------------------------------- ### Query All Intraday Execution Reports - get_execution_reports API Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Retrieves a list of all intraday execution reports. This function takes no parameters and returns a list of execution report objects, detailing trade executions and their outcomes. ```APIDOC get_execution_reports() Returns: list[execrpt]: List of execution report objects. See ExecRpt object documentation for details. ``` ```python get_execution_reports() ``` -------------------------------- ### DataArray::release() Method API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Releases the data set. This method must be called after obtaining a `DataArray` pointer, regardless of the status, to prevent memory leaks. No other member functions should be called after `release()`. ```APIDOC DataArray::release() Function Prototype: void release() ``` -------------------------------- ### OrderQualifier Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines special execution qualifiers for an order, such as best of counterparty or best 5 then cancel. These settings are effective only in live trading mode and depend on exchange definitions. ```cpp OrderQualifier_Unknown = 0 OrderQualifier_BOC = 1 ## 对方最优价格(best of counterparty) OrderQualifier_BOP = 2 ## 己方最优价格(best of party) OrderQualifier_B5TC = 3 ## 最优五档剩余撤销(best 5 then cancel) OrderQualifier_B5TL = 4 ## 最优五档剩余转限价(best 5 then limit) ``` -------------------------------- ### ExecType Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the type of execution report received for an order, indicating its current status or a specific event like a trade or rejection. ```cpp ExecType_Unknown = 0 ExecType_New = 1 ## 已报 ExecType_Canceled = 5 ## 已撤销 ExecType_PendingCancel = 6 ## 待撤销 ExecType_Rejected = 8 ## 已拒绝 ExecType_Suspended = 9 ## 挂起 ExecType_PendingNew = 10 ## 待报 ExecType_Expired = 12 ## 过期 ExecType_Trade = 15 ## 成交 ExecType_OrderStatus = 18 ## 委托状态 ExecType_CancelRejected = 19 ## 撤单被拒绝 ``` -------------------------------- ### Define Cash and Position Change Reasons in Python Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Enumerates the reasons for changes in cash or position within a trading account, primarily due to trades or deposits/withdrawals. This helps in tracking the source of balance alterations. ```Python CashPositionChangeReason_Unknown = 0 CashPositionChangeReason_Trade = 1 ## 交易 CashPositionChangeReason_Inout = 2 ## 出入金 / 出入持仓 ``` -------------------------------- ### DataArray::status() Method API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Retrieves the API call result. This method should be called first after obtaining a `DataArray` pointer to determine if the data query was successful. A return value of 0 indicates success, while non-zero indicates an error code. If status is non-zero, the array should not be traversed. ```APIDOC DataArray::status() Function Prototype: int status() Parameters: 返回值 (int): 0: Success, Non-zero: Error code Notes: 1. If status indicates failure, the array should not be traversed; it should be released directly. ``` -------------------------------- ### OrderType Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the type of order, such as limit, market, or stop orders. ```cpp OrderType_Unknown = 0 OrderType_Limit = 1 ## 限价委托 OrderType_Market = 2 ## 市价委托 OrderType_Stop = 3 ## 止损止盈委托 ``` -------------------------------- ### APIDOC: Position Object Attributes Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Defines the attributes of the Position object, representing a trading holding. It includes details on account, symbol, volume, price, profit/loss, and various timestamps. Formulas for calculated fields like `vwap`, `amount`, `fpnl`, `cost`, `available`, and `available_today` are provided for clarity on how these values are derived. ```APIDOC Position Object Attributes: account_id: str - Account ID account_name: str - Account Login Name symbol: str - Symbol Code side: int - Position Direction (Refer to [PositionSide](#positionside---持仓方向 "PositionSide - 持仓方向")) volume: long - Total Holding Volume; Yesterday's holding volume = `(volume - volume_today)` volume_today: long - Today's Holding Volume vwap: float - Average Holding Price `new_vwap=((position.vwap * position.volume)+(trade.volume*trade.price))/(position.volume+trade.volume)` amount: float - Holding Amount `(volume*vwap*multiplier)` price: float - Current Market Price (0 in backtesting) fpnl: float - Floating P&L `((price - vwap) * volume * multiplier)` (Updated once per day or on position change in backtesting, every 3s in simulation) cost: float - Holding Cost `(vwap * volume * multiplier * margin_ratio)` order_frozen: int - Order Frozen Position order_frozen_today: int - Order Frozen Today's Position available: long - Available Total Position to Close `(volume - order_frozen)`; Available yesterday's position to close = `(available - available_today)` available_today: long - Available Today's Position to Close `(volume_today - order_frozen_today)` (Futures only) last_price: float - Last Transaction Price (0 in backtesting) last_volume: long - Last Transaction Volume (0 in backtesting) last_inout: int - Last In/Out Holding Volume (0 in backtesting) change_reason: int - Position Change Reason (Refer to [CashPositionChangeReason](#cashpositionchangereason---仓位变更原因 "CashPositionChangeReason - 仓位变更原因")) change_event_id: str - ID of Triggering Fund Change Event created_at: datetime.datetime - Position Creation Time updated_at: datetime.datetime - Position Update Time ``` -------------------------------- ### on_trade_data_disconnected - Trade Data Disconnected Callback Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Triggered when trade data is disconnected. ```C++ virtual void on_trade_data_disconnected(); ``` -------------------------------- ### order_cancel API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Detailed API documentation for the `order_cancel` function, used for canceling one or more pending orders. It requires a list of order objects or a single order object, each containing at least the `cl_ord_id`. ```APIDOC Function Prototype: order_cancel(wait_cancel_orders) Parameters: wait_cancel_orders: list[str] - List of order objects or a single order object, must contain cl_ord_id. Refer to [Order Object](#order---委托对象). ``` -------------------------------- ### SecType Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the categories of securities, including stocks, funds, indices, futures, and options. ```cpp SEC_TYPE_STOCK = 1 ## 股票 SEC_TYPE_FUND = 2 ## 基金 SEC_TYPE_INDEX = 3 ## 指数 SEC_TYPE_FUTURE = 4 ## 期货 SEC_TYPE_OPTION = 5 ## 期权 SEC_TYPE_CONFUTURE = 10 ## 虚拟合约 ``` -------------------------------- ### DataArray::count() Method API Documentation Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Returns the number of elements in the array. If status indicates failure, the array should not be traversed. ```APIDOC DataArray::count() Function Prototype: int count() Parameters: 返回值 (int): Number of data elements Notes: 1. If status indicates failure, the array should not be traversed; it should be released directly. ``` -------------------------------- ### order_cancel_all - Cancel All Orders Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Cancels all orders. If the call is successful, subsequent order status changes will trigger the on_order_status callback. ```C++ int order_cancel_all(); ``` ```APIDOC order_cancel_all API Details: Returns: int: Returns 0 on success, error code on failure. ``` -------------------------------- ### OrderDuration Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the time-in-force attributes for an order, specifying how long an order remains active. These settings are effective only in live trading mode and depend on exchange definitions. ```cpp OrderDuration_Unknown = 0 OrderDuration_FAK = 1 ## 即时成交剩余撤销(fill and kill) OrderDuration_FOK = 2 ## 即时全额成交或撤销(fill or kill) OrderDuration_GFD = 3 ## 当日有效(good for day) OrderDuration_GFS = 4 ## 本节有效(good for section) OrderDuration_GTD = 5 ## 指定日期前有效(goodltilldate) OrderDuration_GTC = 6 ## 撤销前有效(goodtillcancel) OrderDuration_GFA = 7 ## 集合竞价前有效(good for auction) ``` -------------------------------- ### on_error - Error Occurred Callback Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Triggered when an error occurs, such as network disconnection. ```C++ virtual void on_error(int error_code, const char *error_msg); ``` ```APIDOC on_error API Details: Parameters: error_code (int): Error code. error_msg (const char *): Error message. ``` -------------------------------- ### order_close_all - Close All Closable Positions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Closes all currently closable positions. If the call is successful, subsequent order status changes will trigger the on_order_status callback. ```C++ DataArray* order_close_all(); ``` ```APIDOC order_close_all API Details: Returns: DataArray*: An array of Order structures. ``` -------------------------------- ### Cash Object API Reference Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Defines the `Cash` object, which represents the financial status of an account within the paper trading system. It includes attributes for account identification, various balance types (net asset value, profit/loss, available funds), cumulative transaction details, and timestamps for changes. ```APIDOC Cash Object: account_id: str - Account ID account_name: str - Account login name currency: int - Currency type nav: float - Net Asset Value (NAV) pnl: float - Net Profit/Loss fpnl: float - Floating Profit/Loss frozen: float - Funds occupied by positions order_frozen: float - Funds frozen by pending orders available: float - Available funds cum_inout: float - Cumulative deposit/withdrawal cum_trade: float - Cumulative trading volume cum_pnl: float - Cumulative closed position profit (before commission) cum_commission: float - Cumulative commission fees last_trade: float - Last trade amount last_pnl: float - Last profit/loss last_commission: float - Last commission fee last_inout: float - Last deposit/withdrawal change_reason: int - Reason for fund change (refers to CashPositionChangeReason) change_event_id: str - ID of the event triggering fund change created_at: datetime.datetime - Initial fund time updated_at: datetime.datetime - Fund change time ``` -------------------------------- ### Enumeration Constant: OrderStatus - Order Status Source: https://github.com/myquant/paper-trading-doc/blob/master/Python.md Defines the possible states of an order within the trading system. These statuses include unknown, new, partially filled, filled, canceled, pending cancel, rejected, suspended, pending new, and expired, providing a clear lifecycle for each order. ```python OrderStatus_Unknown = 0 OrderStatus_New = 1 ## 已报 OrderStatus_PartiallyFilled = 2 ## 部成 OrderStatus_Filled = 3 ## 已成 OrderStatus_Canceled = 5 ## 已撤 OrderStatus_PendingCancel = 6 ## 待撤 OrderStatus_Rejected = 8 ## 已拒绝 OrderStatus_Suspended = 9 ## 挂起 OrderStatus_PendingNew = 10 ## 待报 OrderStatus_Expired = 12 ## 已过期 ``` -------------------------------- ### PositionEffect Enum Definitions Source: https://github.com/myquant/paper-trading-doc/blob/master/C++.md Defines the effect of an order on a position, such as opening a new position, closing an existing one, or specifically closing today's or yesterday's positions. The exact meaning of 'Close' may vary by exchange. ```cpp PositionEffect_Unknown = 0 PositionEffect_Open = 1 ## 开仓 PositionEffect_Close = 2 ## 平仓, 具体语义取决于对应的交易所 PositionEffect_CloseToday = 3 ## 平今仓 PositionEffect_CloseYesterday = 4 ## 平昨仓 ```