forked from EA31337/EA31337-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MQL4.mqh
1198 lines (930 loc) · 39.6 KB
/
MQL4.mqh
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
//+------------------------------------------------------------------+
//| EA31337 - multi-strategy advanced trading robot. |
//| Copyright 2016-2018, 31337 Investments Ltd |
//| https://github.com/EA31337 |
//+------------------------------------------------------------------+
/*
This file is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @file
* Provide backward compability for MQL4 in MT5/MQL5.
*/
// Prevents processing this includes file for the second time.
#ifndef MQL4_MQH
#define MQL4_MQH
//+------------------------------------------------------------------+
//| Declaration of constants
//+------------------------------------------------------------------+
// Index in the order pool.
#ifndef SELECT_BY_POS
#define SELECT_BY_POS 0
#endif
// Some of standard MQL4 constants are absent in MQL5, therefore they should be declared as below.
#ifdef __MQL5__
#define show_inputs script_show_inputs
// --
#define extern input
// --
#define init OnInit
// --
#define Point _Point
#define Digits _Digits
// --
// Defines macros for MQL5.
/* @fixme: Conflicts with SymbolInfo::Ask() method.
#define Ask SymbolInfo::GetAsk(_Symbol)
#define Bid SymbolInfo::GetAsk(_Symbol)
//#define Bid (::SymbolInfoDouble(_Symbol, ::SYMBOL_BID))
//#define Ask (::SymbolInfoDouble(_Symbol, ::SYMBOL_ASK))
*/
// Defines macros for MQL5.
/* @fixme: error: macro too complex
#define Day(void) DateTime::Day()
#define DayOfWeek(void) SymbolInfo::DayOfWeek()
#define DayOfYear(void) SymbolInfo::DayOfYear()
*/
// Define boolean values.
#define True true
#define False false
#define TRUE true
#define FALSE false
// --
/* @fixme: If this is defined, cannot call: DateTime::TimeToStr().
#ifndef TimeToStr
#define TimeToStr(time_value, flags) TimeToString(time_value, flags)
#endif
*/
// --
#ifndef DoubleToStr
#define DoubleToStr DoubleToString
#endif
// --
#define StrToTime StringToTime
// --
#define CurTime TimeCurrent
// --
#define LocalTime TimeLocal
// Mode constants.
#define MODE_TRADES 0
#define MODE_HISTORY 1
// --
#define DOUBLE_VALUE 0
#define FLOAT_VALUE 1
#define LONG_VALUE INT_VALUE
// Chart.
#define CHART_BAR 0
#define CHART_CANDLE 1
//---
#ifndef MODE_ASCEND
#define MODE_ASCEND 0
#endif
#ifndef MODE_DESCEND
#define MODE_DESCEND 1
#endif
//---
#define MODE_LOW 1
#define MODE_HIGH 2
// --
#define MODE_OPEN 0
#define MODE_CLOSE 3
#define MODE_VOLUME 4
#define MODE_REAL_VOLUME 5
// --
#define MODE_TIME 5
#define MODE_BID 9
#define MODE_ASK 10
#define MODE_POINT 11
#define MODE_DIGITS 12
#define MODE_SPREAD 13
#define MODE_STOPLEVEL 14
#define MODE_LOTSIZE 15
#define MODE_TICKVALUE 16
#define MODE_TICKSIZE 17
#define MODE_SWAPLONG 18
#define MODE_SWAPSHORT 19
#define MODE_STARTING 20
#define MODE_EXPIRATION 21
#define MODE_TRADEALLOWED 22
#define MODE_TICK_SIZE 21
#define MODE_TICK_VALUE 22
#define MODE_MINLOT 23
#define MODE_LOTSTEP 24
#define MODE_MAXLOT 25
#define MODE_SWAPTYPE 26
#define MODE_PROFITCALCMODE 27
#define MODE_MARGINCALCMODE 28
#define MODE_MARGININIT 29
#define MODE_MARGINMAINTENANCE 30
#define MODE_MARGINHEDGED 31
#define MODE_MARGINREQUIRED 32
#define MODE_FREEZELEVEL 33
// --
#define OP_BUY ORDER_TYPE_BUY // Buy
#define OP_SELL ORDER_TYPE_SELL // Sell
#define OP_BUYLIMIT ORDER_TYPE_BUY_LIMIT // Pending order of BUY LIMIT type
#define OP_SELLLIMIT ORDER_TYPE_SELL_LIMIT // Pending order of SELL LIMIT type
#define OP_BUYSTOP ORDER_TYPE_BUY_STOP // Pending order of BUY STOP type
#define OP_SELLSTOP ORDER_TYPE_SELL_STOP // Pending order of SELL STOP type
#define OP_BALANCE 6
//---
#define EMPTY -1
#ifndef TRADE_ACTION_CLOSE_BY
#define TRADE_ACTION_CLOSE_BY 1
#endif
// Return codes of the trade server.
#define ERR_NO_ERROR 0
#define ERR_NO_RESULT 1
#define ERR_COMMON_ERROR 2
#define ERR_INVALID_TRADE_PARAMETERS 3
#define ERR_SERVER_BUSY 4
#define ERR_OLD_VERSION 5
#define ERR_NO_CONNECTION 6
#define ERR_NOT_ENOUGH_RIGHTS 7
#define ERR_TOO_FREQUENT_REQUESTS 8
#define ERR_MALFUNCTIONAL_TRADE 9
#define ERR_ACCOUNT_DISABLED 64
#define ERR_INVALID_ACCOUNT 65
#define ERR_TRADE_TIMEOUT 128
#define ERR_INVALID_PRICE 129
#define ERR_INVALID_STOPS 130
#define ERR_INVALID_TRADE_VOLUME 131
#define ERR_MARKET_CLOSED 132
//#define ERR_TRADE_DISABLED 133
#define ERR_NOT_ENOUGH_MONEY 134
#define ERR_PRICE_CHANGED 135
#define ERR_OFF_QUOTES 136
#define ERR_BROKER_BUSY 137
#define ERR_REQUOTE 138
#define ERR_ORDER_LOCKED 139
#define ERR_LONG_POSITIONS_ONLY_ALLOWED 140
#define ERR_TOO_MANY_REQUESTS 141
#define ERR_TRADE_MODIFY_DENIED 145
#define ERR_TRADE_CONTEXT_BUSY 146
#define ERR_TRADE_EXPIRATION_DENIED 147
#define ERR_TRADE_TOO_MANY_ORDERS 148
#define ERR_TRADE_HEDGE_PROHIBITED 149
#define ERR_TRADE_PROHIBITED_BY_FIFO 150
//+------------------------------------------------------------------+
//| Includes.
//+------------------------------------------------------------------+
/**
* Returns market data about securities.
*/
/*
#include "Market.mqh"
double MarketInfo(string _symbol, int _type) {
return Market::MarketInfo(_symbol, _type);
}
*/
#define StringGetChar StringGetCharacter
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
string StringSetChar(const string &String_Var,const int iPos,const ushort Value)
{
string Str=String_Var;
::StringSetCharacter(Str,iPos,Value);
return(Str);
}
int MT4Bars(void) {
return (::Bars(_Symbol, _Period));
}
// #define Bars (::MT4Bars())
#define DEFINE_TIMESERIE(NAME,FUNC,T) \
class CLASS##NAME { \
public: \
static T Get(const string Symb,const int TimeFrame,const int iShift) { \
T tValue[]; \
\
return((Copy##FUNC((Symb == NULL) ? _Symbol : Symb, _Period, iShift, 1, tValue) > 0) ? tValue[0] : -1); \
} \
\
T operator[](const int iPos) const { \
return(CLASS##NAME::Get(_Symbol, _Period, iPos)); \
} \
}; \
\
CLASS##NAME NAME; \
\
T i##NAME(const string Symb,const int TimeFrame,const int iShift) \
{ \
return(CLASS##NAME::Get(Symb, TimeFrame, iShift)); \
}
DEFINE_TIMESERIE(Volume,TickVolume,long)
DEFINE_TIMESERIE(Time,Time,datetime)
DEFINE_TIMESERIE(Open,Open,double)
DEFINE_TIMESERIE(High,High,double)
DEFINE_TIMESERIE(Low,Low,double)
DEFINE_TIMESERIE(Close,Close,double)
#endif // __MQL5__
#ifdef __MQL5__
#ifndef __MT4ORDERS__
#define __MT4ORDERS__
#define RESERVE_SIZE 1000
#define DAY (24 * 3600)
#define HISTORY_PAUSE (MT4HISTORY::IsTester ? 0 : 5)
class MT4HISTORY
{
private:
static const bool IsTester;
long Tickets[];
uint Amount;
datetime LastTime;
int LastTotalDeals;
int LastTotalOrders;
datetime LastInitTime;
#define GETNEXTPOS_FUNCTION(NAME) \
static int GetNextPosMT4##NAME( int iPos ) \
{ \
const int Total = ::History##NAME##sTotal(); \
\
while (iPos < Total) \
{ \
if (MT4HISTORY::IsMT4##NAME(::History##NAME##GetTicket(iPos))) \
break; \
\
iPos++; \
} \
\
return(iPos); \
}
GETNEXTPOS_FUNCTION(Order)
GETNEXTPOS_FUNCTION(Deal)
#undef GETNEXTPOS_FUNCTION
bool RefreshHistory(void)
{
bool Res = false;
const datetime LastTimeCurrent = ::TimeCurrent();
if ((!MT4HISTORY::IsTester) && (LastTimeCurrent >= this.LastInitTime + DAY))
{
this.LastTime = 0;
this.LastTotalOrders = 0;
this.LastTotalDeals = 0;
this.Amount = 0;
::ArrayResize(this.Tickets, this.Amount, RESERVE_SIZE);
this.LastInitTime = LastTimeCurrent;
}
if (::HistorySelect(this.LastTime, ::MathMax(LastTimeCurrent, this.LastTime) + DAY)) // Daily stock.
{
const int TotalOrders = ::HistoryOrdersTotal();
const int TotalDeals = ::HistoryDealsTotal();
Res = ((TotalOrders != this.LastTotalOrders) || (TotalDeals != this.LastTotalDeals));
if (Res)
{
int iOrder = MT4HISTORY::GetNextPosMT4Order(this.LastTotalOrders);
int iDeal = MT4HISTORY::GetNextPosMT4Deal(this.LastTotalDeals);
long TimeOrder = (iOrder < TotalOrders) ? ::HistoryOrderGetInteger(::HistoryOrderGetTicket(iOrder), ORDER_TIME_DONE/*_MSC*/) : LONG_MAX; // ORDER_TIME_DONE_MSC returns zero in the tester (build 1470).
long TimeDeal = (iDeal < TotalDeals) ? ::HistoryDealGetInteger(::HistoryDealGetTicket(iDeal), DEAL_TIME/*_MSC*/) : LONG_MAX;
while ((iDeal < TotalDeals) || (iOrder < TotalOrders))
if (TimeOrder < TimeDeal)
{
this.Amount = ::ArrayResize(this.Tickets, this.Amount + 1, RESERVE_SIZE);
this.Tickets[this.Amount - 1] = -(long)::HistoryOrderGetTicket(iOrder);
iOrder = MT4HISTORY::GetNextPosMT4Order(iOrder + 1);
TimeOrder = (iOrder < TotalOrders) ? ::HistoryOrderGetInteger(::HistoryOrderGetTicket(iOrder), ORDER_TIME_DONE/*_MSC*/) : LONG_MAX; // ORDER_TIME_DONE_MSC returns zero in the tester (build 1470).
}
else
{
this.Amount = ::ArrayResize(this.Tickets, this.Amount + 1, RESERVE_SIZE);
this.Tickets[this.Amount - 1] = (long)::HistoryDealGetTicket(iDeal);
iDeal = MT4HISTORY::GetNextPosMT4Deal(iDeal + 1);
TimeDeal = (iDeal < TotalDeals) ? ::HistoryDealGetInteger(::HistoryDealGetTicket(iDeal), DEAL_TIME/*_MSC*/) : LONG_MAX;
}
TimeOrder = (TotalOrders > 0) ? ::HistoryOrderGetInteger(::HistoryOrderGetTicket(TotalOrders - 1), ORDER_TIME_DONE/*_MSC*/) : 0;
TimeDeal = (TotalDeals > 0) ? ::HistoryDealGetInteger(::HistoryDealGetTicket(TotalDeals - 1), DEAL_TIME/*_MSC*/) : 0;
const long MaxTime = ::MathMax(TimeOrder, TimeDeal);
this.LastTotalOrders = 0;
this.LastTotalDeals = 0;
if (LastTimeCurrent - HISTORY_PAUSE > MaxTime)
this.LastTime = LastTimeCurrent - HISTORY_PAUSE;
else
{
this.LastTime = (datetime)MaxTime;
if (TimeOrder == MaxTime)
for (int i = TotalOrders - 1; i >= 0; i--)
{
if (TimeOrder > ::HistoryOrderGetInteger(::HistoryOrderGetTicket(i), ORDER_TIME_DONE/*_MSC*/))
break;
this.LastTotalOrders++;
}
if (TimeDeal == MaxTime)
for (int i = TotalDeals - 1; i >= 0; i--)
{
if (TimeDeal != ::HistoryDealGetInteger(::HistoryDealGetTicket(TotalDeals - 1), DEAL_TIME/*_MSC*/))
break;
this.LastTotalDeals++;
}
}
}
else if (LastTimeCurrent - HISTORY_PAUSE > this.LastTime)
{
this.LastTime = LastTimeCurrent - HISTORY_PAUSE;
this.LastTotalOrders = 0;
this.LastTotalDeals = 0;
}
}
return(Res);
}
public:
static bool IsMT4Deal( const ulong Ticket )
{
const ENUM_DEAL_TYPE Type = (ENUM_DEAL_TYPE)::HistoryDealGetInteger(Ticket, DEAL_TYPE);
return(((Type != DEAL_TYPE_BUY) && (Type != DEAL_TYPE_SELL)) || ((ENUM_DEAL_ENTRY)::HistoryDealGetInteger(Ticket, DEAL_ENTRY) == DEAL_ENTRY_OUT));
}
static bool IsMT4Order( const ulong Ticket )
{
return((::HistoryOrderGetDouble(Ticket, ORDER_VOLUME_CURRENT) > 0) || (::HistoryOrderGetInteger(Ticket, ORDER_POSITION_ID) == 0));
}
MT4HISTORY(void) : Amount(0), LastTime(0), LastTotalDeals(0), LastTotalOrders(0), LastInitTime(0)
{
::ArrayResize(this.Tickets, this.Amount, RESERVE_SIZE);
this.RefreshHistory();
}
int GetAmount(void)
{
this.RefreshHistory();
return((int)this.Amount);
}
long operator []( const uint Pos )
{
long Res = 0;
if (Pos >= this.Amount)
{
this.RefreshHistory();
if (Pos < this.Amount)
Res = this.Tickets[Pos];
}
else
Res = this.Tickets[Pos];
return(Res);
}
};
static const bool MT4HISTORY::IsTester = (::MQLInfoInteger(MQL_TESTER) || ::MQLInfoInteger(MQL_OPTIMIZATION) ||
::MQLInfoInteger(MQL_VISUAL_MODE) || ::MQLInfoInteger(MQL_FRAME_MODE));
#undef HISTORY_PAUSE
#undef DAY
#undef RESERVE_SIZE
struct MT4_ORDER
{
int Ticket;
int Type;
double Lots;
string Symbol;
string Comment;
double OpenPrice;
datetime OpenTime;
double StopLoss;
double TakeProfit;
double ClosePrice;
datetime CloseTime;
datetime Expiration;
int MagicNumber;
double Profit;
double Commission;
double Swap;
string ToString(void) const
{
static const string Types[] = {"buy", "sell", "buy limit", "sell limit", "buy stop", "sell stop", "balance"};
const int digits = (int)::SymbolInfoInteger(this.Symbol, SYMBOL_DIGITS);
return("#" + (string)this.Ticket + " " +
(string)this.OpenTime + " " +
((this.Type < ::ArraySize(Types)) ? Types[this.Type] : "unknown") + " " +
::DoubleToString(this.Lots, 2) + " " +
this.Symbol + " " +
::DoubleToString(this.OpenPrice, digits) + " " +
::DoubleToString(this.StopLoss, digits) + " " +
::DoubleToString(this.TakeProfit, digits) + " " +
((this.CloseTime > 0) ? ((string)this.CloseTime + " ") : "") +
::DoubleToString(this.ClosePrice, digits) + " " +
::DoubleToString(this.Commission, 2) + " " +
::DoubleToString(this.Swap, 2) + " " +
::DoubleToString(this.Profit, 2) + " " +
((this.Comment == "") ? "" : (this.Comment + " ")) +
(string)this.MagicNumber +
(((this.Expiration > 0) ? (" expiration " + (string)this.Expiration): "")));
}
};
class MT4ORDERS {
private:
static MT4_ORDER Order;
static MT4HISTORY History;
static const bool IsTester;
static ulong GetPositionDealIn( const ulong PositionIdentifier = 0 ) {
ulong Ticket = 0;
if ((PositionIdentifier == 0) ? ::HistorySelectByPosition(::PositionGetInteger(POSITION_IDENTIFIER)) : ::HistorySelectByPosition(PositionIdentifier))
{
const int Total = ::HistoryDealsTotal();
for (int i = 0; i < Total; i++)
{
const ulong TicketDeal = ::HistoryDealGetTicket(i);
if (TicketDeal > 0)
if ((ENUM_DEAL_ENTRY)::HistoryDealGetInteger(TicketDeal, DEAL_ENTRY) == DEAL_ENTRY_IN)
{
Ticket = TicketDeal;
break;
}
}
}
return(Ticket);
}
static double GetPositionCommission(void) {
double Commission = ::PositionGetDouble(POSITION_COMMISSION);
if (Commission == 0)
{
const ulong Ticket = MT4ORDERS::GetPositionDealIn();
if (Ticket > 0)
{
const double LotsIn = ::HistoryDealGetDouble(Ticket, DEAL_VOLUME);
if (LotsIn > 0)
Commission = ::HistoryDealGetDouble(Ticket, DEAL_COMMISSION) * ::PositionGetDouble(POSITION_VOLUME) / LotsIn;
}
}
return(Commission);
}
static string GetPositionComment(void) {
string comment = ::PositionGetString(POSITION_COMMENT);
if (comment == "")
{
const ulong Ticket = MT4ORDERS::GetPositionDealIn();
if (Ticket > 0)
comment = ::HistoryDealGetString(Ticket, DEAL_COMMENT);
}
return(comment);
}
static void GetPositionData(void) {
MT4ORDERS::Order.Ticket = (int)::PositionGetInteger(POSITION_TICKET);
MT4ORDERS::Order.Type = (int)::PositionGetInteger(POSITION_TYPE);
MT4ORDERS::Order.Lots = ::PositionGetDouble(POSITION_VOLUME);
MT4ORDERS::Order.Symbol = ::PositionGetString(POSITION_SYMBOL);
MT4ORDERS::Order.Comment = MT4ORDERS::GetPositionComment();
MT4ORDERS::Order.OpenPrice = ::PositionGetDouble(POSITION_PRICE_OPEN);
MT4ORDERS::Order.OpenTime = (datetime)::PositionGetInteger(POSITION_TIME);
MT4ORDERS::Order.StopLoss = ::PositionGetDouble(POSITION_SL);
MT4ORDERS::Order.TakeProfit = ::PositionGetDouble(POSITION_TP);
MT4ORDERS::Order.ClosePrice = ::PositionGetDouble(POSITION_PRICE_CURRENT);
MT4ORDERS::Order.CloseTime = 0;
MT4ORDERS::Order.Expiration = 0;
MT4ORDERS::Order.MagicNumber = (int)::PositionGetInteger(POSITION_MAGIC);
MT4ORDERS::Order.Profit = ::PositionGetDouble(POSITION_PROFIT);
MT4ORDERS::Order.Commission = MT4ORDERS::GetPositionCommission();
MT4ORDERS::Order.Swap = ::PositionGetDouble(POSITION_SWAP);
return;
}
static void GetOrderData(void) {
MT4ORDERS::Order.Ticket = (int)::OrderGetInteger(ORDER_TICKET);
MT4ORDERS::Order.Type = (int)::OrderGetInteger(ORDER_TYPE);
MT4ORDERS::Order.Lots = ::OrderGetDouble(ORDER_VOLUME_CURRENT);
MT4ORDERS::Order.Symbol = ::OrderGetString(ORDER_SYMBOL);
MT4ORDERS::Order.Comment = ::OrderGetString(ORDER_COMMENT);
MT4ORDERS::Order.OpenPrice = ::OrderGetDouble(ORDER_PRICE_OPEN);
MT4ORDERS::Order.OpenTime = (datetime)::OrderGetInteger(ORDER_TIME_SETUP);
MT4ORDERS::Order.StopLoss = ::OrderGetDouble(ORDER_SL);
MT4ORDERS::Order.TakeProfit = ::OrderGetDouble(ORDER_TP);
MT4ORDERS::Order.ClosePrice = ::OrderGetDouble(ORDER_PRICE_CURRENT);
MT4ORDERS::Order.CloseTime = (datetime)::OrderGetInteger(ORDER_TIME_DONE);
MT4ORDERS::Order.Expiration = (datetime)::OrderGetInteger(ORDER_TIME_EXPIRATION);
MT4ORDERS::Order.MagicNumber = (int)::OrderGetInteger(ORDER_MAGIC);
MT4ORDERS::Order.Profit = 0;
MT4ORDERS::Order.Commission = 0;
MT4ORDERS::Order.Swap = 0;
return;
}
static void GetHistoryOrderData( const ulong Ticket ) {
MT4ORDERS::Order.Ticket = (int)::HistoryOrderGetInteger(Ticket, ORDER_TICKET);
MT4ORDERS::Order.Type = (int)::HistoryOrderGetInteger(Ticket, ORDER_TYPE);
MT4ORDERS::Order.Lots = ::HistoryOrderGetDouble(Ticket, ORDER_VOLUME_CURRENT);
if (MT4ORDERS::Order.Lots == 0)
MT4ORDERS::Order.Lots = ::HistoryOrderGetDouble(Ticket, ORDER_VOLUME_INITIAL);
MT4ORDERS::Order.Symbol = ::HistoryOrderGetString(Ticket, ORDER_SYMBOL);
MT4ORDERS::Order.Comment = ::HistoryOrderGetString(Ticket, ORDER_COMMENT);
MT4ORDERS::Order.OpenPrice = ::HistoryOrderGetDouble(Ticket, ORDER_PRICE_OPEN);
MT4ORDERS::Order.OpenTime = (datetime)::HistoryOrderGetInteger(Ticket, ORDER_TIME_SETUP);
MT4ORDERS::Order.StopLoss = ::HistoryOrderGetDouble(Ticket, ORDER_SL);
MT4ORDERS::Order.TakeProfit = ::HistoryOrderGetDouble(Ticket, ORDER_TP);
MT4ORDERS::Order.ClosePrice = 0;
MT4ORDERS::Order.CloseTime = (datetime)::HistoryOrderGetInteger(Ticket, ORDER_TIME_DONE);
MT4ORDERS::Order.Expiration = (datetime)::HistoryOrderGetInteger(Ticket, ORDER_TIME_EXPIRATION);
MT4ORDERS::Order.MagicNumber = (int)::HistoryOrderGetInteger(Ticket, ORDER_MAGIC);
MT4ORDERS::Order.Profit = 0;
MT4ORDERS::Order.Commission = 0;
MT4ORDERS::Order.Swap = 0;
return;
}
static void GetHistoryPositionData( const ulong Ticket ) {
MT4ORDERS::Order.Ticket = (int)::HistoryDealGetInteger(Ticket, DEAL_TICKET);
MT4ORDERS::Order.Type = (int)::HistoryDealGetInteger(Ticket, DEAL_TYPE);
if ((MT4ORDERS::Order.Type > OP_SELL))
MT4ORDERS::Order.Type += (OP_BALANCE - OP_SELL - 1);
else
MT4ORDERS::Order.Type = 1 - MT4ORDERS::Order.Type;
MT4ORDERS::Order.Lots = ::HistoryDealGetDouble(Ticket, DEAL_VOLUME);
MT4ORDERS::Order.Symbol = ::HistoryDealGetString(Ticket, DEAL_SYMBOL);
MT4ORDERS::Order.Comment = ::HistoryDealGetString(Ticket, DEAL_COMMENT);
MT4ORDERS::Order.OpenPrice = ::HistoryDealGetDouble(Ticket, DEAL_PRICE);
MT4ORDERS::Order.OpenTime = (datetime)::HistoryDealGetInteger(Ticket, DEAL_TIME);
MT4ORDERS::Order.StopLoss = 0;
MT4ORDERS::Order.TakeProfit = 0;
MT4ORDERS::Order.ClosePrice = ::HistoryDealGetDouble(Ticket, DEAL_PRICE);
MT4ORDERS::Order.CloseTime = (datetime)::HistoryDealGetInteger(Ticket, DEAL_TIME);;
MT4ORDERS::Order.Expiration = 0;
MT4ORDERS::Order.MagicNumber = (int)::HistoryDealGetInteger(Ticket, DEAL_MAGIC);
MT4ORDERS::Order.Profit = ::HistoryDealGetDouble(Ticket, DEAL_PROFIT);
MT4ORDERS::Order.Commission = ::HistoryDealGetDouble(Ticket, DEAL_COMMISSION);
MT4ORDERS::Order.Swap = ::HistoryDealGetDouble(Ticket, DEAL_SWAP);
const ulong OpenTicket = MT4ORDERS::GetPositionDealIn(::HistoryDealGetInteger(Ticket, DEAL_POSITION_ID));
if (OpenTicket > 0) {
MT4ORDERS::Order.OpenPrice = ::HistoryDealGetDouble(OpenTicket, DEAL_PRICE);
MT4ORDERS::Order.OpenTime = (datetime)::HistoryDealGetInteger(OpenTicket, DEAL_TIME);
const double OpenLots = ::HistoryDealGetDouble(OpenTicket, DEAL_VOLUME);
if (OpenLots > 0)
MT4ORDERS::Order.Commission += ::HistoryDealGetDouble(OpenTicket, DEAL_COMMISSION) * MT4ORDERS::Order.Lots / OpenLots;
if (MT4ORDERS::Order.MagicNumber == 0)
MT4ORDERS::Order.MagicNumber = (int)::HistoryDealGetInteger(OpenTicket, DEAL_MAGIC);
if (MT4ORDERS::Order.Comment == "")
MT4ORDERS::Order.Comment = ::HistoryDealGetString(OpenTicket, DEAL_COMMENT);
}
return;
}
static bool Waiting( const bool FlagInit = false ) {
static ulong StartTime = 0;
if (FlagInit)
StartTime = ::GetMicrosecondCount();
const bool Res = (::GetMicrosecondCount() - StartTime < MT4ORDERS::OrderSend_MaxPause);
if (Res)
::Sleep(0);
return(Res);
}
static bool EqualPrices( const double Price1, const double Price2, const int digits) {
return(::NormalizeDouble(Price1 - Price2, digits) == 0);
}
#define WHILE(A) while (!(Res = (A)) && MT4ORDERS::Waiting())
static bool OrderSend( const MqlTradeRequest &Request, MqlTradeResult &Result ) {
bool Res = ::OrderSend(Request, Result);
if (Res && !MT4ORDERS::IsTester && (Result.retcode < TRADE_RETCODE_ERROR) && (MT4ORDERS::OrderSend_MaxPause > 0)) {
Res = (Result.retcode == TRADE_RETCODE_DONE);
MT4ORDERS::Waiting(true);
if (Request.action == TRADE_ACTION_DEAL) {
WHILE(::HistoryOrderSelect(Result.order))
;
Res = Res && (((ENUM_ORDER_STATE)::HistoryOrderGetInteger(Result.order, ORDER_STATE) == ORDER_STATE_FILLED) ||
((ENUM_ORDER_STATE)::HistoryOrderGetInteger(Result.order, ORDER_STATE) == ORDER_STATE_PARTIAL));
if (Res)
WHILE(::HistoryDealSelect(Result.deal))
;
}
else if (Request.action == TRADE_ACTION_PENDING) {
if (Res)
WHILE(::OrderSelect(Result.order))
;
else {
WHILE(::HistoryOrderSelect(Result.order))
;
Res = false;
}
}
else if (Request.action == TRADE_ACTION_SLTP) {
if (Res) {
bool EqualSL = false;
bool EqualTP = false;
const int digits = (int)::SymbolInfoInteger(Request.symbol, SYMBOL_DIGITS);
if ((Request.position == 0) ? ::PositionSelect(Request.symbol) : ::PositionSelectByTicket(Request.position)) {
EqualSL = MT4ORDERS::EqualPrices(::PositionGetDouble(POSITION_SL), Request.sl, digits);
EqualTP = MT4ORDERS::EqualPrices(::PositionGetDouble(POSITION_TP), Request.tp, digits);
}
WHILE((EqualSL && EqualTP))
if ((Request.position == 0) ? ::PositionSelect(Request.symbol) : ::PositionSelectByTicket(Request.position)) {
EqualSL = MT4ORDERS::EqualPrices(::PositionGetDouble(POSITION_SL), Request.sl, digits);
EqualTP = MT4ORDERS::EqualPrices(::PositionGetDouble(POSITION_TP), Request.tp, digits);
}
}
}
else if (Request.action == TRADE_ACTION_MODIFY) {
if (Res) {
bool EqualSL = false;
bool EqualTP = false;
const int digits = (int)::SymbolInfoInteger(Request.symbol, SYMBOL_DIGITS);
if (::OrderSelect(Result.order)) {
EqualSL = MT4ORDERS::EqualPrices(::OrderGetDouble(ORDER_SL), Request.sl, digits);
EqualTP = MT4ORDERS::EqualPrices(::OrderGetDouble(ORDER_TP), Request.tp, digits);
}
WHILE((EqualSL && EqualTP))
if (::OrderSelect(Result.order)) {
EqualSL = MT4ORDERS::EqualPrices(::OrderGetDouble(ORDER_SL), Request.sl, digits);
EqualTP = MT4ORDERS::EqualPrices(::OrderGetDouble(ORDER_TP), Request.tp, digits);
}
}
}
else if (Request.action == TRADE_ACTION_REMOVE)
if (Res)
WHILE(::HistoryOrderSelect(Result.order))
;
}
return(Res);
}
#undef WHILE
static bool NewOrderSend( const MqlTradeRequest &Request ) {
MqlTradeResult Result;
return(MT4ORDERS::OrderSend(Request, Result) ? Result.retcode < TRADE_RETCODE_ERROR : false);
}
static bool ModifyPosition( const ulong Ticket, MqlTradeRequest &Request ) {
const bool Res = ::PositionSelectByTicket(Ticket);
if (Res)
{
Request.action = TRADE_ACTION_SLTP;
Request.position = Ticket;
Request.symbol = ::PositionGetString(POSITION_SYMBOL);
}
return(Res);
}
static ENUM_ORDER_TYPE_FILLING GetFilling( const string Symb, const uint Type = ORDER_FILLING_FOK ) {
const ENUM_SYMBOL_TRADE_EXECUTION ExeMode = (ENUM_SYMBOL_TRADE_EXECUTION)::SymbolInfoInteger(Symb, SYMBOL_TRADE_EXEMODE);
const int FillingMode = (int)::SymbolInfoInteger(Symb, SYMBOL_FILLING_MODE);
return((FillingMode == 0 || (Type >= ORDER_FILLING_RETURN) || ((FillingMode & (Type + 1)) != Type + 1)) ?
(((ExeMode == SYMBOL_TRADE_EXECUTION_EXCHANGE) || (ExeMode == SYMBOL_TRADE_EXECUTION_INSTANT)) ?
ORDER_FILLING_RETURN : ((FillingMode == SYMBOL_FILLING_IOC) ? ORDER_FILLING_IOC : ORDER_FILLING_FOK)) :
(ENUM_ORDER_TYPE_FILLING)Type);
}
static bool ModifyOrder( const ulong Ticket, const double Price, const datetime Expiration, MqlTradeRequest &Request ) {
const bool Res = ::OrderSelect(Ticket);
if (Res) {
Request.action = TRADE_ACTION_MODIFY;
Request.order = Ticket;
Request.price = Price;
Request.symbol = ::OrderGetString(ORDER_SYMBOL);
Request.type_filling = MT4ORDERS::GetFilling(Request.symbol);
if (Expiration > 0)
{
Request.type_time = ORDER_TIME_SPECIFIED;
Request.expiration = Expiration;
}
}
return(Res);
}
public:
static bool SelectByPosHistory( const int Index ) {
const int Ticket = (int)MT4ORDERS::History[Index];
const bool Res = (Ticket > 0) ? ::HistoryDealSelect(Ticket) : ((Ticket < 0) ? ::HistoryOrderSelect(-Ticket) : false);
if (Res) {
if (Ticket > 0)
MT4ORDERS::GetHistoryPositionData(Ticket);
else
MT4ORDERS::GetHistoryOrderData(-Ticket);
}
return(Res);
}
// position has higher priority
static bool SelectByPos( const int Index ) {
const int Total = ::PositionsTotal();
const bool Flag = (Index < Total);
const bool Res = (Flag) ? ::PositionSelectByTicket(::PositionGetTicket(Index)) : ::OrderSelect(::OrderGetTicket(Index - Total));
if (Res) {
if (Flag)
MT4ORDERS::GetPositionData();
else
MT4ORDERS::GetOrderData();
}
return(Res);
}
static bool SelectByHistoryTicket( const int Ticket ) {
bool Res = ::HistoryDealSelect(Ticket) ? MT4HISTORY::IsMT4Deal(Ticket) : false;
if (Res)
MT4ORDERS::GetHistoryPositionData(Ticket);
else
{
Res = ::HistoryOrderSelect(Ticket) ? MT4HISTORY::IsMT4Order(Ticket) : false;
if (Res)
MT4ORDERS::GetHistoryOrderData(Ticket);
}
return(Res);
}
static bool SelectByExistingTicket( const int Ticket ) {
bool Res = true;
if (::PositionSelectByTicket(Ticket))
MT4ORDERS::GetPositionData();
else if (::OrderSelect(Ticket))
MT4ORDERS::GetOrderData();
else
Res = false;
return(Res);
}
// One Ticket priority:
// MODE_TRADES: exist position > exist order > deal > canceled order
// MODE_HISTORY: deal > canceled order > exist position > exist order
static bool SelectByTicket( const int Ticket, const int Pool = MODE_TRADES ) {
return((Pool == MODE_TRADES) ?
(MT4ORDERS::SelectByExistingTicket(Ticket) ? true : MT4ORDERS::SelectByHistoryTicket(Ticket)) :
(MT4ORDERS::SelectByHistoryTicket(Ticket) ? true : MT4ORDERS::SelectByExistingTicket(Ticket)));
}
public:
static uint OrderSend_MaxPause;
static bool MT4OrderSelect( const int Index, const int Select, const int Pool = MODE_TRADES ) {
return((Select == SELECT_BY_POS) ?
((Pool == MODE_TRADES) ? MT4ORDERS::SelectByPos(Index) : MT4ORDERS::SelectByPosHistory(Index)) :
MT4ORDERS::SelectByTicket(Index, Pool));
}
// MT5 OrderSelect
static bool MT4OrderSelect( const ulong Ticket ) {
return(::OrderSelect(Ticket));
}
static int MT4OrdersTotal(void) {
return(::OrdersTotal() + ::PositionsTotal());
}
// MT5 OrdersTotal
static int MT4OrdersTotal( const bool MT5 ) {
return(::OrdersTotal());
}
static int MT4OrdersHistoryTotal(void) {
return(MT4ORDERS::History.GetAmount());
}
static int MT4OrderSend( const string Symb, const int Type, const double dVolume, const double Price, const int SlipPage, const double SL, const double TP,
const string comment = NULL, const int magic = 0, const datetime dExpiration = 0, color arrow_color = clrNONE )
{
MqlTradeRequest Request = {0};
Request.action = (((Type == OP_BUY) || (Type == OP_SELL)) ? TRADE_ACTION_DEAL : TRADE_ACTION_PENDING);
Request.magic = magic;
Request.symbol = ((Symb == NULL) ? ::Symbol() : Symb);
Request.volume = dVolume;
Request.price = Price;
Request.tp = TP;
Request.sl = SL;
Request.deviation = SlipPage;
Request.type = (ENUM_ORDER_TYPE)Type;
Request.type_filling = MT4ORDERS::GetFilling(Request.symbol, (uint)Request.deviation);
if (dExpiration > 0) {
Request.type_time = ORDER_TIME_SPECIFIED;
Request.expiration = dExpiration;
}
Request.comment = comment;
MqlTradeResult Result;
return(MT4ORDERS::OrderSend(Request, Result) ?
((Request.action == TRADE_ACTION_DEAL) ? (::HistoryDealSelect(Result.deal) ? (int)::HistoryDealGetInteger(Result.deal, DEAL_POSITION_ID) : -1) : (int)Result.order) : -1);
}
static bool MT4OrderModify( const ulong Ticket, const double Price, const double SL, const double TP, const datetime Expiration, const color Arrow_Color = clrNONE ) {
MqlTradeRequest Request = {0};
// considered case if order and position has the same ticket
bool Res = ((Ticket != MT4ORDERS::Order.Ticket) || (MT4ORDERS::Order.Ticket <= OP_SELL)) ?