-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTwsRtdServer.cs
305 lines (267 loc) · 11.9 KB
/
TwsRtdServer.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/* Copyright (C) 2018 Interactive Brokers LLC. All rights reserved. This code is subject to the terms
* and conditions of the IB API Non-Commercial License or the IB API Commercial License, as applicable. */
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Office.Interop.Excel;
using System.Text;
namespace TwsRtdServer
{
[ProgId("Tws.TwsRtdServerCtrl")]
[Guid("77F86AC4-9BE9-4245-BBE3-DF18996EADFE")]
[ComVisible(true), ClassInterface(ClassInterfaceType.None)]
public partial class TwsRtdServer : IRtdServer
{
// vars
private IRTDUpdateEvent m_callback;
private IDictionary<string, TwsRtdServerConnection> m_connections; // connections map: connectionStr(e.g. 127.0.0.1_4001_1) => TwsRtdServerConnection
private IDictionary<int, TwsRtdServerTopicIdMap> m_topicIdMap; // map: topicId => TwsRtdServerTopicIdMap(connectionStr/mktDataRequestId/topicStr) - to quickly find connection/mktDataRequest/topic
private List<int> m_updatedTopicIds = new List<int>(); // list of updated topicIds (need to sent updates back to Excel)
// constructor
public TwsRtdServer() {}
// this method is called when RTD server is started
public int ServerStart(IRTDUpdateEvent callback)
{
Console.WriteLine("TwsRtdServer Start");
// create empty arrays/lists
if (m_topicIdMap == null)
{
m_topicIdMap = new Dictionary<int, TwsRtdServerTopicIdMap>();
}
if (m_connections == null)
{
m_connections = new Dictionary<string, TwsRtdServerConnection>();
}
m_callback = callback;
return 1;
}
// this method is called when RTD server is stopped (last topic is removed)
public void ServerTerminate()
{
Console.WriteLine("TwsRtdServer Terminate");
foreach (var connectionStr in m_connections.Keys.ToArray())
{
TwsRtdServerConnection connection = null;
if (m_connections.TryGetValue(connectionStr, out connection))
{
if (connection.MktDataRequestsCount() <= 0)
{
connection.TwsRtdServerConnectionDisconnect();
m_connections.Remove(connectionStr);
}
}
}
}
public int Heartbeat()
{
return 1;
}
// this method is called when new topic is requested
public object ConnectData(int topicId, ref Array strings, ref bool newValues)
{
string connectionStr, mktDataRequestStr, topicStr;
newValues = true;
try
{
// parse input strings (connection, marketDataRequest and topic)
connectionStr = TwsRtdServerConnection.ParseConnectionStrings(strings);
mktDataRequestStr = TwsRtdServerMktDataRequest.ParseMktDataRequestStrings(strings);
topicStr = TwsRtdServerTopic.ParseTopicStrings(strings);
// check that connectioStr, mktDataRequestStr and topicStr is not null
if (connectionStr == null)
{
return "TwsRtdServer: Cannot parse connection strings";
}
if (mktDataRequestStr == null)
{
return "TwsRtdServer: Cannot parse mktDataRequest strings";
}
if (topicStr == null)
{
return "TwsRtdServer: Cannot parse topic strings";
}
TwsRtdServerConnection connection = null;
// find connection from RTD server to TWS (to reuse existing connection and not to create new one)
if (!m_connections.TryGetValue(connectionStr, out connection))
{
// if connection is not found, then create new one and add it to collection
connection = new TwsRtdServerConnection(this, connectionStr);
// save connection
m_connections.Add(connectionStr, connection);
}
if (connection != null && connection.GetErrorCode() != -1)
{
// error connecting to TWS
return "TwsRtdServer error: " + connection.GetErrorText();
}
TwsRtdServerMktDataRequest mktDataRequest = connection.GetOrAddMktDataRequest(mktDataRequestStr);
string errorStr = null;
if (mktDataRequest != null)
{
// save topicId -> connection/mktDataRequest/topicStr map
m_topicIdMap.Add(topicId, new TwsRtdServerTopicIdMap(connectionStr, mktDataRequest.TwsReqId(), topicStr));
if (mktDataRequest.GetErrorCode() != -1
&& mktDataRequest.GetErrorCode() != TwsRtdServerErrors.REQUESTED_MARKET_DATA_NOT_SUBSCRIBED)
{
// error creating market data request
return errorStr = "TwsRtdServer error: " + mktDataRequest.GetErrorText();
}
}
else
{
// error creating market data request
return errorStr = "TwsRtdServer error: market data request creation error";
}
TwsRtdServerTopic topic = mktDataRequest.GetOrAddTopic(topicStr, topicId);
if (topic == null)
{
// error creating topic
return errorStr = "TwsRtdServer error: topic creation error";
}
// check if topic is delayed type
if (topic != null && Array.IndexOf(TwsRtdServerData.DelayedTopics(), topic.TopicStr()) < 0
&& mktDataRequest.GetErrorCode() == TwsRtdServerErrors.REQUESTED_MARKET_DATA_NOT_SUBSCRIBED)
{
errorStr = "TwsRtdServer error: " + mktDataRequest.GetErrorText();
}
return ((topic != null && errorStr == null) ? topic.TopicValue() : errorStr);
}
catch
{
return "RTDServer: Error connecting data";
}
}
// this method is called when topic is removed
public void DisconnectData(int topicId)
{
try
{
// find appropriate connection, mktDataRequest and topic
TwsRtdServerTopicIdMap twsRtdServerTopicIdMap = null;
if (!m_topicIdMap.TryGetValue(topicId, out twsRtdServerTopicIdMap))
{
return;
}
// get appropriate connection
TwsRtdServerConnection connection = null;
if (!m_connections.TryGetValue(twsRtdServerTopicIdMap.ConnectionStr(), out connection))
{
return;
}
// get appropriate mktDataRequest
TwsRtdServerMktDataRequest mktDataRequest = connection.GetMktDataRequest(twsRtdServerTopicIdMap.TwsReqId());
if (mktDataRequest != null)
{
// get appropriate topic
TwsRtdServerTopic topic = mktDataRequest.GetTopic(twsRtdServerTopicIdMap.TopicStr());
if (topic != null)
{
// remove topic
mktDataRequest.RemoveTopic(twsRtdServerTopicIdMap.TopicStr());
}
m_topicIdMap.Remove(topicId);
// remove topicId from updatedTopicIds
lock (m_updatedTopicIds)
{
m_updatedTopicIds.Remove(topicId);
}
// try to remove mktDataRequest
connection.RemoveMktDataRequest(twsRtdServerTopicIdMap.TwsReqId());
}
}
catch
{
// error disconnecting data
}
}
// method is called when there are new data to update
public Array RefreshData(ref int topicCount)
{
object[,] data = null;
try
{
TwsRtdServerConnection connection = null;
TwsRtdServerMktDataRequest mktDataRequest = null;
TwsRtdServerTopic topic = null;
// in loop - update all topics from updatedTopicIds array
int[] updatedTopicIds;
lock (m_updatedTopicIds)
{
updatedTopicIds = m_updatedTopicIds.ToArray();
m_updatedTopicIds.Clear();
}
topicCount = updatedTopicIds.Length;
data = new object[2, topicCount];
int n = 0;
foreach(var topicId in updatedTopicIds)
{
TwsRtdServerTopicIdMap twsRtdServerTopicIdMap = null;
if (m_topicIdMap.TryGetValue(topicId, out twsRtdServerTopicIdMap))
{
// get appropriate connection
if (m_connections.TryGetValue(twsRtdServerTopicIdMap.ConnectionStr(), out connection))
{
// get appropriate mktDataRequest
mktDataRequest = connection.GetMktDataRequest(twsRtdServerTopicIdMap.TwsReqId());
if (mktDataRequest != null)
{
// get appropriate topic
topic = mktDataRequest.GetTopic(twsRtdServerTopicIdMap.TopicStr());
}
if (topic != null)
{
// update data array with topic.Id and topic.Value
data[0, n] = topic.TopicId();
data[1, n] = topic.TopicValue();
n++;
}
}
}
}
}
catch //(COMException comException)
{
// comException.Message = "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))"
// Console.WriteLine(comException.Message);
}
return data;
}
public void AddUpdatedTopicId(int topicId)
{
try
{
lock (m_updatedTopicIds)
{
if (!m_updatedTopicIds.Contains(topicId))
{
m_updatedTopicIds.Add(topicId);
}
}
m_callback.UpdateNotify();
}
catch //(COMException comException)
{
// comException.Message = "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))"
// Console.WriteLine(comException.Message);
}
}
public void AddUpdatedTopicIds(List<int> topicIds)
{
try
{
lock (m_updatedTopicIds)
{
m_updatedTopicIds.AddRange(topicIds);
}
m_callback.UpdateNotify();
}
catch //(COMException comException)
{
// comException.Message = "The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER))"
// Console.WriteLine(comException.Message);
}
}
} //TwsRtdServer
}