: | : | :期货量化学习 | :期货量化 |
返回列表 发帖

TWS API v9.72 在线文档 —— 建立连接【翻译】

TWS API v9.72 在线文档 —— 建立连接【翻译】

Connection
【译】 连接

A TCP connection between the API client application and TWS needs to first be established via the IBApi.EClientSocket.eConnect function.

【译】 客户端与TWS采用的是TCP形式进行连接。

TWS acts as a server to receive requests from the API application (the client) and responds by taking appropriate actions. The first step is for the API client to initiate a connection to the socket port on which TWS is listening.

【译】 TWS作为服务器,而用户自己的程序则是客户端。连接的第一步是建立客户端与TWS正监听的端口号的信道。

It is possible to have multiple TWS instances running on the same computer if each is configured with a different API socket port number. Also, each TWS session can receive up to 32 different client applications simultaneously. The client ID field specified in the API connection is used to distinguish different API clients.

【译】 在同一台电脑上,可能存在多个不同的客户端同时运行的情况,这些通过保持不同的端口号与TWS建立单独的信道。而TWS能够维持的会话上限同时是32个。因此,客户端ID字段是用于TWS区分不同客户端的重要方法。

【注】 换句话说,如果开发者希望向同一台安装有TWS软件的目标机器建立不同的会话通道,请确保建立的信道不超过32个,并用不同的ID字段区分不同的客户端,避免应该发送给客户端A的消息,错误的发送给了客户端B。

Establishing an API connection
【译】 建立API连接

Once our two main objects have been created, EWrapper and ESocketClient, the client application can connect via the IBApi.EClientSocket object:

【译】 当EWrapper 和 ESocketClient 这两个主要对象被创建,客户端将通过IBApi.EClientSocket对象建立与TWS的信道。

  1. m_client.eConnect("127.0.0.1", 7497, 0);
复制代码



eConnect starts by requesting from the OS that a TCP socket be opened to the specified IP address and host number- the first two parameters in the function call.

【译】 eConnect通过指定的目标地址和端口号建立与服务器的连接,前两个参数就是地址和端口号。

If the socket cannot be opened, the OS returns an error condition which the API returns as error code 502 to IBApi.EWrapper.error.

【译】 如果socket无法建立通信,系统将返回一个502的错误信息给IBApi.EWrapper.error。

Since this error is not generated by TWS it is not captured in TWS log files.

【译】 如果TWS无法生成错误,那么在TWS的日志文件中也无法找到。

Most commonly error 502 will indicate that TWS is not running with the API enabled or is listening for connection requests on a different socket port.

【译】 多数情况下,502错误指示TWS没有启用API连接或者监听了错误的端口号。

If connecting across a network, it can also occur if there is a firewall or antivirus program blocking connections.

【译】 如果通过网络建立连接,它也有可能是由防火墙或者杀毒软件屏蔽了信号引起的。

After the socket has been opened, both applications need to exchange essential information for the API session.

【译】 当Socket打开了连接通道,主客机都需要通过信道交换重要的消息。

First, the version numbers of the client (API program) and server (TWS) are exchanged so that the server and client each know the function calls supported by one another. In this way backwards compatibility can be maintained between TWS and previous API versions.

【译】 首先,API及TWS的版本号会互相交换。双方可以通过向下匹配的方法,更好的互相兼容。

【注】 但是,最好还是保证TWS和API都处于最新的版本,版本之间差异过大,可能也会带来意想不到的错误或异常发生。

Next TWS will always return certain information for the client session, namely the accounts which are accessible by the TWS session, the next valid order identifier (ID), and the time of connection. In the most common mode of operation the EClient.AsyncEConnect field is set to false and the initial handshake is taken to completion immediately after the socket connection is established. TWS will then immediately provides the API client with this information.

