-
Notifications
You must be signed in to change notification settings - Fork 0
/
CQGDataCollectorManager.cs
1399 lines (1097 loc) · 49.3 KB
/
CQGDataCollectorManager.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
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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Windows.Forms.VisualStyles;
using CQG;
using DataNetClient.Core;
using DataNetClient.Forms;
using DataNetClient.Properties;
using DevComponents.DotNetBar.Schedule;
using Timer = System.Windows.Forms.Timer;
using DADataManager.Models;
using DADataManager;
namespace DataNetClient.CQGDataCollector
{
static class CQGDataCollectorManager
{
#region VARS
private static readonly CQGCEL Cel;
private static List<GroupItemModel> _groups;
private static bool _modeIsAuto;
private static int _groupCurrent;
private static bool _startedManualCollecting;
private static eHistoricalPeriod _aHistoricalPeriod;
private static string _userName;
private static int _rangeStart;
private static int _rangeEnd = -3000;
private static DateTime _rangeDateStart;
private static DateTime _rangeDateEnd;
private static int _sessionFilter = 31;
public static string _historicalPeriod;
private static string _continuationType;
private static bool _isStoped;
private static bool _isFromList;
private static List<string> _symbols = new List<string>();
private static List<string> _symbolsCollected = new List<string>();
private static List<MonthCharYearModel> monthCharYearlList = new List<MonthCharYearModel>();
private static Timer _timerScheduler = new Timer { Interval = 3000 };
private static System.Timers.Timer _timerTimeout = new System.Timers.Timer { Interval = Settings.Default.MaxTimeOutMinutes * 60 * 1000, Enabled = false };// 5 minutes
private static bool _isStarted;
private static object _lockHistInsert = new object();
private static bool _reportIsJustSent = false;
private static string _reportSubject = "[DN] Collecting finished";
private static string _reportText;
private static int _reportSuccessfulSymbolCount = 0;
private static int _reportAllSymbolCount = 0;
private static DateTime _reportStartTime;
#endregion
#region EVENTS
public delegate void SendReportHandler(string subject, string text);
public static event SendReportHandler SendReport;
private static void OnSendReport(string subject, string text)
{
SendReportHandler handler = SendReport;
if (handler != null) handler(subject, text);
}
public delegate void ProgressBarChangedHandler(int i);
public static event ProgressBarChangedHandler ProgressBarChanged;
private static void OnProgressBarChanged(int i)
{
ProgressBarChangedHandler handler = ProgressBarChanged;
if (handler != null) handler(i);
}
public delegate void ItemStateChangedHandler(int index, GroupState state);
public static event ItemStateChangedHandler ItemStateChanged;
private static void OnItemStateChanged(int index, GroupState state)
{
ItemStateChangedHandler handler = ItemStateChanged;
if (handler != null) handler(index, state);
}
public delegate void RunnedStateChangedHandler(bool state);
public static event RunnedStateChangedHandler RunnedStateChanged;
private static void OnRunnedStateChanged(bool state)
{
RunnedStateChangedHandler handler = RunnedStateChanged;
if (handler != null) handler(state);
}
public delegate void CollectedSymbolCountChangedHandler(int index, string symbol, int count, int totalCount, bool isCorrect, int realyInsertedRowsCount, string comments);
public static event CollectedSymbolCountChangedHandler CollectedSymbolCountChanged;
private static void OnCollectedSymbolCountChanged(int index, string symbol, int count, int totalCount, bool isCorrect, int realyInsertedRowsCount, string comments)
{
CollectedSymbolCountChangedHandler handler = CollectedSymbolCountChanged;
if (handler != null) handler(index, symbol, count, totalCount, isCorrect, realyInsertedRowsCount, comments);
}
public delegate void StartTimeChangedHandler(int index, DateTime dateTime);
public static event StartTimeChangedHandler StartTimeChanged;
private static void OnStartTimeChanged(int index, DateTime dateTime)
{
StartTimeChangedHandler handler = StartTimeChanged;
if (handler != null) handler(index, dateTime);
}
public delegate void CQGStatusChangedHandler(bool isConnected);
public static event CQGStatusChangedHandler CQGStatusChanged;
private static void OnCQGStatusChanged(bool isConnected)
{
CQGStatusChangedHandler handler = CQGStatusChanged;
if (handler != null) handler(isConnected);
}
public delegate void UnsuccessfulSymbolHandler(List<string> symbols);
public static event UnsuccessfulSymbolHandler UnsuccessfulSymbol;
private static void OnUnsuccessfulSymbol(List<string> symbols)
{
UnsuccessfulSymbolHandler handler = UnsuccessfulSymbol;
if (handler != null) handler(symbols);
}
public delegate void TickInsertingStartedHandler(string symbols, int count);
public static event TickInsertingStartedHandler TickInsertingStarted;
private static void OnTickInsertingStarted(string symbols, int count)
{
TickInsertingStartedHandler handler = TickInsertingStarted;
if (handler != null) handler(symbols, count);
}
#endregion
#region INIT
static CQGDataCollectorManager()
{
try
{
Cel = new CQGCEL();
Cel.APIConfiguration.TimeZoneCode = eTimeZone.tzGMT;
Cel.APIConfiguration.ReadyStatusCheck = eReadyStatusCheck.rscOff;
Cel.APIConfiguration.CollectionsThrowException = false;
Cel.APIConfiguration.LogSeverity = eLogSeverity.lsDebug;
Cel.APIConfiguration.MessageProcessingTimeout = 30000;
Cel.DataConnectionStatusChanged += _cel_DataConnectionStatusChanged;
_cel_DataConnectionStatusChanged(eConnectionStatus.csConnectionDown);
Cel.InstrumentSubscribed += _cel_InstrumentSubscribed;
Cel.DataError += _cel_DataError;
Cel.IncorrectSymbol += _cel_IncorrectSymbol;
Cel.TimedBarsResolved += _cel_TimedBarsResolved;
Cel.TicksResolved += _cel_TicksResolved;
Cel.HistoricalSessionsResolved += _cel_HistoricalSessionsResolved;
Cel.Startup();
_timerScheduler.Tick += _timerScheduler_Tick;
//_timerTimeout.Tick += _timerTimeout_Tick;
_timerTimeout.Elapsed += _timerTimeout_Elapsed;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
public static void Init(string userName)
{
_userName = userName;
}
#endregion
#region CEL Events Handlers
static void _cel_InstrumentSubscribed(string symbol, CQGInstrument cqgInstrument)
{
//Check expired date
DateTime d = cqgInstrument.ExpirationDate;
Console.WriteLine("Symbol: '" + symbol + "' will be expired:" + d.ToShortDateString());
if ((d - DateTime.Now).TotalHours < (Settings.Default.DaysToExpiration * 24))
{
if (!Settings.Default.EmailedSymbols.Contains(symbol))
{
OnSendReport("Symbol: '" + symbol + "' will expired soon", "Hello. \n The symbol: '" + symbol + "' will be expired on less then " + Settings.Default.DaysToExpiration + " days. \nExpiration date: " + d.ToShortDateString() + "\n\nGood luck");
Settings.Default.EmailedSymbols += symbol;
}
}
//Month
MonthCharYearModel variable = new MonthCharYearModel();
variable.MonthChar = "def";
variable.Year = "def";
foreach (var monthCharYearModel in monthCharYearlList)
{
if (monthCharYearModel.Symbol == symbol)
return;
}
CQGInstrumentProperties props = cqgInstrument.Properties;
var properties = props[eInstrumentProperty.ipMonthChar];
if (props != null && Cel.IsValid(properties.Value))
variable.MonthChar = properties.Value.ToString();
properties = props[eInstrumentProperty.ipYear];
if (props != null && Cel.IsValid(properties.Value))
variable.Year = properties.Value.ToString();
variable.Symbol = symbol;
monthCharYearlList.Add(variable);
Cel.RemoveInstrument(cqgInstrument);
}
static void _cel_HistoricalSessionsResolved(CQGSessionsCollection cqgHistoricalSessions, CQGHistoricalSessionsRequest cqgHistoricalSessionsRequest, CQGError cqgError)
{
}
static void _cel_IncorrectSymbol(string symbol)
{
FinishCollectingSymbol("",symbol, false, 0, "Incorrect symbol");
}
static void _cel_TicksResolved(CQGTicks cqgTicks, CQGError cqgError)
{
ChangeTimeoutState(false, false);
if (_isStoped) return;
var symbol = cqgTicks.Request.Symbol;
StoreTickData(cqgTicks, cqgError, _userName);
}
static void _cel_TimedBarsResolved(CQGTimedBars cqgTimedBars, CQGError cqgError)
{
ChangeTimeoutState(false, false);
if (!IsStarted) return;
if (_isStoped) return;
var symbol = cqgTimedBars.Request.Symbol;
StoreBarData(cqgTimedBars, cqgError, _userName);
}
static void _cel_DataError(object cqgError, string errorDescription)
{
Console.WriteLine(errorDescription);
}
static void _cel_DataConnectionStatusChanged(eConnectionStatus newStatus)
{
OnCQGStatusChanged(newStatus == eConnectionStatus.csConnectionUp);
}
#endregion
#region Collecting Requests
public static void BarRequest(string symbolName)
{
try
{
if (!Cel.IsStarted)
{
FinishCollectingSymbol("B",symbolName, false, 0, "CQG not started");
return;
}
Cel.NewInstrument(symbolName);
var tableName = ClientDatabaseManager.GetBarTableFromSymbol(symbolName, GetTableType(_historicalPeriod));
_aHistoricalPeriod = eHistoricalPeriod.hpUndefined;
if (ClientDatabaseManager.BarTableExist(tableName))
{
if (!ClientDatabaseManager.MonthCharYearExist(tableName))
ClientDatabaseManager.AddMonthCharYearColumnsToBarTable(tableName);
if (ClientDatabaseManager.YearCharExist(tableName))
ClientDatabaseManager.DeleteWrongColumnsFromTable(tableName);
if(Settings.Default.MakeBigger)
ClientDatabaseManager.MakeBarTableBigger(symbolName, GetTableType(_historicalPeriod));
}
else
{
ClientDatabaseManager.CreateBarsTable(symbolName, GetTableType(_historicalPeriod));
}
//DatabaseManager.CreateBarsTable(symbolName, GetTableType(_historicalPeriod));
CQGTimedBarsRequest request = Cel.CreateTimedBarsRequest();
request.RangeStart = _rangeStart;
request.RangeEnd = _rangeEnd;
request.SessionsFilter = _sessionFilter;
request.Symbol = symbolName;
request.Continuation = ConvertToTsts(_continuationType);
var d = GetHistPeriod(_historicalPeriod);
if (d != eHistoricalPeriod.hpUndefined)
{
request.HistoricalPeriod = d;
}
else
{
request.IntradayPeriod = GetIntradayPeriod(_historicalPeriod);
}
var bars = Cel.RequestTimedBars(request);
var curTimedBars = Cel.AllTimedBars.ItemById[bars.Id];
if (curTimedBars.Status == eRequestStatus.rsInProgress)
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
private static eHistoricalPeriod GetHistPeriod(string historicalPeriod)
{
if (historicalPeriod == "Daily")
return eHistoricalPeriod.hpDaily;
if (historicalPeriod == "Weekly")
return eHistoricalPeriod.hpWeekly;
if (historicalPeriod == "Monthly")
return eHistoricalPeriod.hpMonthly;
if (historicalPeriod == "Quarterly")
return eHistoricalPeriod.hpQuarterly;
if (historicalPeriod == "Semiannual")
return eHistoricalPeriod.hpSemiannual;
if (historicalPeriod == "Yearly")
return eHistoricalPeriod.hpYearly;
return eHistoricalPeriod.hpUndefined;
}
private static void TickRequest(string symbolName)
{
try
{
if (!Cel.IsStarted)
{
FinishCollectingSymbol("T",symbolName, false, 0, "CQG not started");
return;
}
if (_rangeDateStart < DateTime.Now.AddDays(-Settings.Default.MaxTickDays))
_rangeDateStart = DateTime.Now.AddDays(-Settings.Default.MaxTickDays);
if (DateTime.Today.DayOfWeek == DayOfWeek.Monday)
_rangeDateStart = _rangeDateStart.AddDays(-2);
_historicalPeriod = "tick";
var tickRequest = Cel.CreateTicksRequest();
//LineTime = CEL.Environment.LineTime;
tickRequest.RangeStart = _rangeDateStart;
tickRequest.RangeEnd = _rangeDateEnd;
tickRequest.Type = eTicksRequestType.trtSinceTimeNotify;
tickRequest.Symbol = symbolName;
tickRequest.SessionsFilter = _sessionFilter;
CQGTicks ticks = Cel.RequestTicks(tickRequest);
if (ticks.Status == eRequestStatus.rsInProgress)
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
#endregion
#region SORING COLLECTED DATA
public static void StoreBarData(CQGTimedBars mCurTimedBars, CQGError cqgError, string userName)
{
//try
//{g
if (cqgError != null && cqgError.Code != 0)
{
FinishCollectingSymbol("B",mCurTimedBars.Request.Symbol, false, 0, "Expired! Error code: " + cqgError.Code + ". Description:" + cqgError.Description);
}
else
{
var str5 = mCurTimedBars.Request.Symbol.Trim();
var str = str5.Split('.');
str5 = str[str.Length - 1];
var tableName = "B_" + str5 + "_" + GetTableType(_historicalPeriod);
var realyInsertedRows = 0;
if (mCurTimedBars.Status == eRequestStatus.rsSuccess)
{
ClientDatabaseManager.DeleteLastBar("B_" + str5 + "_" + GetTableType(_historicalPeriod));
var lastExisting3000BarData = ClientDatabaseManager.GetLast3000BarData(tableName);
if (mCurTimedBars.Count != 0)
{
for (int i = mCurTimedBars.Count - 1; i >= 0; i--)
{
if (!lastExisting3000BarData.Contains(mCurTimedBars[i].Timestamp))
{
AddBar(mCurTimedBars[i], mCurTimedBars.Request.Symbol, DateTime.Now, GetTableType(_historicalPeriod), userName);
realyInsertedRows++;
}
}
}
ClientDatabaseManager.CommitQueueBar();
}
//var rowsCount = mCurTimedBars.Count;//DatabaseManager.GetRowsCount("B_" + str5 + "_" + GetTableType(_historicalPeriod)) - beforeRowsCount
FinishCollectingSymbol("B",mCurTimedBars.Request.Symbol, true, realyInsertedRows, "");
}
//}
//catch (Exception ex)
//{
// Console.WriteLine("BarsAdd."+ex.Message);
//}
}
private static void AddBar(CQGTimedBar timedBar, string symbol, DateTime runDateTime, string tType, string userName)
{
try
{
string MonthChar = "";
string Year = "";
foreach (var monthCharYearModel in monthCharYearlList)
{
if (symbol == monthCharYearModel.Symbol)
{
MonthChar = monthCharYearModel.MonthChar;
Year = monthCharYearModel.Year;
}
}
var str5 = symbol.Trim();
var str = str5.Split('.');
str5 = str[str.Length - 1];
if (GetValueAsString(timedBar.Open) == "N/A")
{
}
else
{
GetValueAsString(timedBar.Open);
}
GetValueAsString(timedBar.Timestamp);
var str3 = "'" + symbol + "'," +
GetValueAsString(Math.Max(timedBar.Open, 0)) + "," +
GetValueAsString(Math.Max(timedBar.High, 0)) + "," +
GetValueAsString(Math.Max(timedBar.Low, 0)) + "," +
GetValueAsString(Math.Max(timedBar.Close, 0)) + "," +
GetValueAsString(Math.Max(timedBar.TickVolume, 0)) + "," +
GetValueAsString(Math.Max(timedBar.ActualVolume, 0)) + "," +
GetValueAsString(Math.Max(timedBar.AskVolume, 0)) + "," +
GetValueAsString(Math.Max(timedBar.BidVolume, 0)) + "," +
GetValueAsString(Math.Max(timedBar.OpenInterest, 0)) + "," +
GetValueAsString(timedBar.Timestamp) + "," +
GetValueAsString(runDateTime) + ",'" +
_continuationType + "','" +
userName + "','" +
MonthChar + "','" +
Year + "'";
var sql = "INSERT IGNORE INTO B_" + str5 + "_" + tType + " (Symbol, OpenValue, HighValue, LowValue, CloseValue," +
" TickVol, ActualVol, AskVol, BidVol, OpenInterest," +
"BarTime, SystemTime, ContinuationType, UserName, MonthChar, Year) VALUES (" + str3 + ");";
ClientDatabaseManager.AddToQueue(sql, 5);
}
catch (Exception ex)
{
Console.WriteLine("AddBar." + ex.Message);
}
}
//**
public static void StoreTickData(CQGTicks cqgTicks, CQGError cqgError, string userName)
{
//try
//{
if ((cqgError != null && cqgError.Code != 0))
{
FinishCollectingSymbol("T",cqgTicks.Request.Symbol, false, 0, "Expired! Error code: " + cqgError.Code + ". Description:" + cqgError.Description);
return;
}
if (cqgTicks.Count == 0)
{
FinishCollectingSymbol("T",cqgTicks.Request.Symbol, false, 0, "No data recived");
return;
}
new Thread(() =>
{
lock (_lockHistInsert)
{
int groupId = 0;
OnTickInsertingStarted(cqgTicks.Request.Symbol, cqgTicks.Count);
DateTime _tmpTime = new DateTime();
int first_start = 0;
int first_end = _rangeDateEnd == _tmpTime ? cqgTicks.Count - 1 : CqgGetId(cqgTicks, _rangeDateEnd);
///****************************************//
//inserting
OnProgressBarChanged(0);
var progr = 0;
var rowsMaxCount = (first_end - first_start);
var rowsInserted = 0;
var cto = (double)rowsMaxCount;
var realyInsertedCount = 0;
for (int i = first_start; i <= first_end; i++)
{
if (_isStoped) break;
ClientDatabaseManager.CreateTickTable(cqgTicks.Request.Symbol, cqgTicks[i].Timestamp);
if (!ClientDatabaseManager.IsThisHourExistsInTable(cqgTicks.Request.Symbol, cqgTicks[i].Timestamp))
{
AddTick(cqgTicks[i], cqgTicks.Request.Symbol, DateTime.Now, ++groupId, userName);
realyInsertedCount++;
}
rowsInserted++;
var newProgr = (int)Math.Round((rowsInserted / cto) * 100f);
if (newProgr > progr)
{
progr = newProgr;
OnProgressBarChanged(progr);
}
}
ClientDatabaseManager.CommitQueueTick();
if (!_isStoped) FinishCollectingSymbol("T",cqgTicks.Request.Symbol, true, realyInsertedCount, "");
OnProgressBarChanged(100);
}
}) { Name = "InsertingHistoricalThread" }.Start();
//}
//catch (Exception ex)
//{
// Console.WriteLine("TicksAdd"+ex.Message);
//}
}
private static void AddTick(CQGTick tick, string symbol, DateTime runDateTime, int groupId, string userName)
{
try
{
var str = symbol.Trim().Split('.');
var query = "INSERT IGNORE INTO T_" + str[str.Length - 1] + "_" + GetIso8601WeekOfYear(tick.Timestamp);
query += "(Symbol, Price, Volume, TickTime, SystemTime, ContinuationType, PriceType, GroupId, UserName) VALUES";
query += "('";
query += symbol + "',";
query += GetValueAsString(tick.Price) + ",";
query += GetValueAsString(tick.Volume) + ",";
query += GetValueAsString(tick.Timestamp) + ",";
query += GetValueAsString(runDateTime) + ",";
query += "'" + _continuationType + "',";
query += "'" + tick.PriceType.ToString() + "',";
query += GetValueAsString(groupId) + ",";
query += "'" + userName + "');";
ClientDatabaseManager.AddToQueue(query, 2);
}
catch (Exception ex)
{
Console.WriteLine("Exception.AddTick." + ex.Message);
}
}
//**
private static string GetValueAsString(object val)
{
try
{
if ((val is Double) || (val is float))
{
var v = (Double)val;
if (v == 0.0)
return "0.0";
return v.ToString("G", CultureInfo.InvariantCulture);
}
if (val is int)
{
return Convert.ToString(val);
}
if (val is DateTime)
return "'" + Convert.ToDateTime(val).ToString("yyyy/MM/dd HH:mm:ss") + "'";
return "NULL";
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "0";
}
}
public static int CqgGetId(CQGTicks ticks, DateTime date)
{
int l = 0; // нижняя граница
int u = ticks.Count - 1; // верхняя граница
int m = -1;
while (l <= u)
{
m = (l + u) / 2;
if (ticks[m].Timestamp == date)//todo test serch
{
////Console.WriteLine((ticks[m].Timestamp));
//if (ticks[m].Timestamp > date)
//{
// l = 0;
// u = m;
// while (l <= u)
// {
// m = (l + u) / 2;
// if (ticks[m].Timestamp.Hour==date.Hour)
// return m;
// //Console.WriteLine(ticks[m].Timestamp);
// if (ticks[m].Timestamp.Hour < date.Hour) l = m + 1;
// if (ticks[m].Timestamp.Hour > date.Hour) u = m - 1;
// }
//}
//if (ticks[m].Timestamp < date)
//{
// l = m;
// u = ticks.Count-1;
// while (l <= u)
// {
// int tmp = m;
// m = (l + u) / 2;
// if (ticks[m].Timestamp.Hour==date.Hour)
// return m;
// if (ticks[m].Timestamp.Day > date.Day)
// return tmp;
// //Console.WriteLine(ticks[m].Timestamp);
// if (ticks[m].Timestamp.Hour < date.Hour) l = m + 1;
// if (ticks[m].Timestamp.Hour > date.Hour) u = m - 1;
// }
//}
//if (l >= u) return m;
return m;
}
if (ticks[m].Timestamp < date) l = m + 1;
if (ticks[m].Timestamp > date) u = m - 1;
}
return m;
}
public static int GetIso8601WeekOfYear(DateTime time)
{
// Seriously cheat. If its Monday, Tuesday or Wednesday, then it'll
// be the same week# as whatever Thursday, Friday or Saturday are,
// and we always get those right
DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time);
if (day == DayOfWeek.Sunday)
time = time.AddDays(1);
if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday)
{
time = time.AddDays(3);
}
// Return the week of our adjusted day
return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
}
#endregion
#region GROUP LIST public
public static void LoadGroups(List<GroupItemModel> groups)
{
_groups = groups.ToList();
foreach (var groupItem in _groups)
{
groupItem.CollectedSymbols.Clear();
}
// RecalcStartTime();
}
public static bool Start()
{
if (IsStarted) return false;
_isFromList = false;
IsStarted = true;
foreach (var groupItem in _groups)
{
groupItem.CollectedSymbols.Clear();
}
new Thread(() =>
{
_reportIsJustSent = false;
_reportText = "";
_reportAllSymbolCount = 0;
_reportSuccessfulSymbolCount = 0;
_isStoped = false;
StartFirst();
}).Start();
return true;
}
public static bool StartFromList(bool isTick, List<string> symbols, DateTime rangeDateStart, DateTime rangeDateEnd, int sessionFilter, string historicalPeriod, string continuationType, int rangeStart, int rangeEnd, string userName)
{
if (IsStarted) return false;
IsStarted = true;
_userName = userName;
_rangeStart = rangeStart;
_rangeEnd = rangeEnd;
_sessionFilter = sessionFilter;
_historicalPeriod = historicalPeriod;
_continuationType = continuationType;
_rangeDateStart = rangeDateStart;
_rangeDateEnd = rangeDateEnd;
new Thread(() =>
{
_isStoped = false;
_isFromList = true;
_symbols = symbols;
_symbolsCollected.Clear();
foreach (var symbol in symbols)
{
Cel.NewInstrument(symbol);
}
foreach (var symbol in _symbols)
{
if (isTick)
TickRequest(symbol);
else
BarRequest(symbol);
}
}).Start();
return true;
}
public static void Stop()
{
if (!IsStarted) return;
IsStarted = false;
_isStoped = true;
if (_isFromList)
{
_symbols.Clear();
_symbolsCollected.Clear();
}
else
FinishCollectingGroup(_groupCurrent);
}
public static void ChangeState(int index, GroupState groupState)
{
_groups[index].GroupState = groupState;
}
#endregion
#region GROUP LIST private
private static bool ThereAreHaveInProgress()
{
int a = 5;
for (int i = 0; i < 10; i++)
{
a++;
}
a++;
return _groups.Any(groupItem => groupItem.GroupState == GroupState.InProgress) || _symbols.Count != _symbolsCollected.Count;
}
private static void StartFirst()
{
if (_isStoped) return;
// searching first InQueue
for (int index = _groups.Count - 1; index >= 0; index--)
{
var groupItem = _groups[index];
if (groupItem.GroupState == GroupState.InQueue)
{
_historicalPeriod = groupItem.GroupModel.TimeFrame;
_continuationType = groupItem.GroupModel.CntType;
// var symbols = listBox_daily_symbols.SelectedItems.Cast<string>().ToList();
Daily_NotChanchedValuesManager.UpdateDailyValues(groupItem.AllSymbols);
_groupCurrent = index;
StartCollectingGroup(index);
return;
}
}
//todo OnSendReport();
if (!_reportIsJustSent)
{
OnSendReport(_reportSubject + " (" + _reportSuccessfulSymbolCount + "/" + _reportAllSymbolCount + ")",
"Hello." + System.Environment.NewLine + "Collecting finished!" +
System.Environment.NewLine + System.Environment.NewLine + _reportText);
_reportIsJustSent = true;
}
IsStarted = false;
//
}
private static void StartCollectingGroup(int index)
{
var group = _groups[index];
_reportStartTime = DateTime.Now;
_reportText += "Group: '" + group.GroupModel.GroupName + "' [" + group.GroupModel.TimeFrame + "]" + System.Environment.NewLine;
StartProgress(index);
OnCollectedSymbolCountChanged(_groupCurrent, "", 0, _groups[index].AllSymbols.Count, true, 0, "");
if (group.AllSymbols.Count == 0)
{
FinishCollectingGroup(index);
}
else
{
ChangeTimeoutState(true, group.GroupModel.CntType.Contains("tsctStandard"));
}
if (group.AllSymbols.Count != 0)
{
if (group.GroupModel.TimeFrame != "tick")
BarRequest(group.AllSymbols.First());
else
TickRequest(group.AllSymbols.First());
}
}
private static void FinishCollectingGroup(int index)
{
FinishProgress(index);
if (_isStoped) return;
_reportText += "Group: '" + _groups[index].GroupModel.GroupName + "' [" + _groups[index].GroupModel.TimeFrame + "]" + System.Environment.NewLine + System.Environment.NewLine;
ChangeTimeoutState(false, false);
if (_isStoped) return;
StartFirst();
}
private static void StartProgress(int index)
{
_groups[index].GroupState = GroupState.InProgress;
OnItemStateChanged(index, GroupState.InProgress);
}
private static void FinishCollectingSymbol(string type,string symbol, bool isCorrect, int realyInsertedRowsCount, string comments)
{
string tableName;
string mintime="";
string maxtime="";
if (type == "B")
{
tableName = ClientDatabaseManager.GetBarTableFromSymbol(symbol, GetTableType(_historicalPeriod));
mintime = ClientDatabaseManager.GetMinTimeBar(tableName).ToString();
maxtime = ClientDatabaseManager.GetMaxTimeBar(tableName).ToString();
}
else if (type == "T")
{
string minname = ClientDatabaseManager.GetTickTableFromSymbolMin(symbol);
mintime = minname != "" ? ClientDatabaseManager.GetMinTime(minname).ToString() : "";
string maxname = ClientDatabaseManager.GetTickTableFromSymbolMax(symbol);
maxtime = maxname != "" ? ClientDatabaseManager.GetMaxTime(maxname).ToString() : "";
}
if (_isFromList)
{
_symbolsCollected.Add(symbol);
var totalCount = _symbols.Count;
var cCount = _symbolsCollected.Count;
OnCollectedSymbolCountChanged(-1, symbol, cCount, totalCount, isCorrect, realyInsertedRowsCount, comments);
FormMainDN.ChangeSymbolInformation(-1, symbol, isCorrect, realyInsertedRowsCount, comments, (DateTime.Now - _reportStartTime).Hours + "h:" + (DateTime.Now - _reportStartTime).Minutes + "m:" + (DateTime.Now - _reportStartTime).Seconds + "s", mintime, maxtime);
if (realyInsertedRowsCount >= FormMainDN.maxrows)
FormMainDN.maxrows = realyInsertedRowsCount;
if (realyInsertedRowsCount <= FormMainDN.minrows)
FormMainDN.minrows = realyInsertedRowsCount;
if (_symbols.Count == _symbolsCollected.Count)
{
FinishCollectingAllSymbols();
}
return;
}
_groups[_groupCurrent].CollectedSymbols.Add(symbol);
var tCount = _groups[_groupCurrent].AllSymbols.Count;
var count = _groups[_groupCurrent].CollectedSymbols.Count;
//todo
//mintime = ClientDatabaseManager.GetMinTime(tableNameTick);
//maxtime = ClientDatabaseManager.GetMaxTime(tableNameTick);
OnCollectedSymbolCountChanged(_groupCurrent, symbol, count, tCount, isCorrect, realyInsertedRowsCount, comments);
FormMainDN.ChangeSymbolInformation(_groupCurrent,symbol, isCorrect, realyInsertedRowsCount, comments, (DateTime.Now - _reportStartTime).Hours + "h:" + (DateTime.Now - _reportStartTime).Minutes + "m:" + (DateTime.Now - _reportStartTime).Seconds+"s",mintime,maxtime);
if (realyInsertedRowsCount >= FormMainDN.maxrows)
FormMainDN.maxrows = realyInsertedRowsCount;
if (realyInsertedRowsCount <= FormMainDN.minrows)