-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathMDI_JISO..cs
More file actions
2592 lines (2463 loc) · 111 KB
/
MDI_JISO..cs
File metadata and controls
2592 lines (2463 loc) · 111 KB
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
/* LEGAL DISCLAIMER **
The currency markets can do ANYTHING at ANY TIME.
This information was developed by backtesting with 12 months of 2017 historical data of currency market activity.
No one can guarantee or forecast how these results will perform or behave in future markets.
Anyone who uses this product or this information is responsible for deciding If, Where, When and How this product and information are used.
Anyone who uses this product or this information is responsible and liable for any outcomes that might result from the use of this product or this information.
There is no warranty or guarantee provided or implied for this product or this information for any purpose.
*/
/*
* Change Log:
*
* Version 1.0 Original.
*
* Version 1.2
* 1. Cerate c:/temp/MDI_JISO directory if it does not exist, for file storade.
* 2. Improvements in Save and Restore System EA State.
*
* Version 1.3
* 1. Prevent exception when MDI_JISO_State s is null when Start() is called.
*
* Version 1.4
* 1. Create directory c:/temp/MDI_JISO.
*
* Version 1.5
* 1. Add MaxSpread.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.ComponentModel;
using Alveo.Interfaces.UserCode;
using Alveo.Common.Classes;
using Alveo.Common.Enums;
using Alveo.UserCode;
namespace Alveo.UserCode
{
[Serializable]
[Description("MDI_JISO Expert Advisor for Alveo")]
// MDI_JISO Features include:
// * Expert Advisor for the Alveo trading platform
// * Unatended Autmated trading 24 hours per day from Sunday evening 22:00:00 UTC to Friday evening UTC 21:55:00
// * User Specified Trading parameters.
// * Designed to be run on M1 currency charts.
// * Uses a McDaniel Dynamic Indiciator (MDI) function to smooth M1 Close Price data.
// * Uses the slope of MDI to determine market trend direction and Entry point for Buy and Sell orders
// * Each order uses fixed Stoploss and Take Profit order limits
// * If enabled, Trailing Stoploss limits are used with all Open orders.
// * Uses a "Jump In and Scale Out" (JISO) technique to enter the specified number of additional orders at Entry points
// * Uses JISO to potentually multiply profitability from strong market trend signals.
// * Evenly distributes JISO Take Profit limits in order to bank profits at regular intervals.
// * If JISO is used, once an order hits TP limit, the Stoploss limit on all remaining orders is set above BreakEvene level.
// * Uses JISO to increase ratio of # Winning trades / Total # of Trades ratio
// * Uses JISO to increase Expectancy, which equals Total Profits / Total # of Trades
// * Maximum number of simultameous Open trades at any time is JISO + 1.
// * Optional Trailing Stoploss enable setting
// * Includes Risk and Money Mangement functionality.
// * Includes interface functions to simulate Alveo system functions for offline development and testing.
// * Includes interface functions for using Genetic Algorithm Optimization to seek optimal trading parameter values.
// * Optimized parameters included for EUR/USD, AUD/USD and GBP/USD currency pairs
// * Automatically generates a Trade Journal file of all closed trades including OpenPrice, OpenDate, Closed Price and ClosedDate.
// * Backtested with 12 months of 2017 M1 historical data.
// * Generates statistics including Profitability, numWins, NumLoss, AvgWin, AvgLoos, MaxDrawdown, numTrades.
// * Saves all of the EA State data into a restore file every M1 bar and will restore the EA State if Alveo restarts (Init) the EA.
// * Detailed progress and error messages sent to Alveo Log file.
// * Include documented Alveo compatible C# source code.
// * Operation and Design theory are described in an eBook.
public class MDI_JISO : ExpertAdvisorBase
{
datetime datetime0 = 0;
internal string pair = "";
#region Properties
[Category("Settings")]
[Description("Parameter Set # and Parameter, Journal and TradeLog File to use")]
public int paramset { get; set; } // specifies dir, dile names and EA strategy name.
[Category("Settings")]
[Description("have EA pick optimized parametrs for this Symbol")]
public bool useOptimzedParams { get; set; }
[Category("Settings")]
[Description("Stoploss limit for all trades in Pips. [ex: 37]")]
public int stoploss { get; set; } // specifies stoploss in Pips
[Category("Settings")]
[Description("Takeprofit limit for all trades in Pips. [ex: 41]")]
public int takeprofit { get; set; } // specifies takeprofit in Pips
[Category("Settings")]
[Description("orderQty in standard Lots [ex: 0.02]")]
public double orderQty { get; set; } // specifies targetQty in Lots
[Category("Settings")]
[Description("the scale factor (period) for the MDI Indicator. Larger = more filtering. [ex: 120]")]
public double MDIperiod { get; set; }
[Category("Settings")]
[Description("specifies the Entry Slope Threshold in multiples of 1e-7. [ex. 101] ")]
public int slopeThreshold { get; set; }
[Category("Settings")]
[Description("enable Trailing Stop to move StopLoss loss as Price moves towards TakeProfit limit ")]
public bool enableTrailigStop { get; set; }
[Category("Settings")]
[Description("the number of additional JISO orders created for each Entry point. Range: 0 to 20. [ex: 4] ")]
public int JISO { get; set; }
[Category("Settings")]
[Description("a Filter value to used to calculate a long-term Average Price, units in percent. [ex: 0.8] ")]
public double AvgPriceFilter { get; set; }
[Category("Settings")]
[Description("a Price distance from AveragePrice to modify Order Quantity, in Pips [ex: 12] ")]
public double farPrice { get; set; }
[Category("Settings")]
[Description("Maximum Spread for trade Entry in Pips [ex: 2.5] ")]
public double MaxSpread { get; set; }
#endregion
public bool simulate; // simulation mode flag
public bool optimize; // optimization mode flag
public string strategy; // strategy name;
string symbol;
public int simBars;
public DateTime simTime;
double pipPos;
int ticketNum;
internal double curPrice;
double simAccountBalance;
internal bool enableJISOstoplossMod;
internal MDI_JISO_State s = null;
DateTime curTime;
internal BarData curBar;
string dataFileDir = "C:\\temp\\MDI_JISO\\";
static System.IO.StreamWriter tradeLogFile;
internal bool isConnected = true;
internal bool Stopped = false;
internal bool isTradeAllowed = false;
internal bool OKtoTrade = true;
internal bool timeToExit = false;
internal bool riskLimitReached = false;
internal bool tradingclosed = false;
internal double accountBalance;
internal double riskLimit = 14; // in Pips, i.e. 1.5% of AccountBallance for 1 Standard lot
internal TimeFrame simTimeframe;
internal double MDIslope;
internal double prevMDIslope;
TimeSpan fridayclose = new TimeSpan(21, 55, 00); // UTC time
TimeSpan sundayOpen = new TimeSpan(22, 00, 00);
TimeSpan dailyMaintStart = new TimeSpan(21, 55, 00);
TimeSpan dailyMaintEnd = new TimeSpan(22, 30, 00);
int nStep = 0; // used to find potential Exception location in EA constructor
bool spreadTooHigh;
// EA constructor
public MDI_JISO()
{
// Basic EA initialization. Don't use this constructor to calculate values
pair = "";
copyright = "";
link = "";
simulate = false;
optimize = simulate;
nStep = 1;
InitEA(1);
}
// EA constuctor with parameters
// used by Test Program
public MDI_JISO(string thePair, bool optimizing)
{
// Basic EA initialization. Don't use this constructor to calculate values
pair = thePair;
copyright = "";
link = "";
simulate = true;
optimize = optimizing;
nStep = 2;
InitEA(0, thePair);
}
// Common EA constructor initialization
// DO NOT include any calls to Alveo here
public void InitEA(int set, string thePair = "EUR/USD")
{
try
{
// Initializa EA variables
nStep = 3;
spreadTooHigh = false;
useOptimzedParams = (optimize) ? false : true;
strategy = "MDI_JISO";
AvgPriceFilter = 0.8;
farPrice = 0;
MaxSpread = 2.0; // Pips
JISO = 4;
stoploss = 41;
takeprofit = 45;
MDIperiod = 128;
slopeThreshold = 73; // * 1e-7
paramset = set;
simBars = 0;
ticketNum = 0;
orderQty = 0.02;
MDIslope = 0;
prevMDIslope = 0;
nStep = 4;
curPrice = double.MinValue;
simTime = DateTime.UtcNow;
simTimeframe = TimeFrame.M1;
curTime = simTime;
curBar = null;
riskLimitReached = false;
dataFileDir = "C:\\temp\\MDI_JISO\\";
isConnected = true;
Stopped = false;
isTradeAllowed = false;
OKtoTrade = true;
timeToExit = false;
enableTrailigStop = false;
enableJISOstoplossMod = false;
simAccountBalance = 1000.00;
nStep = 98;
}
catch (Exception e)
{
nStep = 99;
Print(e.Message); // Prints dont work this early in Alveo
Print(e.StackTrace);
Sleep(500);
}
return;
}
// Write msg to Trade Log file
// optionally Clear Trade Log file before writing msg
internal void WriteTradeLog(string msg, bool clear = false)
{
// Write msg to TradeLog, Delete and Create new file is clear=true
string tradeLogFilename = "TradeLog" + symbol.Replace("/", "") + paramset + ".csv";
if (!System.IO.Directory.Exists(dataFileDir))
System.IO.Directory.CreateDirectory(dataFileDir);
if (clear)
System.IO.File.Delete(dataFileDir + tradeLogFilename);
tradeLogFile = new System.IO.StreamWriter(dataFileDir + tradeLogFilename, true); // create new file
tradeLogFile.WriteLine(msg);
tradeLogFile.Close();
}
//external interface for Simulator
internal int doInit()
{
return this.Init();
}
//+------------------------------------------------------------------+"
//| EA initialization function |"
//| |"
//| called by Alveo to init EA |"
//+------------------------------------------------------------------+"
protected override int Init()
{
try
{
//Print("nStep=" + nStep); // if needed.
symbol = GetSymbol();
if (!simulate) // if running in Alveo
{
pair = Chart.Symbol;
}
if (pair == "")
pair = "EURUSD"; // default
symbol = pair;
if (s == null)
s = new MDI_JISO_State(paramset, symbol); // s = new State object
pipPos = symbol.EndsWith("JPY") ? 100 : 10000; // determine Pip position
if (!optimize)
LogPrint("Version = " + MDI_JISO_State.VERSION);
if (s == null)
throw new Exception("Init: s == null");
var restored = s.CheckRestore(); // check if State Restore is needed
if (s.firstRun)
{
if (!optimize)
{
if (!System.IO.Directory.Exists("C:\\temp"))
System.IO.Directory.CreateDirectory("C:\\temp");
if (!System.IO.Directory.Exists(dataFileDir))
System.IO.Directory.CreateDirectory(dataFileDir);
WriteTradeLog("Type,ID,Qty,OpenDate,OpenPice,Stoploss,TakeProfit,MDI,Slope,CloseDate,ClosePrice,dProfit,Balance", true);
}
s.firstRun = false;
}
if (useOptimzedParams) // override User Settings with optimized values
{
if (symbol == "EUR/USD")
{
JISO = 4;
stoploss = 41;
takeprofit = 45;
MDIperiod = 128;
slopeThreshold = 73; // * 1e-7
}
else if (symbol == "AUD/USD")
{
JISO = 4;
stoploss = 58;
takeprofit = 62;
MDIperiod = 45;
slopeThreshold = 371;
}
else if (symbol == "GBP/USD")
{
JISO = 4;
stoploss = 63;
takeprofit = 67;
MDIperiod = 48;
slopeThreshold = 522; //* 1e-7
}
else
{
JournalLog(" Do not have optimized parameters for Symbol " + symbol + ". Using EUR-USD parameters.");
JISO = 4;
stoploss = 41;
takeprofit = 45;
MDIperiod = 128;
slopeThreshold = 73;
}
}
if (!optimize && restored)
JournalLog(" Init: EA State was Restored.");
if (optimize)
LoadParameters(); // load trading parameters from file for optimization
simTime = DateTime.UtcNow;
s.nBars = 0;
s.curBars = 0;
s.closedOrders.Clear(); // clear closedOrders list
if (!optimize)
LogPrint(" Init: simulate=" + simulate.ToString());
}
catch (Exception e) // Exception Handling
{
Print(e.Message);
Print(e.StackTrace);
Sleep(1000);
}
return 0;
}
//+------------------------------------------------------------------+"
//| expert deinitialization function |"
//| |"
//| called by Alveo to unitialize EA |"
//+------------------------------------------------------------------+"
protected override int Deinit()
{
LogPrint(" Deinit: Shutting Down.");
Sleep(1000);
if (s != null)
s.CloseState();
return 0;
}
// eternal interface for Simulator
internal int doStart()
{
return this.Start();
}
//+------------------------------------------------------------------+"
//| expert start function |"
//| |"
//| called by Alveo for every new bar on chart |"
//| and maybe more often than that. |"
//+------------------------------------------------------------------+"
protected override int Start()
{
try
{
symbol = GetSymbol();
if (s == null)
s = new MDI_JISO_State(paramset, symbol); // s = new State object
accountBalance = GetAccoutBalance();
//orderQty = Math.Max(Math.Round((Math.Sqrt(Math.Max(accountBalance, 0)) - 31) / 10), 1) * 0.01;
if (!simulate)
{
if (DetectChanged(ref s.OKtoTrade, CheckOKToTrade()))
{
JournalLog(" OKtoTrade=" + s.OKtoTrade.ToString());
}
if (!s.OKtoTrade)
{
JournalLog(" OKtoTrade=" + s.OKtoTrade.ToString());
Sleep(1000);
return 0; // EA cannot trade at this time
}
}
var bars = GetBars();
if (bars == 0) // no chart bars
{
Sleep(1000); // sleep 1 sec
return 0;
}
if (s.curBars == bars) // if #bar is unchanged
{
Sleep(1000); // sleep 1 sec
return (0); // nothing to do until new bar arrives
}
s.curBars = bars; // update curBars
s.nBars++; // count bars
s.dI = GetCurBar(); // save bar data
curTime = s.dI.BarTime;
Monitor(); // perform Monitor functions
if (!optimize && !simulate)
s.SaveSystemState(); // save EA State every new Bar
}
catch (Exception e) // Exception handling
{
LogPrint(strategy + " Start: Exception: " + e.Message);
LogPrint("Exception: " + e.InnerException);
LogPrint("Exception: " + e.StackTrace);
Sleep(500);
}
return 0;
}
// get number of Bar on chart
internal int GetBars()
{
if (simulate)
return simBars;
else // Alveo function
return Bars;
}
// Mponitor for Closed orders
// Monitor for Start of Day and start of Hour
// Simulate market Stoploss and TakeProfit
// Update MDI value, monitor MDIslope and create new Orders
public void Monitor()
{
int total = GetTotalOrders();
// count trading numDays
if (s.OldTime3 > curTime || curTime >= s.nextDay) // start of new Day
{
s.stats.numDays++;
s.OldTime3 = curTime;
s.nextDay = new DateTime(
s.OldTime3.Year,
s.OldTime3.Month,
s.OldTime3.Day,
0, 0, 0, 0) + TimeSpan.FromHours(24);
s.startingBalance = accountBalance; // save Daily startingBalance
}
// count trading numHours
if (s.OldTime2 > curTime || curTime.Subtract(s.OldTime2) >= TimeSpan.FromHours(1)) // start of new Hour
{
s.stats.numHours++;
s.OldTime2 = curTime;
s.ordersThisHour = 0;
if (!optimize)
JournalLog(" Monitor still running. " + curTime.ToLongTimeString());
}
curPrice = s.dI.close;
if (AvgPriceFilter > 0) // calculate long-term averagerPrice
{
var alpha = Math.Abs(AvgPriceFilter / 100);
if (s.averagerPrice != double.MinValue)
s.averagerPrice += alpha * (curPrice - s.averagerPrice);
else
s.averagerPrice = curPrice;
}
else // disabled
s.averagerPrice = 0;
if (s.dIprev == null) // if no previous bar
{
s.dI.MDI = curPrice; // save s.dIprev data
s.dIprev = s.dI;
prevMDIslope = 0;
return; // nothing to do without previous bar
}
else // have s.dI and s.dIprev
{
// Calculate MDi and MDIslope
// newMD = prevMD + (Price– prevMD) / (N * Power((Price / prevMD) , 4)) where N is similar to the period of a MA.
if (s.dIprev.MDI <= 0)
s.dIprev.MDI = (double)(s.dIprev.open + s.dIprev.high + s.dIprev.low + s.dIprev.close) / 4.0;
var prevMDI = s.dIprev.MDI;
s.dIprev = s.dI; // save previous bar
//var thePrice = curPrice;
s.dI.typical = (double)(s.dI.open + s.dI.high + s.dI.low + s.dI.close) / 4.0;
var thePrice = s.dI.typical; // DFB
var newMDI = prevMDI + (thePrice - prevMDI) / (MDIperiod * Math.Pow(Math.Abs(thePrice / prevMDI), 4.0));
s.dI.MDI = newMDI;
MDIslope = 2 * prevMDIslope / 3 + (newMDI - prevMDI) / 3;
prevMDIslope = MDIslope;
// wait for MDI to stabilize
if ((double)s.nBars < MDIperiod / 2)
return;
double ask = GetMarketInfo(symbol, MODE_ASK);
double bid = GetMarketInfo(symbol, MODE_BID);
var spread = ask - bid;
if (MaxSpread > 0 && spread > MaxSpread)
{
if (!optimize && !spreadTooHigh)
LogPrint(strategy + " Monitor: Spread too high. Spread=" + spread);
spreadTooHigh = true;
return;
}
else
spreadTooHigh = false;
if (total == 0 && Math.Abs(MDIslope) > ((double)slopeThreshold) * 1e-7) // No Open orders and MDIslope > threshold
{
s.targetDir = (MDIslope > 0) ? 1 : -1; // det direction based upon MDIslope
string msg = newMDI.ToString("F5") + "," + MDIslope.ToString("F7");
CreateOrder(msg); // create first open order
}
if (s.nBars % 5 == 0) // send message every 5 minutes
{
if (!optimize)
{
var pct = MDIslope * 1e7 / ((double)slopeThreshold);
JournalLog(": Slope%=" + pct.ToString("F2") + " targetDir=" + s.targetDir);
}
}
}
RemoveClosedOrders(); // clean up lists of orders
if (simulate) // remove Orders that exceeded StopLoss or TakeProfit limits
{
var highest = s.dI.high;
var lowest = s.dI.low;
// check buyOpenOrders for TP or SL
if (s.buyOpenOrders.Count > 0)
{
foreach (var order in s.buyOpenOrders.Values)
{
double tp = (double)order.TakeProfit;
double sl = (double)order.StopLoss;
if (highest >= tp)
{
ExitOpenTrade(reason: 1, order: order, price: tp + 2 / pipPos);
}
else if (lowest <= sl)
{
ExitOpenTrade(reason: 2, order: order, price: sl - 2 / pipPos);
}
}
}
// check sellOpenOrders for TP or SL
if (s.sellOpenOrders.Count > 0)
{
foreach (var order in s.sellOpenOrders.Values)
{
double tp = (double)order.TakeProfit;
double sl = (double)order.StopLoss;
if (lowest <= tp)
{
ExitOpenTrade(reason: 3, order: order, price: tp - 2 / pipPos);
}
else if (highest >= sl)
{
ExitOpenTrade(reason: 4, order: order, price: sl + 2 / pipPos);
}
}
}
}
// find Order closed by TP
// update Trailing Stoploss
Order foundOrder = null;
if (s.buyOpenOrders.Count > 0)
{
foreach (var order in s.buyOpenOrders.Values)
{
int ticketID = (int)order.Id;
var tm = GetOrderCloseTime(ticketID);
if (tm.DateTime.Year > 1970) // Closed
{
var dProfit = TradeClosed(order);
if (!optimize)
LogPrint("FT: Monitor: Closed Buy order. ID=" + order.Id
+ " CloseTime=" + tm.ToString());
if (foundOrder == null)
{
//if (priceDiff >= takeprofit / pipPos) // was TakeProfit
if (order.ClosePrice >= order.TakeProfit) // was TakeProfit
{
if (!optimize)
LogPrint("was TakeProfit");
//targetDir = 1;
foundOrder = order;
}
else if (order.ClosePrice <= order.StopLoss) // Stoploss
{
if (!optimize)
LogPrint("was Stoploss");
//targetDir = -1;
}
}
}
else // !closed
{
// update Trailing Stoploss
if (enableTrailigStop && curPrice - (double)order.StopLoss - stoploss / pipPos > 4 / pipPos) // if curPrice moved more than 4 Pip
{
order.StopLoss = (decimal)(curPrice - (double)stoploss / pipPos);
ModifyOrder(order, (double)order.StopLoss);
LogPrint("Monitor: Order=" + order.Id + " side=" + order.Side + " Trailing Stoploss=" + order.StopLoss.ToString("F5"));
}
}
}
}
if (foundOrder == null)
{
// check closed sellOpenOrders for TP or SL and set targetDir
if (s.sellOpenOrders.Count > 0)
{
foreach (var order in s.sellOpenOrders.Values)
{
int ticketID = (int)order.Id;
var tm = GetOrderCloseTime(ticketID);
if (tm.DateTime.Year > 1970) // Closed
{
var dProfit = TradeClosed(order);
if (!optimize)
LogPrint(strategy + "Monitor: Closed Sell order. ID=" + order.Id
+ " CloseTime=" + tm.ToString());
if (foundOrder == null)
{
if (order.ClosePrice >= order.StopLoss) // was StopLoss
{
if (!optimize)
LogPrint("was Stoploss");
//targetDir = 1;
}
else if (order.ClosePrice <= order.TakeProfit) // TakeProfit
{
if (!optimize)
LogPrint("was TakeProfit");
//targetDir = -1;
foundOrder = order;
}
}
}
else // !closed, update trailing Stoploss
{
if (enableTrailigStop && (double)order.StopLoss - curPrice - stoploss / pipPos > 4 / pipPos)
{
order.StopLoss = (decimal)(curPrice + (double)stoploss / pipPos);
ModifyOrder(order, (double)order.StopLoss);
LogPrint("Monitor: Order=" + order.Id + " side=" + order.Side + " Trailing Stoploss=" + order.StopLoss.ToString("F5"));
}
}
}
}
}
RemoveClosedOrders(); // clean up closed orders
// if enableJISOstoplossMod and JISO AND TP triggered, then move Stoploss to BE
if (foundOrder != null) // found TP
{
if (!optimize)
LogPrint("foundOrder=" + foundOrder.Id);
if (enableJISOstoplossMod && JISO > 0)
{
total = GetTotalOrders();
if (total > 0)
{
decimal delta = (decimal)(2.0 / pipPos);
foreach (var order in s.buyOpenOrders.Values)
{
if (order.StopLoss < order.OpenPrice) // move StopLoss to above Breakeven level
if (curPrice - (double)order.OpenPrice >= 9.0 / pipPos)
{
//modify order StopLoss
var orderSL = order.OpenPrice + delta;
order.StopLoss = (orderSL > order.StopLoss) ? orderSL : order.StopLoss;
ModifyOrder(order, (double)order.StopLoss);
}
}
foreach (var order in s.sellOpenOrders.Values)
{
if (order.StopLoss > order.OpenPrice) // move StopLoss to above Breakeven level
if ((double)order.OpenPrice - curPrice >= 9.0 / pipPos)
{
//modify order StopLoss
var orderSL = order.OpenPrice - delta;
order.StopLoss = (orderSL < order.StopLoss) ? orderSL : order.StopLoss;
ModifyOrder(order, (double)order.StopLoss);
}
}
}
}
foundOrder = null;
}
}
// remove closedOrders from buyOpenOrders and sellOpenOrders
internal void RemoveClosedOrders()
{
if (s.closedOrders.Count > 0)
foreach (var iD in s.closedOrders.Keys)
{
s.buyOpenOrders.Remove(iD);
s.sellOpenOrders.Remove(iD);
}
s.closedOrders.Clear();
}
// EA State object to remeber data that must be Restored after distrubtion and Init
[Serializable]
internal class MDI_JISO_State
{
internal const string VERSION = "1.4"; //Restore file format
internal bool firstRun = true;
internal bool isConnected = true;
internal bool Stopped = false;
internal bool isTradeAllowed = false;
internal bool OKtoTrade = true;
internal bool timeToExit = false;
internal int curBars;
internal Statistics stats = new Statistics(0);
internal BarData dI;
internal BarData dIprev;
internal int nBars = 0;
internal DateTime OldTime, OldTime2, OldTime3, nextDay;
internal int targetDir;
internal double startingBalance;
internal int ordersThisHour;
System.IO.StreamWriter restore = null;
System.IO.StreamReader restoreRead = null;
internal string restorePath;
private Object thisLock = new Object();
string dataFileDir = "C:\\temp\\MDI_JISO\\";
int paramset = 1;
internal string stateSymbol;
internal double averagerPrice;
internal Dictionary<long, Order> buyOpenOrders = null;
internal Dictionary<long, Order> sellOpenOrders = null;
internal Dictionary<long, Order> closedOrders = null;
/// <summary>
/// DENA3_State Class object constructor
/// </summary>
public MDI_JISO_State()
{
paramset = 1;
stateSymbol = "EUR/USD";
ClearState();
}
// Constructor with parameters
public MDI_JISO_State(int set, string chartSymbol)
{
paramset = set;
stateSymbol = chartSymbol;
ClearState();
}
/// <summary>
/// DENA3_State initialization
/// </summary>
internal void ClearState()
{
if (firstRun)
{
lock (thisLock) // lock to prevent multiple access of file
{
restorePath = dataFileDir + "Restore" + stateSymbol.Replace('/', '-') + paramset + ".csv";
System.IO.File.Delete(restorePath); // Delete Restore file on starteup
}
}
curBars = 0;
nBars = 0;
isConnected = true;
Stopped = false;
isTradeAllowed = false;
timeToExit = false;
stats = new Statistics(0);
dI = null;
dIprev = null;
targetDir = 0;
startingBalance = double.MinValue;
ordersThisHour = 0;
OldTime = DateTime.UtcNow;
OldTime2 = OldTime;
OldTime3 = DateTime.UtcNow;
nextDay = new DateTime(
OldTime3.Year,
OldTime3.Month,
OldTime3.Day,
0, 0, 0, 0) + TimeSpan.FromHours(24);
buyOpenOrders = new Dictionary<long, Order>();
sellOpenOrders = new Dictionary<long, Order>();
closedOrders = new Dictionary<long, Order>();
averagerPrice = double.MinValue;
}
// Delete Resore file on Shutdown
internal void CloseState()
{
lock (thisLock)
{
if (restore != null)
{
restore.Close();
restore = null;
}
if (restoreRead != null)
{
restoreRead.Close();
restoreRead = null;
}
restorePath = dataFileDir + "Restore" + stateSymbol.Replace('/', '-') + paramset + ".csv";
System.IO.File.Delete(restorePath);
}
}
// Save EA State
public void SaveSystemState()
{
lock (thisLock)
{
restore = new System.IO.StreamWriter(restorePath, false);
SaveState();
SaveAllOrders(ref restore);
restore.Close();
restore = null;
}
//JournalLog("SaveState successful.");
}
/// <summary>
/// Save All Orders in orders list to restore file
/// <param name="restore">ref to System.IO.StreamWriter</param>
/// </summary>
internal void SaveAllOrders(ref System.IO.StreamWriter restore)
{
restore.WriteLine(buyOpenOrders.Count);
foreach (var kvp in buyOpenOrders)
{
restore.WriteLine(kvp.Key);
SaveOrder(ref restore, kvp.Value);
}
restore.WriteLine(sellOpenOrders.Count);
foreach (var kvp in sellOpenOrders)
{
restore.WriteLine(kvp.Key);
SaveOrder(ref restore, kvp.Value);
}
}
/// <summary>
/// Save clsOrder object to restore file
/// <param name="restore">ref to System.IO.StreamWriter</param>
/// </summary>
public void SaveOrder(ref System.IO.StreamWriter restore, Order order)
{
order.Symbol = stateSymbol;
restore.WriteLine(order.Id + ", " + order.Symbol);
restore.WriteLine(order.OpenDate + ", " + order.Side);
restore.WriteLine(order.Comment);
restore.WriteLine(order.OpenPrice
+ ", " + order.ClosePrice
+ ", " + order.Profit
+ ", " + order.TakeProfit
+ ", " + order.OpenBid
+ ", " + order.OpenAsk);
restore.WriteLine(order.TrailingStop
+ ", " + order.CloseDate
+ ", " + order.Price
+ ", " + order.Type
+ ", " + order.Quantity
+ ", " + order.StopLoss);
restore.WriteLine(order.FilledBid
+ ", " + order.FilledAsk
+ ", " + ((order.FillDate == null) ? DateTime.MinValue : order.FillDate).ToString()
);
restore.WriteLine(order.CustomId);
restore.WriteLine(order.ExternId
+ ", " + order.Status
+ ", " + order.TimeInForce
+ ", " + ((order.ExpirationDate == null) ? DateTime.MinValue : order.ExpirationDate).ToString()
);
}
/// <summary>
/// Save DENA3_State to restore file
/// <param name="restore">ref to System.IO.StreamWriter</param>
/// </summary>
public void SaveState()
{
restore.WriteLine(VERSION + ", " + stateSymbol);
restore.WriteLine(DateTime.UtcNow.ToString());
restore.WriteLine(firstRun.ToString()
+ ", " + isConnected.ToString()
+ ", " + Stopped.ToString()
+ ", " + isTradeAllowed.ToString()
+ ", " + OKtoTrade.ToString()
+ ", " + timeToExit.ToString()
);
restore.WriteLine(curBars
+ ", " + nBars
+ ", " + targetDir
+ ", " + startingBalance
+ ", " + ordersThisHour
+ ", " + averagerPrice
);
restore.WriteLine(OldTime
+ ", " + OldTime2
+ ", " + OldTime3
+ ", " + nextDay
);
stats.SaveStats(ref restore);
if (dI == null)
restore.WriteLine("null");
else
dI.SaveBarData(ref restore);
if (dIprev == null)
restore.WriteLine("null");
else
dIprev.SaveBarData(ref restore);
}
// return True if Resore file exists
internal bool CheckRestore()
{
bool ret = false;
if (System.IO.File.Exists(restorePath))
ret = RestoreSystemState();
return ret;
}
// Restore EA State from file
internal bool RestoreSystemState()
{
bool restored = false;
lock (thisLock) // lock to prevent multiple access to file
{
restoreRead = new System.IO.StreamReader(restorePath);
RestoreState(ref restoreRead);
RestoreAllOrders(ref restoreRead);
restoreRead.Close();
restoreRead = null;
restored = true;
}
return restored;
}
// Restore Lists of orders from file
internal void RestoreAllOrders(ref System.IO.StreamReader restore)
{
char[] delimiterChars = { ',', '\t' };
String line;
string[] vals;
string parseError = "Exception RestoreState: parse error at ";
line = restore.ReadLine();
vals = line.Split(delimiterChars);
if (vals.Length != 1)
throw new Exception(parseError + "buyOpenOrders.Count");
int cnt;
int key;