易达交易系统
This document mainly walks through the methods of applying YD's internal API. Besides YD's original API, we also provide raw protocol interface and CTP simulation interface. For more information about raw protocol interface, see raw protocol interface. For more information about CTP simulation interface, see direct connection package.
ydApi is available on Linux and Windows. The Linux version of ydApi has plenty of optimizations based on the Linux platform, making its performance more outstanding than the Windows version. Therefore, we suggest all users use Linux version ydClient.
The communication between ydClient and ydServer mainly consisted of upstream and downstream. In upstream, requests (like system login, placement and cancellation of orders, changing password and uploading heartbeat messages) are transferred from ydClient to ydServer. In downstream, data are sent from ydServer to ydClient. (i.e. initializing static data, responses of placed/filled orders and market data) Moreover, initializing static data at the beginning of the day will also sync to the local database. Initialization/orders/order return/market data will execute ydClient's "call-after" function. In ydClient, you can use local call of YDApi::getX series of functions to obtain initialized static data of the beginning of the day. However, users need to calculate their margin, cost of the transaction, available capital and position according to orders/matched trade returns.
Note: ydApi indicates the Hanlin's api itself and YDAPI is the class of ydApi.
ydClient Release contains:
According to regulatory requirements, ydApi need to collect data from hardware's BIOS detail. It might require administrator permission (Windows OS) or root permission (Linux OS). Besides that, ydApi doesn't have any operating system dependency in Windows.
Linux:
ydServer only provides data initialization mode under push mode, which does not offer any searching function. Data initialization based on push mode mainly includes the following steps:
When the ydClient calling method makeYDApi, the configuration file used by ydClient needs to be assigned. The configuration file mainly includes three categories:
The configuration file list below is the best example template for ydAp in a developing environment. This template achieves:
########################################### ######### Network configurations ######### ########################################### # IP address of yd trading server TradingServerIP=127.0.0.1 # TCP port of yd trading server, other ports will be delivered after logged in TradingServerPort=51000 ########################################### ######### Trading configurations ######### ########################################### # Whether using UDP when sending orders, no for sending TCP orders # When accessing yd trading server via Internet or other UDP-banned network enviornments, must set to no UDPTrading=yes # Timeout of select() when receiving order/trade notifications, in millisec. -1 indicates running without select() TradingServerTimeout=-1 # Affinity CPU ID for thread to receive order/trade notifications, -1 indicate no need to set CPU affinity TCPTradingCPUID=3 ########################################### ####### MarketData configurations ######## ########################################### # Whether need to connect to TCP market data server ConnectTCPMarketData=no # Timeout of select() when receiving TCP market data, in millisec. -1 indicates running without select() TCPMarketDataTimeout=-1 # Affinity CPU ID for thread to receive TCP market data, -1 indicate no need to set CPU affinity TCPMarketDataCPUID=-1 # Whether need to receive UDP multicast market data ReceiveUDPMarketData=no
Network configurations include YD Trading Server Port and ID address. For more information about network configuration in the development environment, please contact the IT Department of your futures company.
RecorySiteCount: Number of the recovery site. It is used to achieve high availability at the expense of a bit of performance of order notification. 0 for no recovery, 1 for recovery always use the primary site, 2 for recovery use primary and secondary sites. If the primary site crashes, the secondary site (Use TradingServerIP2 and TradingServerPort2 to configure) will ensure that ydApi is reconnected to the trading server and recovered to the latest state.
TradingServerIP: IP address of the primary trading server.
TradingServerPort: Port of the trading server. ydServer generally provides three ports: TCP Trading Server Port, TCP Market Data Server Port and UDP Trading Server Port. (UDP Market Data Server Port is closed by default). The required port number is the TCP port number of the primary trading server. ydServer will deliver other ports after logged in. Set the "UDPTrading " value to "yes" if you wish to use UPD instead of TCP. Note that directly setting the "TradingServerPort" value into a UDP trading server port number will cause failure to connect.
TCPMarketDataServerPort: Port of TCP market data server. Try not to use or change this parameter since it is automatically delivered by ydServer. If NAT(Network Address Translation) is applied while accessing ydServer via Internet, TCP market data server port would be replaced and cannot receive TCP market data. In this case, the parameter needs to be filled with the port number provided by the futures company.
UDPTradingServerPort: Port of UDP trading server. Try not to use or change this parameter since it is automatically delivered by ydServer. If NAT(Network Address Translation) is applied while accessing ydServer via the Internet, the UDS trading server port would be replaced and not receive UDP trading data. In this case, the parameter needs to be filled with the port number provided by the futures company.
TradingServerIP2: IP address of the secondary trading server. Valid only when RecoverySiteCount equals 2.
TradingServerPort2: TCP port of the secondary trading server. Valid only when RecoverySiteCount equals 2.
TCPMarketDataServerPort2: TCP port of the secondary market data server. Valid only when RecoverySiteCount equals 2.
UDPTradingServerPort2: UDP port of the secondary trading server. Valid only when RecoverySiteCount equals 2.
RecalcMode:Recalculation mode for recalculation of margin and position profit. Valid when using ydExtendedApi. Set as "auto" by default.
RecalcMarginPositionProfitGap: Gap between recalculations, in milliseconds. It is set as 1000 by default. It will be adjusted to 1000 if less than 1000. Valid when RecalcMode is set to auto.
RecalcFreeGap: Delay of recalculation after market data arrives to avoid collision with input order, in milliseconds. Users can adjust this parameter, so there's enough time to recalculate according to different futures Exchanges' conditions. Users should set it between 0 and 100. It will be adjusted to 100 if larger than 100 and will be adjusted to 0 if smaller than 0. Valid when RecalcMode is set to auto.
UDPTrading: Whether using UDP or TCP when sending orders. "yes" means sending UDP orders, and "no" means sending TCP orders. We highly recommend using UDP for sending orders in the development environment because ydServer's excellent performance is based on the UDP trading. TCP can not support ydServer to reach its best performance with TCP's relatively slow property. However, UDP trading isn't available in several situations like internet or firewall secured network without special network configurations. When accessing ydServer via the Internet or other UDP-banned network environment, must set "UDPTrading" to "no". Otherwise, you won't be able to send orders, although you can log in.
TradingServerTimeout: Timeout of select() when receiving order/trade notifications, in milliseconds. -1 indicates running without select() and will maximize CPU usage to 100%. Suppose the affinity of threads and CPU/Core has not been set up to distribute the usage of CPU/Core wisely. In that case, it will severely slow ydClient's performance, and delay will increase significantly.
TCPTradingCPUID: Affinity CPU ID for the thread to receive order/trade notification, -1 indicated no need to set CPU affinity.
Please note, in ydServer, neither TCP market data nor UDP multicast market data is not high-speed market data. By far, it is only used for calculating margin and position profit by ydServer and ydClient. If you need market data in a development environment, please contact your futures company.
ConnectTCPMarketData: Whether connect to TCP market data server or not.
TCPMarketDataTimeout: Timeout of select() when receiving TCP market data, in milliseconds. -1 indicates running without select() and will maximize CPU usage to 100%. If ydClient has not been set up to distribute, and delay will increase significantly.
TCPMarketDataCPUID: Affinity CPU ID for the thread to receive TCP market data, -1 indicate no need to set CPU affinity.
ReceiveUDPMarketData: Whether receive UDP multicast market data or not. By far, all ydServer's UDP multicast market data features are closed. Please set it to "no".
ReportMethod: Method of calling dmidecode when generating ydClient report. Not available in Windows. In Linux, 0 indicates using suid, which uses chmod +s/usr/sbin/dmidecode to gain permission; 1 indicates using sudo that ydApi will gain hardware's detail through sudo dmidecode.
AppID and AuthCode: Users can set up AppID and AuthCode in the configuration file. If you type NULL when login, ydApi will use values in the configuration file.
LogDir: Destinated directory of your log report. Log report won't be created by default. If the corresponding directory doesn't exist, ydClient won't create the log report either.
In ydClient 1.108, we provide two high availabilities(HA): Single-Server HA and Active/Standby Server HA.
When high availability is on, ydAPI will search for available nodes and connect to them if the primary ydServer loses connectivity, as long as the new ydServer has the same signature as the old server.
You can configure RecoverySiteCount and other parameters to turn on ydAPI's high availabilities(HA). Click here for more details.
You don't need to configure anything to use Single-Server HA. Upon starting, ydApi won't quit when ydServer restarts. Under "RecoverySiteCount=1", when ydServer restarts, ydApi will first receive message "YD_AE_ServerRestarted=4" and then automatically reconnect to ydServer.
Active/Standby Server HA can ensure the greatest high availability: When downtime, network disconnection, or other malfunctions occur, the standby server will restore users' trading in the shortest time. Active/Standby Server HA makes three servers into a group:
To avoid useless failover, we generally suggest that futures companies use two networks. To configure active/standby server HA, you need a prepaid authorization file to activate. When ydApi uses Active/Standy Server HA (RecoverySiteCount=2), it will connect to the primary server. If the primary server cannot work(downtime, network disconnection), ydApi will automatically connect to the secondary server. Active/Standy Server HA's connection system is shown below:
No matter what HA is in use, all trading data are saved. However, if Exchanges return data during a breakdown, the system might not recognise and match the user's order. Thus, order returns and matched trade returns with OrderRef and OrderLocalID equal -1 might be received. There are two solutions, and you should handle that data based on conditions:
All data types are located at file ydDataType.h.
Types of products.
Types of options.
Trading directions of an order or orders.
Long or short position.
Trading date of position.
Types of trading strategies.
In our system, HedgeFlag's rules of use is list below:
Trading permission for users.
Opening or liquidation indicator.
Based on our understanding: SHFE and INE differentiate today's positions' liquidation and historical positions' liquidation. When liquidating, CFFEX prefers to use today's positions first; DCE & CZCE prefers to use historical positions first. You can find out which position is used during liquidating by "YDExchange::UseTodayPosition".
Users need to calculate historical and today's position according to the initial position and daily volume and choose different indicators according to different exchanges.
In our system, OffsetFlag:
Types of trading orders.
Trading orders, which are defined in the YD System, are the combinations of exchanges' orders. The comparison table of YD orders and exchanges' orders are listed below:
Status of orders.
Orders' indicator.
Quotation indicator.
Combined trading strategies
Types of DCE Combined Position Strategies.
Types of SSE/SZSE Combined Position Strategies.
Methods to select which seat to connect.
For admins only
For admins only.
Account function indicator.
Determine to use which base price to calculate margin.
Types of ID returned by Exchanges.
Types of general risk parameters.
Data structures begin with "SystemUse" are ydApi's internal fields. Users should not make any assumption about or modify those fields.
User-defined fields will reset to 0 before YDListener::notifyFinishInit() is called. Users can save some business logic values in those fields, and ydApi won't modify them. In C++, data members declared as mutable can be modified even though they are the part of an object declared as const. Simple data can be saved in UserFloat, UserInt or UserInt2; complex data can be saved in class or data structure that its address is saved in *pUser.
System parameters, YDString is a character array.
0: previous day's settlement price
1: price to establish a position
2: last price
3: market average price
4: Max(last price, previous day's settlement price )
In CTP system, futures use 1 and options use 4.
5: order price ( use limit up if it is a market order)
7: use MarginBasePrice
In CTP system's rule, both futures and options use 1.
Note, in option execution order, the frozen margin is always based on previous day's settlement price
5: quotation (use limit down if it is a market order)
6: no reverse-frozen
In CTP system, default value is 6.
Note, in eastablishing a buying option position, frozen premium is always based on order price(use limit up if it is a market order) .
Trading limitations.
Information of the exchange.
Trade limitation
Exchange trade constraint means that constraint on the summation of every contract of an account in the Exchange. For example, if OpenLimit is 500, the volume of the opening of positions in all orders of that day of that account can not exceed 500 lots.
Explanations of parameters:
We used a "pessimistic" algorithm to control transaction flow. Take ProductCancelLimit as an example, if a user submits a limit order, then total cancel orders will increase by the amount of that limit order immediately; if the limit order is filled or rejected by the exchange, the total cancel orders will decrease by the amount of that limit order. This "pessimistic" algorithm is also adopted by ProductOpenLimit, ProductPositionLimit and ProductTradeVolumeLimit.
Product information.
Instrument information.
Market data information.
The timestamp indicates the time from the beginning of the trading day up to this time. Every trading day begins at 5 pm, so 17:00:00 equals 0 in the timestamp. This timestamp is designed base on China's overnight trading. Trading on Friday night belongs to the following Monday. There are three parts of Monday's trading hours: Friday night (0-25199999), Saturday early morning (25200000-34199999) and Monday daytime (34200000-86399999).
Definition of combined position.
Client/Account capital information.
Note: Users need to calculate profit or loss of liquidating position, cash into or out of option instruments, commission, profit or loss of the position, margin used, cash balance and available balance by themselves according to orders, matched trades and current price.
Previous day's position of client.
Combined position.
Order.
InputOrder is used for standard order, option execution order, abandoning option execution order, quotation and making/splitting combined position.Instruction for filling those fields is listed below:Note that except for the trading direction of option execution order and abandoning option execution order, every field that is not required must be filled with 0. You don't need to consider this situation if you always cleared inputOrder to 0 at the beginning.
Different exchanges have different rules about option execution or abandoning option execution.
Order return.
Cancel order.
Cancellation requests are used for standard cancel order, option execution cancel order, and option abandoned execution cancel order. The required values of each field are listed below:
Failed cancel order.
Matched/Affermitive trade return.
Price quotation.
Different exchanges have different rules about BidVolume and AskVolume:
Different exchanges have different rules about BidHedgeFlag and AskHedgeFlag:
Quotation return.
Cancel quotation.
Failed cancel quotation.
Request for quotation.
Margin rate.
Commission rate.
Exchange ID.
Update margin rate.
Account's exchange information and trading permission.
Account's product information.
Account's instrument information.
General risk parameters.
Extended information of orders. YDExtendedOrder is a subclass of YDOrder. Extended fields are listed below:
Extended information of matched trade return. YDExtendedTrade is a subclass of YDTrade. Extended fields are listed below:
Extended information of quotation. ExtendedQuote is a subclass of YDQuote. Extended fields are listed below:
Extended information of request for quotation. YDExtendedRequestForQuote is a subclass of YDRequestForQuote. Extended field is listed below:
Extended information of an account.
Extended information of the position.
Extended detail of the combined position.
Information filter of the extended position.
Information filter of orders.
Information filter of quotations.
Information filter of matched trades.
Information filter of the combined position's detail.
ydApi mainly consists of two parts: extended YDListener's callback functions that receive trading data pushed by ydServer; and ydApi initialization.
ydApi initialization is made of three steps. The first step is to initialize a YDAPI instance; the second step is to call new to create an extended YDListener instance; the third step is to call YDAPI::start to connect the YDApi instance with YDListener instance to launch internal management thread and network communication thread.
YD offers two types of API: ydApi and ydExtendedApi. In that, ydApi has extremely outstanding performance but needs users to maintain balance and position by themselves; ydExtendedApi can help users maintain balance and position with a cost of performance. Users can choose different API base on their demand.
While using ydExtendedApi, users can get balance by getExtendedAccount, and get position by getExtendedPosition and findExtendedPostion. Order still uses insertOrder, which is inherited from ydApi to achieve high-speed order submission.
There is no particular optimisation for multiple connections during the design and development stages of the YD system. However, many users create multiple ydApi instances to achieve multiple accounts trading at the same time. To avoid loss due to misuse, please be aware of the problems listed below while using a single process to achieve multiple ydApi instances:
YDApi *makeYDApi(const char *configFilename);
configFilename is the file name of network connection and CPU/Core related configuration.
This function asks the operating system for space to initialize a YDApi instance.
YDExtendedApi *makeYDExtendedApi(const char *configFilename);
This function asks the operating system for space to initialize a YDExtendedApi instance.
const char *getYDVersion(void);
Returns YDAPI's four-part version number. ( i.e. 1.2.0.1)
unsigned long long getYDNanoTimestamp();
Returns timestamp, in nanoseconds, by an efficient and accurate method. It can be used to measure the API's running time of submitting an order.
YDListener is a group of threads of network-listener execution. According to different configuration files, the number of threads can be different; however, one thread to receive returns of TCP trading from ydServer is necessary. If need to receive market data from ydServer, one or two more threads is required. Those threads maintain the local database after downstream data are received. And those threads call notify-function to inform ydClient.
virtual void notifyBeforeApiDestory(void);
A callback function called after startDestory is called and before data cleanup.
virtual void notifyAfterApiDestory(void);
A callback function called after startDestory is called and after data cleanup.
virtual void notifyEvent(int apiEvent);
When connecting or disconnecting to TCP trading server or TCP market data server, or finding out ydServer restarted, this callback function will notify users.
When ydListener receives the message YD_AE_ServerRestarted, ydApi will quit if users do not react to the message. If you do not wish ydApi to stop, you can call startDestory to destroy the ydApi object on your own.
virtual void notifyReadyForLogin(bool hasLoginFailed);
A callback function called by ydApi after ydClient successfully connected to the ydServer. It means ydClient has already connected to the ydServer's TCP server and is ready for login.
This function has a bool called hasLoginFailed, which tells whether ydClient failed to log in last time. If ydClient tried to log in and failed, ydClient will wait for 3 seconds and then call notifyReadyForLogin. Besides that, hasLoginFailed will be TRUE. Note: The same instance of YDApi class will not support switching usernames during runtime.
virtual void notifyLogin(int errorNo, int maxOrderRef, bool isMonitor);
After the login request is sent, ydServer will check if the username and password are correct, send the login result back to ydClient. After that, ydApi will call function notifyLogin. errorNo indicates whether login succeeds. If success, isMonitor shows if the user is an administrator or not; If true, maxOrderRef will be 0.
maxOrderRef is ydClient's maximum local order reference ID used in one trading day. ydServer allows users to repeat using one username/password many times. However, ydClient needs some mechanism to ensure that there is no duplication in local order reference IDs, like monotonically increasing sequence.
virtual void notifyFinishInit(void);
ydApi will call notifyFinishInit only once during runtime after ydClient receives data initialization sent by ydServer. If no order or matched trade return received (like the first run during overnight trading), ydClient can start inital logic here. If YDApi::hasFinishedInit is called after, it will return True; if before, it will return False. The initialized database can be used safely, and user-defined fields will be reset as 0.
Till now, all data in the local initialized database are ready. Required memory is applied. ydClient can use the getX() method of YDApi to retrieve data. The address of the database does not change; thus, ydClient can use pointers without concerns. However, ydClient still needs to calculate margin, commission, balance and position according to order returns and matched trade returns. The data saved in the local database is initialized data, and deposit/withdrawal and trading permissions which the administrator modifies after trading.
ydClient will call notifyFinishInit only once during runtime; moreover, there won't be any callback even if network disconnected. Since ydServer has not been restarted and initialized static data and order/matched trade returns has not changed after disconnection, there is no need to re-initialize after being reconnected to the ydServer. Thereofre, this method is suitable for initializing users' business data.
virtual void notifyCaughtUp(void);
A callback function will notify users that ydClient has already received all orders and matched trade returns. This function must be called after notifyFinishInit. Every time ydClient disconnects with ydServer, notifyCaughtUp will be called after reconnection.
virtual void notifyTradingSegment(const YDExchange *pExchange, int segmentTime);
A callback function will notify users the change of trading segment. To reduce cost of communication, ydServer only notify ydClient the time of change, segmentTime indicates seconds passed from beginning of trading day till now. Every trading day begins at 5pm, so 17:00:00 equals 0 in timestamp. It does not distinguish between Saturday and Monday because of overnight trading.
virtual void notifyCombPosition(const YDCombPosition *pCombPosition,const YDCombPositionDef *pCombPositionDef,const YDAccount *pAccount)
A callback function, called between notifyFinishInit and notifyCaughtUp, recives current combined positions' data to startup.
virtual void notifyOrder(const YDOrder *pOrder, const YDInstrument *pInstrument, const YDAccount *pAccount); virtual void notifyFailedOrder(const YDInputOrder *pFailedOrder, const YDInstrument *pInstrument, const YDAccount *pAccount);
Get the order return. For YDApi::insertOrder and YDApi::cancelOrder, both use callback functions notifyOrder and notifyFailedOrder to retrieve the result. The order rejected by ydServer is retrieved by notifyFailedOrder. Order accepted or rejected by exchanges is retrieved by notifyOrder.
For every connected seat, ydServer uses continual local order reference ID. For instance, the system's local order reference ID is 100. When receiving an order, after passing the test, its local order reference ID is set as 101 and is sent to the exchange via seat No.0. After that, another order was received, and its local order reference ID will be placed as 102 even though it was sent to the exchange via seat No.1.
ydServer get order returns and matched trade returns through the exchange's private flow; therefore, it might get order returns and matched trade returns from other systems. To distinguish the difference between returns of YD and returns of other systems, the local order reference ID of returns from other systems are set as -1. If ydServer restarts due to malfunction, the local order reference ID generated by ydServer during the last runtime will be set as -1.
If the exchange rejects an order, pOrder->ErrorNo contains the error code from the exchange. If the exchange accepts it, its ErrorNo is 0.
Order return progressions are different in different exchanges. For limit orders, every exchange would have a return of YD_OS_Queuing and have a corresponding return against matched trade or cancellation. For FAK/FOK/MKT order, DCE will still have a return of YD_OS_Queuing and have a return of YD_OS_Canceled or YD_OS_AllTraded almost simultaneously; other exchanges would only have a return of YD_OS_Canceled or YD_OS_AllTraded.
virtual void notifyFailedCancelOrder(const YDFailedCancelOrder *pFailedCancelOrder,const YDExchange *pExchange,const YDAccount *pAccount)
Generate notifyFailedCancelOrder when cancel order is rejected.
virtual void notifyTrade(const YDTrade *pTrade, const YDInstrument *pInstrument, const YDAccount *pAccount)
Receive matched trade returns.
virtual void notifyQuote(const YDQuote *pQuote, const YDInstrument *pInstrument, const YDAccount *pAccount)
Receive quotation returns.
virtual void notifyFailedQuote(const YDInputQuote *pFailedQuote, const YDInstrument *pInstrument, const YDAccount *pAccount)
Receive wrong quotation returns.
virtual void notifyFailedCancelQuote(const YDFailedCancelQuote *pFailedCancelQuote,const YDExchange *pExchange,const YDAccount *pAccount)
virtual void notifyRequestForQuote(const YDRequestForQuote *pRequestForQuote,const YDInstrument *pInstrument)
Receive request for quote.
virtual void notifyMarketData(const YDMarketData *pMarketData);
Returns market data.
virtual void notifyAccount(const YDAccount *pAccount);
Notify when changes have been made in account information. By far, if MaxMoneyUsage, Deposit, Withdraw, FrozenWithdraw, TradingRight or LoginCount is modified in YDAccount, notifyAccount will be triggered.
virtual void notifyAccountExchangeInfo(const YDAccountExchangeInfo *pAccountExchangeInfo); virtual void notifyAccountProductInfo(const YDAccountProductInfo *pAccountProductInfo); virtual void notifyAccountInstrumentInfo(const YDAccountInstrumentInfo *pAccountInstrumentInfo);
Returns information about trading permission.
virtual void notifyIDFromExchange(const YDIDFromExchange *pIDFromExchange,const YDExchange *pExchange);
Returns Exchange's system ID.
virtual void notifyUpdateMarginRate(const YDUpdateMarginRate *pUpdateMarginRate);
Returns the response of changing password. If errorNo equals 0, it means passwords changed successfully; otherwise, failed to change password. The administrator can change the user's password.
virtual void notifyChangePassword(int errorNo);
virtual void notifyResponse(int errorNo,int requestType);
Returns error ID and request type which causes this error.
virtual void notifyRecalctime(void);
Get recalculation time. It is the suggested time to calculate the margin and the profit or loss of the position while using YDApi; it is the callback every time calculating margin and profit or loss of the position automatically while using YDExtendedApi.
YDApi provides three methods for ydClient to connect.
virtual bool start(YDListener *pListener)=0;
*pListener is a pointer of YDListener. Return false if the configuration file is not set up correctly.
This function achieves making YDApi and YDListener connected to share YDApi's initialized database and internal managing service. It starts internal managing threads YDListener required to monitor network communication according to the configuration file. Theoretically, ydApi supports multiple YDApi/YDListener instances (even two YDApi instances sharing one YDListener instance) within one client program. However, we do not suggest such a development model because of the complexity of its internal data synchronization logic.
virtual void startDestroy(void)=0;
After calling this function, api will try to shut down all connections and stops all threads of executions that belong to this api.
During the destruction, all trading functions and notifications are disabled. The data retrieving function is still abled. When destroying is done, notifyBeforeApiDestroy will be sent to the listener. The second phase will start to release all data structures from api.
Never delete api by yourself, but users suppose to delete the listener on their own.
virtual void disconnect(void)=0;
Disconnect from ydServer.
virtual bool login(const char *username, const char *password const char *appID, const char *authCode)=0;
Send login request to ydServer. Return false if network disconnects. ydServer's feedback will be retrieved by callback function YDListener::notifyLogin.
ydServer will generate a unique instance number whenever it starts. ydApi will save this instance number whenever ydClient logs in. Successful login after disconnection will receive ydServer's instance number in the login response. If the new instance number doesn't match with the old instance number, ydClient will quit. Since the user's serial sequence will change after a restart, ydClient needs to re-login and synchronize all data to finish the initialization. ydClient needs to monitor its application's status. Once ydServer restarts, ydClient need to decide whether to restart the application or not. If it restarts, ydClient need to synchronize all data and complete initialization.
Send login request to ydServer. Return false if network disconnects. ydServer's feedback will be retrieved by YDListener::notifyLogin. App ID and authorization code provided below can be used during the development environment and testing environment.
//#define APP_ID "ydDev 1.0"#define AUTH_CODE "9ba749b1e1848a32ba67182c5ffee0fe"
You need to provide App ID to the future company before the launch. An authorization code will be issued if the App ID is verified. Use new App ID and authorization code for the production environment.
virtual bool insertOrder(YDInputOrder *pInputOrder,const YDInstrument *pInstrument, const YDAccount *pAccount=0)=0;
Send login request to ydServer. Return false if network disconnects. ydServer's feedback will be retrieved by YDListener::notifyOrder or YDListener::notifyFailedOrder. YDListener::notifyOrder handles order returns that are accepted by ydServer but might be rejected by exchanges. Thus, YDListener::notifyOrder needs to determine order returns' ErrorNo.
YDListener::notifyFailedOrder handles order returns that are rejected by ydServer, mainly caused by ydServer's risk management. For failed orders with causes like disconnection and flow control, they are handled the same as those rejected by exchanges.
Due to seat disconnection or flow control, it might be failed to submit or cancel orders. ydServer will return false to ydClient. For failed orders, its OrderStatus will be YD_OS_Rejected, and ErrorNo will be given.
Note that this function has two parameters, one is order record, and another is a pointer which points to YDInstrument. It is apparently different from any other trading systems on the market. It reduces copy and comparison of strings to optimize the system's efficiency. Thus, for instruments required by the business, we suggest that after getInstrumentByID() is called, you should cache its pointer to reduce the comparison of strings.
When an order is sent into the ydServer, if it doesn't pass risk management analysis or flow control check, its status will be changed into YD_OS_Rejected. ydClient will receive the return from YDListener::notifyFailedOrder. If ydServer restarts after a malfunction, this order's record won't be saved.
If an order passes the risk management analysis or flow control check, its status will be changed into YD_OS_Accepted. (This status won't be sent to ydClient.) ydServer will submit this order to exchange and wait for the order return.
After receiving returns from the exchange, if the order passes the exchange's examination, it will become a valid order. Its status will turn into YD_OS_Queueing (This order is confirmed by the exchange and saved in ydServer's permanent transaction record. It won't be lost even if ydServer restarts due to a malfunction.) ydClient will receive the callback from YDListener::notifyOrder. If the order does not pass the exchange's examination, its status will turn into YD_OS_Rejected. ydClient will receive the callback from YDListener::notifyOrder with YD_OS_Rejected status. If ydServer restarts due to a malfunction, the order's record will not be saved.
The order with YD_OS_Queueing status might be completely traded, partly traded, or completely untraded. The trading situation can be determined by the field YDOrder::TradeVolume of YDListener::notifyOrder's callback.
If there is a matched trade while queueing, users will receive the callback from YDListener::notifyOrder and YDListener::notifyTrade. If there are multiple matched trades while queueing, users will receive multiple callbacks. YDOrder::TradeVolume will increase as matched trades increase. To illustrate, if an affirmed order with three lots is in the exchange's queue. At first, YDOrder::TradeVolume of YDListener::nofityOrder will be 0. Then, it is divided into three transactions in one minute, one lot per transaction. Therefore, YDOrder::TradeVolume will be 1, 2, 3 in the next three callbacks.
YD system allows accounts to trade by default. It means that without setting YD_TR_CloseOnly, YD_TR_Forbidden, and even YD_TR_Allow, ydServer will enable accounts to trade regardlessly. No matter how users set the setting, ydServer always allow users to delete their orders. ydServer check users' permission in order of account, instrument, product and exchange. If any of them forbids trading, users can not submit the order; if any prohibits opening positions, users can only liquidate positions.
For every user under YD System, OrderRef. Whenever users login in, the maximum OrderRef of all orders and quotations will be retrieved. If a user hasn't submitted any order yet, OrderRef would be 0. We suggest users' automated trading system always number the orders and quotations successively, starting from the next number after MaxOrderRef.
For orders and quotations, all data returned will contain OrdeRef, which users fill when submitting. YD System won't check OrderRef's uniqueness or monotonicity. For orders derived by quotations, the order's OrderRef will be the same as the quotation's. For orders and quotations not submitted by YD System or are not submitted from this time, their OrderRef will be -1; for orders and quotations from YDClient.exe, OrderRef will be 0.
ydClient can use YDAPI's getExchange or getExchangeByID methods to retrieve YDExchange's pointer. The ConnectionCount indicates the number of seat connection. Note that connected seat number starts from 0, in ascending order, until ConnectionCount equals to -1.
Exchanges require that all counter systems connect to the exchange via FENS. However, the connected front-end processors(FEP) allocated by FENS are random. Different ydServer instances' same seat might connect to different FEP; even during runtime, a seat might connect to different FEP due to reconnection.
YD_CS_Any means not selecting a fixed seat to connect. ydServer submits orders or cancels orders to the exchange as fast as possible. If all connections are unavailable due to flow control or network disconnection, ydServer will retrieve the error report via YDListener::notifyOrder.
YD_CS_Fixed means selecting a fixed seat to connect. If the fixed seat is unavailable due to flow control or network disconnection, ydServer will immediately return the error report. If the fixed seat is processing other orders in the meantime, the system will wait for 200 ms. If excess 200 ms, YDListener::notifyOrder will return the error report.
YD_CS_Prefered means selected a preferred seat to connect. Suppose the fixed seat is unavailable due to flow control, network disconnection or processing other orders. In that case, it will switch the selection type to YD_CS_Any.
ErrorNo is not required at submitting an order; thus, it is set as 0.
virtual bool cancelOrder(YDCancelOrder *pCancelOrder,const YDExchange *pExchange, const YDAccount *pAccount=0)=0;
Send a cancel order to ydServer. Return false if network disconnects. ydServer's feedback is retrieved by YDListener::notifyOrder. Cancellation is successful if the order's status turns into YD_OS_Canceled; the cancellation is failed if the order's status is not YD_OS_Canceled or no feedback is retrieved. You should set a time-out to resubmit the cancel order after a period elapsed.
Note, correct cancel order's return will be retrieved by YDListener::notifyOrder, and incorrect cancel order's return will be retrieved by YDListener::notifyFailedCancelOrder.
virtual bool insertQuote(YDInputQuote *pInputQuote,const YDInstrument *pInstrument, const YDAccount *pAccount=NULL)=0;
Sent a quotation to ydServer. Return false if network disconnects.
If a quotation is successful, there will be one YDListener::notifyQuote callback and several YDListener::notifyOrder callbacks:
There are two conditions if a quotation is failed:
virtual bool cancelQuote(YDCancelQuote *pCancelQuote,const YDExchange *pExchange, const YDAccount *pAccount=NULL)=0;
Send a cancel quotation to ydServer. Return false if network disconnects.
ydServer's feedback is retrieved by YDListener::notifyOrder. One cancel quotation for one pending quotation. The cancellation is successful If the quotation's status turns into YD_OS_Canceled; the cancellation is failed if the quotation's status does not turn into YD_OS_Canceled or no feedback retrieved.
virtual bool insertCombPositionOrder(YDInputOrder *pInputOrder,const YDCombPositionDef *pCombPositionDef,const YDAccount *pAccount=NULL)=0;
Make a combined position or split a combined position. Return false if network disconnects.
If an order is rejected by ydServer, order return will be retrieved by YDListener::notifyFailedCombPositionOrder. If an order is forwarded to the exchange, order return will be retrieved by YDListener::notifyCombPositionOrder.
virtual bool insertOptionExecTogetherOrder(YDInputOrder *pInputOrder,const YDInstrument *pInstrument,const YDInstrument *pInstrument2,const YDAccount *pAccount)=0;
Send an option trading combination execution order. Return false if network disconnects.
If an order is rejected by ydServer, order return will be retrieved by YDListener::notifyFailedOptionExecTogetherOrder. If an order is forwarded to the exchange, an order return will be retrieved by YDListener::notifyOpentExecTogetherOrder.
virtual bool insertMultiOrders(unsigned count, YDInputOrder inputOrders[],const YDInstrument *instruments[], const YDAccount *pAccount=NULL);
The variable count is the number of orders in a batch, up to 16. Orders sent in a batch can also be cancelled in a batch or be cancelled individually.
Return true if all orders in a batch are accepted; return false if orders are partly or entirely rejected.
virtual bool cancelMultiOrders(unsigned count, YDCancelOrder cancelOrders[],const YDExchange *exchanges[], const YDAccount *pAccount=NULL);
The variable count is the number of cancel orders in a batch, up to 16.
Return true if all cancel orders are accepted; return false if cancellation orders are partly or entirely rejected.
virtual bool insertMultiQuotes(unsigned count, YDInputQuote inputQuotes[],const YDInstrument *instruments[], const YDAccount *pAccount=NULL)=0;
The variable count is the number of quotations in a batch, up to 16. The quotation sent in a batch can also be cancelled in a batch or be cancelled individually.
Return true if all quotaitons in a batch are accepted; return false if quotations are partly or entirely rejected.
virtual bool cancelMultiQuotes(unsigned count, YDCancelQuote cancelQuotes[],const YDExchange *exchanges[], const YDAccount *pAccount=NULL)=0;
The variable count is the number of cancel quotations in a batch, up to 16.
Return true if all cancel quotations in a batch are accepted; return false if quotations are partly or entirely rejected.
virtual bool subscribe(const YDInstrument *pInstrument)=0;
According to ydServer's configuration file, ydServer can subscribe to exchange's market data and send them to the client via TCP or UDP.
After the client's initialization (YDListener::notifyFinishInit), YDApi::subscribe can be used to subscribe to designated instruments' market data. It can subscribe to multiple instruments by setting up multiple instruments. If the network disconnects while the client is running, there is no need for users to re-subscribe once reconnected to the network. The earlier subscription is still valid and will receive the latest market data automatically.
After subscribing, market data will be retrieved via YDListener::notifyMarketData() method. Suppose TCP market data and UDP market data are both configured in the configuration file. In that case, ydApi will merge those market data to ensure one notice for one market data client.
Return false if network disconnects.
Historical market data subscription is not supported.
virtual bool unsubscribe(const YDInstrument *pInstrument)=0;
Send request for unsubscribing to ydApi/ydServer. Return false if network disconnects. No callback will be received from YDListerner::notifyMarket if users unsubscribe.
virtual bool setTradingRight(const YDAccount *pAccount, const YDInstrument *pInstrument, const YDProduct *pProduct, const YDExchange *pExchange, int tradingRight)=0;
An administrator interface.
If pInstrument is given to set the account's trading right of a specific instrument, pProduct and pExchange are meaningless and should be filled with NULL. If pProduct is given to set the account's trading right of a specific product, pInstrument and pExchange are meaningless and should be filled with NULL. If pExchange is given to set the account's trading right in a specific exchange, pInstrument and pProduct are meaningless and should be filled with NULL.
Return false if network disconnects. ydServer's feedback is retrieved by YDListener::notifyAccount. notifyAccount indicates the account level; notifyAccountExchangeInfo indicates the exchange level; notifyAccountProductInfo indicates the product level; notifyAccountInstrumentInfo indicates the instrument level. If the account you are trying to modify is connecting to ydServer, notification will also be received.
virtual bool alterMoney(const YDAccount *pAccount, int alterMoneyType, double alterValue)=0;
An administrator interface used for setting balance.
Return false if network disconnects. ydServer's feedback will be retrieved by the callback function YDListener::notifyAccount. If the account you are trying to modify is connecting to ydServer, notification will also be received.
virtual bool updateMarginRate(const YDUpdateMarginRate *pUpdateMarginRate)=0;
An administrator interface used for setting margin rate.
Return false if network disconnects. ydServer's feedback will be retrieved by the callback function YDLisener::notifyUpdateMarginRate. If the account you are trying to modify is connecting to ydServer, notification will also be received.
virtual bool changePassword(const char *username, const char *oldPassword, const char *newPassword)=0;
Change user's password. Standard users are allowed to change their own password. Administrators are allowed to change their own password and standard users' password. When an administrator changes a standard user's password, oldPassword will be set as NULL.
Return false if network disconnects. ydServer's feedback will be retrieved by the callback function YDLisener::notifyChangePassword's parameter errorNo.
virtual bool selectConnections(const YDExchange *pExchange,unsigned long long connectionList)=0;
Send the connection selection result to ydServer. When ydServer receives orders using YD_CS_Any, it will send order based on connection selection result.
This function can only be used by administrators or accounts with YD_AF_SelectConnection indicator. connectionList is a list which occupies 4 bytes, smallest number has a highest piority, must cover all connections needs to switch.
For example, if need to set the connection order as 2-3-0-1-4 that connectionList will be expressed in binary as 0100 0001 0000 0011 0010.
virtual bool hasFinishedInit(void)=0;
Determine whether ydApi receives complete initialized data from ydServer. If true, data initializaiton is finished that initialized data and user-defined fields can be used securely.
virtual int getSystemParamCount(void);virtual const YDSystemParam *getSystemParam(int pos);virtual const YDSystemParam *getSystemParamByName(const char *name,const char *target);
Get system's parameter.
virtual int getExchangeCount(void)=0;virtual const YDExchange *getExchange(int pos)=0;virtual const YDExchange *getExchangeByID(const char *exchangeID)=0;
Get exchange's basic information, including seat connections, risk management and flow control.
virtual int getProductCount(void)=0;virtual const YDProduct *getProduct(int pos)=0;virtual const YDProduct *getProductByID(const char *productID)=0;
Get product's information
virtual int getInstrumentCount(void)=0;virtual const YDInstrument *getInstrument(int pos)=0;virtual const YDInstrument *getInstrumentByID(const char *instrumentID)=0;
Get instrument's information
virtual int getCombPositionDefCount(void)=0;virtual const YDCombPositionDef *getCombPositionDef(int pos)=0;virtual const YDCombPositionDef *getCombPositionDefByID(const char *combPositionID,int combHedgeFlag)=0;
Get combined position definition's information.
virtual int getAccountCount(void)=0;virtual const YDAccount *getAccount(int pos)=0;virtual const YDAccount *getAccountByID(const char *accountID)=0;
For administrators only. Get account's information.
Standard user should use function below to acquire account's information
//following function for YDAccount can only be used by tradervirtual; const YDAccount *getMyAccount(void)=0;
Get the value of position holding before the beginning of the day. Static data and won't change within the same trading day.
virtual int getMarginRateCount(void)=0;virtual const YDMarginRate *getMarginRate(int pos)=0;
Get the value of the margin rate. Due to the hierarchical structure, the value is usually sparse. In general, you should use getAccountInstrumentInfo to get the specific instrument's margin rate.
virtual int getCommissionRateCount(void)=0;virtual const YDCommissionRate *getCommissionRate(int pos)=0;
Get the value of the commission rate. Due to the hierarchical structure, the value is usually sparse. In general, you should use getAccountInstrumentInfo to get the specific instrument's commission rate.
virtual const YDAccountExchangeInfo *getAccountExchangeInfo(const YDExchange *pExchange, const YDAccount *pAccount=NULL)=0;virtual const YDAccountProductInfo *getAccountProductInfo(const YDProduct *pProduct, const YDAccount *pAccount=NULL)=0;virtual const YDAccountInstrumentInfo *getAccountInstrumentInfo(const YDInstrument *pInstrument, const YDAccount *pAccount=NULL)=0;
Get information about the user's exchange, product, instrument, margin rate and commission rate. Those functions ensure values at every level. In general, you should use getAccountInstrumentInfo to get the specific value.
virtual int getGeneralRiskParamCount(void)=0;virtual const YDGeneralRiskParam *getGeneralRiskParam(int pos)=0;
Get general risk management parameters.
virtual void writeLog(const char *format,...)=0;
If there is ./log under yd.so(Linux) or yd.dll(Windows) directory, ydApi will save key log about network communication. The log applies syslog format and is named ccyymmddlog.txt. ydClient can use the writeLog method to modify the log.
virtual const char *getVersion(void)=0
Get ydApi's four-part version number.
virtual int getClientPacketHeader(YDPacketType type, unsigned char* header, int len)=0;
Get the packet header of the client while using raw protocol orders. In that, YDpacketType can be YD_CLIENT_PACKET_INSERT_ORDER or YD_CLIENT_PACKET_CANCEL_ORDER. header and len is the head pointer and the length of storage space pre-created by the user. The storage space is used for storing header data generated by ydApi. len should be greater than the header length of corresponding types. This method can only be called after notifyFinishInit.
The return value is the actual header length. The header length of orders and cancel orders are both 16. Return 0 if failed to acquire the packet header, mainly because of early call time or lack of permission to use raw protocol orders.
virtual int getTradingDay(void)=0;
Get the trading date after successfully logging in.
您的电子邮箱地址不会被公开。 必填项已用*标注
在此浏览器中保存我的显示名称、邮箱地址和网站地址,以便下次评论时使用。