forked from StockSharp/StockSharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MessageAdapter.cs
621 lines (518 loc) · 16.8 KB
/
MessageAdapter.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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
#region S# License
/******************************************************************************************
NOTICE!!! This program and source code is owned and licensed by
StockSharp, LLC, www.stocksharp.com
Viewing or use of this code requires your acceptance of the license
agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE
Removal of this comment is a violation of the license agreement.
Project: StockSharp.Messages.Messages
File: MessageAdapter.cs
Created: 2015, 11, 11, 2:32 PM
Copyright 2010 by StockSharp, LLC
*******************************************************************************************/
#endregion S# License
namespace StockSharp.Messages
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using Ecng.Collections;
using Ecng.Common;
using Ecng.Interop;
using Ecng.Serialization;
using MoreLinq;
using StockSharp.Logging;
using StockSharp.Localization;
/// <summary>
/// The base adapter converts messages <see cref="Message"/> to the command of the trading system and back.
/// </summary>
public abstract class MessageAdapter : BaseLogReceiver, IMessageAdapter
{
private class CodeTimeOut
//where T : class
{
private readonly CachedSynchronizedDictionary<long, TimeSpan> _registeredKeys = new CachedSynchronizedDictionary<long, TimeSpan>();
private TimeSpan _timeOut = TimeSpan.FromSeconds(10);
public TimeSpan TimeOut
{
get => _timeOut;
set
{
if (value <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(value), value, LocalizedStrings.IntervalMustBePositive);
_timeOut = value;
}
}
public void StartTimeOut(long key)
{
//if (key == 0)
// throw new ArgumentNullException(nameof(key));
_registeredKeys.SafeAdd(key, s => TimeOut);
}
public IEnumerable<long> ProcessTime(TimeSpan diff)
{
if (_registeredKeys.Count == 0)
return Enumerable.Empty<long>();
return _registeredKeys.SyncGet(d =>
{
var timeOutCodes = new List<long>();
foreach (var pair in d.CachedPairs)
{
d[pair.Key] -= diff;
if (d[pair.Key] > TimeSpan.Zero)
continue;
timeOutCodes.Add(pair.Key);
d.Remove(pair.Key);
}
return timeOutCodes;
});
}
}
private DateTimeOffset _prevTime;
private readonly CodeTimeOut _secLookupTimeOut = new CodeTimeOut();
private readonly CodeTimeOut _pfLookupTimeOut = new CodeTimeOut();
/// <summary>
/// Initialize <see cref="MessageAdapter"/>.
/// </summary>
/// <param name="transactionIdGenerator">Transaction id generator.</param>
protected MessageAdapter(IdGenerator transactionIdGenerator)
{
if (transactionIdGenerator == null)
throw new ArgumentNullException(nameof(transactionIdGenerator));
Platform = Platforms.AnyCPU;
TransactionIdGenerator = transactionIdGenerator;
SecurityClassInfo = new Dictionary<string, RefPair<SecurityTypes, string>>();
StorageName = GetType().Namespace.Remove(nameof(StockSharp)).Remove(".");
Platform = GetType().GetAttribute<TargetPlatformAttribute>()?.Platform ?? Platforms.AnyCPU;
}
private MessageTypes[] _supportedMessages = ArrayHelper.Empty<MessageTypes>();
/// <inheritdoc />
[Browsable(false)]
public virtual MessageTypes[] SupportedMessages
{
get => _supportedMessages;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var duplicate = value.GroupBy(m => m).FirstOrDefault(g => g.Count() > 1);
if (duplicate != null)
throw new ArgumentException(LocalizedStrings.Str415Params.Put(duplicate.Key), nameof(value));
_supportedMessages = value;
}
}
private MarketDataTypes[] _supportedMarketDataTypes = ArrayHelper.Empty<MarketDataTypes>();
/// <inheritdoc />
[Browsable(false)]
public virtual MarketDataTypes[] SupportedMarketDataTypes
{
get => _supportedMarketDataTypes;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
var duplicate = value.GroupBy(m => m).FirstOrDefault(g => g.Count() > 1);
if (duplicate != null)
throw new ArgumentException(LocalizedStrings.Str415Params.Put(duplicate.Key), nameof(value));
_supportedMarketDataTypes = value;
}
}
/// <inheritdoc />
[Browsable(false)]
public IDictionary<string, RefPair<SecurityTypes, string>> SecurityClassInfo { get; }
private TimeSpan _heartbeatInterval = TimeSpan.Zero;
/// <summary>
/// Server check interval for track the connection alive. The value is <see cref="TimeSpan.Zero"/> turned off tracking.
/// </summary>
[Display(
ResourceType = typeof(LocalizedStrings),
Name = LocalizedStrings.Str192Key,
Description = LocalizedStrings.Str193Key,
GroupName = LocalizedStrings.Str186Key)]
public TimeSpan HeartbeatInterval
{
get => _heartbeatInterval;
set
{
if (value < TimeSpan.Zero)
throw new ArgumentOutOfRangeException();
_heartbeatInterval = value;
}
}
/// <inheritdoc />
[Browsable(false)]
public virtual bool SecurityLookupRequired => this.IsMessageSupported(MessageTypes.SecurityLookup);
/// <inheritdoc />
[Browsable(false)]
public virtual bool PortfolioLookupRequired => this.IsMessageSupported(MessageTypes.PortfolioLookup);
/// <inheritdoc />
[Browsable(false)]
public virtual bool OrderStatusRequired => this.IsMessageSupported(MessageTypes.OrderStatus);
/// <summary>
/// Native identifier can be stored.
/// </summary>
[Browsable(false)]
public virtual bool IsNativeIdentifiersPersistable => true;
/// <inheritdoc />
[Browsable(false)]
public virtual bool IsNativeIdentifiers => false;
/// <inheritdoc />
[Browsable(false)]
public virtual bool IsFullCandlesOnly => true;
/// <inheritdoc />
[Browsable(false)]
public virtual bool IsSupportSubscriptions => true;
/// <inheritdoc />
[Browsable(false)]
public virtual bool IsSupportSubscriptionBySecurity => true;
/// <inheritdoc />
[Browsable(false)]
public virtual bool IsSupportSubscriptionByPortfolio => this.IsMessageSupported(MessageTypes.Portfolio);
/// <inheritdoc />
[Browsable(false)]
public virtual string StorageName { get; }
/// <inheritdoc />
[Browsable(false)]
public virtual OrderCancelVolumeRequireTypes? OrderCancelVolumeRequired { get; } = null;
/// <summary>
/// Gets a value indicating whether the connector supports security lookup.
/// </summary>
protected virtual bool IsSupportNativeSecurityLookup => false;
/// <summary>
/// Gets a value indicating whether the connector supports position lookup.
/// </summary>
protected virtual bool IsSupportNativePortfolioLookup => false;
/// <summary>
/// Bit process, which can run the adapter.
/// </summary>
[Browsable(false)]
public Platforms Platform { get; }
/// <inheritdoc />
[Browsable(false)]
public virtual Tuple<string, Type>[] SecurityExtendedFields { get; } = ArrayHelper.Empty<Tuple<string, Type>>();
/// <inheritdoc />
public virtual OrderCondition CreateOrderCondition()
{
return null;
}
/// <inheritdoc />
[CategoryLoc(LocalizedStrings.Str174Key)]
public ReConnectionSettings ReConnectionSettings { get; } = new ReConnectionSettings();
private IdGenerator _transactionIdGenerator;
/// <inheritdoc />
[Browsable(false)]
public IdGenerator TransactionIdGenerator
{
get => _transactionIdGenerator;
set
{
if (value == null)
throw new ArgumentNullException(nameof(value));
_transactionIdGenerator = value;
}
}
/// <summary>
/// Securities and portfolios lookup timeout.
/// </summary>
/// <remarks>
/// By defaut is 10 seconds.
/// </remarks>
[Browsable(false)]
public TimeSpan LookupTimeOut
{
get => _secLookupTimeOut.TimeOut;
set
{
_secLookupTimeOut.TimeOut = value;
_pfLookupTimeOut.TimeOut = value;
}
}
/// <summary>
/// Default value for <see cref="AssociatedBoardCode"/>.
/// </summary>
public const string DefaultAssociatedBoardCode = "ALL";
/// <summary>
/// Associated board code. The default is ALL.
/// </summary>
[CategoryLoc(LocalizedStrings.Str186Key)]
[DisplayNameLoc(LocalizedStrings.AssociatedSecurityBoardKey)]
[DescriptionLoc(LocalizedStrings.Str199Key)]
public string AssociatedBoardCode { get; set; } = DefaultAssociatedBoardCode;
/// <summary>
/// Outgoing message event.
/// </summary>
public event Action<Message> NewOutMessage;
bool IMessageChannel.IsOpened => true;
void IMessageChannel.Open()
{
}
void IMessageChannel.Close()
{
}
/// <summary>
/// Send incoming message.
/// </summary>
/// <param name="message">Message.</param>
public void SendInMessage(Message message)
{
if (message.Type == MessageTypes.Connect)
{
if (!Platform.IsCompatible())
{
SendOutMessage(new ConnectMessage
{
Error = new InvalidOperationException(LocalizedStrings.Str169Params.Put(GetType().Name, Platform))
});
return;
}
}
InitMessageLocalTime(message);
switch (message.Type)
{
case MessageTypes.Reset:
_prevTime = default(DateTimeOffset);
break;
case MessageTypes.PortfolioLookup:
{
if (!IsSupportNativePortfolioLookup)
_pfLookupTimeOut.StartTimeOut(((PortfolioLookupMessage)message).TransactionId);
break;
}
case MessageTypes.SecurityLookup:
{
if (!IsSupportNativeSecurityLookup)
_secLookupTimeOut.StartTimeOut(((SecurityLookupMessage)message).TransactionId);
break;
}
}
try
{
OnSendInMessage(message);
}
catch (Exception ex)
{
this.AddErrorLog(ex);
switch (message.Type)
{
case MessageTypes.Connect:
SendOutMessage(new ConnectMessage { Error = ex });
return;
case MessageTypes.Disconnect:
SendOutMessage(new DisconnectMessage { Error = ex });
return;
case MessageTypes.OrderRegister:
case MessageTypes.OrderReplace:
case MessageTypes.OrderCancel:
case MessageTypes.OrderGroupCancel:
{
var replyMsg = ((OrderMessage)message).CreateReply();
SendOutErrorExecution(replyMsg, ex);
return;
}
case MessageTypes.OrderPairReplace:
{
var replyMsg = ((OrderPairReplaceMessage)message).Message1.CreateReply();
SendOutErrorExecution(replyMsg, ex);
return;
}
case MessageTypes.MarketData:
{
var reply = (MarketDataMessage)message.Clone();
reply.OriginalTransactionId = reply.TransactionId;
reply.Error = ex;
SendOutMessage(reply);
return;
}
case MessageTypes.SecurityLookup:
{
var lookupMsg = (SecurityLookupMessage)message;
SendOutMessage(new SecurityLookupResultMessage
{
OriginalTransactionId = lookupMsg.TransactionId,
Error = ex
});
return;
}
case MessageTypes.PortfolioLookup:
{
var lookupMsg = (PortfolioLookupMessage)message;
SendOutMessage(new PortfolioLookupResultMessage
{
OriginalTransactionId = lookupMsg.TransactionId,
Error = ex
});
return;
}
case MessageTypes.ChangePassword:
{
var pwdMsg = (ChangePasswordMessage)message;
SendOutMessage(new ChangePasswordMessage
{
OriginalTransactionId = pwdMsg.TransactionId,
Error = ex
});
return;
}
}
SendOutError(ex);
}
}
private void SendOutErrorExecution(ExecutionMessage execMsg, Exception ex)
{
execMsg.ServerTime = CurrentTime;
execMsg.Error = ex;
execMsg.OrderState = OrderStates.Failed;
SendOutMessage(execMsg);
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
protected abstract void OnSendInMessage(Message message);
/// <summary>
/// Send outgoing message and raise <see cref="NewOutMessage"/> event.
/// </summary>
/// <param name="message">Message.</param>
public virtual void SendOutMessage(Message message)
{
InitMessageLocalTime(message);
if (/*message.IsBack && */message.Adapter == null)
message.Adapter = this;
if (_prevTime != DateTimeOffset.MinValue)
{
var diff = message.LocalTime - _prevTime;
_secLookupTimeOut
.ProcessTime(diff)
.ForEach(id => SendOutMessage(new SecurityLookupResultMessage { OriginalTransactionId = id }));
_pfLookupTimeOut
.ProcessTime(diff)
.ForEach(id => SendOutMessage(new PortfolioLookupResultMessage { OriginalTransactionId = id }));
}
_prevTime = message.LocalTime;
NewOutMessage?.Invoke(message);
}
/// <summary>
/// Initialize local timestamp <see cref="Message"/>.
/// </summary>
/// <param name="message">Message.</param>
private void InitMessageLocalTime(Message message)
{
message.TryInitLocalTime(this);
if (message is BaseChangeMessage<PositionChangeTypes> posMsg && posMsg.ServerTime.IsDefault())
{
posMsg.ServerTime = CurrentTime;
}
}
/// <summary>
/// Initialize a new message <see cref="ErrorMessage"/> and pass it to the method <see cref="SendOutMessage"/>.
/// </summary>
/// <param name="description">Error details.</param>
protected void SendOutError(string description)
{
SendOutError(new InvalidOperationException(description));
}
/// <summary>
/// Initialize a new message <see cref="ErrorMessage"/> and pass it to the method <see cref="SendOutMessage"/>.
/// </summary>
/// <param name="error">Error details.</param>
protected void SendOutError(Exception error)
{
SendOutMessage(error.ToErrorMessage());
}
/// <summary>
/// Initialize a new message <see cref="SecurityMessage"/> and pass it to the method <see cref="SendOutMessage"/>.
/// </summary>
/// <param name="securityId">Security ID.</param>
protected void SendOutSecurityMessage(SecurityId securityId)
{
SendOutMessage(new SecurityMessage { SecurityId = securityId });
}
/// <summary>
/// Initialize a new message <see cref="SecurityMessage"/> and pass it to the method <see cref="SendOutMessage"/>.
/// </summary>
/// <param name="originalTransactionId">ID of the original message for which this message is a response.</param>
protected void SendOutMarketDataNotSupported(long originalTransactionId)
{
SendOutMessage(new MarketDataMessage { OriginalTransactionId = originalTransactionId, IsNotSupported = true });
}
/// <summary>
/// Check the connection is alive. Uses only for connected states.
/// </summary>
/// <returns><see langword="true" />, is the connection still alive, <see langword="false" />, if the connection was rejected.</returns>
public virtual bool IsConnectionAlive()
{
return true;
}
/// <summary>
/// Create market depth builder.
/// </summary>
/// <param name="securityId">Security ID.</param>
/// <returns>Order log to market depth builder.</returns>
public virtual IOrderLogMarketDepthBuilder CreateOrderLogMarketDepthBuilder(SecurityId securityId)
{
throw new NotSupportedException();
}
/// <summary>
/// Load settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public override void Load(SettingsStorage storage)
{
Id = storage.GetValue(nameof(Id), Id);
HeartbeatInterval = storage.GetValue<TimeSpan>(nameof(HeartbeatInterval));
SupportedMessages = storage.GetValue<string[]>(nameof(SupportedMessages)).Select(i => i.To<MessageTypes>()).ToArray();
AssociatedBoardCode = storage.GetValue(nameof(AssociatedBoardCode), AssociatedBoardCode);
base.Load(storage);
}
/// <summary>
/// Save settings.
/// </summary>
/// <param name="storage">Settings storage.</param>
public override void Save(SettingsStorage storage)
{
storage.SetValue(nameof(Id), Id);
storage.SetValue(nameof(HeartbeatInterval), HeartbeatInterval);
storage.SetValue(nameof(SupportedMessages), SupportedMessages.Select(t => t.To<string>()).ToArray());
storage.SetValue(nameof(AssociatedBoardCode), AssociatedBoardCode);
base.Save(storage);
}
/// <summary>
/// Create a copy of <see cref="MessageAdapter"/>.
/// </summary>
/// <returns>Copy.</returns>
public virtual IMessageChannel Clone()
{
var clone = GetType().CreateInstance<MessageAdapter>(TransactionIdGenerator);
clone.Load(this.Save());
return clone;
}
object ICloneable.Clone()
{
return Clone();
}
}
/// <summary>
/// Special adapter, which transmits directly to the output of all incoming messages.
/// </summary>
public class PassThroughMessageAdapter : MessageAdapter
{
/// <summary>
/// Initializes a new instance of the <see cref="PassThroughMessageAdapter"/>.
/// </summary>
/// <param name="transactionIdGenerator">Transaction id generator.</param>
public PassThroughMessageAdapter(IdGenerator transactionIdGenerator)
: base(transactionIdGenerator)
{
}
/// <summary>
/// Send message.
/// </summary>
/// <param name="message">Message.</param>
protected override void OnSendInMessage(Message message)
{
SendOutMessage(message);
}
}
}