-
Notifications
You must be signed in to change notification settings - Fork 0
/
@ArtTS Futures Info CH
1800 lines (1587 loc) · 67.6 KB
/
@ArtTS Futures Info CH
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
// Michael Burke - Art of TradeStation - 2020
#region - Documentation -
{
---------------------------------------------------------------------------------------------------
IDENTIFICATION
==============
Name: #Futures Info
Type: Indicator
TS Version: 9.5 Build 26 or later
---------------------------------------------------------------------------------------------------
DOCUMENTATION
=============
This module displays information about the futures symbol in data1 of the associated chart.
---------------------------------------------------------------------------------------------------
}
#endregion
#region - History -
{
---------------------------------------------------------------------------------------------------
HISTORY
=======
Date Version Task
--------- -------- -------------------------------------------------------------------
10/30/18 08.00.00 * Developed and updated
02/09/19 09.00.00 * Expand documentation
* Include #region functionality
* Method organization
* Inserted Composite Formatting
* Added CurChar to XML
* Added CurChar for CHF
09.01.00 * Add Bitcoin futures support
* Use composite formatting on Futures Chain Form
02/14/19 09.02.00 * Version label on Futures Chain form
09.02.01 * Remove TempQP vector
02/28/19 09.02.02 * Add Global Dictionary Utility
02/28/19 09.02.03 * Add Micros
10/23/19 09.03.00 * Address datetime issues for non-US regions
* Display dates in local regional format
* Display session times in local regional format
* Correct symbol currency character display
12/10/19 09.04.00 * New 12/10/19 web site structure
* Added LogStep option
09.05.00 * Add check for empty XML document from WorkArea
12/11/19 09.06.00 * Add iMaxDaysOld check
* Updtd format back to include HH:mm:ss
---------------------------------------------------------------------------------------------------
TO DO LIST
==========
Date Version Task
--------- -------- -------------------------------------------------------------------
---------------------------------------------------------------------------------------------------
}
#endregion
#region - Usings -
using elsystem;
using elsystem.collections;
using elsystem.drawing;
using elsystem.io;
using elsystem.xml;
using elsystem.windows.forms;
using tsdata.common;
using tsdata.marketdata;
#endregion
#region - Inputs_Study -
Inputs:
int ContractMultiplierDefault(1),
bool LoadGD(true),
int iMaxDaysOld(0), // Maximum number of days old the XML file may be before it must be re-extracted
// 0 ==> Only today; 1 ==> Yesterday or today
bool iLogSteps(False);
#endregion
#region - Constants_Study -
constants:
string AppVersion("09.06.00"),
string MDYHMSFormat("%m/%d/%y %H:%M:%S"),
string Currencies( "AUD,CAD,CHF,CNH,CZK,DKK,EUR,GBP,HKD,HUF,JPY,MNX,NAD,NOK,PLN,SGD,TRY,USD,XAG,XBR,XTI,ZAR" ),
string XmlDocName( "FuturesMarginTA.xml" ),
string WEBAWS("WEB"),
string UpperCaseAndDigits("ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"),
string TSWebSiteURL("https://www.tradestation.com/pricing/futures-margin-requirements/"),
string AWSWebSiteURL("https://s3.us-east-2.amazonaws.com/tradestationmargin/FuturesMarginTA.xml"),
string USDCurrency("$"),
string EURCurrency("€"),
string GBPCurrency("£"),
string CHFCurrency("₣");
constants:
tr("tr");
#endregion
#region - Variables_Study -
variables:
Version TSVersion(null),
intrabarpersist int YY(0),
intrabarpersist int MM(0),
intrabarpersist bool LastBar(false),
intrabarpersist bool WebDocComplete( false ),
intrabarpersist string fSymbol( "" ),
intrabarpersist bool SymbolOK( false ),
Vector BSymbols(Null),
Vector BLTD(Null),
Vector BFND(Null),
Vector QPS(Null),
intrabarpersist BarValue(0),
intrabarpersist string ThisSymbolRoot(""),
intrabarpersist int ContCalc(1),
intrabarpersist string FrontSym( "" ),
intrabarpersist string CurrentSym( "" ),
intrabarpersist string NextSym( "" ),
intrabarpersist string FrontSymLTD( "" ),
intrabarpersist string CurrentSymLTD( "" ),
intrabarpersist string NextSymLTD( "" ),
intrabarpersist string FrontSymFND( "" ),
intrabarpersist string CurrentSymFND( "" ),
intrabarpersist string NextSymFND( "" ),
Timer tmrOneSecond( NULL ),
XmlDocument XD( NULL ), { XmlDocument to hold information }
XmlNode XNSymbolRoots( NULL ),
XmlElement XE( NULL ),
Form frmBrowser( NULL ),
WebBrowser Browser( NULL ), { browser to navigate to margin page }
GlobalDictionary MR( NULL),
intrabarpersist int SymbolType(0),
intrabarpersist int TestCount( 0 ),
intrabarpersist string oSymbolDesc(""),
intrabarpersist string oSymbolExch(""),
intrabarpersist string oSymbolCurrency(""),
intrabarpersist string oSymbolCurrencyChar("$"),
intrabarpersist double oInitialMargin(0),
intrabarpersist double oMaintenanceMargin(0),
intrabarpersist double oDayRatePercent(0),
intrabarpersist string oUpdated(""),
TokenList CurrencyListTL( NULL ),
tokenlist FMonths(NULL),
intrabarpersist int DecimalPlacesX(0),
SymbolPriceScale(0),
//-------------------------------------------------------------------------------------
// strings that should be in the web page - are constants but syntax of EL does not support it
//-------------------------------------------------------------------------------------
{
intrabarpersist string StartTag( "<TABLE class=" + DoubleQuote + "table full" + DoubleQuote + ">" ), // start tag of margin table
intrabarpersist string endTag( "</TABLE>" ), // end tag of margin table
intrabarpersist string StartTagl( "<table class=" + DoubleQuote + "table full" + DoubleQuote + ">" ), // start tag of margin table
intrabarpersist string endTagl( "</table>" ); // end tag of margin table
}
String StartTagLC("<tbody>"),
String EndTagLC("</tbody>");
#endregion
#region - Initialization -
method void AnalysisTechnique_Initialized( elsystem.Object sender, elsystem.InitializedEventArgs args )
begin
// if iLogSteps then ClearPrintLog();
// if iLogSteps then Print(string.Format("{0:MM/dd/yy HH:mm:ss} Futures Margin TA Init", DateTime.Now));
MR = GlobalDictionary.Create(TRUE, "GD_Margin");
fSymbol = Symbol;
SymbolOK = CheckSymbol( fSymbol );
NumDecimalsX();
SymbolType = SecurityType.Future;
tmrOneSecond = Timer.Create();
If SymbolOK AND SymbolType = Category then
begin
FMonths = new tokenlist;
YY = strtonum(DateTime.Today.Format("%y")) astype int;
MM = DateTime.Today.Month astype int;
BSymbols = New Vector;
BLTD = New Vector;
BFND = New Vector;
QPS = New Vector;
ThisSymbolRoot = SymbolRoot;
//-------------------------------------------------------------------------------------
// Create XMLDocument for holding futures information
//-------------------------------------------------------------------------------------
CreateXmlDoc();
//-------------------------------------------------------------------------------------
// Initialize Form Controls
//-------------------------------------------------------------------------------------
FormInit();
// if iLogSteps then Print(string.Format("{0:MM/dd/yy HH:mm:ss} Form Initialized", DateTime.Now));
//-------------------------------------------------------------------------------------
// Put symbol related values into form
//-------------------------------------------------------------------------------------
SetMonthCodes();
SetSessions();
SetPointValues();
If FMonths.Count > 0 AND FMonths[0] astype string <> "invalidRoot" then BuildQPS();
CurrencyListTL = new Tokenlist;
CurrencyListTL.Add(Currencies);
//-------------------------------------------------------------------------------------
// Create OneSecond timer
//-------------------------------------------------------------------------------------
CreateTimer();
// if iLogSteps then Print(string.Format("{0:MM/dd/yy HH:mm:ss} Timer Started", DateTime.Now));
//-------------------------------------------------------------------------------------
// Get Margin Information from Web Page - defer until last bar
//-------------------------------------------------------------------------------------
//GetMarginFromWeb();
// if iLogSteps then Print(string.Format("{0:MM/dd/yy HH:mm:ss} Init Complete", DateTime.Now));
end;
end;
#endregion
#region - Get Number of Decimal Places -
method void NumDecimalsX()
Begin
SymbolPriceScale = PriceScale;
if SymbolPriceScale > 0 then
begin
DecimalPlacesX = NumDecimals(SymbolPriceScale);
end ;
End;
#endregion
#region - Form Methods -
method void FormInit()
begin
//-------------------------------------------------------------------------------------
// Set Anchor Properties
//-------------------------------------------------------------------------------------
LblBasics.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
BPointValue.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
MinMvD.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
MinMv.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
BarVal.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
Session.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
Exchange.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
MonthCodes.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
InitalM.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
MaintM.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
DayTrdM.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
Update.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
ChartFN.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
ChartLD.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
FrontFND.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
FrontLTD.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
CurrentFND.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
CurrentLTD.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
NextFND.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
NextLTD.Anchor = AnchorStyles.Left + AnchorStyles.Top + AnchorStyles.Right;
TSVersion = elsystem.Environment.GetPlatformVersion();
LblVersion.Text = string.format("TS {0}.{1}.{2} App {3}",
TSVersion.Major, TSVersion.Minor, TSVersion.Revision, AppVersion);
LblVersionFC.Text = LblVersion.Text;
ConCalc.Value = ContractMultiplierDefault;
LblBasics.Text = LblBasics.Text + " - " + LeftStr(Description, InStr(Description, " "));
Sym2.Text = "n/a";
Sym3.Text = "n/a";
Sym4.Text = "n/a";
Last2.Text = "-";
Last3.Text = "-";
Last4.Text = "-";
PctCh2.Text = "-";
PctCh3.Text = "-";
PctCh4.Text = "-";
end;
//-------------------------------------------------------------------------------------
// Contract multiplier value changed
//-------------------------------------------------------------------------------------
Method void ShowForm()
Begin
Form.Show();
FormVol.Show();
end;
//-------------------------------------------------------------------------------------
// Set Point Values
//-------------------------------------------------------------------------------------
Method void SetPointValues()
variables:
string Tempstr;
Begin
BPointValue.Text = string.Format("PointValue: {0:C0}", BigPointValue * ConCalc.Value).Replace("$", oSymbolCurrencyChar);
//MinMvD.Text = "MinMove $: " + NumtoStr((MinMove/PriceScale)*BigpointValue * ConCalc.Value,NumDecimals( PriceScale ));
MinMvD.Text = string.Format("MinMove: {0:C#}".Replace("#", NumtoStr(DecimalPlacesX,0)),
(MinMove/PriceScale)*BigpointValue * ConCalc.Value).Replace("$", oSymbolCurrencyChar); ;
TempStr = "MinMove Pts: {0:N#}".Replace("#", NumtoStr(DecimalPlacesX, 0));
//MinMv.Text = "MinMove: " + NumtoStr(MinMove/PriceScale,NumDecimals( PriceScale ));
MinMv.Text = string.Format(TempStr, MinMove/PriceScale);
Exchange.Text = "Exchange: " + Exchlisted;
end;
//-------------------------------------------------------------------------------------
// Update Margin information in form
//-------------------------------------------------------------------------------------
method void SetMargin()
vars: double DayM;
begin
InitalM.Text = string.Format("Initial: {0:C0}", + oInitialMargin * ConCalc.Value).Replace("$", oSymbolCurrencyChar);
MaintM.Text = string.Format("Maint: {0:C0}",oMaintenanceMargin* ConCalc.Value).Replace("$", oSymbolCurrencyChar);
DayM = oDayRatePercent;
if oDayRatePercent = 13 then DayM = 12.5;
DayTrdM.Text = string.Format("DayTrd: {0:P1} / {1}{2:N0}",
DayM *.01, oSymbolCurrencyChar, DayM *.01 * oInitialMargin * ConCalc.Value);
Update.Text = "LastUpdate: " + oUpdated;
end;
method void ConCalc_ValueChanged( elsystem.Object sender, elsystem.EventArgs args )
begin
ContCalc = ConCalc.Value astype int;
SetPointValues();
SetMargin();
end;
#endregion
#region - Check String Character Set -
//-------------------------------------------------------------------------------------
// Returns 0 if all characters in toCheck are in the validChars string
//-------------------------------------------------------------------------------------
method int InvalidCharIndex( string toCheck, string validChars )
Variables:
Int Index,
int InvalidIndex;
begin
InvalidIndex = 0;
for Index = 1 to strlen( toCheck )
begin
if instr( validChars, midstr( tocheck, Index, 1 ) ) = 0 then
begin
InvalidIndex = Index;
break;
end;
end;
return InvalidIndex;
end;
#endregion
#region - Validate Symbol -
//-------------------------------------------------------------------------------------
// Check for valid symbol using TSOpt
//-------------------------------------------------------------------------------------
method bool CheckSymbol( string MySymbol )
variables:
bool IsValid ,
tsopt.job job,
tsopt.security security;
begin
job = new tsopt.job;
security = job.securities.addSecurity();
security.symbol = MySymbol;
IsValid = job.securities.ValidateSymbols( false );
return IsValid;
end;
#endregion
#region - Get Margin Information from Web Site Page -
method void GetMarginFromWeb()
Vars:
bool ifneeded;
begin
// if iLogSteps then Print(string.Format("{0:MM/dd/yy HH:mm:ss} GetMarginFromWeb Called", DateTime.Now));
//-------------------------------------------------------------------------------------
// Create a form to be used for the browser and locate if one display to the left
// and down
//-------------------------------------------------------------------------------------
frmBrowser = Form.Create( " ", 0, 0 );
frmBrowser.Location( -1024, -1024 );
//-------------------------------------------------------------------------------------
// create the browser control
//-------------------------------------------------------------------------------------
Browser = WebBrowser.Create( 0, 0 );
Browser.ScriptErrorsSuppressed = true;
Browser.Visible = true;
frmBrowser.AddControl( Browser );
//-------------------------------------------------------------------------------------
// First try to load XML Document and then if not available will go to web or aws
//-------------------------------------------------------------------------------------
ifneeded = FALSE;
if not LoadXmlDoc() then
begin
ifNeeded = true;
end
else
begin
GetMarginXML();
end;
// if iLogSteps then
// Print(string.Format("{0:MM/dd/yy HH:mm:ss} GetMarginFromWeb - Needed={1} Src={2}",
// DateTime.Now, IfNeeded, WEBAWS));
if ifNeeded then
begin
switch WEBAWS.ToUpper().Trim()
begin
case "WEB":
GetWeb();
case "AWS":
GetAWS();
break;
default:
GetWeb();
end;
end;
end;
//-------------------------------------------------------------------------------------
// Initiate loading web page
//-------------------------------------------------------------------------------------
method void GetWeb()
begin
frmBrowser.Show();
Browser.DocumentCompleted += OnDocumentCompletedWEB;
Browser.Navigate(TSWebSiteURL);
end;
//-------------------------------------------------------------------------------------
// Initiate loading XmlDocument from AWS
//-------------------------------------------------------------------------------------
method void GetAWS()
begin
frmBrowser.Show();
Browser.DocumentCompleted += OnDocumentCompletedAWS;
Browser.Navigate(AWSWebSiteURL);
end;
//-------------------------------------------------------------------------------------
// method called when the document finishes loading from Web Site Page
//-------------------------------------------------------------------------------------
method void OnDocumentCompletedWEB( elsystem.Object sender, WebBrowserDocumentCompletedEventArgs args )
variables:
XmlDocument doc,
XmlNodeList rows,
XmlNodeList cols,
int cnt,
string rawmargindata,
string xmlmargindata,
string singlechar,
int row,
int StartIndex,
int EndIndex;
begin
//-------------------------------------------------------------------------------------
// check if on a prior completed event everything needed was found
//-------------------------------------------------------------------------------------
if iLogSteps then
Print(string.Format("{0:MM/dd/yy HH:mm:ss} DocComplete-Web Complete={1}", DateTime.Now, WebDocComplete));
if WebDocComplete then return;
try
//-------------------------------------------------------------------------------------
// Search for starting string of table with both uppercase and lowercase - if neither
// found continue waiting for next completed event as it seems that sometimes the
// required information is not returned by the first completed event
//-------------------------------------------------------------------------------------
StartIndex = Browser.DocumentText.IndexOf(StartTagLC); //, 0, Browser.DocumentText.Length, StringComparison.CurrentCultureIgnoreCase); // documenttext contains the entire html page
//-------------------------------------------------------------------------------------
// Extract table information and perform some basic cleanup on the HTML text to make
// it XML loadable
//-------------------------------------------------------------------------------------
rawmargindata = Browser.DocumentText.Substring(StartIndex);
EndIndex = rawmargindata.IndexOf( endTagLC ); // find the end of the margin table - now using first endtag
if iLogSteps then
Print(string.Format("{0:MM/dd/yy HH:mm:ss} DocCompleted SX={1} EX={2}", DateTime.Now, StartIndex, EndIndex));
//-------------------------------------------------------------------------------------
// The following statement works with the new website as of 12/10/19
//-------------------------------------------------------------------------------------
rawmargindata = rawmargindata.Substring(0 , EndIndex + EndTagLC.Length ); // and strip everything after it.
//-------------------------------------------------------------------------------------
// the rawmargindata string is almost xml, but we need to get rid of ampersands
//
// NOTE: This is a bit flawed as we have the following in the code
// &
// &euro
// £
//-------------------------------------------------------------------------------------
xmlmargindata = rawmargindata.Replace("&", "" );
//-------------------------------------------------------------------------------------
// Load table into XMlDocument and then extract margin information from it
//-------------------------------------------------------------------------------------
doc = New XmlDocument(); // instantiate an xml document
doc.LoadXml( xmlmargindata ); // load in the xml string
// print(xmlmargindata);
CreateXmlDoc();
GetMargin( doc );
WriteXmlDoc(); // Maybe premature
GetMarginXML();
//-------------------------------------------------------------------------------------
// All done getting margin information
//-------------------------------------------------------------------------------------
WebDocComplete = true;
catch (Exception ex)
Print("OnDocumentCompleted Error: ", ex.Message );
if ex.InnerException <> NULL then Print( ex.InnerException.Message );
end;
//-------------------------------------------------------------------------------------
// All done - can get rid of browser form
//-------------------------------------------------------------------------------------
frmBrowser = NULL;
Browser = NULL;
end;
//-------------------------------------------------------------------------------------
// method called when the Xmldocument finishes loading from AWS
//-------------------------------------------------------------------------------------
method void OnDocumentCompletedAWS( elsystem.Object sender, WebBrowserDocumentCompletedEventArgs args )
variables:
string xmlmargindata;
begin
xmlmargindata = Browser.Documenttext.ToString();
try
XD.LoadXml(xmlmargindata);
WriteXmlDoc();
GetMarginXML();
catch (Exception ex)
//Print("OnDocumentCompleted Error: ", ex.Message );
//if ex.InnerException <> NULL then Print( ex.InnerException.Message );
end;
frmBrowser = NULL;
Browser = NULL;
end;
//-------------------------------------------------------------------------------------
// Extract margin information from scraped text from web page
//-------------------------------------------------------------------------------------
method void GetMargin( XmlDocument doc )
variables:
XmlNodeList rows,
XmlNodeList cols,
int RowIndex,
string SymDesc,
string SymRoot,
double InitMargin,
double MaintenanceMargin,
double DayRatePercent,
string SymExchange,
string SymCurrency,
string SymCurrencyChar,
string SymCategory,
string Work,
string SectionExchange,
Vector WorkSplit,
string WorkPart,
double IMPercent,
double MMPercent;
begin
try
//-------------------------------------------------------------------------------------
// Now xmlmargindata can contains the margin table and is more or less xml,
// let's load it into an xmldocument and parse the data
//-------------------------------------------------------------------------------------
rows = doc.GetElementsByTagName( tr );
if iLogSteps then
Print(string.Format("{0:MM/dd/yy HH:mm:ss} Extracting {1} Rows", DateTime.Now, rows.Count));
SymCategory = "";
for RowIndex = 1 to rows.Count - 1
begin
cols = rows.Item( RowIndex ).ChildNodes;
//-------------------------------------------------------------------------------------
// process header
//-------------------------------------------------------------------------------------
if cols <> NULL and Cols.Count > 00 and cols.Count < 05 then
begin
Work = cols.Item( 0 ).InnerText.ToUpper();
SymCategory = cols.Item( 0 ).InnerText;
SectionExchange = GetExchange(Work);
if iLogSteps then
Print(string.Format("{0:MM/dd/yy HH:mm:ss} Category {1} Rows", DateTime.Now, SymCategory));
Continue;
end;
//-------------------------------------------------------------------------------------
// Ignore rows with other than 5 columns as they are just headers
//-------------------------------------------------------------------------------------
if cols <> NULL and Cols.Count > 00 and cols.Count = 07 then
begin
SymDesc = cols.Item( 0 ).InnerText.Replace( "*", "" );
SymDesc = SymDesc.Replace( "amp;", "&" );
//print(SymDesc);
//-------------------------------------------------------------------------------------
// Get Symbol Root
//-------------------------------------------------------------------------------------
SymRoot = cols.Item( 1 ).InnerText;
SymRoot = OnlyUCAndDigits(SymRoot); // Remove any non-Uppercase nor non-digit characters
// print(SymRoot);
//-------------------------------------------------------------------------------------
// Get initial margin
//
// NOTE: If it starts with nn% then it is a Bitcoin future
//-------------------------------------------------------------------------------------
Work = cols.Item( 2 ).InnerText;
if cols.Item( 2 ).InnerText.Contains("%")
and double.TryParse(cols.Item( 2 ).InnerText.Substring(0, cols.Item( 2 ).InnerText.IndexOf("%")), IMPercent)
and cols.Item( 3 ).InnerText.Contains("%")
and double.TryParse(cols.Item( 3 ).InnerText.Substring(0, cols.Item( 3 ).InnerText.IndexOf("%")), MMPercent) then
begin
//-------------------------------------------------------------------------------------
// Bitcoin - Extract percent and multiple by open price
//-------------------------------------------------------------------------------------
SymCurrency ="USD";
SymCurrencyChar = USDCurrency;
InitMargin = GetBitcoinPercent(Work) * Open * 0.01;
end
else
begin
// print("Outside BTC Loop");
//-------------------------------------------------------------------------------------
// Non-dynamic margin
//-------------------------------------------------------------------------------------
// Get initial margin
//-------------------------------------------------------------------------------------
SymCurrency = GetSymCurrency( Work );
SymCurrencyChar = GetSymCurrencyChar( Work );
Work = GetValueWOCurrency( Work );
Work = Parsestringx( Work );
InitMargin = strtonum( Work );
// print("InitMargin");
// print(InitMargin);
//-------------------------------------------------------------------------------------
// Get maintenance margin
//-------------------------------------------------------------------------------------
Work = cols.Item( 3 ).InnerText;
Work = GetValueWOCurrency( Work );
Work = Parsestring( Work );
MaintenanceMargin = strtonum( Work );
// print("MaintenanceMargin");
// print(MaintenanceMargin);
//-------------------------------------------------------------------------------------
// Get day Rate
//-------------------------------------------------------------------------------------
Work = cols.Item( 6 ).InnerText.Trim();
// Print("DAYRATE: ", SymRoot, " ", Work);
if Work.ToUpper() = "NONE" then
begin
DayRatePercent = 100;
IMPercent = DayRatePercent;
MMPercent = DayRatePercent;
//Print(SymRoot, " ", "NONE Choosen");
end
else if Work.ToUpper().EndsWith("OF INITIAL") then
begin
WorkSplit = Work.ToUpper().Split(" ");
WorkPart = WorkSplit[0] astype string;
WorkPart = WorkPart.Trim();
if WorkPart.EndsWith("%") then WorkPart = Workpart.Substring(0, WorkPart.Length - 1);
DayRatePercent = 100;
if not double.TryParse(WorkPart, DayRatePercent) then
begin
Print("Unrecognized Day Rate % value: ", Work);
end;
IMPercent = DayRatePercent;
MMPercent = DayRatePercent;
end
else if Work.EndsWith("%") then
begin
//Print("Percent Substring");
WorkPart = Work.Substring(0, Work.Length - 1);
if double.TryParse(WorkPart, DayRatePercent) then
Begin
//Print("DayRateDoubleParse");
DayRatePercent = double.parse(WorkPart);
//Print(SymRoot, " ", DayRatePercent, " ", WorkPart);
end;
end
else
begin
//print("in garbage");
//print (cols.Item(6).InnerText.Trim());
DayRatePercent = 100;
IMPercent = DayRatePercent;
MMPercent = DayRatePercent;
end;
end;
//Print("ended");
//-------------------------------------------------------------------------------------
// Exchange
//-------------------------------------------------------------------------------------
SymExchange = GetExchange( SymDesc );
if SymExchange = "" then
begin
SymExchange = SectionExchange;
end;
//-------------------------------------------------------------------------------------
// Remove Exchange from description
//-------------------------------------------------------------------------------------
SymDesc = Symdesc.Replace( "(" + SymExchange + ")", "" );
//-------------------------------------------------------------------------------------
// Add element with attributes to XML Document
//-------------------------------------------------------------------------------------
//print("inLoadGD");
If LoadGD then
begin
If MR.Contains(SymRoot) = FALSE then
begin
MR.ADD(SymRoot,InitMargin);
End
else
begin
If MR.Items[SymRoot] <> InitMargin then
MR.Items[SymRoot] = InitMargin;
end;
end;
XE = XD.CreateElement( "SymbolRoot" );
XE.SetAttribute( "Root", SymRoot );
XE.SetAttribute( "Exch", SymExchange );
XE.SetAttribute( "Cur", SymCurrency );
XE.SetAttribute( "CurChar", SymCurrencyChar );
XE.SetAttribute( "InitMrgn", Numtostr( InitMargin, 0 ) );
XE.SetAttribute( "MaintMrgn", Numtostr( MaintenanceMargin, 0) );
XE.SetAttribute( "DRPct", Numtostr( DayRatePercent, 0 ) );
XE.SetAttribute( "Desc", SymDesc );
XE.SetAttribute( "Updtd", DateTime.Now.Format(MDYHMSFormat) );
XNSymbolRoots.AppendChild( XE );
//Print(XNSymbolRoots.Childnodes.Count);
end;
end;
catch (Exception ex)
Print("GetMargin Error: ", ex.Message );
end;
end;
method double GetBitcoinPercent(string text)
variables:
int Ndx,
double Value;
begin
Ndx = text.IndexOf("%");
if Ndx > 0 and double.TryParse(text.Substring(0, Ndx), Value) then
begin
return Value;
end
else
begin
return 0;
end;
end;
//-------------------------------------------------------------------------------------
// Check for UpperCase and Digits
//-------------------------------------------------------------------------------------
method string OnlyUCAndDigits(string input)
variables:
int Ndx,
string NewString;
begin
NewString = "";
for Ndx = 0 to input.Length - 1
begin
if UpperCaseAndDigits.IndexOf(input.Substring(Ndx, 1), 0, UpperCaseAndDigits.Length - 1) >= 0 then
NewString = NewString + input.Substring(Ndx, 1);
end;
return NewString;
end;
//-------------------------------------------------------------------------------------
// Determine currency from HTML
//-------------------------------------------------------------------------------------
method string GetSymCurrency( string stp )
variables:
int Index,
string TestCurrency;
begin
if stp.StartsWith("$") then return "USD";
if stp.StartsWith("pound;")
or stp.StartsWith("£") then return "GBP";
if stp.StartsWith("euro;")
or stp.StartsWith("€") then return "EUR";
for Index = 0 to CurrencyListTL.Count - 1
begin
TestCurrency = CurrencyListTL.Item[Index] astype string;
if stp.StartsWith(TestCurrency) then return TestCurrency;
end;
return "XXX";
end;
//-------------------------------------------------------------------------------------
// Determine currency character from HTML
//-------------------------------------------------------------------------------------
method string GetSymCurrencyChar( string stp )
variables:
int Index,
string TestCurrency;
begin
if stp.StartsWith("$") then return USDCurrency;
if stp.StartsWith("pound;")
or stp.StartsWith("£") then return GBPCurrency;
if stp.StartsWith("euro;")
or stp.StartsWith("€") then return EURCurrency;
if stp.StartsWith("CHF") then return CHFCurrency;
for Index = 0 to CurrencyListTL.Count - 1
begin
TestCurrency = CurrencyListTL.Item[Index] astype string;
if stp.StartsWith(TestCurrency) then return TestCurrency;
end;
return "XXX";
end;
//-------------------------------------------------------------------------------------
// Get the value without the currency
//-------------------------------------------------------------------------------------
method string GetValueWOCurrency( string stp )
variables:
int Index,
string Work,
string TestCurrency;
begin
if stp.Substring(0, 1) = "$" then return stp.Substring(1);
if stp.StartsWith("pound;") then return stp.Substring("pound;".Length - 1);
if stp.StartsWith("£") then return stp.Substring(1);
if stp.StartsWith("euro;") then return stp.Substring("euro;".Length - 1);
if stp.StartsWith("€") then return stp.Substring(1);
//-------------------------------------------------------------------------------------
// Check for string representation of currecny
//-------------------------------------------------------------------------------------
for Index = 0 to CurrencyListTL.Count - 1
begin
TestCurrency = CurrencyListTL.Item[Index] astype string + " ";
if stp.StartsWith(TestCurrency) then return stp.Replace(TestCurrency, "").Trim();
end;
return "0";
end;
#region - Remove Currency and commas from string -
//-------------------------------------------------------------------------------------
// Removes Currency and commas
//-------------------------------------------------------------------------------------
method string Parsestring( string stp )
variables:
string work,
int x,
string ts1,
string ts2;
begin
work = stp;
if work.StartsWith("$") or work.StartsWith("£") or work.StartsWith("€") then
work = rightstr( work, Strlen( work ) - 1 );
work = work.Replace(",", "");
return work;
end;
#endregion
//-------------------------------------------------------------------------------------
// Removes Currency and commas
//-------------------------------------------------------------------------------------
method string Parsestringx( string stp )
variables:
string work,
int x,
string ts1,
string ts2;
begin
work = stp;
if work.StartsWith("$") or work.StartsWith("£") or work.StartsWith("€") then
work = rightstr( work, Strlen( work ) - 1 );
work = work.Replace(",", "");
return work;
end;
//-------------------------------------------------------------------------------------
// Extract Exchange
//-------------------------------------------------------------------------------------
method string GetExchange( string work )
begin
if instr( work, "(CME)" ) > 0 then return "CME";
if instr( work, "(CBOT)" ) > 0 then return "CBOT";
if instr( work, "(COMEX)" ) > 0 then return "COMEX";
if instr( work, "(ICE)" ) > 0 then return "ICE";
if instr( work, "(NYMEX)" ) > 0 then return "NYMEX";
if instr( work, "LIFFE" ) > 0 then return "LIFFE"; // Without ()
if instr( work, "EUREX" ) > 0 then return "EUREX"; // Without ()
if work = "INDEXES" then return "CME";
// Handle mislabeled items
if instr( work, "MINI DOW JONES") > 0
or instr( work, "Micro YM") > 0 then return "CBOT";
return "";
end;
#endregion
#region - XML Document Methods -
//-------------------------------------------------------------------------------------
// Create an XML Document and export it to a file emulating a serialized object
//-------------------------------------------------------------------------------------
method void CreateXmlDoc()
begin
XD = XmlDocument.Create();
XD.AppendChild(XD.CreateElement( "FuturesMargin" ));
XNSymbolRoots = XD.CreateElement( "SymbolRoots" );
XD.DocumentElement.AppendChild( XNSymbolRoots );
end;
//-------------------------------------------------------------------------------------
// Load XMLDocument from a file in the MyWork directory if available
//-------------------------------------------------------------------------------------
method bool LoadXmlDoc()
variables:
string FilePath,
XmlElement XEDE,
XmlElement XESymbolsRoot,
XmlElement XESymbol,
DateTime Updated;
begin
FilePath = elsystem.Environment.GetMyWorkDirectory() + "/" + XmlDocName;
try
XD.Load(FilePath);
//-------------------------------------------------------------------------------------
// Check that XML has a root element with corrct name
//-------------------------------------------------------------------------------------
XEDE = XD.DocumentElement;
if XEDE <> null and XEDE.Name = "FuturesMargin" and XEDE.ChildNodes.Count = 1 then
begin
//-------------------------------------------------------------------------------------
// Check that XML has a root element with corrct name
//-------------------------------------------------------------------------------------
XESymbolsRoot = XEDE.FirstChild astype XmlElement;