【译】 接着,TWS会经常性的为客户端返回重要信息,包括账户是否被许可与TWS建立通信,下一个有效命令的ID,连接的时长。在大多数普通模式下,EClient.AsyncEConnect 字段被设置为false,同时当socket建立信道时,初始握手会非常快速完成,TWS也会非常快返回这些信息。


  1. Important: The IBApi.EWrapper.nextValidID callback is commonly used to indicate that the connection is completed and other messages can be sent from the API client to TWS. There is the possibility that function calls made prior to this time could be dropped by TWS.
复制代码



【译】 重要提示:IBApi.EWrapper.nextValidID的回掉通常指示连接已经完成,以及客户端能够向TWS发送消息。当然,也存在着在此之前进行的函数调用被TWS删除的可能。

【注】 这种情况可能比较常见,因此IB要求开发者应该在建立起连接后,先测试连接是否被完整建立,以及TWS是否会向客户端返回信息,以避免请求被TWS丢弃,或者连接被TWS中断。

There is also an alternative mode of connection used in special cases in wich the variable AsyncEconnect is set to true, and the call to startAPI is only called from the connectAck() function. All IB samples use the mode AsyncEconnect = False.

【译】 这里也存在针对于特殊情况的替代模式,通过将AsyncEconnect设置为true,对startAPI的调用只会由connectAck()函数发起。当前,所有的IB样例里,AsyncEconnect被设置为False,即,不支持异步调用。

The EReader Thread
API programs always have at least two threads of execution. One thread is used for sending messages to TWS, and another thread is used for reading returned messages. The second thread uses the API EReader class to read from the socket and add messages to a queue.

【译】 API程序执行时最少应有两个线程。一个线程用来发送消息给TWS,另一个用于获取从TWS返回的消息。第二个线程通过API EReader类从socket中获取消息,并把它添加到队列中。

【注】 你在刚开始接触API开发时,其实可以用一个线程处理这些事,只不过效率不高罢了。

Everytime a new message is added to the message queue, a notification flag is triggered to let other threads now that there is a message waiting to be processed. In the two-thread design of an API program, the message queue is also processed by the first thread. In a three-thread design, an additional thread is created to perform this task.

【译】 每次一个新消息被加入到消息队列,就会被标记,这样,其他线程便知道队列里有数据需要处理。在双线程的API程序里,消息队列总时由第一个线程进行处理。在三线程的设计里,新增的线程用于处理这个工作。

The thread responsible for the message queue will decode messages and invoke the appropriate functions in EWrapper. The two-threaded design is used in the IB Python sample Program.py and the C++ sample TestCppClient, while the 'Testbed' samples in the other languages use a three-threaded design. Commonly in a Python asynchronous network application, the asyncio module will be used to create a more sequential looking code design.

【译】 新增的第三个线程负责对消息队列的消息进行处理,并激活在EWrapper中对应的方法。Python以及C++的'Testbed'用例里,使用的是双线程模型,而在其他代码的用例里是三线程模型。通常,在Python的异步网络通信程序里,asyncio模块用于创建一个更像序列化的代码风格。

The class which has functionality for reading and parsing raw messages from TWS is the IBApi.EReader class.

【译】 以下的代码,向您展现了如何处理从TWS IBApi.EReader获取到的“生消息”(未加工的消息)的过程。


  1. final EReader reader = new EReader(m_client, m_signal);   

  2. reader.start();
  3. //An additional thread is created in this program design to empty the messaging queue
  4. new Thread(() -> {
  5.     while (m_client.isConnected()) {
  6.         m_signal.waitForSignal();
  7.         try {
  8.             reader.processMsgs();
  9.         } catch (Exception e) {
  10.             System.out.println("Exception: "+e.getMessage());
  11.         }
  12.     }
  13. }).start();
复制代码



