FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
StockSharp/Algo/EntityCache.cs at master · StockSharp/StockSharp · GitHub
Uh oh!
There was an error while loading.
Please reload this page
.
StockSharp
/
StockSharp
Public
Notifications
You must be signed in to change notification settings
Fork
2.3k
Star
10.7k
Code
Issues
1
Pull requests
1
Actions
Security and quality
0
Insights
Additional navigation options
Code
Issues
Pull requests
Actions
Security and quality
Insights
Expand file tree
Breadcrumbs
StockSharp
/
Algo
/
EntityCache.cs
Copy path
More file actions
More file actions
Latest commit
History
History
History
1373 lines (1104 loc) · 40.2 KB
Breadcrumbs
StockSharp
/
Algo
/
EntityCache.cs
Copy path
File metadata and controls
1373 lines (1104 loc) · 40.2 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace
StockSharp
.
Algo
;
/// <summary>
/// Order operation types.
/// </summary>
public
enum
OrderOperations
{
/// <summary>
/// Order registration.
/// </summary>
Register
,
/// <summary>
/// Order cancellation.
/// </summary>
Cancel
,
/// <summary>
/// Order modification.
/// </summary>
Edit
,
}
/// <summary>
/// Entity cache for storing orders, trades, news and other trading entities.
/// </summary>
/// <param name="logReceiver">Log receiver for logging messages.</param>
/// <param name="tryGetSecurity">Function to get security by id.</param>
/// <param name="exchangeInfoProvider">Exchange info provider.</param>
/// <param name="positionProvider">Position provider.</param>
public
class
EntityCache
(
ILogReceiver
logReceiver
,
Func
<
SecurityId
?
,
Security
>
tryGetSecurity
,
IExchangeInfoProvider
exchangeInfoProvider
,
IPositionProvider
positionProvider
)
:
ISnapshotHolder
{
/// <summary>
/// Information about order state change.
/// </summary>
public
class
OrderChangeInfo
{
private
OrderChangeInfo
(
)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="OrderChangeInfo"/>.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="isNew">Is new order.</param>
/// <param name="isChanged">Is order changed.</param>
/// <param name="isEdit">Is order edited.</param>
public
OrderChangeInfo
(
Order
order
,
bool
isNew
,
bool
isChanged
,
bool
isEdit
)
{
Order
=
order
??
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
IsNew
=
isNew
;
IsChanged
=
isChanged
;
IsEdit
=
isEdit
;
}
/// <summary>
/// Order.
/// </summary>
public
Order
Order
{
get
;
}
/// <summary>
/// Is new order.
/// </summary>
public
bool
IsNew
{
get
;
}
/// <summary>
/// Is order changed.
/// </summary>
public
bool
IsChanged
{
get
;
}
/// <summary>
/// Is order edited.
/// </summary>
public
bool
IsEdit
{
get
;
}
/// <summary>
/// Order does not exist.
/// </summary>
public
static
readonly
OrderChangeInfo
NotExist
=
new
(
)
;
}
private
class
OrderInfo
(
EntityCache
parent
,
Order
order
,
bool
raiseNewOrder
)
{
private
readonly
EntityCache
_parent
=
parent
??
throw
new
ArgumentNullException
(
nameof
(
parent
)
)
;
public
Order
Order
{
get
;
}
=
order
??
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
public
IEnumerable
<
OrderChangeInfo
>
ApplyChanges
(
ExecutionMessage
message
,
OrderOperations
operation
,
Action
<
Order
>
process
)
{
if
(
process
is
null
)
throw
new
ArgumentNullException
(
nameof
(
process
)
)
;
var
order
=
Order
;
OrderChangeInfo
retVal
;
if
(
order
.
State
==
OrderStates
.
Done
)
{
// данные о заявке могут приходить из маркет-дата и транзакционного адаптеров
retVal
=
new
OrderChangeInfo
(
order
,
raiseNewOrder
,
false
,
false
)
;
raiseNewOrder
=
false
;
process
(
order
)
;
yield
return
retVal
;
//throw new InvalidOperationException("Изменение заявки в состоянии Done невозможно.");
}
else
if
(
order
.
State
==
OrderStates
.
Failed
)
{
// some adapters can resend order's info
//throw new InvalidOperationException();
yield
break
;
}
var
isPending
=
order
.
State
==
OrderStates
.
Pending
;
// is we have Pending order and received Done event
// add intermediate Active event
if
(
isPending
&&
message
.
OrderState
==
OrderStates
.
Done
)
{
var
clone
=
message
.
TypedClone
(
)
;
clone
.
OrderState
=
OrderStates
.
Active
;
clone
.
Balance
=
null
;
foreach
(
var
i
in
ApplyChanges
(
clone
,
operation
,
process
)
)
yield
return
i
;
}
if
(
message
.
OrderId
!=
null
)
order
.
Id
=
message
.
OrderId
.
Value
;
if
(
!
message
.
OrderStringId
.
IsEmpty
(
)
)
order
.
StringId
=
message
.
OrderStringId
;
if
(
!
message
.
OrderBoardId
.
IsEmpty
(
)
)
order
.
BoardId
=
message
.
OrderBoardId
;
if
(
message
.
Balance
!=
null
)
order
.
Balance
=
(
(
decimal
?
)
order
.
Balance
)
.
ApplyNewBalance
(
message
.
Balance
.
Value
,
order
.
TransactionId
,
_parent
.
_logReceiver
)
;
if
(
message
.
OrderState
!=
null
)
{
// Do not allow state "resurrection" after Done (out-of-order updates can arrive).
if
(
order
.
State
!=
OrderStates
.
Done
||
message
.
OrderState
.
Value
==
OrderStates
.
Done
)
order
.
ApplyNewState
(
message
.
OrderState
.
Value
,
_parent
.
_logReceiver
)
;
}
if
(
order
.
Time
==
DateTime
.
MinValue
)
order
.
Time
=
message
.
ServerTime
;
// для новых заявок используем серверное время,
// т.к. заявка получена первый раз и не менялась
// ServerTime для заявки - это время регистрации
order
.
ServerTime
=
raiseNewOrder
?
message
.
ServerTime
:
message
.
LocalTime
;
order
.
LocalTime
=
message
.
LocalTime
;
if
(
message
.
OrderState
==
OrderStates
.
Done
)
{
if
(
message
.
IsCanceled
(
)
)
order
.
CancelledTime
??=
message
.
ServerTime
;
else
order
.
MatchedTime
??=
message
.
ServerTime
;
}
if
(
message
.
OrderPrice
!=
0
)
order
.
Price
=
message
.
OrderPrice
;
if
(
message
.
OrderVolume
!=
null
)
order
.
Volume
=
message
.
OrderVolume
.
Value
;
if
(
message
.
Commission
!=
default
)
order
.
Commission
=
message
.
Commission
;
if
(
!
message
.
CommissionCurrency
.
IsEmpty
(
)
)
order
.
CommissionCurrency
=
message
.
CommissionCurrency
;
if
(
message
.
TimeInForce
!=
default
)
order
.
TimeInForce
=
message
.
TimeInForce
.
Value
;
if
(
message
.
Latency
!=
default
)
{
switch
(
operation
)
{
case
OrderOperations
.
Register
:
{
if
(
isPending
&&
order
.
State
!=
OrderStates
.
Pending
)
order
.
LatencyRegistration
=
message
.
Latency
.
Value
;
break
;
}
case
OrderOperations
.
Cancel
:
{
order
.
LatencyCancellation
=
message
.
Latency
.
Value
;
break
;
}
case
OrderOperations
.
Edit
:
{
order
.
LatencyEdition
=
message
.
Latency
.
Value
;
break
;
}
default
:
throw
new
ArgumentOutOfRangeException
(
operation
.
ToString
(
)
)
;
}
}
if
(
message
.
AveragePrice
!=
default
)
order
.
AveragePrice
=
message
.
AveragePrice
;
if
(
message
.
Yield
!=
default
)
order
.
Yield
=
message
.
Yield
;
if
(
message
.
PostOnly
!=
default
)
order
.
PostOnly
=
message
.
PostOnly
;
if
(
message
.
SeqNum
!=
default
)
order
.
SeqNum
=
message
.
SeqNum
;
if
(
message
.
Leverage
!=
default
)
order
.
Leverage
=
message
.
Leverage
;
if
(
message
.
MarketPrice
!=
default
)
order
.
MarketPrice
=
message
.
MarketPrice
;
retVal
=
new
OrderChangeInfo
(
order
,
raiseNewOrder
,
true
,
operation
==
OrderOperations
.
Edit
)
;
raiseNewOrder
=
false
;
process
(
order
)
;
yield
return
retVal
;
}
}
private
class
SecurityData
{
public
readonly
CachedSynchronizedDictionary
<
(
long
transId
,
long
tradeId
,
string
tradeStrId
)
,
MyTrade
>
MyTrades
=
[
]
;
public
readonly
CachedSynchronizedDictionary
<
(
long
transId
,
bool
conditional
,
OrderOperations
operation
)
,
OrderInfo
>
Orders
=
[
]
;
public
OrderInfo
TryGetOrder
(
OrderTypes
?
type
,
long
transactionId
,
OrderOperations
operation
)
{
return
Orders
.
TryGetValue
(
CreateOrderKey
(
type
,
transactionId
,
operation
)
)
??
(
type
==
null
?
Orders
.
TryGetValue
(
CreateOrderKey
(
OrderTypes
.
Conditional
,
transactionId
,
operation
)
)
:
null
)
;
}
public
readonly
SynchronizedDictionary
<
long
,
Order
>
OrdersById
=
[
]
;
public
readonly
SynchronizedDictionary
<
string
,
Order
>
OrdersByStringId
=
new
(
StringComparer
.
InvariantCultureIgnoreCase
)
;
}
private
readonly
SynchronizedDictionary
<
Security
,
SecurityData
>
_securityData
=
[
]
;
private
SecurityData
GetData
(
Security
security
)
=>
_securityData
.
SafeAdd
(
security
)
;
private
readonly
SynchronizedDictionary
<
(
long
transId
,
OrderOperations
operation
)
,
Order
>
_allOrdersByTransactionId
=
[
]
;
private
readonly
SynchronizedDictionary
<
(
long
transId
,
OrderOperations
operation
)
,
OrderFail
>
_allOrdersByFailedId
=
[
]
;
private
readonly
SynchronizedDictionary
<
long
,
Order
>
_allOrdersById
=
[
]
;
private
readonly
SynchronizedDictionary
<
string
,
Order
>
_allOrdersByStringId
=
new
(
StringComparer
.
InvariantCultureIgnoreCase
)
;
private
readonly
SynchronizedDictionary
<
Order
,
(
decimal
totalVolume
,
decimal
weightedPriceSum
)
>
_ordersAvgPrices
=
[
]
;
private
readonly
SynchronizedDictionary
<
string
,
News
>
_newsById
=
new
(
StringComparer
.
InvariantCultureIgnoreCase
)
;
private
readonly
SynchronizedList
<
News
>
_newsWithoutId
=
[
]
;
/// <summary>
/// All news.
/// </summary>
public
IEnumerable
<
News
>
News
=>
[
..
_newsWithoutId
.
SyncGet
(
t
=>
t
.
ToArray
(
)
)
,
..
_newsById
.
SyncGet
(
t
=>
t
.
Values
.
ToArray
(
)
)
]
;
private
int
_ordersKeepCount
=
1000
;
/// <summary>
/// Maximum number of orders to keep in cache. Default is 1000.
/// </summary>
public
int
OrdersKeepCount
{
get
=>
_ordersKeepCount
;
set
{
if
(
_ordersKeepCount
==
value
)
return
;
if
(
value
<
0
)
throw
new
ArgumentOutOfRangeException
(
nameof
(
value
)
,
value
,
LocalizedStrings
.
NegativeOrderCountStorage
)
;
_ordersKeepCount
=
value
;
RecycleOrders
(
)
;
}
}
private
void
AddOrder
(
Order
order
)
{
if
(
order
==
null
)
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
if
(
OrdersKeepCount
>
0
)
_orders
.
Add
(
order
,
null
)
;
RecycleOrders
(
)
;
}
private
readonly
HashSet
<
long
>
_orderStatusTransactions
=
[
]
;
private
readonly
HashSet
<
long
>
_massCancelationTransactions
=
[
]
;
/// <summary>
/// Exchange info provider.
/// </summary>
public
IExchangeInfoProvider
ExchangeInfoProvider
{
get
;
}
=
exchangeInfoProvider
??
throw
new
ArgumentNullException
(
nameof
(
exchangeInfoProvider
)
)
;
private
readonly
CachedSynchronizedDictionary
<
Order
,
IMessageAdapter
>
_orders
=
[
]
;
/// <summary>
/// All orders.
/// </summary>
public
IEnumerable
<
Order
>
Orders
=>
_orders
.
CachedKeys
;
private
readonly
CachedSynchronizedList
<
MyTrade
>
_myTrades
=
[
]
;
/// <summary>
/// All own trades.
/// </summary>
public
IEnumerable
<
MyTrade
>
MyTrades
=>
_myTrades
.
Cache
;
private
readonly
SynchronizedList
<
OrderFail
>
_orderRegisterFails
=
[
]
;
/// <summary>
/// Order registration failures.
/// </summary>
public
IEnumerable
<
OrderFail
>
OrderRegisterFails
=>
_orderRegisterFails
.
SyncGet
(
c
=>
c
.
ToArray
(
)
)
;
private
readonly
SynchronizedList
<
OrderFail
>
_orderCancelFails
=
[
]
;
/// <summary>
/// Order cancellation failures.
/// </summary>
public
IEnumerable
<
OrderFail
>
OrderCancelFails
=>
_orderCancelFails
.
SyncGet
(
c
=>
c
.
ToArray
(
)
)
;
private
readonly
SynchronizedList
<
OrderFail
>
_orderEditFails
=
[
]
;
/// <summary>
/// Order modification failures.
/// </summary>
public
IEnumerable
<
OrderFail
>
OrderEditFails
=>
_orderEditFails
.
SyncGet
(
c
=>
c
.
ToArray
(
)
)
;
private
readonly
ILogReceiver
_logReceiver
=
logReceiver
??
throw
new
ArgumentNullException
(
nameof
(
logReceiver
)
)
;
private
readonly
Func
<
SecurityId
?
,
Security
>
_tryGetSecurity
=
tryGetSecurity
??
throw
new
ArgumentNullException
(
nameof
(
tryGetSecurity
)
)
;
private
readonly
IPositionProvider
_positionProvider
=
positionProvider
??
throw
new
ArgumentNullException
(
nameof
(
positionProvider
)
)
;
/// <summary>
/// Clear all cached data.
/// </summary>
public
void
Clear
(
)
{
_securityData
.
Clear
(
)
;
_allOrdersById
.
Clear
(
)
;
_allOrdersByStringId
.
Clear
(
)
;
_allOrdersByTransactionId
.
Clear
(
)
;
_allOrdersByFailedId
.
Clear
(
)
;
_orders
.
Clear
(
)
;
_newsById
.
Clear
(
)
;
_newsWithoutId
.
Clear
(
)
;
_myTrades
.
Clear
(
)
;
_orderStatusTransactions
.
Clear
(
)
;
_massCancelationTransactions
.
Clear
(
)
;
_orderCancelFails
.
Clear
(
)
;
_orderRegisterFails
.
Clear
(
)
;
_orderEditFails
.
Clear
(
)
;
_securityValues
.
Clear
(
)
;
_orderBookSnapshots
.
Clear
(
)
;
}
/// <summary>
/// Add order status transaction id.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
public
void
AddOrderStatusTransactionId
(
long
transactionId
)
{
if
(
!
_orderStatusTransactions
.
Add
(
transactionId
)
)
throw
new
InvalidOperationException
(
)
;
}
/// <summary>
/// Remove order status transaction id.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
public
void
RemoveOrderStatusTransactionId
(
long
transactionId
)
{
_orderStatusTransactions
.
Remove
(
transactionId
)
;
}
/// <summary>
/// Get orders by security and state.
/// </summary>
/// <param name="security">Security.</param>
/// <param name="state">Order state.</param>
/// <returns>Orders.</returns>
public
IEnumerable
<
Order
>
GetOrders
(
Security
security
,
OrderStates
state
)
{
if
(
security
==
null
)
throw
new
ArgumentNullException
(
nameof
(
security
)
)
;
return
GetData
(
security
)
.
Orders
.
CachedValues
.
Select
(
info
=>
info
.
Order
)
.
Filter
(
state
)
;
}
/// <summary>
/// Try add mass cancelation transaction id.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
public
void
TryAddMassCancelationId
(
long
transactionId
)
{
_massCancelationTransactions
.
TryAdd
(
transactionId
)
;
//if (!_massCancelationTransactions.Add(transactionId))
// throw new InvalidOperationException();
}
/// <summary>
/// Check if transaction is mass cancelation.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
/// <returns><see langword="true"/> if mass cancelation.</returns>
public
bool
IsMassCancelation
(
long
transactionId
)
=>
_massCancelationTransactions
.
Contains
(
transactionId
)
;
/// <summary>
/// Check if transaction is order status request.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
/// <returns><see langword="true"/> if order status request.</returns>
public
bool
IsOrderStatusRequest
(
long
transactionId
)
=>
_orderStatusTransactions
.
Contains
(
transactionId
)
;
/// <summary>
/// Add order by cancelation transaction id.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="transactionId">Transaction id.</param>
public
void
AddOrderByCancelationId
(
Order
order
,
long
transactionId
)
{
AddOrderByTransactionId
(
order
,
transactionId
,
OrderOperations
.
Cancel
)
;
}
/// <summary>
/// Add order by registration transaction id.
/// </summary>
/// <param name="order">Order.</param>
public
void
AddOrderByRegistrationId
(
Order
order
)
{
AddOrder
(
order
)
;
AddOrderByTransactionId
(
order
,
order
.
TransactionId
,
OrderOperations
.
Register
)
;
}
/// <summary>
/// Add order by edition transaction id.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="transactionId">Transaction id.</param>
public
void
AddOrderByEditionId
(
Order
order
,
long
transactionId
)
{
AddOrderByTransactionId
(
order
,
transactionId
,
OrderOperations
.
Edit
)
;
}
/// <summary>
/// Add order fail by transaction id.
/// </summary>
/// <param name="fail">Order fail.</param>
/// <param name="operation">Order operation.</param>
/// <param name="transactionId">Transaction id.</param>
public
void
AddOrderFailById
(
OrderFail
fail
,
OrderOperations
operation
,
long
transactionId
)
{
_allOrdersByFailedId
.
TryAdd2
(
(
transactionId
,
operation
)
,
fail
)
;
}
private
void
AddOrderByTransactionId
(
Order
order
,
long
transactionId
,
OrderOperations
operation
)
{
if
(
order
==
null
)
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
GetData
(
order
.
Security
)
.
Orders
.
Add
(
CreateOrderKey
(
order
.
Type
,
transactionId
,
operation
)
,
new
OrderInfo
(
this
,
order
,
operation
==
OrderOperations
.
Register
)
)
;
_allOrdersByTransactionId
.
Add
(
(
transactionId
,
operation
)
,
order
)
;
}
/// <summary>
/// Try get order by id.
/// </summary>
/// <param name="orderId">Order id.</param>
/// <param name="orderStringId">Order string id.</param>
/// <returns>Order or <see langword="null"/>.</returns>
public
Order
TryGetOrder
(
long
?
orderId
,
string
orderStringId
)
=>
orderId
!=
null
?
_allOrdersById
.
TryGetValue
(
orderId
.
Value
)
:
(
orderStringId
.
IsEmpty
(
)
?
null
:
_allOrdersByStringId
.
TryGetValue
(
orderStringId
)
)
;
/// <summary>
/// Try get order by transaction id and operation.
/// </summary>
/// <param name="transactionId">Transaction id.</param>
/// <param name="operation">Operation.</param>
/// <returns>Order or <see langword="null"/>.</returns>
public
Order
TryGetOrder
(
long
transactionId
,
OrderOperations
operation
)
=>
_allOrdersByTransactionId
.
TryGetValue
(
(
transactionId
,
operation
)
)
;
private
void
UpdateOrderIds
(
Order
order
,
SecurityData
securityData
)
{
// так как биржевые идентифиаторы могут повторяться, то переписываем старые заявки новыми как наиболее актуальными
if
(
order
.
Id
!=
null
)
{
securityData
.
OrdersById
[
order
.
Id
.
Value
]
=
order
;
_allOrdersById
[
order
.
Id
.
Value
]
=
order
;
}
if
(
!
order
.
StringId
.
IsEmpty
(
)
)
{
securityData
.
OrdersByStringId
[
order
.
StringId
]
=
order
;
_allOrdersByStringId
[
order
.
StringId
]
=
order
;
}
}
/// <summary>
/// Try get message adapter for order.
/// </summary>
/// <param name="order">Order.</param>
/// <returns>Adapter or <see langword="null"/>.</returns>
public
IMessageAdapter
TryGetAdapter
(
Order
order
)
{
if
(
order
is
null
)
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
return
_orders
.
TryGetValue
(
order
)
;
}
/// <summary>
/// Try set message adapter for order.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="adapter">Adapter.</param>
public
void
TrySetAdapter
(
Order
order
,
IMessageAdapter
adapter
)
{
if
(
order
is
null
)
throw
new
ArgumentNullException
(
nameof
(
order
)
)
;
if
(
adapter
is
null
or
BasketMessageAdapter
)
return
;
_orders
[
order
]
=
adapter
;
}
/// <summary>
/// Process order message.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="security">Security.</param>
/// <param name="message">Message.</param>
/// <param name="transactionId">Transaction id.</param>
/// <param name="getPortfolio">Function to get portfolio.</param>
/// <returns>Order change info.</returns>
public
IEnumerable
<
OrderChangeInfo
>
ProcessOrderMessage
(
Order
order
,
Security
security
,
ExecutionMessage
message
,
long
transactionId
,
Func
<
string
,
Portfolio
>
getPortfolio
)
{
if
(
security
is
null
)
throw
new
ArgumentNullException
(
nameof
(
security
)
)
;
if
(
message
is
null
)
throw
new
ArgumentNullException
(
nameof
(
message
)
)
;
if
(
getPortfolio
is
null
)
throw
new
ArgumentNullException
(
nameof
(
getPortfolio
)
)
;
if
(
!
message
.
IsOk
(
)
)
throw
new
ArgumentException
(
LocalizedStrings
.
MessageHasStateAndError
.
PutEx
(
message
)
)
;
var
securityData
=
GetData
(
security
)
;
if
(
transactionId
==
0
&&
message
.
OrderId
==
null
&&
message
.
OrderStringId
.
IsEmpty
(
)
)
throw
new
ArgumentException
(
LocalizedStrings
.
NoOrderIds
)
;
if
(
transactionId
==
0
)
{
var
info
=
securityData
.
Orders
.
CachedValues
.
FirstOrDefault
(
i
=>
{
if
(
order
!=
null
)
return
i
.
Order
==
order
;
if
(
message
.
OrderId
!=
null
)
return
i
.
Order
.
Id
==
message
.
OrderId
;
else
return
i
.
Order
.
StringId
.
EqualsIgnoreCase
(
message
.
OrderStringId
)
;
}
)
;
if
(
info
==
null
)
{
yield
return
OrderChangeInfo
.
NotExist
;
//throw new InvalidOperationException(LocalizedStrings.OrderNotFound.Put(orderId.To<string>() ?? orderStringId));
}
else
{
foreach
(
var
i
in
info
.
ApplyChanges
(
message
,
OrderOperations
.
Register
,
o
=>
UpdateOrderIds
(
o
,
securityData
)
)
)
yield
return
i
;
}
}
else
{
var
cancelledInfo
=
securityData
.
TryGetOrder
(
message
.
OrderType
,
transactionId
,
OrderOperations
.
Cancel
)
;
var
registeredInfo
=
securityData
.
TryGetOrder
(
message
.
OrderType
,
transactionId
,
OrderOperations
.
Register
)
;
var
editedInfo
=
securityData
.
TryGetOrder
(
message
.
OrderType
,
transactionId
,
OrderOperations
.
Edit
)
;
// проверяем не отмененная ли заявка пришла
if
(
cancelledInfo
!=
null
)
// && (cancelledOrder.Id == orderId || (!cancelledOrder.StringId.IsEmpty() && cancelledOrder.StringId.EqualsIgnoreCase(orderStringId))))
{
var
cancellationOrder
=
cancelledInfo
.
Order
;
if
(
registeredInfo
==
null
)
{
_logReceiver
.
LogDebug
(
"Сancel '{0}': {1}"
,
cancellationOrder
.
TransactionId
,
message
)
;
foreach
(
var
i
in
cancelledInfo
.
ApplyChanges
(
message
,
OrderOperations
.
Cancel
,
o
=>
UpdateOrderIds
(
o
,
securityData
)
)
)
yield
return
i
;
yield
break
;
}
var
newOrderState
=
message
.
OrderState
;
if
(
(
newOrderState
==
OrderStates
.
Active
||
newOrderState
==
OrderStates
.
Done
)
&&
cancellationOrder
.
State
!=
OrderStates
.
Done
)
{
_logReceiver
.
LogDebug
(
"Replace-cancel '{0}': {1}"
,
cancellationOrder
.
TransactionId
,
message
)
;
cancellationOrder
.
ApplyNewState
(
OrderStates
.
Done
,
_logReceiver
)
;
if
(
message
.
Latency
!=
null
)
cancellationOrder
.
LatencyCancellation
=
message
.
Latency
.
Value
;
yield
return
new
OrderChangeInfo
(
cancellationOrder
,
false
,
true
,
false
)
;
//var isCancelOrderOnly = (message.OrderId != null && message.OrderId == cancellationOrder.Id)
// || (message.OrderStringId != null && message.OrderStringId == cancellationOrder.StringId)
// || (message.OrderBoardId != null && message.OrderBoardId == cancellationOrder.BoardId);
//if (isCancelOrderOnly)
//{
// _logReceiver.AddDebugLog("Replace-reg empty");
// yield break;
//}
}
_logReceiver
.
LogDebug
(
"Replace-reg '{0}': {1}"
,
registeredInfo
.
Order
.
TransactionId
,
message
)
;
foreach
(
var
i
in
registeredInfo
.
ApplyChanges
(
message
,
OrderOperations
.
Register
,
o
=>
UpdateOrderIds
(
o
,
securityData
)
)
)
yield
return
i
;
yield
break
;
}
if
(
editedInfo
!=
null
)
{
_logReceiver
.
LogDebug
(
"Edit '{0}': {1}"
,
editedInfo
.
Order
.
TransactionId
,
message
)
;
if
(
message
.
Latency
!=
null
)
editedInfo
.
Order
.
LatencyEdition
=
message
.
Latency
.
Value
;
foreach
(
var
i
in
editedInfo
.
ApplyChanges
(
message
,
OrderOperations
.
Edit
,
o
=>
UpdateOrderIds
(
o
,
securityData
)
)
)
yield
return
i
;
yield
break
;
}
if
(
registeredInfo
==
null
)
{
// This branch builds an order nobody here has seen before, so the message is its only
// source of truth. Without a side there is no order to build.
if
(
message
.
Side
is
not
Sides
side
)
throw
new
ArgumentException
(
LocalizedStrings
.
OrderSideNotSpecified
,
nameof
(
message
)
)
;
var
o
=
new
Order
{
Security
=
security
,
Type
=
message
.
OrderType
,
TransactionId
=
transactionId
,
Time
=
message
.
ServerTime
,
ServerTime
=
message
.
ServerTime
,
Price
=
message
.
OrderPrice
,
Volume
=
message
.
OrderVolume
??
0
,
Side
=
side
,
Comment
=
message
.
Comment
,
ExpiryDate
=
message
.
ExpiryDate
,
Condition
=
message
.
Condition
,
UserOrderId
=
message
.
UserOrderId
,
StrategyId
=
message
.
StrategyId
,
ClientCode
=
message
.
ClientCode
,
BrokerCode
=
message
.
BrokerCode
,
IsMarketMaker
=
message
.
IsMarketMaker
,
MarginMode
=
message
.
MarginMode
,
Slippage
=
message
.
Slippage
,
IsManual
=
message
.
IsManual
,
MinVolume
=
message
.
MinVolume
,
PositionEffect
=
message
.
PositionEffect
,
PostOnly
=
message
.
PostOnly
,
SeqNum
=
message
.
SeqNum
,
Leverage
=
message
.
Leverage
}
;
if
(
message
.
Balance
!=
null
)
{
if
(
message
.
Balance
.
Value
<
0
)
_logReceiver
.
LogError
(
$
"Order
{
transactionId
}
: balance
{
message
.
Balance
.
Value
}
< 0"
)
;
o
.
Balance
=
message
.
Balance
.
Value
;
}
o
.
Portfolio
=
getPortfolio
(
message
.
PortfolioName
)
;
AddOrder
(
o
)
;
_allOrdersByTransactionId
.
TryAdd2
(
(
transactionId
,
OrderOperations
.
Register
)
,
o
)
;
registeredInfo
=
new
OrderInfo
(
this
,
o
,
true
)
;
securityData
.
Orders
.
Add
(
CreateOrderKey
(
o
.
Type
,
transactionId
,
OrderOperations
.
Register
)
,
registeredInfo
)
;
}
foreach
(
var
i
in
registeredInfo
.
ApplyChanges
(
message
,
OrderOperations
.
Register
,
o
=>
UpdateOrderIds
(
o
,
securityData
)
)
)
yield
return
i
;
}
}
/// <summary>
/// Process order fail message.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="security">Security.</param>
/// <param name="message">Message.</param>
/// <returns>Order fails with operations.</returns>
public
IEnumerable
<
(
OrderFail
,
OrderOperations
)
>
ProcessOrderFailMessage
(
Order
order
,
Security
security
,
ExecutionMessage
message
)
{
if
(
security
==
null
)
throw
new
ArgumentNullException
(
nameof
(
security
)
)
;
if
(
message
==
null
)
throw
new
ArgumentNullException
(
nameof
(
message
)
)
;
var
data
=
GetData
(
security
)
;
var
orders
=
new
List
<
(
Order
order
,
OrderOperations
operation
)
>
(
)
;
if
(
message
.
OriginalTransactionId
==
0
)
throw
new
ArgumentOutOfRangeException
(
nameof
(
message
)
,
message
.
OriginalTransactionId
,
LocalizedStrings
.
TransactionInvalid
)
;
var
orderType
=
message
.
OrderType
;
if
(
order
==
null
)
{
var
cancelledOrder
=
data
.
TryGetOrder
(
orderType
,
message
.
OriginalTransactionId
,
OrderOperations
.
Cancel
)
?
.
Order
;
if
(
cancelledOrder
!=
null
&&
orderType
==
null
)
orderType
=
cancelledOrder
.
Type
;
if
(
cancelledOrder
!=
null
/*&& order.Id == message.OrderId*/
)
orders
.
Add
(
(
cancelledOrder
,
OrderOperations
.
Cancel
)
)
;
var
registeredOrder
=
data
.
TryGetOrder
(
orderType
,
message
.
OriginalTransactionId
,
OrderOperations
.
Register
)
?
.
Order
;
if
(
registeredOrder
!=
null
)
orders
.
Add
(
(
registeredOrder
,
OrderOperations
.
Register
)
)
;
var
editedOrder
=
data
.
TryGetOrder
(
orderType
,
message
.
OriginalTransactionId
,
OrderOperations
.
Edit
)
?
.
Order
;
if
(
editedOrder
!=
null
)
orders
.
Add
(
(
editedOrder
,
OrderOperations
.
Edit
)
)
;
if
(
cancelledOrder
==
null
&&
registeredOrder
==
null
&&
editedOrder
==
null
)
{
if
(
!
message
.
OrderStringId
.
IsEmpty
(
)
)
{
order
=
data
.
OrdersByStringId
.
TryGetValue
(
message
.
OrderStringId
)
;
if
(
order
!=
null
)
{
var
pair
=
data
.
Orders
.
LastOrDefault
(
p
=>
p
.
Value
.
Order
==
order
)
;
if
(
pair
.
Value
!=
null
)
orders
.
Add
(
(
pair
.
Value
.
Order
,
pair
.
Key
.
operation
)
)
;
}
}
}
}
else
{
void
TryAdd
(
OrderOperations
operation
)
{
var
foundOrder
=
data
.
TryGetOrder
(
order
.
Type
,
message
.
OriginalTransactionId
,
operation
)
?
.
Order
;
if
(
foundOrder
!=
null
)
orders
.
Add
(
(
foundOrder
,
operation
)
)
;
}
TryAdd
(
OrderOperations
.
Cancel
)
;
TryAdd
(
OrderOperations
.
Register
)
;
TryAdd
(
OrderOperations
.
Edit
)
;
}
if
(
orders
.
Count
==
0
)
{
var
fails
=
new
List
<
(
OrderFail
,
OrderOperations
)
>
(
)
;
Order
TryAddFail
(
OrderOperations
operation
)
{
using
(
_allOrdersByFailedId
.
EnterScope
(
)
)
{
if
(
_allOrdersByFailedId
.
TryGetAndRemove
(
(
message
.
OriginalTransactionId
,
operation
)
,
out
var
fail
)
)
{
fails
.
Add
(
(
fail
,
operation
)
)
;
return
fail
.
Order
;
}
}
return
null
;
}
TryAddFail
(
OrderOperations
.
Edit
)
;
TryAddFail
(
OrderOperations
.
Cancel
)
;
var
regOrder
=
TryAddFail
(
OrderOperations
.
Register
)
;
if
(
regOrder
!=
null
&&
regOrder
.
State
==
OrderStates
.
None
)
{
regOrder
.
State
=
OrderStates
.
Failed
;
regOrder
.
ServerTime
=
message
.
ServerTime
;
regOrder
.
LocalTime
=
message
.
LocalTime
;
}
return
fails
;
}
return
orders
.
Select
(
t
=>
{
var
o
=
t
.
order
;
var
operation
=
t
.
operation
;
o
.
ServerTime
=
message
.
ServerTime
;
o
.
LocalTime
=
message
.
LocalTime
;
if
(
message
.
OrderStatus
!=
null
)
o
.
Status
=
message
.
OrderStatus
;
//для ошибок снятия не надо менять состояние заявки
if
(
operation
==
OrderOperations
.
Register
)
o
.
ApplyNewState
(
OrderStates
.
Failed
,
_logReceiver
)
;
if
(
message
.
Commission
!=
null
)
o
.
Commission
=
message
.
Commission
;
if
(
!
message
.
CommissionCurrency
.
IsEmpty
(
)
)
o
.
CommissionCurrency
=
message
.
CommissionCurrency
;
var
error
=
message
.
Error
??
new
InvalidOperationException
(
operation
==
OrderOperations
.
Cancel
?
LocalizedStrings
.
ErrorCancelling
:
LocalizedStrings
.
ErrorRegistering
)
;
var
fail
=
new
OrderFail
{
Order
=
o
,
Error
=
error
,
ServerTime
=
message
.
ServerTime
,
LocalTime
=
message
.
LocalTime
,
SeqNum
=
message
.
SeqNum
,
TransactionId
=
message
.
OriginalTransactionId
,
}
;
return
(
fail
,
operation
)
;
}
)
;
}
/// <summary>
/// Process own trade message.
/// </summary>
/// <param name="order">Order.</param>
/// <param name="security">Security.</param>
/// <param name="message">Message.</param>
/// <param name="transactionId">Transaction id.</param>
/// <returns>Trade and is new flag.</returns>
public
(
MyTrade
trade
,
bool
isNew
)
ProcessOwnTradeMessage
(
Order
order
,
Security
security
,
ExecutionMessage
message
,
long
transactionId
)
{
if
(
security
==
null
)
throw
new
ArgumentNullException
(
nameof
(
security
)
)
;
if
(
message
==
null
)
throw
new
ArgumentNullException
(
nameof
(
message
)
)
;
// Validate trade price and volume to avoid downstream division by zero or invalid data
if
(
message
.
TradePrice
==
null
||
message
.
TradePrice
<=
0
)
throw
new
ArgumentException
(
"Trade price must be a positive value."
,
nameof
(
message
)
)
;
if
(
message
.
TradeVolume
==
null
||
message
.
TradeVolume
<=
0
)
throw
new
ArgumentException
(
"Trade volume must be a positive value."
,
nameof
(
message
)
)
;
var
securityData
=
GetData
(
security
)
;
if
(
transactionId
==
0
&&
message
.
OrderId
==
null
&&
message
.
OrderStringId
.
IsEmpty
(
)
)
throw
new
ArgumentOutOfRangeException
(
nameof
(
message
)
,
transactionId
,
LocalizedStrings
.
TransactionInvalid
)
;
var
tradeKey
=
(
transactionId
,
message
.
TradeId
??
0
,
message
.
TradeStringId
??
string
.
Empty
)
;
if
(
securityData
.
MyTrades
.
TryGetValue
(
tradeKey
,
out
var
myTrade
)
)
return
(
myTrade
,
false
)
;
if
(
order
==
null
)
{
if
(
security
==
null
)
throw
new
ArgumentNullException
(
nameof
(
security
)
)
;
var
orderId
=
message
.
OrderId
;
var
orderStringId
=
message
.
OrderStringId
;
if
(
transactionId
==
0
&&
orderId
==
null
&&
orderStringId
.
IsEmpty
(
)
)
throw
new
ArgumentException
(
LocalizedStrings
.
NoOrderIds
)
;
var
data
=
GetData
(
security
)
;
if
(
transactionId
!=
0
)
order
=
data
.
TryGetOrder
(
OrderTypes
.
Limit
,
transactionId
,
OrderOperations
.
Register
)
?
.
Order
;
if
(
order
==
null
)
{
if
(
orderId
!=
null
)
order
=
data
.
OrdersById
.
TryGetValue
(
orderId
.
Value
)
;
if
(
order
==
null
&&
!
orderStringId
.
IsEmpty
(
)
)
order
=
data
.
OrdersByStringId
.
TryGetValue
(
orderStringId
)
;
if
(
order
==
null
)
return
default
;
}
}
var
isNew
=
false
;
myTrade
=
securityData
.
MyTrades
.
SafeAdd
(
tradeKey
,
key
=>
{
isNew
=
true
;
var
trade
=
(
ITickTradeMessage
)
message
.
TypedClone
(
)
;
if
(
message
.
SeqNum
!=
default
)
trade
.
SeqNum
=
message
.
SeqNum
;
var
t
=
new
MyTrade
{
Order
=
order
,
Trade
=
trade
}
;
if
(
message
.
Commission
!=
null
)
t
.
Commission
=
message
.
Commission
;
if
(
!
message
.
CommissionCurrency
.
IsEmpty
(
)
)
t
.
CommissionCurrency
=
message
.
CommissionCurrency
;
if
(
message
.
Slippage
!=
null
)
t
.
Slippage
=
message
.
Slippage
;
if
(
message
.
PnL
!=
null
)
t
.
PnL
=
message
.
PnL
;
if
(
message
.
Position
!=
null
)
t
.
Position
=
message
.
Position
;
if
(
message
.
Initiator
!=
null
)
t
.
Initiator
=
message
.
Initiator
;
if
(
message
.
Yield
!=
null
)
t
.
Yield
=
message
.
Yield
;
_myTrades
.
Add
(
t
)
;
if
(
order
.
AveragePrice
is
null
)
{
var
weightedPrice
=
trade
.
Price
*
trade
.
Volume
;
if
(
_ordersAvgPrices
.
TryGetValue
(
order
,
out
var
t1
)
)
{
t1
.
totalVolume
+=
trade
.
Volume
;
t1
.
weightedPriceSum
+=
weightedPrice
;
_ordersAvgPrices
[
order
]
=
t1
;
}
else
{
_ordersAvgPrices
.
Add
(
order
,
t1
=
new
(
trade
.
Volume
,
weightedPrice
)
)
;
}
order
.
AveragePrice
=
t1
.
weightedPriceSum
/
t1
.
totalVolume
;
}
return
t
;
}
)
;
return
(
myTrade
,
isNew
)
;
}
/// <summary>
/// Process news message.
/// </summary>
/// <param name="security">Security.</param>
/// <param name="message">Message.</param>
/// <returns>News and is new flag.</returns>
public
(
News
news
,
bool
isNew
)
ProcessNewsMessage
(
Security
security
,
NewsMessage
message
)
{
if
(
message
==
null
)
throw
new
ArgumentNullException
(
nameof
(
message
)
)
;
var
isNew
=
false
;
View remainder of file in raw view
Back
|
FazBrowse Home
|
New Git URL