-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathFalcon_A.mq4
2715 lines (2354 loc) · 270 KB
/
Falcon_A.mq4
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
//+------------------------------------------------------------------------------+
//| Falcon EA Template v2.0|
//| Copyright 2015,Lucas Liew|
//| [email protected]|
//| Stat_Euclidean_Metric.mq4 |
//| StatBars TO |
//| http://ridecrufter.narod.ru |
//| Best uses with explanations provided in this course|
//| https://www.udemy.com/self-learning-trading-robot/?couponCode=SELF-LEARN-BOT |
//+------------------------------------------------------------------------------+
#include <01_GetHistoryOrder.mqh>
#include <02_OrderProfitToCSV.mqh>
#include <03_ReadCommandFromCSV.mqh>
#include <08_TerminalNumber.mqh>
#include <096_ReadMarketTypeFromCSV.mqh>
#include <12_ReadDataFromDSS.mqh>
#include <10_isNewBar.mqh>
#include <16_LogMarketType.mqh>
#include <17_CheckIfMarketTypePolicyIsOn.mqh>
#include <19_AssignMagicNumber.mqh>
#property copyright "Copyright 2018, Vladimir Zhbanko"
#property link "https://vladdsm.github.io/myblog_attempt/"
#property version "1.04"
#property strict
#define v_dim_x 6 //number of vectors used for recognition...
#define Num_neighbour 10 //number of nearest neighbours to forecast whether new values belongs to 0 or 1
/*
==================================================================
VERY VERY IMPORTANT: USE STRATEGY TESTER TO PERFORM ROBOT TRAINING
==================================================================
1. Set parameter Base = True
2. Select time period and start trading simulation
3. Switch parameter Base = False, test trading again
4. Move *.dat files from tester folder to Files folder of the sandbox and launch the robot
Release Notes:
- System is based on the Falcon Template that is now containing custom functions
- System is working using kNN algorithm and output the probabilities to win trades adapted from Stat_Euclidean_Metric.mq4
- System uses history experience to enter the trade
- History experience is created in TESTER
- In order to trade files.dat must be manually transferred to the File sandbox
- Made some corrections acc to: https://www.mql5.com/ru/code/8645
- Trading system is only working on new bar entry
- Rearranged Headers
- 90 minor warnings
v1.01 Release Notes:
- critical fix: adding buy probability formula as it was missed
- set variable close_orders = true by default as this teach the system to be more robust, much less trades are generated in live trading
- critical fix: invese position open added variable to trading conditions
v1.04 Release Notes:
- added full features of Decision Support System developed so far
- see Falcon_F2
- less minor warnings
- to be used with Market Type Recognition
*/
//+------------------------------------------------------------------+
//| Setup
//+------------------------------------------------------------------+
extern string Header1="----------EA General Settings-----------";
extern string StrategyNumber = "32";
extern int TerminalType = 1; //0 mean slave, 1 mean master
extern bool R_Management = true; //R_Management to set true for trading, false for testing
extern int Slippage = 3; //Slippage In Pips
extern bool IsECNbroker = false; // Is your broker an ECN
extern bool OnJournaling = false; // Add EA updates in the Journal Tab
extern bool EnableDashboard = false; // Turn on Dashboard
extern string Header2="----------Trading Rules Variables-----------";
extern bool Base =false;
extern double buy_threshold =0.7;
extern double sell_threshold =0.7;
extern bool inverse_position_open =false;
extern double invers_buy_threshold =0.3;
extern double invers_sell_threshold =0.3;
extern int fast =12;
extern int slow =34;
extern bool close_orders =false;
extern bool use_market_type =false;
extern bool closeAllOnFridays = True; //close all orders on Friday 1hr before market closure
extern string Header3="----------Position Sizing Settings-----------";
extern string Lot_explanation ="If IsSizingOn = true, Lots variable will be ignored";
extern double Lots =0.01;
extern bool IsSizingOn =False;
extern double Risk =1; // Risk per trade (in percentage)
extern int MaxPositionsAllowed =1;
extern string Header4="----------TP & SL Settings-----------";
extern bool UseFixedStopLoss =True; // If this is false and IsSizingOn = True, sizing algo will not be able to calculate correct lot size.
extern double FixedStopLoss =0; // Hard Stop in Pips. Will be overridden if vol-based SL is true
extern bool IsVolatilityStopOn =True;
extern double VolBasedSLMultiplier =6; // Stop Loss Amount in units of Volatility
extern bool UseFixedTakeProfit =True;
extern double FixedTakeProfit =0; // Hard Take Profit in Pips. Will be overridden if vol-based TP is true
extern bool IsVolatilityTakeProfitOn=True;
extern double VolBasedTPMultiplier =6; // Take Profit Amount in units of Volatility
extern string Header5="----------Hidden TP & SL Settings-----------";
extern bool UseHiddenStopLoss =False;
extern double FixedStopLoss_Hidden =0; // In Pips. Will be overridden if hidden vol-based SL is true
extern bool IsVolatilityStopLossOn_Hidden=False;
extern double VolBasedSLMultiplier_Hidden=0; // Stop Loss Amount in units of Volatility
extern bool UseHiddenTakeProfit =False;
extern double FixedTakeProfit_Hidden =0; // In Pips. Will be overridden if hidden vol-based TP is true
extern bool IsVolatilityTakeProfitOn_Hidden=False;
extern double VolBasedTPMultiplier_Hidden=0; // Take Profit Amount in units of Volatility
extern string Header6="----------Breakeven Stops Settings-----------";
extern bool UseBreakevenStops =False;
extern double BreakevenBuffer =0; // BreakevenBuffer In pips
extern string Header7="----------Hidden Breakeven Stops Settings-----------";
extern bool UseHiddenBreakevenStops =False;
extern double BreakevenBuffer_Hidden =0; // BreakevenBuffer_Hidden In pips
extern string Header8="----------Trailing Stops Settings-----------";
extern bool UseTrailingStops=False;
extern double TrailingStopDistance =0; // TrailingStopDistance In pips
extern double TrailingStopBuffer =0; // TrailingStopBuffer In pips
extern string Header9="----------Hidden Trailing Stops Settings-----------";
extern bool UseHiddenTrailingStops=False;
extern double TrailingStopDistance_Hidden=0; //TrailingStopDistance_Hidden In pips
extern double TrailingStopBuffer_Hidden=0; //TrailingStopBuffer_Hidden In pips
extern string Header10="----------Volatility Trailing Stops Settings-----------";
extern bool UseVolTrailingStops=False;
extern double VolTrailingDistMultiplier=0; // In units of ATR
extern double VolTrailingBuffMultiplier=0; // In units of ATR
extern string Header11="----------Hidden Volatility Trailing Stops Settings-----------";
extern bool UseHiddenVolTrailing=False;
extern double VolTrailingDistMultiplier_Hidden=0; // In units of ATR
extern double VolTrailingBuffMultiplier_Hidden=0; // In units of ATR
extern string Header12="----------Volatility Measurement Settings-----------";
extern int atr_period=14;
extern string Header13="----------Set Max Loss Limit-----------";
extern bool IsLossLimitActivated=False;
extern double LossLimitPercent=50;
extern string Header14="----------Set Max Volatility Limit-----------";
extern bool IsVolLimitActivated=False;
extern double VolatilityMultiplier=3; // VolatilityMultiplier In units of ATR
extern int ATRTimeframe=60; //ATRTimeframe In minutes
extern int ATRPeriod=14;
string InternalHeader1="----------Errors Handling Settings-----------";
int RetryInterval=100; // Pause Time before next retry (in milliseconds)
int MaxRetriesPerTick=10;
string InternalHeader2="----------Service Variables-----------";
double Stop,Take;
double StopHidden,TakeHidden;
int P;
int YenPairAdjustFactor;
double myATR;
double FastMA1, SlowMA1, Price1;
// Declaring Variables (and the extern variables above)
int CrossTriggered0, CrossTriggered1, CrossTriggered2, CrossTriggered3;
int candleType;
int OrderNumber;
double HiddenSLList[][2]; // First dimension is for position ticket numbers, second is for the SL Levels
double HiddenTPList[][2]; // First dimension is for position ticket numbers, second is for the TP Levels
double HiddenBEList[]; // First dimension is for position ticket numbers
double HiddenTrailingList[][2]; // First dimension is for position ticket numbers, second is for the hidden trailing stop levels
double VolTrailingList[][2]; // First dimension is for position ticket numbers, second is for recording of volatility amount (one unit of ATR) at the time of trade
double HiddenVolTrailingList[][3]; // First dimension is for position ticket numbers, second is for the hidden trailing stop levels, third is for recording of volatility amount (one unit of ATR) at the time of trade
string InternalHeader3="----------Analytical Centre Variables-----------";
int MagicNumber, myTerminal;
bool TradeAllowed = true; // this will be commanded by Decision Support Centre
bool isMarketTypePolicyON = true;
datetime ReferenceTime; //used for order history
int MyMarketType; //used to receive market status from AI
bool BuyMarket = false; //variables used to set specific market based on the Market Recognition function
bool SellMarket = false;
int Direction; //variable to retrieve direction that is coming from the R script
bool isFridayActive = false;
string InternalHeader4="----------ai knn Variables-----------";
double Prob_win_buy, Prob_win_sell; //define value for probabilities to win a trade
double base_buy[][v_dim_x];
double base_sell[][v_dim_x];
int numbers_of_vectors_buy=0;
int numbers_of_vectors_sell=0;
int Hadle_1, Hadle_2; //defined files *.dat
//+------------------------------------------------------------------+
//| End of Setup
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Initialization
//+------------------------------------------------------------------+
int init()
{
//Automatically Assign magic number
myTerminal = T_Num();
MagicNumber = AssignMagicNumber(Symbol(), StrategyNumber, myTerminal);
ReferenceTime = TimeCurrent(); // record time for order history function
//write file system control to enable initial trading
TradeAllowed = BoolReadDataFromDSS(MagicNumber, 0, "read_command");
if(TradeAllowed == false)
{
Comment("Trade is not allowed");
}
else if(TradeAllowed == true) // or file does not exist, create a new file
{
string fileName = "SystemControl"+string(MagicNumber)+".csv";//create the name of the file same for all symbols...
// open file handle
int handle = FileOpen(fileName,FILE_CSV|FILE_READ|FILE_WRITE); FileSeek(handle,0,SEEK_END);
string data = string(MagicNumber)+","+string(TerminalType);
FileWrite(handle,data); FileClose(handle);
//end of writing to file
Comment("Trade is allowed");
}
P=GetP(); // To account for 5 digit brokers. Used to convert pips to decimal place
YenPairAdjustFactor=GetYenAdjustFactor(); // Adjust for YenPair
//----------(Hidden) TP, SL and Breakeven Stops Variables-----------
// If EA disconnects abruptly and there are open positions from this EA, records form these arrays will be gone.
if(UseHiddenStopLoss) ArrayResize(HiddenSLList,MaxPositionsAllowed,0);
if(UseHiddenTakeProfit) ArrayResize(HiddenTPList,MaxPositionsAllowed,0);
if(UseHiddenBreakevenStops) ArrayResize(HiddenBEList,MaxPositionsAllowed,0);
if(UseHiddenTrailingStops) ArrayResize(HiddenTrailingList,MaxPositionsAllowed,0);
if(UseVolTrailingStops) ArrayResize(VolTrailingList,MaxPositionsAllowed,0);
if(UseHiddenVolTrailing) ArrayResize(HiddenVolTrailingList,MaxPositionsAllowed,0);
// Knn EA accomodation
if(!Base)
{
//1. for buy orders:
if(TerminalType == 1) Hadle_1 = FileOpen("Buy_Position"+string(MagicNumber)+".dat",FILE_BIN|FILE_READ);
//to make sure code will work in both terminals 3 and 4 by providing only 1 file e.g. Buy_Position8132100.dat
if(TerminalType == 0 && T_Num() == 3) Hadle_1 = FileOpen("Buy_Position"+string(MagicNumber-200)+".dat",FILE_BIN|FILE_READ);
if(TerminalType == 0 && T_Num() == 4) Hadle_1 = FileOpen("Buy_Position"+string(MagicNumber-300)+".dat",FILE_BIN|FILE_READ);
ArrayResize(base_buy,FileSize(Hadle_1)/(v_dim_x*8));
int count=0;
while(!FileIsEnding(Hadle_1))
{
//on init we record values into the memory from file
base_buy[count][0]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
base_buy[count][1]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
base_buy[count][2]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
base_buy[count][3]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
base_buy[count][4]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
base_buy[count][5]=FileReadDouble(Hadle_1,DOUBLE_VALUE);
//Print(base_buy[count][5]);
count++;
}
numbers_of_vectors_buy=count; //this records number of vectors available in the file (it will be used in the Euclidean function)
if(TerminalType == 1) Hadle_2 = FileOpen("Sell_Position"+string(MagicNumber)+".dat",FILE_BIN|FILE_READ);
//to make sure code will work in both terminals 3 and 4 by providing only 1 file e.g. Sell_Position8132100.dat
if(TerminalType == 0 && T_Num() == 3) Hadle_2 = FileOpen("Sell_Position"+string(MagicNumber-200)+".dat",FILE_BIN|FILE_READ);
if(TerminalType == 0 && T_Num() == 4) Hadle_2 = FileOpen("Sell_Position"+string(MagicNumber-300)+".dat",FILE_BIN|FILE_READ);
ArrayResize(base_sell,FileSize(Hadle_2)/(v_dim_x*8));
count=0;
//2. for sell orders
while(!FileIsEnding(Hadle_2))
{
base_sell[count][0]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
base_sell[count][1]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
base_sell[count][2]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
base_sell[count][3]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
base_sell[count][4]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
base_sell[count][5]=FileReadDouble(Hadle_2,DOUBLE_VALUE);
//Print(base_sell[count][5]);
count++;
}
numbers_of_vectors_sell=count;
FileClose(Hadle_1);
FileClose(Hadle_2);
}
start();
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Initialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert Deinitialization
//+------------------------------------------------------------------+
int deinit()
{
//----Delete file InTrade...csv on deinitialization
FileDelete("InTrade"+string(MagicNumber)+".csv");
//----
//knn portion
//after the trade run during TESTER run we record results of the trades and corresponding status of vectors at the moment of opening trades
if(Base)
{
Hadle_1=FileOpen("Buy_Position"+string(MagicNumber)+".dat",FILE_BIN|FILE_WRITE);
int count;
double ordinate_1,ordinate_2,ordinate_3,ordinate_4,ordinate_5;
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
if(OrderType()==0) //generate database for BUY orders
{
if(OrderProfit()>=0)//writing vectors to the database only for profitable orders
{
//write condition of indicators at the moment when trade was open
count=iBarShift(Symbol(),Period(),OrderOpenTime());
count++;//use bars before the orders were opened to forecast the probabilities
//divide small value of indicator by higher value ??? why? it becomes a vector...
ordinate_1=iMA(Symbol(),Period(),89,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),144,0,0,5,count));
ordinate_2=iMA(Symbol(),Period(),144,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),233,0,0,5,count));
ordinate_3=iMA(Symbol(),Period(),21,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_4=iMA(Symbol(),Period(),55,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_5=iMA(Symbol(),Period(),2,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),55,0,0,5,count));
FileWriteDouble(Hadle_1,ordinate_1,DOUBLE_VALUE);//writing to the file database...
FileWriteDouble(Hadle_1,ordinate_2,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_3,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_4,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_5,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,1,DOUBLE_VALUE); //write label 1 as profit
}
if(OrderProfit()<0)//writing vectors to the database only for negative profit
{
count=iBarShift(Symbol(),Period(),OrderOpenTime());
count++;//use bars before the orders were opened to forecast the probabilities
ordinate_1=iMA(Symbol(),Period(),89,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),144,0,0,5,count));
ordinate_2=iMA(Symbol(),Period(),144,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),233,0,0,5,count));
ordinate_3=iMA(Symbol(),Period(),21,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_4=iMA(Symbol(),Period(),55,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_5=iMA(Symbol(),Period(),2,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),55,0,0,5,count));
FileWriteDouble(Hadle_1,ordinate_1,DOUBLE_VALUE);//writing to the file database...
FileWriteDouble(Hadle_1,ordinate_2,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_3,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_4,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,ordinate_5,DOUBLE_VALUE);
FileWriteDouble(Hadle_1,0,DOUBLE_VALUE); //write label 0 as loss
}
}
}
Hadle_2=FileOpen("Sell_Position"+string(MagicNumber)+".dat",FILE_BIN|FILE_WRITE);
for(int i=OrdersHistoryTotal()-1;i>=0;i--)
{
OrderSelect(i,SELECT_BY_POS,MODE_HISTORY);
if(OrderType()==1) //generate database for SELL orders
{
if(OrderProfit()>=0)//writing vectors to the database only for profitable orders
{
count=iBarShift(Symbol(),Period(),OrderOpenTime());
count++;//use bars before the orders were opened to forecast the probabilities
ordinate_1=iMA(Symbol(),Period(),89,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),144,0,0,5,count));
ordinate_2=iMA(Symbol(),Period(),144,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),233,0,0,5,count));
ordinate_3=iMA(Symbol(),Period(),21,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_4=iMA(Symbol(),Period(),55,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_5=iMA(Symbol(),Period(),2,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),55,0,0,5,count));
FileWriteDouble(Hadle_2,ordinate_1,DOUBLE_VALUE);//writing to the file database...
FileWriteDouble(Hadle_2,ordinate_2,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_3,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_4,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_5,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,1,DOUBLE_VALUE); //write label 1 as profit
}
if(OrderProfit()<0)//writing vectors to the database only for negative profit
{
count=iBarShift(Symbol(),Period(),OrderOpenTime());
count++;//use bars before the orders were opened to forecast the probabilities
ordinate_1=iMA(Symbol(),Period(),89,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),144,0,0,5,count));
ordinate_2=iMA(Symbol(),Period(),144,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),233,0,0,5,count));
ordinate_3=iMA(Symbol(),Period(),21,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_4=iMA(Symbol(),Period(),55,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,count));
ordinate_5=iMA(Symbol(),Period(),2,0,0,5,count)/(0.0000001 + iMA(Symbol(),Period(),55,0,0,5,count));
FileWriteDouble(Hadle_2,ordinate_1,DOUBLE_VALUE);//writing to the file database...
FileWriteDouble(Hadle_2,ordinate_2,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_3,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_4,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,ordinate_5,DOUBLE_VALUE);
FileWriteDouble(Hadle_2,0,DOUBLE_VALUE); //write label 0 as loss
}
}
}
//Closing files after writing the data
FileClose(Hadle_1);
FileClose(Hadle_2);
}
return(0);
}
//+------------------------------------------------------------------+
//| End of Expert Deinitialization
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert start
//+------------------------------------------------------------------+
int start()
{
OrderProfitToCSV(myTerminal); //write previous orders profit results for auto analysis in R
//----------Order management through R - to avoid slow down the system only enable with external parameters
if(R_Management && isNewBar())
{
//code that only executed once a bar
// Direction = -1; //set direction to -1 by default in order to achieve cross!
OrderProfitToCSV(T_Num()); //write previous orders profit results for auto analysis in R
MyMarketType = (int)ReadDataFromDSS(Symbol(), 60, "read_mt"); //read analytical output from the Decision Support System
//get the Reinforcement Learning policy for specific Market Type
if(TerminalType == 0 && use_market_type == true)
{
//this will return true/false value by interpreting the file generated by Reinforcement Learning
isMarketTypePolicyON = CheckIfMarketTypePolicyIsOn(MagicNumber, MyMarketType);
} else
{
isMarketTypePolicyON = true;
}
TradeAllowed = ReadCommandFromCSV(MagicNumber); //read command from R to make sure trading is allowed
}
//----------Variables to be Refreshed-----------
OrderNumber=0; // OrderNumber used in Entry Rules
//----------Entry & Exit Variables-----------
//define variables for trade entry...
double MACD_1=iMACD(Symbol(),Period(),fast,slow,9,PRICE_TYPICAL,0,1); //1 periods before
double MACD_2=iMACD(Symbol(),Period(),fast,slow,9,PRICE_TYPICAL,0,2); //2 periods before
double MACD_3=iMACD(Symbol(),Period(),fast,slow,9,PRICE_TYPICAL,0,3); //3 periods before...
double vector[5]; //prepare array vector of dim 5
vector[0]=iMA(Symbol(),Period(),89,0,0,5,1)/(0.0000001 + iMA(Symbol(),Period(),144,0,0,5,1)); //calculate indicators and put them to vector[5] array
vector[1]=iMA(Symbol(),Period(),144,0,0,5,1)/(0.0000001 + iMA(Symbol(),Period(),233,0,0,5,1));
vector[2]=iMA(Symbol(),Period(),21,0,0,5,1)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,1));
vector[3]=iMA(Symbol(),Period(),55,0,0,5,1)/(0.0000001 + iMA(Symbol(),Period(),89,0,0,5,1));
vector[4]=iMA(Symbol(),Period(),2,0,0,5,1)/(0.0000001 + iMA(Symbol(),Period(),55,0,0,5,1));
if(!Base) Prob_win_sell = Euclidean_Metric(base_sell,vector,numbers_of_vectors_sell); //calculate Probabiltiy to win using function Euclidean_Metric...
if(!Base) Prob_win_buy = Euclidean_Metric(base_buy,vector, numbers_of_vectors_buy); //calculate Probabiltiy to win using function Euclidean_Metric...
CrossTriggered0=Crossed0(MACD_3, MACD_2); // value 2 means MACD3 < MACD_2 (cross) Sell signal; value 1 MACD3 > MACD 2 Buy signal
CrossTriggered1=Crossed1(MACD_2, MACD_1); // value 1 means MACD_2 > MACD_1 (cross) sell signal; value 2 MACD_2 < MACD_1 Buy signal
/*
Buy Entry: Crossed0 == 1 && Crossed1 == 2
Sel Entry: Crossed0 == 2 && Crossed1 == 1
If Output is 0: No cross happened
If Output is 1: Line 1 above Line 2
If Output is 2: Line 1 below Line 2
*/
//Exit variables:
if(closeAllOnFridays)
{
//check if it's Friday and 1 hr before market closure
if(Hour()== 22 && DayOfWeek()== 5)
{
isFridayActive = true;
} else
{
isFridayActive = false;
}
}
//----------TP, SL, Breakeven and Trailing Stops Variables-----------
myATR=iATR(NULL,Period(),atr_period,1);
if(UseFixedStopLoss==False)
{
Stop=0;
} else {
Stop=VolBasedStopLoss(IsVolatilityStopOn,FixedStopLoss,myATR,VolBasedSLMultiplier,P);
}
if(UseFixedTakeProfit==False)
{
Take=0;
} else {
Take=VolBasedTakeProfit(IsVolatilityTakeProfitOn,FixedTakeProfit,myATR,VolBasedTPMultiplier,P);
}
if(UseBreakevenStops) BreakevenStopAll(OnJournaling,RetryInterval,BreakevenBuffer,MagicNumber,P);
if(UseTrailingStops) TrailingStopAll(OnJournaling,TrailingStopDistance,TrailingStopBuffer,RetryInterval,MagicNumber,P);
if(UseVolTrailingStops) {
UpdateVolTrailingList(OnJournaling,RetryInterval,MagicNumber);
ReviewVolTrailingStop(OnJournaling,VolTrailingDistMultiplier,VolTrailingBuffMultiplier,RetryInterval,MagicNumber,P);
}
//----------(Hidden) TP, SL, Breakeven and Trailing Stops Variables-----------
if(UseHiddenStopLoss) TriggerStopLossHidden(OnJournaling,RetryInterval,MagicNumber,Slippage,P);
if(UseHiddenTakeProfit) TriggerTakeProfitHidden(OnJournaling,RetryInterval,MagicNumber,Slippage,P);
if(UseHiddenBreakevenStops) {
UpdateHiddenBEList(OnJournaling,RetryInterval,MagicNumber);
SetAndTriggerBEHidden(OnJournaling,BreakevenBuffer,MagicNumber,Slippage,P,RetryInterval);
}
if(UseHiddenTrailingStops) {
UpdateHiddenTrailingList(OnJournaling,RetryInterval,MagicNumber);
SetAndTriggerHiddenTrailing(OnJournaling,TrailingStopDistance_Hidden,TrailingStopBuffer_Hidden,Slippage,RetryInterval,MagicNumber,P);
}
if(UseHiddenVolTrailing) {
UpdateHiddenVolTrailingList(OnJournaling,RetryInterval,MagicNumber);
TriggerAndReviewHiddenVolTrailing(OnJournaling,VolTrailingDistMultiplier_Hidden,VolTrailingBuffMultiplier_Hidden,Slippage,RetryInterval,MagicNumber,P);
}
//----------Exit Rules (All Opened Positions)-----------
// TDL 2: Setting up Exit rules. Modify the ExitSignal() function to suit your needs.
if(Base)
{
//in test mode
if(CountPosOrders(MagicNumber,OP_BUY)>=1 && ExitSignal(CrossTriggered0)==2 && ExitSignal(CrossTriggered1)==1 && close_orders)
{ // Close Long Positions
CloseOrderPosition(OP_BUY, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
if(CountPosOrders(MagicNumber,OP_SELL)>=1 && ExitSignal(CrossTriggered0)==1 && ExitSignal(CrossTriggered1)==2 && close_orders)
{ // Close Short Positions
CloseOrderPosition(OP_SELL, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
}
if(!Base)
{
//in trading mode
if(CountPosOrders(MagicNumber,OP_BUY)>=1 && ((ExitSignal(CrossTriggered0)==2 && ExitSignal(CrossTriggered1)==1 && close_orders) || isFridayActive == true))
{ // Close Long Positions
CloseOrderPosition(OP_BUY, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
if(CountPosOrders(MagicNumber,OP_SELL)>=1 && ((ExitSignal(CrossTriggered0)==1 && ExitSignal(CrossTriggered1)==2 && close_orders) || isFridayActive == true))
{ // Close Short Positions
CloseOrderPosition(OP_SELL, OnJournaling, MagicNumber, Slippage, P, RetryInterval);
}
}
//----------Entry Rules (Market and Pending) -----------
if(IsLossLimitBreached(IsLossLimitActivated,LossLimitPercent,OnJournaling,EntrySignal(CrossTriggered0))==False)
if(IsVolLimitBreached(IsVolLimitActivated,VolatilityMultiplier,ATRTimeframe,ATRPeriod)==False)
if(IsMaxPositionsReached(MaxPositionsAllowed,MagicNumber,OnJournaling)==False)
{
//order opening in TESTING
if(Base && EntrySignal(CrossTriggered0)==1 && EntrySignal(CrossTriggered1)==2)
{ // Open Long Positions
OrderNumber=OpenPositionMarket(OP_BUY,GetLot(IsSizingOn,Lots,Risk,YenPairAdjustFactor,Stop,P),Stop,Take,MagicNumber,Slippage,OnJournaling,P,IsECNbroker,MaxRetriesPerTick,RetryInterval);
// Set Stop Loss value for Hidden SL
if(UseHiddenStopLoss) SetStopLossHidden(OnJournaling,IsVolatilityStopLossOn_Hidden,FixedStopLoss_Hidden,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
}
if(Base && EntrySignal(CrossTriggered0)==2 && EntrySignal(CrossTriggered1)==1)
{ // Open Short Positions
OrderNumber=OpenPositionMarket(OP_SELL,GetLot(IsSizingOn,Lots,Risk,YenPairAdjustFactor,Stop,P),Stop,Take,MagicNumber,Slippage,OnJournaling,P,IsECNbroker,MaxRetriesPerTick,RetryInterval);
// Set Stop Loss value for Hidden SL
if(UseHiddenStopLoss) SetStopLossHidden(OnJournaling,IsVolatilityStopLossOn_Hidden,FixedStopLoss_Hidden,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
}
//order opening in TRADING
//if(TradeAllowed && Prob_win>=buy_threshold)OrderSend(Symbol(),OP_BUY,0.01,Ask,3,Bid-sl*Point,Ask+tp*Point);
//if(TradeAllowed && inverse_position_open && Prob_win<=invers_buy_threshold)OrderSend(Symbol(),OP_SELL,0.01,Bid,3,Ask+sl*Point,Bid-tp*Point);
if(!Base && !isFridayActive && TradeAllowed && isMarketTypePolicyON && (Prob_win_buy >= buy_threshold || (inverse_position_open && Prob_win_sell <= invers_sell_threshold)) &&
EntrySignal(CrossTriggered0)==1 && EntrySignal(CrossTriggered1)==2)
{ // Open Long Positions
OrderNumber=OpenPositionMarket(OP_BUY,GetLot(IsSizingOn,Lots,Risk,YenPairAdjustFactor,Stop,P),Stop,Take,MagicNumber,Slippage,OnJournaling,P,IsECNbroker,MaxRetriesPerTick,RetryInterval);
// Log current MarketType to the file in the sandbox
LogMarketType(MagicNumber, OrderNumber, MyMarketType);
// Set Stop Loss value for Hidden SL
if(UseHiddenStopLoss) SetStopLossHidden(OnJournaling,IsVolatilityStopLossOn_Hidden,FixedStopLoss_Hidden,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
}
//if(TradeAllowed && Prob_win >= sell_threshold)OrderSend(Symbol(),OP_SELL,0.01,Bid,3,Ask+sl*Point,Bid-tp*Point);
//if(TradeAllowed && inverse_position_open && Prob_win<=invers_sell_threshold)OrderSend(Symbol(),OP_BUY,0.01,Ask,3,Bid-sl*Point,Ask+tp*Point);
if(!Base && !isFridayActive && TradeAllowed && isMarketTypePolicyON && (Prob_win_sell >= sell_threshold || (inverse_position_open && Prob_win_buy <= invers_buy_threshold)) &&
EntrySignal(CrossTriggered0)==2 && EntrySignal(CrossTriggered1)==1)
{ // Open Short Positions
OrderNumber=OpenPositionMarket(OP_SELL,GetLot(IsSizingOn,Lots,Risk,YenPairAdjustFactor,Stop,P),Stop,Take,MagicNumber,Slippage,OnJournaling,P,IsECNbroker,MaxRetriesPerTick,RetryInterval);
// Log current MarketType to the file in the sandbox
LogMarketType(MagicNumber, OrderNumber, MyMarketType);
// Set Stop Loss value for Hidden SL
if(UseHiddenStopLoss) SetStopLossHidden(OnJournaling,IsVolatilityStopLossOn_Hidden,FixedStopLoss_Hidden,myATR,VolBasedSLMultiplier_Hidden,P,OrderNumber);
// Set Take Profit value for Hidden TP
if(UseHiddenTakeProfit) SetTakeProfitHidden(OnJournaling,IsVolatilityTakeProfitOn_Hidden,FixedTakeProfit_Hidden,myATR,VolBasedTPMultiplier_Hidden,P,OrderNumber);
// Set Volatility Trailing Stop Level
if(UseVolTrailingStops) SetVolTrailingStop(OnJournaling,RetryInterval,myATR,VolTrailingDistMultiplier,MagicNumber,P,OrderNumber);
// Set Hidden Volatility Trailing Stop Level
if(UseHiddenVolTrailing) SetHiddenVolTrailing(OnJournaling,myATR,VolTrailingDistMultiplier_Hidden,MagicNumber,P,OrderNumber);
}
}
//----------Pending Order Management-----------
/*
Not Applicable (See Desiree for example of pending order rules).
*/
//----
//adding dashboard
if(EnableDashboard==True) ShowDashboard("Magic Number", MagicNumber,
"Market Type", MyMarketType,
"xxx", 0,
"Prob_win_buy", Prob_win_buy,
"xxx", 0,
"Prob_win_sell", Prob_win_sell,
"xxx", 0,
"xxx", 0);
return(0);
}
//----
//+------------------------------------------------------------------+
//| End of expert start function |
//+------------------------------------------------------------------+
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//| FUNCTIONS LIBRARY
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
/*
Content:
1) EntrySignal
2) ExitSignal
3) GetLot
4) CheckLot
5) CountPosOrders
6) IsMaxPositionsReached
7) OpenPositionMarket
8) OpenPositionPending
9) CloseOrderPosition
10) GetP
11) GetYenAdjustFactor
12) VolBasedStopLoss
13) VolBasedTakeProfit
14) Crossed1 / Crossed2
15) IsLossLimitBreached
16) IsVolLimitBreached
17) SetStopLossHidden
18) TriggerStopLossHidden
19) SetTakeProfitHidden
20) TriggerTakeProfitHidden
21) BreakevenStopAll
22) UpdateHiddenBEList
23) SetAndTriggerBEHidden
24) TrailingStopAll
25) UpdateHiddenTrailingList
26) SetAndTriggerHiddenTrailing
27) UpdateVolTrailingList
28) SetVolTrailingStop
29) ReviewVolTrailingStop
30) UpdateHiddenVolTrailingList
31) SetHiddenVolTrailing
32) TriggerAndReviewHiddenVolTrailing
33) HandleTradingEnvironment
34) GetErrorDescription
35) ReadAutoPrediction
*/
//+------------------------------------------------------------------+
//| ENTRY SIGNAL |
//+------------------------------------------------------------------+
int EntrySignal(int CrossOccurred)
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for entry signals
int entryOutput=0;
if(CrossOccurred==1) entryOutput=1;
if(CrossOccurred==2) entryOutput=2;
return(entryOutput);
}
//+------------------------------------------------------------------+
//| End of ENTRY SIGNAL |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Exit SIGNAL |
//+------------------------------------------------------------------+
int ExitSignal(int CrossOccurred)
{
// Type: Customisable
// Modify this function to suit your trading robot
// This function checks for exit signals
int ExitOutput=0;
if(CrossOccurred==1) ExitOutput=1;
if(CrossOccurred==2) ExitOutput=2;
return(ExitOutput);
}
//+------------------------------------------------------------------+
//| End of Exit SIGNAL
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Position Sizing Algo
//+------------------------------------------------------------------+
// Type: Customisable
// Modify this function to suit your trading robot
// This is our sizing algorithm
double GetLot(bool IsSizingOnTrigger,double FixedLots,double RiskPerTrade,int YenAdjustment,double STOP,int K)
{
double output;
if(IsSizingOnTrigger==true)
{
output=RiskPerTrade*0.01*AccountBalance()/(MarketInfo(Symbol(),MODE_LOTSIZE)*MarketInfo(Symbol(),MODE_TICKVALUE)*STOP*K*Point); // Sizing Algo based on account size
output=output*YenAdjustment; // Adjust for Yen Pairs
} else {
output=FixedLots;
}
output=NormalizeDouble(output,2); // Round to 2 decimal place
return(output);
}
//+------------------------------------------------------------------+
//| End of Position Sizing Algo
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| CHECK LOT
//+------------------------------------------------------------------+
double CheckLot(double Lot,bool Journaling)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function checks if our Lots to be trade satisfies any broker limitations
double LotToOpen=0;
LotToOpen=NormalizeDouble(Lot,2);
LotToOpen=MathFloor(LotToOpen/MarketInfo(Symbol(),MODE_LOTSTEP))*MarketInfo(Symbol(),MODE_LOTSTEP);
if(LotToOpen<MarketInfo(Symbol(),MODE_MINLOT))LotToOpen=MarketInfo(Symbol(),MODE_MINLOT);
if(LotToOpen>MarketInfo(Symbol(),MODE_MAXLOT))LotToOpen=MarketInfo(Symbol(),MODE_MAXLOT);
LotToOpen=NormalizeDouble(LotToOpen,2);
if(Journaling && LotToOpen!=Lot)Print("EA Journaling: Trading Lot has been changed by CheckLot function. Requested lot: "+(string)Lot+". Lot to open: "+(string)LotToOpen);
return(LotToOpen);
}
//+------------------------------------------------------------------+
//| End of CHECK LOT
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| COUNT POSITIONS
//+------------------------------------------------------------------+
int CountPosOrders(int Magic,int TYPE)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function counts number of positions/orders of OrderType TYPE
int Orders=0;
for(int i=0; i<OrdersTotal(); i++)
{
if(OrderSelect(i,SELECT_BY_POS,MODE_TRADES)==true && OrderSymbol()==Symbol() && OrderMagicNumber()==Magic && OrderType()==TYPE)
Orders++;
}
return(Orders);
}
//+------------------------------------------------------------------+
//| End of COUNT POSITIONS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| MAX ORDERS
//+------------------------------------------------------------------+
bool IsMaxPositionsReached(int MaxPositions,int Magic,bool Journaling)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function checks the number of positions we are holding against the maximum allowed
bool result=False;
if(CountPosOrders(Magic,OP_BUY)+CountPosOrders(Magic,OP_SELL)>MaxPositions)
{
result=True;
if(Journaling)Print("Max Orders Exceeded");
} else if(CountPosOrders(Magic,OP_BUY)+CountPosOrders(Magic,OP_SELL)==MaxPositions) {
result=True;
}
return(result);
/* Definitions: Position vs Orders
Position describes an opened trade
Order is a pending trade
How to use in a sentence: Jim has 5 buy limit orders pending 10 minutes ago. The market just crashed. The orders were executed and he has 5 losing positions now lol.
*/
}
//+------------------------------------------------------------------+
//| End of MAX ORDERS
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| OPEN FROM MARKET
//+------------------------------------------------------------------+
int OpenPositionMarket(int TYPE,double LOT,double SL,double TP,int Magic,int Slip,bool Journaling,int K,bool ECN,int Max_Retries_Per_Tick,int Retry_Interval)
{
// Type: Fixed Template
// Do not edit unless you know what you're doing
// This function submits new orders
int tries=0;
string symbol=Symbol();
int cmd=TYPE;
double volume=CheckLot(LOT,Journaling);
if(MarketInfo(symbol,MODE_MARGINREQUIRED)*volume>AccountFreeMargin())
{
Print("Can not open a trade. Not enough free margin to open "+(string)volume+" on "+symbol);
return(-1);
}
int slippage=Slip*K; // Slippage is in points. 1 point = 0.0001 on 4 digit broker and 0.00001 on a 5 digit broker
string comment=" "+(string)TYPE+"(#"+(string)Magic+")";
int magic=Magic;
datetime expiration=0;
color arrow_color=0;if(TYPE==OP_BUY)arrow_color=Blue;if(TYPE==OP_SELL)arrow_color=Green;
double stoploss=0;
double takeprofit=0;
double initTP = TP;
double initSL = SL;
int Ticket=-1;
double price=0;
if(!ECN)
{
while(tries<Max_Retries_Per_Tick) // Edits stops and take profits before the market order is placed
{
RefreshRates();
if(TYPE==OP_BUY)price=Ask;if(TYPE==OP_SELL)price=Bid;
// Sets Take Profits and Stop Loss. Check against Stop Level Limitations.
if(TYPE==OP_BUY && SL!=0)
{
stoploss=NormalizeDouble(Ask-SL*K*Point,Digits);
if(Bid-stoploss<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_SELL && SL!=0)
{
stoploss=NormalizeDouble(Bid+SL*K*Point,Digits);
if(stoploss-Ask<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_BUY && TP!=0)
{
takeprofit=NormalizeDouble(Ask+TP*K*Point,Digits);
if(takeprofit-Bid<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(TYPE==OP_SELL && TP!=0)
{
takeprofit=NormalizeDouble(Bid-TP*K*Point,Digits);
if(Ask-takeprofit<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string(MarketInfo(Symbol(),MODE_STOPLEVEL)/K)+" pips");
}
}
if(Journaling)Print("EA Journaling: Trying to place a market order...");
HandleTradingEnvironment(Journaling,Retry_Interval);
Ticket=OrderSend(symbol,cmd,volume,price,slippage,stoploss,takeprofit,comment,magic,expiration,arrow_color);
if(Ticket>0)break;
tries++;
}
}
if(ECN) // Edits stops and take profits after the market order is placed
{
HandleTradingEnvironment(Journaling,Retry_Interval);
if(TYPE==OP_BUY)price=Ask;if(TYPE==OP_SELL)price=Bid;
if(Journaling)Print("EA Journaling: Trying to place a market order...");
Ticket=OrderSend(symbol,cmd,volume,price,slippage,0,0,comment,magic,expiration,arrow_color);
if(Ticket>0)
if(Ticket>0 && OrderSelect(Ticket,SELECT_BY_TICKET)==true && (SL!=0 || TP!=0))
{
// Sets Take Profits and Stop Loss. Check against Stop Level Limitations.
if(TYPE==OP_BUY && SL!=0)
{
stoploss=NormalizeDouble(OrderOpenPrice()-SL*K*Point,Digits);
if(Bid-stoploss<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string((OrderOpenPrice()-stoploss)/(K*Point))+" pips");
}
}
if(TYPE==OP_SELL && SL!=0)
{
stoploss=NormalizeDouble(OrderOpenPrice()+SL*K*Point,Digits);
if(stoploss-Ask<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
stoploss=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Stop Loss changed from "+(string)initSL+" to "+string((stoploss-OrderOpenPrice())/(K*Point))+" pips");
}
}
if(TYPE==OP_BUY && TP!=0)
{
takeprofit=NormalizeDouble(OrderOpenPrice()+TP*K*Point,Digits);
if(takeprofit-Bid<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Ask+MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string((takeprofit-OrderOpenPrice())/(K*Point))+" pips");
}
}
if(TYPE==OP_SELL && TP!=0)
{
takeprofit=NormalizeDouble(OrderOpenPrice()-TP*K*Point,Digits);
if(Ask-takeprofit<=MarketInfo(Symbol(),MODE_STOPLEVEL)*Point)
{
takeprofit=NormalizeDouble(Bid-MarketInfo(Symbol(),MODE_STOPLEVEL)*Point,Digits);
if(Journaling)Print("EA Journaling: Take Profit changed from "+(string)initTP+" to "+string((OrderOpenPrice()-takeprofit)/(K*Point))+" pips");
}
}
bool ModifyOpen=false;
while(!ModifyOpen)
{
HandleTradingEnvironment(Journaling,Retry_Interval);
ModifyOpen=OrderModify(Ticket,OrderOpenPrice(),stoploss,takeprofit,expiration,arrow_color);
if(Journaling && !ModifyOpen)Print("EA Journaling: Take Profit and Stop Loss not set. Error Description: "+GetErrorDescription(GetLastError()));
}
}
}
if(Journaling && Ticket<0)Print("EA Journaling: Unexpected Error has happened. Error Description: "+GetErrorDescription(GetLastError()));
if(Journaling && Ticket>0)