Now it is time to revisit the role of IBApi.EReaderSignal initially introduced in The EClientSocket Class. As mentioned in the previous paragraph, after the EReader thread places a message in the queue, a notification is issued to make known that a message is ready for processing. In the (C++, C#/.NET, Java) APIs, this is done via the IBApi.EReaderSignal object we initiated within the IBApi.EWrapper's implementer. In the Python API, it is handled automatically by the Queue class.

【译】 现在,是时候重温一下最初在 EClientSocket 中介绍的 IBApi.EReaderSignal。在之前的章节中我们提到,EReader往队列中添加新的消息,并生成一个标记,告知其他线程可以对该消息进行处理。在(C++, C#/.NET, Java)API中,这一步通过IBApi.EReaderSignal的对象实现。在Python的API中,它由Queue类自动完成。

The client application is now ready to work with the Trader Workstation! At the completion of the connection, the API program will start receiving events such as IBApi.EWrapper.nextValidId and IBApi.EWrapper.managedAccounts. In TWS (not IB Gateway)if there is an active network connection, there will also immediately be callbacks to IBApi::EWrapper::error with errorId as -1 and errorCode=2104,2106, errorMsg = "Market Data Server is ok" to indicate there is an active connection to the IB market data server.

【译】 至此,已经可以与Trader Workstation通信并工作了!当完成了连接,API程序将开始接收消息,如IBApi.EWrapper.nextValidId,IBApi.EWrapper.managedAccounts。在TWS(而不是IB网关),如果有活跃的网络连接,也会被立即的通过回掉传值给IBApi::EWrapper::error,errorId为-1,errorCode=2104,2106,errorMsg = "Market Data Server is ok" 用于指示有活跃的连接到IB市场数据服务器。

Callbacks to IBApi::EWrapper::error with errorId as -1 do not represent true 'errors' but only notifications that a connection has been made successfully to the IB market data farms.

【译】 回掉传给IBApi::EWrapper::error为-1的值,并不意味着真的有错误,而仅仅表示连接是有效的,并且已经可以获得来自IB的市场数据。

IB Gateway by contrast will not make connections to market data farms until a request is made by the IB client. Until this time the connection indicator in the IB Gateway GUI will show a yellow color of 'inactive' rather than an 'active' green indication.

【译】 作为对比,IB网关并不会连接至IB的市场数据农场,直到从IB客户端发起了请求。直到此时,IB网关的连接指示灯也只是显示为黄色“不活跃”而不是表示“活跃”的绿色。

When initially making requests from an API application it is important that the verifies that a response is received rather than proceeding assuming that the network connection is ok and the subscription request (portfolio updates, account information, etc) was made successfully.

【译】 初始的,当从API程序产生了请求后,非常重要的一点是需要先确保能够从服务器获得回应而不是急着处理消息,从而确认网络是否连通,以及订阅请求(组合更新情况,账户信息,以及其他数据)是成功的。

Accepting an API connection from TWS
【译】 接收来自TWS的消息

For security reasons, by default the API is not configured to automatically accept connection requests from API applications. After a connection attempt, a dialogue will appear in TWS asking the user to manually confirm that a connection can be made:

【译】 出于安全的考虑,API默认不自动的从API程序获取信息。当尝试过连接后,在TWS会弹出对话框要求用户手动确认来自客户端的连接。

conn_prompt

To prevent the TWS from asking the end user to accept the connection, it is possible to configure it to automatically accept the connection from a trusted IP address and/or the local machine. This can easily be done via the TWS API settings:

【译】 为了阻止TWS每次都弹出确认对话框,需要在可信区内配置客户端的IP地址。它可以被很简单的配置到TWS中:

tws_allow_connections

Note: you have to make sure the connection has been fully established before attempting to do any requests to the TWS. Failure to do so will result in the TWS closing the connection. Typically this can be done by waiting for a callback from an event and the end of the initial connection handshake, such as IBApi.EWrapper.nextValidId or IBApi.EWrapper.managedAccounts.

【译】 注意:你必须确保连接被完整的建立,而不是猴急的做任何消息请求。在失败的情况下做请求,会导致TWS关闭连接。典型的,它会出现在等待事件的回掉与初次握手,例如 IBApi.EWrapper.nextValidId或者IBApi.EWrapper.managedAccounts。

In rare cases in which IB Gateway or TWS has a momentarily delay in establishing connecting to the IB servers, messages sent immediately after receiving the nextValidId could be dropped and would need to be resent. If the API client has not receive the expected callbacks from issued requests, it should not proceed assumming the connection is ok.

【译】 非常少见的情况下,IB网关或者TWS在建立与IB服务器的连接时会有短暂的延迟,此时发送消息并获取nextValidId会导致连接被抛弃。如果客户端没有收到期望的回掉,它就不应该在假设连接是正常的情况下做任何事。

Broken API socket connection
【译】 API连接中断

If there is a problem with the socket connection between TWS and the API client, for instance if TWS suddenly closes, this will trigger an exception in the EReader thread which is reading from the socket. This exception will also occur if an API client attempts to connect with a client ID that is already in use.

【译】 如果在TWS与API客户端之间的连接存在问题,例如,TWS突然的关闭,客户端会从EReader的线程收到一个异常。这个异常同样存在,当客户端试图以一个已经存在的ID连接至TWS时,将会报错。

The socket EOF is handled slightly differently in different API languages. For instance in Java, it is caught and sent to the client application to IBApi::EWrapper::error with errorCode 507: "Bad Message". In C# it is caught and sent to IBApi::EWrapper::error with errorCode -1. The client application needs to handle this error message and use it to indicate that an exception has been thrown in the socket connection. Associated functions such as IBApi::EWrapper::connectionClosed and IBApi::EClient::IsConnected functions are not called automatically by the API code but need to be handled at the API client-level.

【译】 Socket的EOF在不同的语言中会有细微差别。例如,在Java语言中,它会以 errorCode 507: "Bad Message" 的形式被 IBApi::EWrapper::error捕捉到。在C#语言中,会以errorCode -1被IBApi::EWrapper::error捕捉。客户端需要处理这个错误信息,并知道是由socket抛出。对应的函数为IBApi::EWrapper::connectionClosed 和 IBApi::EClient::IsConnected ,它们并不会自动的被调用,而且需要被客户端层级(代码层级)进行处理。

论坛官方微信、群(期货热点、量化探讨、开户与绑定实盘)
 
期货论坛 - 版权/免责声明   1.本站发布源码(包括函数、指标、策略等)均属开放源码,用意在于让使用者学习程序化语法撰写,使用者可以任意修改语法內容并调整参数。仅限用于个人学习使用,请勿转载、滥用,严禁私自连接实盘账户交易
  2.本站发布资讯(包括文章、视频、历史记录、教材、评论、资讯、交易方案等)均系转载自网络主流媒体,内容仅为作者当日个人观点,本网转载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。本网不对该类信息或数据做任何保证。不对您构成任何投资建议,不能依靠信息而取代自身独立判断,不对因使用本篇文章所诉信息或观点等导致的损失承担任何责任。
  3.本站发布资源(包括书籍、杂志、文档、软件等)均从互联网搜索而来,仅供个人免费交流学习,不可用作商业用途,本站不对显示的内容承担任何责任。请在下载后24小时内删除。如果喜欢,请购买正版,谢谢合作!
  4.龙听期货论坛原创文章属本网版权作品,转载须注明来源“龙听期货论坛”,违者本网将保留追究其相关法律责任的权力。本论坛除发布原创文章外,亦致力于优秀财经文章的交流分享,部分文章推送时若未能及时与原作者取得联系并涉及版权问题时,请及时联系删除。联系方式:http://www.qhlt.cn/thread-262-1-1.html
如何访问权限为100/255贴子:/thread-37840-1-1.html;注册后仍无法回复:/thread-23-1-1.html;微信/QQ群:/thread-262-1-1.html;网盘链接失效解决办法:/thread-93307-1-1.html

返回列表