-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathForm1.cs
3750 lines (3256 loc) · 143 KB
/
Form1.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;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using XTAPI;
using LOG;
namespace X_Platform2
{
/// <summary>
/// Main Application form
/// </summary>
public partial class Form1 : Form
{
#region Variables
/// <summary>
/// Create two log file classes, log for application actions and prc for Time and sales
/// </summary>
private LogFiles log = null;
private LogFiles prc = null;
/// <summary>
/// Instantiate XTAPI Objects
/// </summary>
private XTAPI.TTGateClass ttGate = null;
private XTAPI.TTDropHandler ttDropHandler = null;
private XTAPI.TTInstrNotifyClass ttInstrNotify = null;
private XTAPI.TTInstrNotifyClass ttInstrNotifyLast = null;
private XTAPI.TTInstrNotifyClass ttInstrNotifyOpen = null;
private XTAPI.TTInstrObj ttInstrObj = null;
private XTAPI.TTOrderSetClass ttOrderSet = null;
private bool isOn = false; //Application on or off - true/false
private bool isContractFound = false; //Is the contract loaded?
private bool isOrderServerUP = false; //Is the TT Order Server connected?
private bool isPriceServerUP = false; //Is the TT Price Server connected?
private bool isFillServerUP = false; //Is the TT Fill Server connected?
private bool isOpenDelivered = false; //Has exchange open price been delivered?
private bool isOpenComparedToLast = false; //Has open been checked against first last print?
private bool isOpenCaptured = false; //Should the application capture open from last print at start time?
internal bool isExchangeOpenUsed = true; //By default, use official exchange open price.
private bool isOrderCalculated = false; //Have orders been calculated?
private bool isOrderQueued = false; //Has the next order been queued up?
private bool isAllocationDataVerified = false; //If alloc file is verified allocations are created.
private bool isTradingLimitDisabled = false; //debug purposes disable trading limits
private bool isAutoSendAllocationsOn = false;
private bool isRollContractDropped = false;
private bool isLimitOrderSent = false; //syntheticSL is order sent
private bool isOrderHung = false;
private bool isCustomAllocLoaded = false;
/// <summary>
/// If the application is started with command line parameter /auto bAlertOn is set to false
/// bAlertOn: by default (true) All alerting functions are on.
/// ALGO: nativeSL
/// true: orders submit on hold
/// false: orders submit active at the exchange
/// ALGO: syntheticSL
/// true: Alert sounds when order submitted
/// false: no alert on order submission
///
/// false: no compare last/open alert
/// </summary>
private bool isAlertOn = true;
//only needed if depth is enabled
//private Array aBidDepth;
//private Array aAskDepth;
private string siteOrderKey = null; //Variable to store TT Order key
private string msgAlert = "ALERT: EXECUTION ALERT";
private decimal oneTick = 0; //value of 1 tick in decimals
//Trading parameters
private int ordNum = 1;
private decimal tradePrice1 = 0;
private decimal tradePrice2 = 0;
private decimal last = 0;
private int lstQty = 0;
internal decimal open = 0;
private decimal priorOpen = 0; //track changes in open price
private int tradeQty = 0;
private int fillQty = 0;
private int fillCount = 0;
private decimal stopPrice = 0;
private string buySell = null;
private decimal limitPrice = 0;
private string ttGateway = null;
private string ttProduct = null;
private string ttProductType = "FUTURE";
private string ttContract = null;
private string ttCustomer = "XTAPI";
private string contractDescription = null;
//these variables are set from MDR data
internal string longShort = null; //S or L
private int startPosition = 0;
private int mdrQty1 = 0;
private int mdrQty2 = 0;
internal decimal buystop = 0;
internal decimal bV = 0;
internal decimal sellstop = 0;
private decimal dV = 0;
private TimeSpan startTime;
private TimeSpan stopTime;
// ^ above is current MDR data
private decimal StdAllocMultiplier = 1M;
private decimal CustomAllocMultiplier = 1M;
/// <summary>
/// table for contract data
/// </summary>
public DataSet setMDRData = new DataSet("MDR_Data");
private DataTable tblContract = null;
/// <summary>
/// allocation data setup
/// </summary>
private DataSet setAllocData = new DataSet("Allocation");
private DataTable tblAccounts = null;
private DataTable tblSetup = null;
//email variables setup
private DataSet setINI = new DataSet("INI");
private DataTable tblAddress = null;
private DataTable tblParameters = null;
private DataTable tblStartup = null;
private string msgBody = string.Empty;
//custom templar allocation
private DataSet setCustom = new DataSet("CustomAllocation");
private DataTable tblAddress1 = null;
private DataTable tblTemplar = null;
private SortedDictionary<decimal, int> fillList = new SortedDictionary<decimal, int>();
private SortedDictionary<int, int> qty1Alloc = new SortedDictionary<int, int>();
private SortedDictionary<int, int> qty2Alloc = new SortedDictionary<int, int>();
private SortedDictionary<int, string> accountNumbers = new SortedDictionary<int, string>();
private Color lstColor = Color.LightGray;
private string algo = "syntheticSL";
private enum Algorithm
{
syntheticSL,
nativeSL,
stopMarket
}
private Algorithm currentAlgo = Algorithm.syntheticSL;
#endregion
/// <summary>
/// Main Form
/// </summary>
public Form1()
{
InitializeComponent();
}
/// <summary>
/// Load TT Objects , register events, run startup procedures
/// </summary>
/// <param name="sender">not used</param>
/// <param name="e">not used</param>
private void Form1_Load(object sender, EventArgs e)
{
log = new LogFiles(this.listBox1, "X_PLATFORM");
prc = new LogFiles(this.listBox1, "Prices");
log.CleanLog();
log.WriteLog("Form1_Load");
log.WriteLog(Application.ExecutablePath);
log.WriteLog(Application.ProductVersion);
ttGate = new XTAPI.TTGateClass();
ttInstrObj = new XTAPI.TTInstrObj();
ttDropHandler = new XTAPI.TTDropHandlerClass();
ttInstrNotify = new XTAPI.TTInstrNotifyClass();
ttInstrNotifyLast = new TTInstrNotifyClass();
ttInstrNotifyOpen = new TTInstrNotifyClass();
ttOrderSet = new XTAPI.TTOrderSetClass();
ttInstrObj.MergeImpliedsIntoDirect = 1;
// Subscribe to the OnExchangeStateUpdate.
ttGate.OnExchangeStateUpdate +=
new XTAPI._ITTGateEvents_OnExchangeStateUpdateEventHandler(TTGate_OnExchangeStateUpdate);
ttGate.OnStatusUpdate +=
new XTAPI._ITTGateEvents_OnStatusUpdateEventHandler(TTGate_OnStatusUpdate);
// Setup the instrument notification call back functions
ttInstrNotify.OnNotifyFound +=
new XTAPI._ITTInstrNotifyEvents_OnNotifyFoundEventHandler(this.TTInstrNotify_OnNotifyFound);
ttInstrNotify.OnNotifyNotFound +=
new _ITTInstrNotifyEvents_OnNotifyNotFoundEventHandler(TTInstrNotify_OnNotifyNotFound);
//m_TTInstrNotify.OnNotifyUpdate +=
//new XTAPI._ITTInstrNotifyEvents_OnNotifyUpdateEventHandler(m_TTInstrNotify_OnNotifyUpdate);
//m_TTInstrNotify.OnNotifyDepthData +=
// new XTAPI._ITTInstrNotifyEvents_OnNotifyDepthDataEventHandler(m_TTInstrNotify_OnNotifyDepthData);
// Subscribe to the fill events.
ttDropHandler.OnNotifyDrop +=
new XTAPI._ITTDropHandlerEvents_OnNotifyDropEventHandler(this.TTDropHandler_OnNotifyDrop);
ttOrderSet.OnOrderFillData +=
new XTAPI._ITTOrderSetEvents_OnOrderFillDataEventHandler(TTOrderSet_OnOrderFillData);
ttOrderSet.OnOrderRejected +=
new XTAPI._ITTOrderSetEvents_OnOrderRejectedEventHandler(TTOrderSet_OnOrderRejected);
ttOrderSet.OnOrderSetUpdate +=
new XTAPI._ITTOrderSetEvents_OnOrderSetUpdateEventHandler(TTOrderSet_OnOrderSetUpdate);
// Enable the TTOrderTracker.
//ttOrderSet.EnableOrderUpdateData = 1;
// Register the active form for drag and drop.
ttDropHandler.RegisterDropWindow((int)this.Handle);
// Enable the depth updates.
//ttInstrNotify.EnableDepthUpdates = 1;
ttInstrNotifyLast.EnablePriceUpdates = 1;
ttInstrNotifyLast.UpdateFilter = "Last,LastQty";
ttInstrNotifyLast.OnNotifyUpdate +=
new _ITTInstrNotifyEvents_OnNotifyUpdateEventHandler(TTInstrNotifyLast_OnNotifyUpdate);
ttInstrNotifyOpen.EnablePriceUpdates = 1;
ttInstrNotifyOpen.UpdateFilter = "OPEN";
ttInstrNotifyOpen.OnNotifyUpdate +=
new _ITTInstrNotifyEvents_OnNotifyUpdateEventHandler(TTInstrNotifyOpen_OnNotifyUpdate);
_LoadMDR();
_LoadAlloc();
_LoadINI();
_LoadCustomAlloc();
_processCustomParameters();
_displayParameters(false); //record parameters in logfile
_connectExchange();
//_ChkCustomers();
button5.Enabled = true;
lblOrder.Text = string.Empty;
_verifyDirectoryStructure();
}
/// <summary>
/// closing cleanup
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
log.WriteLog("Form1_FormClosing");
log.WriteLog(e.CloseReason.ToString());
log.CloseLog();
prc.CloseLog();
}
/// <summary>
/// verify that the expected directory structure is present
/// </summary>
private void _verifyDirectoryStructure()
{
_VerifyDirectory(@"\..\_alerts");
_VerifyDirectory(@"\..\_allocations");
_VerifyDirectory(@"\..\_allocations\archive");
_VerifyDirectory(@"\..\_allocCustom");
_VerifyDirectory(@"\..\_allocCustom\archive");
_ArchiveFiles(@"\..\_allocations", "MMddyy");
_ArchiveFiles(@"\..\_allocCustom", "yyyyMMdd");
}
/// <summary>
/// move previous day files to archive folder
/// </summary>
/// <param name="dir"></param> directory to scan
/// <param name="DateFormat"></param> date format found in file to determine what trade date the file belongs to
private void _ArchiveFiles(string dir, string DateFormat)
{
try
{
string[] files = Directory.GetFiles(Application.StartupPath.ToString() + dir);
foreach (string fn in files)
{
log.WriteLog(_tradeDate(DateFormat));
//move files to processed folder if trade date does not match
if (!fn.Contains(_tradeDate(DateFormat)))
{
log.WriteLog(fn);
int i = fn.LastIndexOf(@"\");
string tmp = fn.Substring(i + 1);
log.LogListBox(tmp);
try
{
if (File.Exists(fn.Insert(i + 1, @"archive\")))
{ File.Delete(fn); }
else
{ File.Move(fn, fn.Insert(i + 1, @"archive\")); }
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
}
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// verify a single directory exists, if not create it
/// </summary>
/// <param name="d1"></param>
private void _VerifyDirectory(string d1)
{
try
{
bool blnDirectoryExists = Directory.Exists(Application.StartupPath.ToString() + d1);
if (!blnDirectoryExists)
{
Directory.CreateDirectory(Application.StartupPath.ToString() + d1);
}
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// Custom Parameters
/// /auto = auto mode
/// ALGO: nativeSL - orders submit active at the exchange
/// ALGO: stopMarket - sound alert when order activated
///
/// /NOLIMIT - DEBUG PURPOSES removes trading limits
///
/// /x:## /y:## if used both required
/// specify desktop location of application form in pixels
/// </summary>
private void _processCustomParameters()
{
string[] args = Environment.GetCommandLineArgs();
log.LogListBox("Command Line Args: " + args.Length.ToString());
int x = -10000;
int y = -10000;
foreach (string arg in args)
{
log.LogListBox(arg.ToUpperInvariant());
if (arg.ToUpperInvariant().Equals("/AUTO") || arg.ToUpperInvariant().Equals("AUTO"))
{
isAlertOn = false;
log.LogListBox("AUTO MODE ENABLED");
//nativeSL submits orders live to the exchange instead of placing on hold
//no change for other algorithms
}
if (arg.ToUpperInvariant().Equals("/NOLIMIT"))
{
isTradingLimitDisabled = true;
log.LogListBox("TRADING LIMITS DISABLED");
}
if (arg.ToUpperInvariant().Contains("/X:"))
{ x = Convert.ToInt32(arg.Substring(3)); }
if (arg.ToUpperInvariant().Contains("/Y:"))
{ y = Convert.ToInt32(arg.Substring(3)); }
}
if (x != -10000 && y != -10000)
{
log.LogListBox(string.Format("Custom Desktop Location {0}x{1}", x, y));
this.DesktopLocation = new Point(x, y);
}
else
{ _setDesktopLocation(); }
}
/// <summary>
/// hardcoded location for existing products
/// </summary>
private void _setDesktopLocation()
{
if (SystemInformation.WorkingArea.Width == 1920 && SystemInformation.WorkingArea.Height >= 1170)
{
switch (ttProduct)
{
case "6E":
this.DesktopLocation = new Point(0, 0);
break;
case "6J":
this.DesktopLocation = new Point(0, this.Height);
break;
case "Sugar No 11":
this.DesktopLocation = new Point(this.Width, 0);
break;
case "6C":
this.DesktopLocation = new Point(this.Width, this.Height);
break;
case "ZN":
this.DesktopLocation = new Point(this.Width * 2, 0);
break;
case "GC":
this.DesktopLocation = new Point(this.Width * 2, this.Height);
break;
case "SI":
this.DesktopLocation = new Point(this.Width * 3, 0);
break;
case "NQ":
this.DesktopLocation = new Point(this.Width * 3, this.Height);
break;
case "CL":
this.DesktopLocation = new Point(this.Width * 4, 0);
break;
case "NG":
this.DesktopLocation = new Point(this.Width * 4, this.Height);
break;
case "ZC":
this.DesktopLocation = new Point(this.Width * 5, 0);
break;
case "ZS":
this.DesktopLocation = new Point(this.Width * 5, this.Height);
break;
case "FGBL":
this.DesktopLocation = new Point(0, this.Height * 2);
break;
case "FESX":
this.DesktopLocation = new Point(this.Width, this.Height * 2);
break;
case "FDAX":
this.DesktopLocation = new Point(this.Width * 2, this.Height * 2);
break;
case "NK":
this.DesktopLocation = new Point(this.Width, 0);
break;
case "TSE JGB":
this.DesktopLocation = new Point(this.Width * 2, 0);
break;
case "HKFE HSI":
this.DesktopLocation = new Point(this.Width * 3, 0);
break;
default:
log.LogListBox("Desktop Location NOT customized for : "+ttProduct );
break;
}
}
}
/// <summary>
/// custom form setup for different algorithms
/// </summary>
private void _ALGOsetup()
{
log.LogListBox("ALGO: " + algo);
switch (algo)
{
case "nativeSL":
currentAlgo = Algorithm.nativeSL;
break;
case "syntheticSL":
currentAlgo = Algorithm.syntheticSL;
this.listBox1.BackColor = Color.Yellow;
break;
case "stopMarket":
currentAlgo = Algorithm.stopMarket;
label1.Text = "Trigger";
break;
default:
log.LogListBox(algo + " NOT SET UP CORRECTLY!!");
break;
}
groupBox3.Text = string.Format("Active Order: {0} - ALGO: {1}", ordNum, currentAlgo.ToString());
}
/// <summary>
/// handles rejected orders differently for different algorithms
/// </summary>
/// <param name="sok"></param>
/// <param name="msg"></param>
private void _ALGO_OnOrderRejected(string sok, string msg)
{
if (sok == siteOrderKey)
{
switch (algo)
{
case "syntheticSL":
if (sok == siteOrderKey)
{ isLimitOrderSent = false; }
break;
case "stopMarket":
case "nativeSL":
default:
break;
}
siteOrderKey = null;
}
msgAlert = "ALERT: ORDER REJECTED " + msg;
log.LogListBox(msgAlert);
AlertTimer.Interval = 1000;
AlertTimer.Start();
}
/// <summary>
/// load contract data from CONTRACT.XML File.
/// Application cannot run without a CONTRACT.XML File
/// </summary>
internal void _LoadMDR()
{
log.WriteLog("_LoadDT");
try
{
if (File.Exists("CONTRACT.XML"))
{
log.LogListBox("CONTRACT.XML file Exists");
setMDRData.Clear();
setMDRData.ReadXml("CONTRACT.XML");
tblContract = setMDRData.Tables[0];
DataRow dr = tblContract.Rows[0];
try
{
ttGateway = dr["Gateway"].ToString();
ttProduct = dr["Product"].ToString();
ttProductType = dr["ProdType"].ToString();
ttContract = dr["Contract"].ToString();
startPosition = Convert.ToInt32(dr["CurPos"]);
longShort = dr["PosDir"].ToString();
mdrQty1 = Convert.ToInt32(dr["Q1"]);
if (longShort == "S")
{ buystop = Convert.ToDecimal(dr["StopPrc"]); }
else
{ sellstop = Convert.ToDecimal(dr["StopPrc"]); }
bV = Convert.ToDecimal(dr["bV"]);
dV = Convert.ToDecimal(dr["dV"]);
mdrQty2 = Convert.ToInt32(dr["Q2"]);
startTime = TimeSpan.Parse(dr["StartTime"].ToString());
stopTime = TimeSpan.Parse(dr["StopTime"].ToString());
//only set bOpenCapture to true if the application is loaded before trading time
//bOpenCapture default value is false
if (!_isValidTradingTime()) { isOpenCaptured = Convert.ToBoolean(dr["bCaptureOpen"]); }
if (isOpenCaptured) { isExchangeOpenUsed = false; }
algo = dr["ALGO"].ToString();
_ALGOsetup();
nudOffSet.Value = Math.Max(Convert.ToDecimal(dr["offset"]),nudOffSet.Minimum);
this.Text = string.Format("{0} not yet loaded", ttContract);
fillQty = mdrQty1;
contractDescription = dr["Description"].ToString();
}
catch (Exception ex)
{
MessageBox.Show("MDR Data not loaded!\r\nError in CONTRACT.XML data file\r\nMESSAGE: " + ex.Message,ttContract );
log.WriteLog("MDR Data not loaded!\r\nError in CONTRACT.XML data file");
log.WriteLog(ex.ToString());
}
}
else
{ log.LogListBox("CONTRACT.XML file does not exist"); }
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// Load ALLOC.XML containing allocation data fro trades 1 and 2 quantities
/// application can run without ALLOC.XML file but no allocations will be sent
/// </summary>
private void _LoadAlloc()
{
log.WriteLog("_LoadAlloc");
try
{
int qty1Tot = 0;
int qty2Tot = 0;
if (File.Exists("ALLOC.XML"))
{
log.LogListBox("ALLOC.XML file Exists");
setAllocData.ReadXml("ALLOC.XML");
if (setAllocData.Tables.Contains("accounts"))
{
tblAccounts = setAllocData.Tables[0];
foreach (DataRow row in tblAccounts.Rows)
{
qty1Alloc[Convert.ToInt32(row[2])] = Convert.ToInt32(row[0]);
qty1Tot += Convert.ToInt32(row[0]);
qty2Alloc[Convert.ToInt32(row[2])] = Convert.ToInt32(row[1]);
qty2Tot += Convert.ToInt32(row[1]);
accountNumbers[Convert.ToInt32(row[2])] = row[3].ToString();
}
}
else
{ log.LogListBox("No allocation data found"); }
if (setAllocData.Tables.Contains("setup"))
{
tblSetup = setAllocData.Tables[1];
foreach (DataColumn col in tblSetup.Columns)
{
log.WriteLog("setup Table Column: " + col.ColumnName);
if (string.Equals(col.ColumnName, "PriceMultiplier", StringComparison.OrdinalIgnoreCase))
{
StdAllocMultiplier = Convert.ToDecimal(tblSetup.Rows[0].ItemArray[col.Ordinal]);
if (StdAllocMultiplier != 0)
{ log.LogListBox("Allocation Price Multiplier: " + StdAllocMultiplier.ToString()); }
else
{
StdAllocMultiplier = 1;
log.LogListBox("Allocation Price Multiplier ERROR, using default multiplier of 1.00 ");
}
}
//start here
if (string.Equals(col.ColumnName, "Open", StringComparison.OrdinalIgnoreCase))
{
decimal savedOpen = 0;
savedOpen = Convert.ToDecimal(tblSetup.Rows[0].ItemArray[col.Ordinal]);
if (savedOpen != 0)
{
open = savedOpen;
nudOpen.Value = savedOpen;
chkBxOpen.Checked = true;
isOpenCaptured = false;
isExchangeOpenUsed = false;
isOpenDelivered = true;
log.LogListBox("Saved Open Price: " + savedOpen.ToString());
}
}
if (string.Equals(col.ColumnName, "OrdNum", StringComparison.OrdinalIgnoreCase))
{
int lastOrdNum = 0;
lastOrdNum = Convert.ToInt32(tblSetup.Rows[0].ItemArray[col.Ordinal]);
if (lastOrdNum != 0)
{
ordNum = lastOrdNum;
log.LogListBox("Saved Order Number: " + lastOrdNum.ToString());
if (lastOrdNum > 1) { fillQty = mdrQty2; }
}
}
//stop here
}
}
log.LogListBox(string.Format("Alloc Q1: {0} account #'s - Total Qty: {1}", qty1Alloc.Count, qty1Tot));
log.LogListBox(string.Format("Alloc Q2: {0} account #'s - Total Qty: {1}", qty2Alloc.Count, qty2Tot));
if (mdrQty1 != qty1Tot || mdrQty2 != qty2Tot)
{
string msg = "Error in Allocation data\r\n" +
"Total Quantity does not match Trade Quantity\r\n" +
"allocation files will be incorrect";
log.WriteLog(msg);
MessageBox.Show(msg,ttContract );
}
else
{
log.LogListBox("Allocation data matches trade data");
log.LogListBox("Allocation files will be automatically generated");
}
}
else
{ log.LogListBox("ALLOC.XML file does not exist"); }
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// Load email settings, and optionally the saved open and ordnum
/// if the application has been restarted during the day
/// </summary>
private void _LoadINI()
{
log.WriteLog("Load Email Parameters");
try
{
if (File.Exists("INI.XML"))
{
log.LogListBox("INI.XML file Exists");
setINI.ReadXml("INI.XML");
log.LogListBox("INI.XML: Data Loaded");
//set up email address table
//record email recipients in log file
if (setINI.Tables.Contains("address"))
{
tblAddress = setINI.Tables["address"];
log.WriteLog("Allocation Email Recipients:");
foreach (DataRow row in tblAddress.Rows)
{
log.WriteLog(row.ItemArray[0].ToString());
}
}
//setup email
if (setINI.Tables.Contains("parameters"))
{
tblParameters = setINI.Tables["parameters"];
bool[] verifyColumns = new bool[6];
DataRow r = tblParameters.Rows[0];
log.WriteLog("Email Server Details:");
foreach (DataColumn col in tblParameters.Columns)
{
log.WriteLog(string.Format("{0} : {1}", col.ColumnName, r[col.ColumnName].ToString()));
}
if (tblParameters.Columns.Contains("FROM")) { verifyColumns[0] = true; }
if (tblParameters.Columns.Contains("SERVER")) { verifyColumns[1] = true; }
if (tblParameters.Columns.Contains("PORT")) { verifyColumns[2] = true; }
if (tblParameters.Columns.Contains("SSL")) { verifyColumns[3] = true; }
if (tblParameters.Columns.Contains("LOGIN")) { verifyColumns[4] = true; }
if (tblParameters.Columns.Contains("PWORD")) { verifyColumns[5] = true; }
bool IsEmailSetup = true;
int i =0;
foreach (bool item in verifyColumns)
{
if (!item)
{
log.LogListBox("MISSING EMAIL PARAMETER: " + tblParameters.Columns[i].ColumnName );
IsEmailSetup = false;
}
i++;
}
if (IsEmailSetup) { isAutoSendAllocationsOn = true; }
}
//load saved data for current trade date
bool IsCurrentDaySaved = false;
if (setINI.Tables.Contains("startup"))
{
tblStartup = setINI.Tables["startup"];
if (setINI.Tables["startup"].Columns.Contains("TRADEDATE"))
{
log.WriteLog("setup Table Column: " + "TRADEDATE");
int i = setINI.Tables["startup"].Columns["TRADEDATE"].Ordinal;
string savedDate = Convert.ToString(tblStartup.Rows[0].ItemArray[i]);
if (string.Equals(savedDate, _tradeDate("MMddyy")))
{
log.LogListBox(string.Format("INI.XML: SavedDate: {0} matches Tradedate: {1}", savedDate, _tradeDate("MMddyy")));
IsCurrentDaySaved = true;
}
else
{ log.LogListBox("INI.XML: Saved Trade date does not match"); }
}
if (IsCurrentDaySaved)
{
if (setINI.Tables["startup"].Columns.Contains("OPEN"))
{
log.WriteLog("setup Table Column: " + "OPEN");
int i = setINI.Tables["startup"].Columns["OPEN"].Ordinal;
decimal savedOpen = Convert.ToDecimal(tblStartup.Rows[0].ItemArray[i]);
if (savedOpen != 0)
{
open = savedOpen;
nudOpen.Value = savedOpen;
chkBxOpen.Checked = true;
isOpenCaptured = false;
isExchangeOpenUsed = false;
isOpenDelivered = true;
log.LogListBox("Saved Open Price: " + savedOpen.ToString());
}
else
{ log.LogListBox("INI.XML: Saved open = 0"); }
}
if (setINI.Tables["startup"].Columns.Contains("ORDNUM"))
{
log.WriteLog("setup Table Column: " + "ORDNUM");
int i = setINI.Tables["startup"].Columns["ORDNUM"].Ordinal;
int savedOrdNum = Convert.ToInt32(tblStartup.Rows[0].ItemArray[i]);
if (savedOrdNum != 0)
{
ordNum = savedOrdNum;
log.LogListBox("Saved Order Number: " + savedOrdNum.ToString());
if (savedOrdNum > 1) { fillQty = mdrQty2; }
}
else
{ log.LogListBox("INI.XML: Saved OrdNum = 0"); }
}
}
}
if (setINI.Tables.Contains("location"))
{
//not implemented - possible replacement for custom startup parameters
}
}
else
{ log.LogListBox("INI.XML file does not exist"); }
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// Load Templar allocation parameters
/// </summary>
private void _LoadCustomAlloc()
{
try
{
if (File.Exists("CUSTOMALLOC.XML"))
{
log.LogListBox("CUSTOMALLOC.XML file Exists");
setCustom.ReadXml("CUSTOMALLOC.XML");
log.LogListBox("CUSTOMALLOC.XML: Data Loaded");
if (setCustom.Tables.Contains("address1"))
{
tblAddress1 = setCustom.Tables["address1"];
log.WriteLog("Allocation Email Recipients:");
foreach (DataRow row in tblAddress1.Rows)
{
log.LogListBox(row.ItemArray[0].ToString());
}
}
if (setCustom.Tables.Contains("templar"))
{
tblTemplar = setCustom.Tables["templar"];
DataRow r = tblTemplar.Rows[0];
log.WriteLog("Templar Details:");
foreach (DataColumn col in tblTemplar.Columns)
{
log.WriteLog(string.Format("{0} : {1}", col.ColumnName, r[col.ColumnName].ToString()));
}
log.WriteLog("finished Loading Templar Details");
isCustomAllocLoaded = true;
}
if (setCustom.Tables.Contains("multiplier"))
{
DataTable dt = setCustom.Tables["multiplier"];
if (dt.Rows.Count == 1)
{
CustomAllocMultiplier = Convert.ToDecimal(dt.Rows[0].ItemArray[0]);
log.WriteLog("CustomAllocMultiplier: " + CustomAllocMultiplier.ToString());
}
}
}
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
//deprecated - using _saveCurrentDaySettingINI() & INI.XML file for OPEN and ORDNUM
private void _saveCurrentDaySetting(string col, object value)
{
try
{
if (setAllocData.Tables.Contains("setup"))
{
if (!tblSetup.Columns.Contains(col)) { tblSetup.Columns.Add(col, value.GetType()); }
DataRow currentDay = tblSetup.Rows[0];
currentDay[col] = value;
setAllocData.WriteXml("ALLOC.XML");
}
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// persists Current tradedate, OrdNum and Open price in INI.XML file
/// </summary>
internal void _saveCurrentDaySettingINI()
{
try
{
if (!setINI.Tables.Contains("startup"))
{
tblStartup = new DataTable("startup");
setINI.Tables.Add(tblStartup);
log.LogListBox("ADD TABLE");
}
if (!setINI.Tables["startup"].Columns.Contains("TRADEDATE"))
{
setINI.Tables["startup"].Columns.Add("TRADEDATE", typeof(string));
log.LogListBox("COLUMN ADDED");
}
if (!setINI.Tables["startup"].Columns.Contains("OPEN"))
{
setINI.Tables["startup"].Columns.Add("OPEN", typeof(decimal));
log.LogListBox("COLUMN ADDED");
}
if (!setINI.Tables["startup"].Columns.Contains("ORDNUM"))
{
setINI.Tables["startup"].Columns.Add("ORDNUM", typeof(int));
log.LogListBox("COLUMN ADDED");
}
DataRow currentDay = setINI.Tables["startup"].NewRow();
currentDay["TRADEDATE"] = _tradeDate("MMddyy");
currentDay["ORDNUM"] = ordNum;
currentDay["OPEN"] = open;
setINI.Tables["startup"].Rows.Clear();
setINI.Tables["startup"].Rows.Add(currentDay);
setINI.AcceptChanges();
setINI.WriteXml("INI.XML");
}
catch (Exception ex)
{ log.LogListBox(ex.ToString()); }
}
/// <summary>
/// msgbx = FALSE : Record all loaded data in log file
/// msgbx = True : Display on form control
/// </summary>
/// <param name="msgbx"></param>
private void _displayParameters(bool msgbx)
{
if (!msgbx)
{
log.LogListBox("sExchange: " + ttGateway);
log.LogListBox("sProduct: " + ttProduct);
log.LogListBox("sProductType: " + ttProductType);
log.LogListBox("sContract: " + ttContract);
log.LogListBox("sPos: " + longShort);
log.LogListBox("iPos: " + startPosition.ToString());