-
Notifications
You must be signed in to change notification settings - Fork 0
/
PolygonWPFDemoWindow.xaml.cs
1255 lines (1041 loc) · 34.2 KB
/
PolygonWPFDemoWindow.xaml.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.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Newtonsoft.Json;
using PolygonApi;
using PolygonApi.Clusters;
using PolygonApi.Data;
using System.Reflection;
using PolygonWPFDemo.Controls;
using WebSocket4Net.Command;
using PolygonWPFDemo.Helpers;
using System.Diagnostics;
namespace PolygonWPFDemo
{
public delegate void OnRTDataRowMouseDoubleClickDel( string ClusterName, string Symbol );
public partial class PolygonWPFDemoWindow : Window
{
#region Variables
string InitialMessage =
"\n *** =>>> HOW TO USE YOUR Polygon.io API KEY ***" + "\n\n" +
@" 1. You can enter your ApiKey in the json\PGDemoConfig.json file" + "\n" +
"\te.g." + @" ""appValues"": { ""ApiKey"": ""mypolygonioapikey"" }" + "\n\n" +
" 2. You can use the UI to enter/paste your ApiKey" + "\n" +
"\tClick on the 'ApiKey label' or key image (upper right)," + "\n" +
"\tPaste or enter the key, then hit Enter to start the app." + "\n\n" +
" 3. From your custom app: call PGonApi.SetApiKey( ApiKey ); to set the ApiKey." + "\n\n" +
" 4. You can also hard-code your ApiKey\n" +
"\t(e.g.) ApiKey = " + @"""mypolygonioapikey"";" + "\n" +
"\tHard-coding your ApiKey will auto-start this app using the hard-coded ApiKey.\n\n" +
"See the " + @"Docs\PolygonWPFDemo.docx file for more information." + "\n";
private string ApiKey = "";
bool InitialMessageDisplayed;
AppValues appValues;
// Note: values are read from json\PGDemoConfig.json
bool VerboseInfo;
bool CloseWindowOnEscape;
// Simulation -> for use when the market is closed
// ( Equities only, but modify test file as needed )
string PGonJSONTextTestFile = @"Testing\PGonJSONTextTest.txt";
bool SimulationModeStarted;
int LineNum = 0;
List<string> JSONTextLines = new List<string>();
TimerHelper SimulationTimer;
double RTDataGridHeight;
#endregion
#region Properties
public PGonApi PGApi
{
get { return _PGApi = _PGApi ?? new PGonApi(); }
set { _PGApi = value; }
}
PGonApi _PGApi = null;
public ConfigHelper configHelper
{
get { return _ConfigHelper = _ConfigHelper ?? new ConfigHelper(); }
set { _ConfigHelper = value; }
}
ConfigHelper _ConfigHelper = null;
public static Dispatcher dispatcher
{
get { return _Dispatcher ?? Application.Current.Dispatcher; }
set { _Dispatcher = value; }
}
static Dispatcher _Dispatcher = null;
public bool IsSimulationMode
{
get { return _IsSimulationMode; }
set
{
_IsSimulationMode = value;
int Offset = _IsSimulationMode ? 2 : 0;
SetBorder( SimulationBorder, Offset );
StartButton.Margin = new Thickness( 0, Offset, 0, 0 );
}
}
bool _IsSimulationMode;
public bool IsJSONTextMode
{
get { return _IsJSONTextMode; }
set { _IsJSONTextMode = value; }
}
bool _IsJSONTextMode;
public bool IsPaused
{
get { return _IsPaused; }
set { _IsPaused = value; }
}
bool _IsPaused;
#endregion
#region Events
#endregion
public PolygonWPFDemoWindow()
{
InitializeComponent();
InitConfig();
if ( string.IsNullOrEmpty( ApiKey ) )
{
AppTextBox.Text = InitialMessage;
InitialMessageDisplayed = true;
}
}
private void InitConfig()
{
try
{
// load app's json config file
configHelper.LoadConfig();
// Note: data is read from json\PGDemoConfig.json
appValues = ConfigHelper.Instance.appConfig.appValues;
// check for hard-coded ApiKey
if ( string.IsNullOrEmpty( ApiKey ) )
ApiKey = appValues.ApiKey;
// check for ApiKey in config file
if ( !string.IsNullOrEmpty( ApiKey ) )
PGApi.SetApiKey( ApiKey );
// VerboseInfo will provide more text info
VerboseInfo = appValues.VerboseInfo;
CloseWindowOnEscape = appValues.CloseWindowOnEscape;
}
catch ( System.Exception ex )
{
string ErrorMessage = $"InitConfig() error: {ex.Message}";
Debug.WriteLine( ErrorMessage );
}
}
#region Intialization
private void InitPolygonWPFDemo()
{
PGBase.Dispatcher = dispatcher;
// capture initial RTDataGridHeight
RTDataGridHeight = RTDataControlsGrid.Height;
DisplayRTDataGrid( false, false );
// local initialization
PGApi.SetVerboseInfo( VerboseInfo );
InitEquitiesUI();
InitForexUI();
InitCryptoUI();
// PGApi initialization
PGApi.InitPGClusters();
PGApi.InitEvents();
InitPGClusterEvents();
// Note: optional, used for consolidated Trade/Quote
// unused in this app
PGApi.Equities.SetConsolidateLevel1( true );
InitClearTextPrompt();
InitEvents();
// realtime data initialization
InitClustersRTData();
if ( !string.IsNullOrEmpty( ApiKey ) )
OnApiKeyEntered( ApiKey );
}
private void InitPGClusterEvents()
{
UnInitPGClusterEvents();
foreach ( var Cluster in PGApi.PGClusters )
{
Cluster.OnSubscribeEvent += RTDataHelper.Instance.OnSubscribe;
Cluster.OnUnSubscribeEvent += RTDataHelper.Instance.OnUnSubscribe;
}
}
private void UnInitPGClusterEvents()
{
foreach ( var Cluster in PGApi.PGClusters )
{
Cluster.OnSubscribeEvent -= RTDataHelper.Instance.OnSubscribe;
Cluster.OnUnSubscribeEvent -= RTDataHelper.Instance.OnUnSubscribe;
}
}
private void InitEquitiesUI()
{
configHelper.EquitiesSymbols.Sort();
EquitiesCBox.ItemsSource = configHelper.EquitiesSymbols;
EquitiesCBox.Tag = PGApi.Equities.ClusterName;
ApplyComboBoxCharacterCasing( EquitiesCBox );
}
private void InitForexUI()
{
configHelper.ForexSymbols.Sort();
ForexCBox.ItemsSource = configHelper.ForexSymbols;
ForexCBox.Tag = PGApi.Forex.ClusterName;
ApplyComboBoxCharacterCasing( ForexCBox );
}
private void InitCryptoUI()
{
configHelper.CryptoSymbols.Sort();
CryptoCBox.ItemsSource = configHelper.CryptoSymbols;
CryptoCBox.Tag = PGApi.Crypto.ClusterName;
ApplyComboBoxCharacterCasing( CryptoCBox );
}
#endregion
#region InitEvents/UnInitEvents
public void InitEvents()
{
UnInitEvents();
RTDataHelper.Instance.OnSubscribedSymbolEvent += OnSubscribedSymbol;
RTDataHelper.Instance.OnUnSubscribedSymbolEvent += OnUnSubscribedSymbol;
EquitiesRTData.OnRTDataRowMouseDoubleClickEvent += OnRTDataRowMouseDoubleClick;
ForexRTData.OnRTDataRowMouseDoubleClickEvent += OnRTDataRowMouseDoubleClick;
CryptoRTData.OnRTDataRowMouseDoubleClickEvent += OnRTDataRowMouseDoubleClick;
// Note: PGApi.OnTextInfoEvent is a single source for TextInfo
PGApi.OnTextInfoEvent += OnClusterTextInfo;
PGApi.Equities.OnTradeEvent += OnEquitiesTrade;
PGApi.Equities.OnQuoteEvent += OnEquitiesQuote;
PGApi.Equities.OnDailyOpenCloseEvent += RTDataHelper.Instance.OnDailyOpenClose;
PGApi.Equities.OnPreviousCloseEvent += RTDataHelper.Instance.OnPreviousClose;
PGApi.Equities.OnTradeEvent += RTDataHelper.Instance.OnEquitiesTrade;
PGApi.Equities.OnQuoteEvent += RTDataHelper.Instance.OnEquitiesQuote;
PGApi.Equities.OnPGClusterReadyEvent += OnPGClusterReady;
PGApi.Forex.OnForexQuoteEvent += OnForexQuote;
PGApi.Forex.OnForexAggEvent += OnForexAgg;
PGApi.Forex.OnDailyOpenCloseEvent += RTDataHelper.Instance.OnDailyOpenClose;
PGApi.Forex.OnPreviousCloseEvent += RTDataHelper.Instance.OnPreviousClose;
PGApi.Forex.OnForexQuoteEvent += RTDataHelper.Instance.OnForexQuote;
PGApi.Forex.OnForexAggEvent += RTDataHelper.Instance.OnForexAgg;
PGApi.Forex.OnPGClusterReadyEvent += OnPGClusterReady;
PGApi.Crypto.OnCryptoTradeEvent += OnCryptoTrade;
PGApi.Crypto.OnCryptoQuoteEvent += OnCryptoQuote;
PGApi.Crypto.OnCryptoAggEvent += OnCryptoAgg;
PGApi.Crypto.OnCryptoLevel2Event += OnCryptoLevel2;
PGApi.Crypto.OnDailyOpenCloseEvent += RTDataHelper.Instance.OnDailyOpenClose;
PGApi.Crypto.OnPreviousCloseEvent += RTDataHelper.Instance.OnPreviousClose;
PGApi.Crypto.OnCryptoTradeEvent += RTDataHelper.Instance.OnCryptoTrade;
PGApi.Crypto.OnCryptoQuoteEvent += RTDataHelper.Instance.OnCryptoQuote;
PGApi.Crypto.OnCryptoAggEvent += RTDataHelper.Instance.OnCryptoAgg;
PGApi.Crypto.OnCryptoLevel2Event += RTDataHelper.Instance.OnCryptoLevel2;
PGApi.Crypto.OnPGClusterReadyEvent += OnPGClusterReady;
}
public void UnInitEvents()
{
RTDataHelper.Instance.OnSubscribedSymbolEvent -= OnSubscribedSymbol;
RTDataHelper.Instance.OnUnSubscribedSymbolEvent -= OnUnSubscribedSymbol;
// Note: PGApi.OnTextInfoEvent is a single source for TextInfo
PGApi.OnTextInfoEvent -= OnClusterTextInfo;
PGApi.Equities.OnTradeEvent -= OnEquitiesTrade;
PGApi.Equities.OnQuoteEvent -= OnEquitiesQuote;
PGApi.Equities.OnTradeEvent -= RTDataHelper.Instance.OnEquitiesTrade;
PGApi.Equities.OnQuoteEvent -= RTDataHelper.Instance.OnEquitiesQuote;
PGApi.Equities.OnPGClusterReadyEvent -= OnPGClusterReady;
PGApi.Forex.OnForexQuoteEvent -= OnForexQuote;
PGApi.Forex.OnForexAggEvent -= OnForexAgg;
PGApi.Forex.OnForexQuoteEvent -= RTDataHelper.Instance.OnForexQuote;
PGApi.Forex.OnForexAggEvent -= RTDataHelper.Instance.OnForexAgg;
PGApi.Forex.OnPGClusterReadyEvent -= OnPGClusterReady;
PGApi.Crypto.OnCryptoTradeEvent -= OnCryptoTrade;
PGApi.Crypto.OnCryptoQuoteEvent -= OnCryptoQuote;
PGApi.Crypto.OnCryptoAggEvent -= OnCryptoAgg;
PGApi.Crypto.OnCryptoLevel2Event -= OnCryptoLevel2;
PGApi.Crypto.OnCryptoTradeEvent -= RTDataHelper.Instance.OnCryptoTrade;
PGApi.Crypto.OnCryptoQuoteEvent -= RTDataHelper.Instance.OnCryptoQuote;
PGApi.Crypto.OnCryptoAggEvent -= RTDataHelper.Instance.OnCryptoAgg;
PGApi.Crypto.OnCryptoLevel2Event -= RTDataHelper.Instance.OnCryptoLevel2;
PGApi.Crypto.OnPGClusterReadyEvent -= OnPGClusterReady;
}
#endregion
#region Window events
private void Window_Loaded( object sender, RoutedEventArgs e )
{
InitPolygonWPFDemo();
}
private void Window_Closing( object sender, System.ComponentModel.CancelEventArgs e )
{
PGApi.TerminateApiInterface();
}
protected void OnWindow_KeyDown( object sender, KeyEventArgs e )
{
switch ( e.Key )
{
case Key.Escape:
if ( CloseWindowOnEscape )
Close(); // Close on Escape
break;
default:
break;
}
}
private void AppTextBox_MouseDoubleClick( object sender, MouseButtonEventArgs e )
{
AppTextBox.Text = string.Empty;
}
private void JSONText_Checked( object sender, RoutedEventArgs e )
{
UseJSONText.IsChecked = true;
UseJSONText.Foreground = new SolidColorBrush( Colors.LightSteelBlue );
UseClassValues.Foreground = new SolidColorBrush( Colors.White );
IsJSONTextMode = true;
}
private void ClassValues_Checked( object sender, RoutedEventArgs e )
{
UseClassValues.IsChecked = true;
UseClassValues.Foreground = new SolidColorBrush( Colors.LightSteelBlue );
UseJSONText.Foreground = new SolidColorBrush( Colors.White );
IsJSONTextMode = false;
}
private void ExitButton_Click( object sender, RoutedEventArgs e )
{
Close();
}
#endregion
#region PGApi
private void OnPGClusterReady( string ClusterName, bool IsReconnect )
{
ComboBox CBox = null;
switch ( ClusterName )
{
case PGClusterNames.Equities:
CBox = EquitiesCBox;
break;
case PGClusterNames.Forex:
CBox = ForexCBox;
break;
case PGClusterNames.Crypto:
CBox = CryptoCBox;
break;
default:
throw new Exception( $"Unknown ClusterName: {ClusterName}" );
}
if ( !IsReconnect )
SubscribeChannelsForSymbol( CBox, true );
}
private void SubscribeClusterPresetSymbols( string ClusterName )
{
AppendText( $"Subscribing to {ClusterName} Preset Symbols... " );
// 100 msecs delay to allow for UI updates...
TimerHelper UITimer = new TimerHelper( SubscribeClusterPresets, Data: ClusterName )
{ IsOneShot = true };
}
private void SubscribeClusterPresets( object Data )
{
string ClusterName = Data as string;
switch ( ClusterName )
{
case PGClusterNames.Equities:
SubscribeClusterSymbolChannels( PGApi.Equities, configHelper.EquitiesPresetSymbols, PGEquities.DefaultEquitiesChannels );
break;
case PGClusterNames.Forex:
SubscribeClusterSymbolChannels( PGApi.Forex, configHelper.ForexPresetSymbols, PGForex.DefaultForexChannels );
break;
case PGClusterNames.Crypto:
SubscribeClusterSymbolChannels( PGApi.Crypto, configHelper.CryptoPresetSymbols, PGCrypto.DefaultCryptoChannels );
break;
default:
throw new Exception( $"Unknown ClusterName: {ClusterName}" );
}
}
private string SubscribeClusterSymbolChannels( PGClusterBase Cluster, List<string> Symbols, List<string> Channels )
{
// format Params by adding Channel.Symbol for each Symbol
string Params = string.Empty;
foreach ( var Symbol in Symbols )
{
Params = string.Empty;
foreach ( var Channel in Channels )
Params += $"{Channel}.{Symbol},";
AppendText( $"Subscribing to {Params}" );
Cluster.SendSubscribeMessage( Params );
}
return Params.TrimEnd(',');
}
// Note: PGApi.OnTextInfoEvent is a single source for TextInfo
private void OnClusterTextInfo( string Text )
{
AppendText( Text );
}
#endregion
#region Equities
private void OnEquitiesTrade( Trade trade )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( trade );
else
{
Text = $"Trade: Symbol: {trade.sym}, " +
$"Price: {trade.p}, Size: {trade.s}, " +
$"Trade ID: {trade.i}, Exchange ID: {trade.x}, " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( trade.t )} EST";
}
AppendText( Text );
}
private void OnEquitiesQuote( Quote quote )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( quote );
else
{
Text = $"Quote: Symbol: {quote.sym}, " +
$"Bid: {quote.bp}, Bid Size: {quote.bs}, " +
$"Ask: {quote.ap}, Ask Size: {quote.asz}, " +
$"Bid ID: {quote.bx}, Ask ID: {quote.ax} " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( quote.t )} EST";
}
AppendText( Text );
}
protected void OnLastTrade( LastTrade lastTrade )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( lastTrade );
else
{
Text = $"Trade: Symbol: {lastTrade.symbol}, " +
$"Price: {lastTrade.last.price}, Size: {lastTrade.last.size}, " +
$"Exchange ID: {lastTrade.last.exchange}, " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( lastTrade.last.timestamp )}";
}
AppendText( Text );
}
protected void OnLastQuote( LastQuote LastQuote )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( LastQuote );
else
{
Text = $"LastQuote: Symbol: {LastQuote.symbol}, " +
$"Bid: {LastQuote.last.bidprice}, Bid Size: {LastQuote.last.bidsize}, " +
$"Ask: {LastQuote.last.askprice}, Ask Size: {LastQuote.last.asksize}, " +
$"Bid ID: {LastQuote.last.bidexchange}, Ask ID: {LastQuote.last.askexchange} " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( LastQuote.last.timestamp )} EST";
}
AppendText( Text );
}
#endregion
#region Forex
private void OnForexQuote( ForexQuote quote )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( quote );
else
{
Text = $"Quote: Pair: {quote.p}, " +
$"Bid: {quote.b}, Ask: {quote.a}, " +
$"FX Exchange: {quote.x}, " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( quote.t )} EST";
}
AppendText( Text );
}
private void OnForexAgg( ForexAggregate forexAgg )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( forexAgg );
else
{
Text = $"Quote: Pair: {forexAgg.pair}, " +
$"Open: {forexAgg.o}, Close: {forexAgg.c}, " +
$"High: {forexAgg.h}, Low: {forexAgg.l}, " +
$"Volume: {forexAgg.v} EST" +
$"Tick Start: {PGBase.UnixTimestampMillisToESTDateTime( forexAgg.s )} EST";
}
AppendText( Text );
}
#endregion
#region Crypto
private void OnCryptoTrade( CryptoTrade trade )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( trade );
else
{
Text = $"Trade: Pair: {trade.pair}, " +
$"Price: {trade.p}, Size: {trade.s}, " +
$"Trade ID: {trade.i}, Exchange ID: {trade.xt}, " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( trade.t )} EST";
}
AppendText( Text );
}
private void OnCryptoQuote( CryptoQuote quote )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( quote );
else
{
Text = $"Trade: Pair: {quote.pair}, " +
$"Last Trade: {quote.lp}, Last Trade Size: {quote.ls}, " +
$"Bid: {quote.bp}, Bid Size: {quote.bs}, " +
$"Ask: {quote.ap}, Ask Size: {quote.asz}, " +
$"Exchange ID: {quote.xt}, " +
$"Exchange Timestamp: {PGBase.UnixTimestampMillisToESTDateTime( quote.t )} EST";
}
AppendText( Text );
}
private void OnCryptoAgg( CryptoAggregate cryptoAgg )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( cryptoAgg );
else
{
Text = $"Trade: Pair: {cryptoAgg.pair}, " +
$"Open: {cryptoAgg.o}, Open Exchange: {cryptoAgg.ox}, " +
$"High: {cryptoAgg.h}, High Exchange: {cryptoAgg.hx}, " +
$"Low: {cryptoAgg.l}, Low Exchange: {cryptoAgg.lx}, " +
$"Close: {cryptoAgg.cl}, Close Exchange: {cryptoAgg.cx}, " +
$"Volume: {cryptoAgg.v}, " +
$"Tick Start: {PGBase.UnixTimestampMillisToESTDateTime( cryptoAgg.s )} EST" +
$"Tick End: {PGBase.UnixTimestampMillisToESTDateTime( cryptoAgg.e )} EST";
}
AppendText( Text );
}
private void OnCryptoLevel2( CryptoLevel2 cryptoLevel2 )
{
string Text;
if ( IsJSONTextMode )
Text = JsonConvert.SerializeObject( cryptoLevel2 );
else
{
Text = $"Trade: Pair: {cryptoLevel2.pair}, " +
$"Bid Prices: {cryptoLevel2.b.ToString()}" +
$"Ask Prices: {cryptoLevel2.a.ToString()}, " +
$"Exchange ID: {cryptoLevel2.xt}, " +
$"Time: {PGBase.UnixTimestampMillisToESTDateTime( cryptoLevel2.t )} EST";
}
AppendText( Text );
}
#endregion
#region Go/Pause
private void StartButtonButton_Click( object sender, RoutedEventArgs e )
{
if ( !IsSimulationMode )
{
// check for an Api Key, prompt if not present
if ( !CheckApiKey() )
return;
}
bool IsNowPaused = !IsPaused;
string Text = string.Format( "App is {0}...", !IsNowPaused ? "Running" : "Paused" );
AppendText( Text );
IsPaused = IsNowPaused;
StartButton.Content = IsPaused ? "Start" : "Pause";
if ( !IsPaused )
StartApp();
}
private void StartApp()
{
if ( IsSimulationMode && !SimulationModeStarted )
{
StartSimulationMode();
}
else if ( !IsSimulationMode )
{
// start/connect
foreach ( var Cluster in PGApi.PGClusters )
StartCluster( Cluster );
}
}
private void StartCluster( PGClusterBase Cluster )
{
if ( !Cluster.PGStatus.PGLogonSucceeded )
{
AppendText( $"Starting...{Cluster.ClusterName}" );
Cluster.Start();
}
}
private void RestartButton_Click( object sender, RoutedEventArgs e )
{
if ( IsSimulationMode )
{
AppendText( "Restarting Simulation..." );
EndSimulationMode();
StartSimulationMode();
}
else
{
AppendText( "\nRestarting.Clusters..\n" );
foreach ( var Cluster in PGApi.PGClusters )
{
Cluster.UnSubscribeAll();
Cluster.IsStarted = false;
Cluster.Start();
}
}
}
private void Simulation_Click( object sender, RoutedEventArgs e )
{
IsSimulationMode = Simulation.IsChecked.Value;
if ( SimulationModeStarted )
EndSimulationMode();
}
#endregion
#region ApiKey
private bool CheckApiKey( bool Report = true )
{
bool IsApiKey = !string.IsNullOrEmpty( PGApi.ApiKey );
if ( !IsApiKey && Report )
AppendText( $"Please enter/paste an Api Key..." );
return IsApiKey;
}
EnterApiKeyControl ApiKeyControl;
private void ApiKey_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
{
if ( ApiKeyControl == null )
{
ApiKeyControl = new EnterApiKeyControl( ApiKey );
ApiKeyControl.OnApiKeyEvent += OnApiKeyEntered;
ApiKeyControl.OnOKEvent += OnApiKeyOK;
ApiKeyControl.OnCancelEvent += OnCloseEnterApiKey;
Grid.SetRow( ApiKeyControl, 0 );
Grid.SetRowSpan( ApiKeyControl, 3 );
Grid.SetColumn( ApiKeyControl, 0 );
Grid.SetColumnSpan( ApiKeyControl, 19 );
LayoutRoot.Children.Add( ApiKeyControl );
}
}
private void OnApiKeyOK()
{
string ApiKey = ApiKeyControl.ApiKeyText.Text;
OnApiKeyEntered( ApiKey );
OnCloseEnterApiKey();
}
private void OnCloseEnterApiKey()
{
if ( ApiKeyControl != null )
{
LayoutRoot.Children.Remove( ApiKeyControl );
ApiKeyControl = null;
}
}
private void OnApiKeyEntered( string ApiKey )
{
if ( !string.IsNullOrEmpty( ApiKey ) )
{
ApiKeyText.Foreground = new SolidColorBrush( (Color)ColorConverter.ConvertFromString( "LightGreen" ));
PGApi.SetApiKey( ApiKey );
IsPaused = false;
StartApp();
}
}
private void OnApiKeyPaste( object sender, DataObjectPastingEventArgs e )
{
var IsText = e.SourceDataObject.GetDataPresent( DataFormats.UnicodeText, true );
if ( !IsText )
return;
string ApiKey = e.SourceDataObject.GetData( DataFormats.UnicodeText ) as string;
PGApi.SetApiKey( ApiKey );
e.Handled = true;
}
#endregion
#region UI Helpers
private void OnRTDataRowMouseDoubleClick( string ClusterName, string Symbol )
{
PGClusterBase Cluster = PGApi.GetCluster( ClusterName );
bool IsSubscribed = Cluster.IsSymbolSubscribed( Symbol );
// UnSubscribe on RTDataRow DoubleClick
if ( IsSubscribed )
Cluster.UnSubscribeSymbol( Symbol );
}
private void OnSubscribeEquitiesPresets( object sender, RoutedEventArgs e )
{
SubscribeClusterPresetSymbols( PGClusterNames.Equities );
e.Handled = true;
}
private void OnSubscribeForexPresets( object sender, RoutedEventArgs e )
{
SubscribeClusterPresetSymbols( PGClusterNames.Forex );
e.Handled = true;
}
private void OnSubscribeCryptoPresets( object sender, RoutedEventArgs e )
{
SubscribeClusterPresetSymbols( PGClusterNames.Crypto );
e.Handled = true;
}
private void ClusterComboBoxMouseDoubleClick( object sender, MouseButtonEventArgs e )
{
ComboBox CBox = ( sender as ComboBox );
string ClusterName = CBox.Tag as string;
string Symbol = CBox.Text;
List<string> SymbolsList = CBox.ItemsSource as List<string>;
// remove on DoubleClick
if ( SymbolsList.Contains( Symbol ) )
SymbolsList.Remove( Symbol );
e.Handled = true;
}
private void OnClusterComboBoxKeyDown( object sender, KeyEventArgs e )
{
if ( e.Key == Key.Enter )
{
ComboBox CBox = ( sender as ComboBox );
string ClusterName = CBox.Tag as string;
string Symbol = CBox.Text;
if ( !string.IsNullOrEmpty( Symbol ) )
{
List<string> SymbolsList = CBox.ItemsSource as List<string>;
// is Symbol already there?
if ( SymbolsList.Contains( Symbol ) )
{
PGClusterBase Cluster = PGApi.GetCluster( ClusterName );
bool IsSubscribed = Cluster.IsSymbolSubscribed( Symbol );
// Subscribe on Enter
if ( !IsSubscribed )
SubscribeChannelsForSymbol( CBox, true );
}
else if ( !string.IsNullOrEmpty( Symbol ) )
{
// add a new Symbol
SymbolsList.Add( Symbol );
SymbolsList.Sort();
SubscribeChannelsForSymbol( CBox, true );
}
e.Handled = true;
}
}
}
private void OnClusterComboBoxDropDownClosed( object sender, EventArgs e )
{
ComboBox CBox = ( sender as ComboBox );
string ClusterName = CBox.Tag as string;
string Symbol = CBox.Text;
if ( !string.IsNullOrEmpty( Symbol ) )
{
PGClusterBase Cluster = PGApi.GetCluster( ClusterName );
bool IsSubscribed = Cluster.IsSymbolSubscribed( Symbol );
if ( IsSubscribed )
return;
SubscribeChannelsForSymbol( ( sender as ComboBox ), true );
}
}
private void OnClusterComboBoxSelectionChanged( object sender, SelectionChangedEventArgs e )
{
}
#endregion
#region SubscribeChannels
private void SubscribeChannelsForSymbol( ComboBox CBox, bool Subscribe )
{
// Note: it is benign to Subscribe and already Subscribed symbol
string Symbol = CBox.Text;
if ( string.IsNullOrEmpty( Symbol ) )
return;
string ClusterName = CBox.Tag as string;
PGClusterBase Cluster = PGApi.GetPGCluster( ClusterName );
if ( Cluster == null )
throw new Exception( $"Unknown ClusterName: {ClusterName}" );
// check for PGApi Cluster ready
if ( !Cluster.PGStatus.PGLogonSucceeded )
AppendText( $"{ClusterName} has not been started (use the Start button)" );
if ( Subscribe )
Cluster.SubscribeSymbol( Symbol );
else
Cluster.UnSubscribeSymbol( Symbol );
}
private void RequestLast( RTDataRec rtDataRec )
{
AppendText( $"Request Last for {rtDataRec.Symbol}" );
switch ( rtDataRec.ClusterName )
{
case PGClusterNames.Equities:
LastTrade lastTrade = PGApi.Equities.RequestLastTrade( rtDataRec.Symbol );
if ( lastTrade != null )
{
// check invalid symbol
if ( lastTrade.status == PGStatusMessages.NotFound )
HandleInvalidSymbol( rtDataRec );
else if ( lastTrade != null && lastTrade.last != null )
{
rtDataRec.Price = lastTrade.last.price;
rtDataRec.LastSize = lastTrade.last.size;
}
}
LastQuote LastQuote = PGApi.Equities.RequestLastQuote( rtDataRec.Symbol );
if ( LastQuote != null )
{
if ( LastQuote != null && LastQuote.last != null )
{
rtDataRec.Ask = LastQuote.last.askprice;
rtDataRec.Bid = LastQuote.last.bidprice;
}
}
break;
case PGClusterNames.Forex:
ForexLastQuote ForexLastquote = PGApi.Forex.RequestForexLastQuote( rtDataRec.Symbol );
if ( ForexLastquote != null )
{
// check invalid symbol
if ( ForexLastquote.status == PGStatusMessages.NotFound )
HandleInvalidSymbol( rtDataRec );
else if ( ForexLastquote != null && ForexLastquote.last != null )
{
rtDataRec.Ask = ForexLastquote.last.ask;
rtDataRec.Bid = ForexLastquote.last.bid;
}
}
break;
case PGClusterNames.Crypto:
CryptoLastTrade CryptoLasttrade = PGApi.Crypto.RequestCryptoLastTrade( rtDataRec.Symbol );
if ( CryptoLasttrade != null )
{
// check invalid symbol
if ( CryptoLasttrade.status == PGStatusMessages.NotFound )
HandleInvalidSymbol( rtDataRec );
else if ( CryptoLasttrade != null && CryptoLasttrade.last != null )
{
rtDataRec.Price = CryptoLasttrade.last.price;
rtDataRec.CryptoSize = CryptoLasttrade.last.size;
}
}
break;
default:
throw new Exception( $"Unknown ClusterName: {rtDataRec.ClusterName}" );
}
// get Previous values
PGClusterBase Cluster = PGApi.GetPGCluster( rtDataRec.ClusterName );
if ( Cluster != null )
{
Cluster.RequestPreviousClose( rtDataRec.Symbol );
Cluster.RequestDailyOpenClose( rtDataRec.Symbol );
}
}
private void HandleInvalidSymbol( RTDataRec rtDataRec )
{
AppendText( $"{rtDataRec.Symbol} is an invalid symbol", true );
PGClusterBase Cluster = PGApi.GetPGCluster( rtDataRec.ClusterName );
if ( Cluster == null )
throw new Exception( $"Unknown ClusterName: {rtDataRec.ClusterName}" );
Cluster.RemoveSymbol( rtDataRec.Symbol );
RTDataHelper.Instance.RemoveRTData( rtDataRec );
}
#endregion
#region Simulation