forked from EA31337/EA31337-classes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Order.mqh
2443 lines (2311 loc) · 85.2 KB
/
Order.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 framework |
//| Copyright 2016-2020, 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 <https://www.gnu.org/licenses/>.
*/
/**
* @file
* Implements class for managing orders.
*/
// Prevents processing this includes file for the second time.
#ifndef ORDER_MQH
#define ORDER_MQH
// Includes.
#include "Log.mqh"
#include "String.mqh"
#include "SymbolInfo.mqh"
// Enums.
// Order conditions.
enum ENUM_ORDER_CONDITION {
ORDER_COND_NONE = 0, // Empty condition.
ORDER_COND_IN_LOSS, // When order in loss
ORDER_COND_IN_PROFIT, // When order in profit
ORDER_COND_IS_CLOSED, // When order is closed
ORDER_COND_IS_OPEN, // When order is open
ORDER_COND_LIFETIME_GT_ARG, // Order lifetime greater than argument value.
ORDER_COND_LIFETIME_LT_ARG, // Order lifetime lesser than argument value.
ORDER_COND_PROP_EQ_ARG, // Order property equals argument value.
ORDER_COND_PROP_GT_ARG, // Order property greater than argument value.
ORDER_COND_PROP_LT_ARG, // Order property lesser than argument value.
FINAL_ORDER_CONDITION_ENTRY
};
// Order actions.
enum ENUM_ORDER_ACTION {
ORDER_ACTION_CLOSE = 1, // Close the order.
ORDER_ACTION_OPEN, // Open the order.
FINAL_ORDER_ACTION_ENTRY
};
#ifndef __MQL5__
// Enums.
// Direction of an open position (buy or sell).
// @docs
// - https://www.mql5.com/en/docs/constants/tradingconstants/positionproperties
enum ENUM_POSITION_TYPE {
POSITION_TYPE_BUY, // Buy position.
POSITION_TYPE_SELL // Sell position.
};
// Defines the reason for order placing.
enum ENUM_ORDER_REASON {
ORDER_REASON_CLIENT, // The order was placed from a desktop terminal.
ORDER_REASON_EXPERT, // The order was placed from an MQL5-program (e.g. by an EA or a script).
ORDER_REASON_MOBILE, // The order was placed from a mobile application.
ORDER_REASON_SL, // The order was placed as a result of Stop Loss activation.
ORDER_REASON_SO, // The order was placed as a result of the Stop Out event.
ORDER_REASON_TP, // The order was placed as a result of Take Profit activation.
ORDER_REASON_WEB, // The order was placed from a web platform.
};
#else
// Enums has sense only in MQL5.
enum ENUM_ORDER_SELECT_TYPE {
ORDER_SELECT_TYPE_NONE,
ORDER_SELECT_TYPE_ACTIVE,
ORDER_SELECT_TYPE_HISTORY,
ORDER_SELECT_TYPE_DEAL,
ORDER_SELECT_TYPE_POSITION
};
enum ENUM_ORDER_SELECT_DATA_TYPE {
ORDER_SELECT_DATA_TYPE_INTEGER,
ORDER_SELECT_DATA_TYPE_DOUBLE,
ORDER_SELECT_DATA_TYPE_STRING
};
#endif
#ifndef __MQL__
// For functions OrderGet(), OrderGetDouble() and HistoryOrderGetDouble().
// @docs https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
enum ENUM_ORDER_PROPERTY_DOUBLE {
ORDER_VOLUME_INITIAL, // Order initial volume.
ORDER_VOLUME_CURRENT, // Order current volume.
ORDER_PRICE_OPEN, // Price specified in the order.
ORDER_SL, // Stop Loss value.
ORDER_TP, // Take Profit value.
ORDER_PRICE_CURRENT, // The current price of the order symbol.
ORDER_PRICE_STOPLIMIT // The Limit order price for the StopLimit order.
};
// A variety of properties for reading order values.
// For functions OrderGet(), OrderGetInteger() and HistoryOrderGetInteger().
// @docs https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
enum ENUM_ORDER_PROPERTY_INTEGER {
ORDER_TICKET, // Order ticket. Unique number assigned to each order.
ORDER_TIME_SETUP, // Order setup time.
ORDER_TYPE, // Order type.
ORDER_STATE, // Order state.
ORDER_TIME_EXPIRATION, // Order expiration time.
ORDER_TIME_DONE, // Order execution or cancellation time.
ORDER_TIME_SETUP_MSC, // The time of placing an order for execution in milliseconds since 01.01.1970.
ORDER_TIME_DONE_MSC, // Order execution/cancellation time in milliseconds since 01.01.1970.
ORDER_TYPE_FILLING, // Order filling type.
ORDER_TYPE_TIME, // Order lifetime.
ORDER_MAGIC, // ID of an Expert Advisor that has placed the order.
ORDER_REASON, // The reason or source for placing an order.
ORDER_POSITION_ID, // Position identifier that is set to an order as soon as it is executed.
ORDER_POSITION_BY_ID // Identifier of an opposite position used for closing by order ORDER_TYPE_CLOSE_BY.
};
#endif
/* Defines for backward compability. */
// Index in the order pool.
#ifndef SELECT_BY_POS
#define SELECT_BY_POS 0
#endif
// Index by the order ticket.
#ifndef SELECT_BY_TICKET
#define SELECT_BY_TICKET 1
#endif
#ifndef POSITION_TICKET
#define POSITION_TICKET 1
#endif
#ifndef ORDER_TICKET
#define ORDER_TICKET 1
#endif
#ifndef DEAL_TICKET
#define DEAL_TICKET 1
#endif
#ifndef ORDER_EXTERNAL_ID
// Order identifier in an external trading system (on the Exchange).
// Note: Required for backward compability in MQL4.
// @see: https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties#enum_order_property_string
#define ORDER_EXTERNAL_ID 20
#endif
#ifndef ORDER_REASON
// The reason or source for placing an order.
// Note: Required for backward compability in MQL4.
// @see: https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
#define ORDER_REASON 23
#endif
/* Structs */
#ifdef __MQL4__
// The Structure of Results of a Trade Request Check (MqlTradeCheckResult).
// The check is performed using the OrderCheck() function.
// @docs https://www.mql5.com/en/docs/constants/structures/mqltradecheckresult
struct MqlTradeCheckResult {
unsigned int retcode; // Reply code.
double balance; // Balance after the execution of the deal.
double equity; // Equity after the execution of the deal.
double profit; // Floating profit.
double margin; // Margin requirements.
double margin_free; // Free margin.
double margin_level; // Margin level.
string comment; // Comment to the reply code (description of the error).
};
#endif
struct OrderParams {
bool dummy; // Whether order is dummy (fake) or not (real).
color color_arrow; // Color of the opening arrow on the chart.
unsigned short refresh_rate; // How often to refresh order values (in sec).
ENUM_ORDER_CONDITION cond_close; // Close condition.
MqlParam cond_args[]; // Close condition argument.
// Special struct methods.
void OrderParams() : dummy(false), color_arrow(clrNONE), refresh_rate(10), cond_close(ORDER_COND_NONE){};
void OrderParams(bool _dummy) : dummy(_dummy), color_arrow(clrNONE), refresh_rate(10), cond_close(ORDER_COND_NONE){};
// Getters.
bool HasCloseCondition() { return cond_close > ORDER_COND_NONE; }
// Setters.
void SetConditionClose(ENUM_ORDER_CONDITION _cond, MqlParam &_args[]) {
cond_close = _cond;
ArrayResize(cond_args, ArraySize(_args));
for (int i = 0; i < ArraySize(_args); i++) {
cond_args[i] = _args[i];
}
}
void SetRefreshRate(unsigned short _value) { refresh_rate = _value; }
};
// Defines order data.
struct OrderData {
unsigned long ticket; // Ticket number.
unsigned long magic; // Magic number.
ENUM_ORDER_STATE state; // State.
double profit; // Profit.
double price_open; // Open price.
double price_close; // Close price.
double price_current; // Current price.
double price_stoplimit; // The limit order price for the StopLimit order.
datetime time_open; // Open time.
datetime time_close; // Close time.
datetime expiration; // Order expiration time (for the orders of ORDER_TIME_SPECIFIED type).
double sl; // Current Stop loss level of the order.
double tp; // Current Take Profit level of the order.
ENUM_ORDER_TYPE type; // Type.
ENUM_ORDER_TYPE_FILLING type_filling; // Filling type.
ENUM_ORDER_TYPE_TIME type_time; // Lifetime (the order validity period).
ENUM_ORDER_REASON reason; // Reason or source for placing an order.
datetime last_update; // Last update of order values.
unsigned int last_error; // Last error code.
double volume; // Current volume.
string comment; // Comment.
string ext_id; // External trading system identifier.
string symbol; // Symbol of the order.
Log *logger; // Pointer to logger.
OrderData()
: ticket(0),
magic(0),
state(ORDER_STATE_STARTED),
profit(0),
price_open(0),
price_close(0),
price_current(0),
price_stoplimit(0),
time_close(0),
time_open(0),
expiration(0),
sl(0),
tp(0),
last_update(0),
last_error(ERR_NO_ERROR),
volume(0) {}
// Getters.
// ...
// Setters.
void ProcessLastError() { last_error = fmax(last_error, Terminal::GetLastError()); }
void ResetError() {
ResetLastError();
last_error = ERR_NO_ERROR;
}
void SetComment(string _value) { comment = _value; }
void SetExpiration(datetime _exp) { expiration = _exp; }
void SetLastError(unsigned int _value) { last_error = _value; }
void SetLastUpdate(datetime _value) { last_update = _value; }
void SetMagicNo(unsigned long _value) { magic = _value; }
void SetPriceClose(double _value) { price_close = _value; }
void SetPriceCurrent(double _value) {
price_current = _value;
UpdateProfit();
}
void SetPriceOpen(double _value) { price_open = _value; }
void SetPriceStopLimit(double _value) { price_stoplimit = _value; }
void SetProfit(double _profit) { profit = _profit; }
void SetProfitTake(double _value) { tp = _value; }
void SetReason(long _reason) { reason = (ENUM_ORDER_REASON)_reason; }
void SetReason(ENUM_ORDER_REASON _reason) { reason = _reason; }
void SetState(ENUM_ORDER_STATE _state) { state = _state; }
void SetState(long _state) { state = (ENUM_ORDER_STATE)_state; }
void SetStopLoss(double _value) { sl = _value; }
void SetSymbol(string _value) { symbol = _value; }
void SetTicket(unsigned long _value) { ticket = _value; }
void SetTimeClose(datetime _value) { time_close = _value; }
void SetTimeOpen(datetime _value) { time_open = _value; }
void SetType(ENUM_ORDER_TYPE _type) { type = _type; }
void SetType(long _type) { type = (ENUM_ORDER_TYPE)_type; }
void SetTypeFilling(ENUM_ORDER_TYPE_FILLING _type) { type_filling = _type; }
void SetTypeFilling(long _type) { type_filling = (ENUM_ORDER_TYPE_FILLING)_type; }
void SetTypeTime(ENUM_ORDER_TYPE_TIME _value) { type_time = _value; }
void SetTypeTime(long _value) { type_time = (ENUM_ORDER_TYPE_TIME)_value; }
void SetVolume(double _value) { volume = _value; }
void UpdateProfit() { profit = price_open - price_current; }
};
#ifndef __MQLBUILD__
// Order operation type.
// @docs
// - https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
enum ENUM_ORDER_TYPE {
ORDER_TYPE_BUY, // Market Buy order.
ORDER_TYPE_SELL, // Market Sell order.
ORDER_TYPE_BUY_LIMIT, // Buy Limit pending order.
ORDER_TYPE_SELL_LIMIT, // Sell Limit pending order.
ORDER_TYPE_BUY_STOP, // Buy Stop pending order
ORDER_TYPE_SELL_STOP, // Sell Stop pending order.
ORDER_TYPE_BUY_STOP_LIMIT, // Upon reaching the order price, a pending Buy Limit order is placed at the StopLimit
// price.
ORDER_TYPE_SELL_STOP_LIMIT, // Upon reaching the order price, a pending Sell Limit order is placed at the StopLimit
// price.
ORDER_TYPE_CLOSE_BY // Order to close a position by an opposite one.
}
// Defines.
// Mode constants.
// @see: https://docs.mql4.com/trading/orderselect
#define MODE_TRADES 0
#define MODE_HISTORY 1
#endif
// Defines modes for order type values (Take Profit and Stop Loss).
enum ENUM_ORDER_TYPE_VALUE {
ORDER_TYPE_TP = ORDER_TP,
ORDER_TYPE_SL = ORDER_SL
};
/**
* Class to provide methods to deal with the order.
*
* @see
* - https://www.mql5.com/en/docs/trading/ordergetinteger
* - https://www.mql5.com/en/articles/211
*/
class Order : public SymbolInfo {
public:
/*
* Default enumerations:
*
* Trade operation:
* 0: OP_BUY (Buy operation)
* 1: OP_SELL (Sell operation)
* 2: OP_BUYLIMIT (Buy limit pending order)
* 3: OP_SELLLIMIT (Sell limit pending order)
* 4: OP_BUYSTOP (Buy stop pending order)
* 5: OP_SELLSTOP (Sell stop pending order)
*/
protected:
// Struct variables.
OrderParams oparams;
OrderData odata;
MqlTradeRequest orequest; // Trade Request Structure.
MqlTradeCheckResult oresult_check; // Results of a Trade Request Check.
MqlTradeResult oresult; // Trade Request Result.
#ifdef __MQL5__
static unsigned long selected_ticket_id;
static ENUM_ORDER_SELECT_TYPE selected_ticket_type;
#endif
public:
/**
* Class constructors.
*/
Order(long _ticket_no) {
odata.SetTicket(_ticket_no);
Update();
}
Order(const MqlTradeRequest &_request, bool _send = true) {
orequest = _request;
if (_send) {
if (!oparams.dummy) {
OrderSend();
} else {
OrderSendDummy();
}
}
}
Order(const MqlTradeRequest &_request, const OrderParams &_oparams, bool _send = true) {
orequest = _request;
oparams = _oparams;
if (_send) {
if (!oparams.dummy) {
OrderSend();
} else {
OrderSendDummy();
}
}
}
/**
* Class copy constructors.
*/
Order(const Order &_order, bool _send = true) {
oparams = _order.oparams;
odata = _order.odata;
orequest = _order.orequest;
oresult_check = _order.oresult_check;
oresult = _order.oresult;
if (_send) {
if (!oparams.dummy) {
OrderSend();
} else {
OrderSendDummy();
}
}
}
/**
* Class deconstructor.
*/
~Order() {}
/* Getters */
/**
* Get order's params.
*/
OrderParams GetParams() const { return oparams; }
/**
* Get order's data.
*/
OrderData GetData() const { return odata; }
/**
* Get order's request.
*/
MqlTradeRequest GetRequest() { return orequest; }
/**
* Get order's result.
*/
MqlTradeResult GetResult() { return oresult; }
/**
* Get order's check result.
*/
MqlTradeCheckResult GetResultCheck() { return oresult_check; }
/* Setters */
/* State checkers */
/**
* Is order is open.
*/
bool IsOpen() { return odata.time_close == 0 && odata.price_close == 0; }
/**
* Is order closed.
*/
bool IsClosed() { return odata.time_close > 0 && odata.price_close > 0; }
/* Trade methods */
/**
* Gets allowed order filling mode.
*
* @docs
* - https://www.mql5.com/en/docs/constants/environment_state/marketinfoconstants#symbol_filling_mode
*/
static ENUM_ORDER_TYPE_FILLING GetOrderFilling(const string _symbol) {
// Default policy is used only for market orders (Buy and Sell), limit and stop limit orders
// and only for the symbols with Market or Exchange execution.
// In case of partial filling a market or limit order with remaining volume is not canceled but processed further.
ENUM_ORDER_TYPE_FILLING _result = ORDER_FILLING_RETURN;
const long _filling_mode = SymbolInfo::GetFillingMode(_symbol);
if ((_filling_mode & SYMBOL_FILLING_IOC) == SYMBOL_FILLING_IOC) {
// Execute a deal with the volume maximally available in the market within that indicated in the order.
// In case the order cannot be filled completely, the available volume of the order will be filled, and the
// remaining volume will be canceled. The possibility of using IOC orders is determined at the trade server.
_result = ORDER_FILLING_IOC;
} else if ((_filling_mode & SYMBOL_FILLING_FOK) == SYMBOL_FILLING_FOK) {
// A deal can be executed only with the specified volume.
// In MT4, orders are usually on an FOK basis in that you get a complete fill or nothing.
// If the necessary amount of a financial instrument is currently unavailable in the market, the order will not be
// executed. The required volume can be filled using several offers available on the market at the moment.
_result = ORDER_FILLING_FOK;
}
return (_result);
}
/**
* Gets order's filling mode.
*/
ENUM_ORDER_TYPE_FILLING GetOrderFilling() {
Update(ORDER_TYPE_FILLING);
return odata.type_filling;
}
/**
* Get allowed order filling modes.
*/
static ENUM_ORDER_TYPE_FILLING GetOrderFilling(const string _symbol, const long _type) {
const ENUM_SYMBOL_TRADE_EXECUTION _exe_mode =
(ENUM_SYMBOL_TRADE_EXECUTION)SymbolInfo::SymbolInfoInteger(_symbol, SYMBOL_TRADE_EXEMODE);
const long _filling_mode = SymbolInfo::GetFillingMode(_symbol);
return ((_filling_mode == 0 || (_type >= ORDER_FILLING_RETURN) || ((_filling_mode & (_type + 1)) != _type + 1))
? (((_exe_mode == SYMBOL_TRADE_EXECUTION_EXCHANGE) || (_exe_mode == SYMBOL_TRADE_EXECUTION_INSTANT))
? ORDER_FILLING_RETURN
: ((_filling_mode == SYMBOL_FILLING_IOC) ? ORDER_FILLING_IOC : ORDER_FILLING_FOK))
: (ENUM_ORDER_TYPE_FILLING)_type);
}
/* MT ORDER METHODS */
/**
* Closes opened order.
*
* @docs
* - https://docs.mql4.com/trading/orderclose
* - https://www.mql5.com/en/docs/constants/tradingconstants/enum_trade_request_actions
*
* @return
* Returns true if successful, otherwise false.
* To get details about error, call the GetLastError() function.
*/
static bool OrderClose(unsigned long _ticket, // Unique number of the order ticket.
double _lots, // Number of lots.
double _price, // Closing price.
int _deviation, // Maximal possible deviation/slippage from the requested price (in points).
color _arrow_color = CLR_NONE // Color of the closing arrow on the chart.
) {
#ifdef __MQL4__
return ::OrderClose((int)_ticket, _lots, _price, _deviation, _arrow_color);
#else
if (::OrderSelect(_ticket) || ::PositionSelectByTicket(_ticket) || ::HistoryOrderSelect(_ticket)) {
MqlTradeRequest _request = {0};
MqlTradeCheckResult _result_check = {0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_DEAL;
_request.position = ::PositionGetInteger(POSITION_TICKET);
_request.symbol = ::PositionGetString(POSITION_SYMBOL);
_request.type = NegateOrderType((ENUM_POSITION_TYPE)::PositionGetInteger(POSITION_TYPE));
_request.volume = _lots;
_request.price = _price;
_request.deviation = _deviation;
return Order::OrderSend(_request, _result, _result_check, _arrow_color);
}
return false;
#endif
}
bool OrderClose(string _comment = "") {
odata.ResetError();
if (!OrderSelect()) {
if (!OrderSelectHistory()) {
odata.ProcessLastError();
return false;
}
}
MqlTradeRequest _request = {0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_DEAL;
_request.comment = _comment;
_request.deviation = orequest.deviation;
_request.type = NegateOrderType(orequest.type);
_request.position = oresult.deal;
_request.price = SymbolInfo::GetCloseOffer(orequest.type);
_request.symbol = orequest.symbol;
_request.volume = orequest.volume;
Order::OrderSend(_request, oresult, oresult_check);
if (oresult.retcode == TRADE_RETCODE_DONE) {
odata.SetTimeClose(DateTime::TimeTradeServer()); // For now, sets the current time.
odata.SetPriceClose(SymbolInfo::GetCloseOffer(odata.type)); // For now, sets using the actual close price.
odata.SetLastError(ERR_NO_ERROR);
Update();
return true;
} else {
odata.last_error = oresult.retcode;
}
return false;
}
/**
* Closes a position by an opposite one.
*/
static bool OrderCloseBy(long _ticket, long _opposite, color _color) {
#ifdef __MQL4__
return ::OrderCloseBy((int)_ticket, (int)_opposite, _color);
#else
if (::OrderSelect(_ticket) || ::PositionSelectByTicket(_ticket) || ::HistoryOrderSelect(_ticket)) {
MqlTradeRequest _request = {0};
MqlTradeCheckResult _result_check = {0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_CLOSE_BY;
_request.position = ::PositionGetInteger(POSITION_TICKET);
_request.position_by = _opposite;
_request.symbol = ::PositionGetString(POSITION_SYMBOL);
_request.type = NegateOrderType((ENUM_POSITION_TYPE)::PositionGetInteger(POSITION_TYPE));
_request.volume = ::PositionGetDouble(POSITION_VOLUME);
return Order::OrderSend(_request, _result);
}
return false;
#endif
}
/**
* Returns close price of the currently selected order.
*/
static double OrderClosePrice() {
#ifdef __MQL4__
return ::OrderClosePrice();
#else // __MQL5__
return ::PositionGetDouble(POSITION_PRICE_CURRENT);
#endif
}
double GetClosePrice() { return odata.price_close; }
/**
* Returns open time of the currently selected order.
*
* @see
* - https://docs.mql4.com/trading/orderopentime
* - https://www.mql5.com/en/docs/trading/ordergetinteger
*/
static datetime OrderOpenTime() {
#ifdef __MQL4__
return ::OrderOpenTime();
#else
return (datetime)Order::OrderGetInteger(ORDER_TIME_SETUP);
#endif
}
datetime GetOpenTime() { return odata.time_open; }
/*
* Returns close time of the currently selected order.
*
* @see:
* - https://docs.mql4.com/trading/orderclosetime
* - https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
*/
static datetime OrderCloseTime(unsigned long _ticket = 0) {
#ifdef __MQL4__
if (_ticket > 0) {
OrderSelect(_ticket, SELECT_BY_TICKET, MODE_HISTORY);
}
return ::OrderCloseTime();
#else // __MQL5__
// @docs https://www.mql5.com/en/docs/trading/historydealgetinteger
if (HistorySelect(0, INT_MAX)) {
int i;
for (i = HistoryDealsTotal() - 1; i >= 0; i--) {
const unsigned long _curr_ticket = HistoryDealGetTicket(i);
if (_curr_ticket == _ticket) {
const ENUM_DEAL_ENTRY _entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(_curr_ticket, DEAL_ENTRY);
if (_entry == DEAL_ENTRY_OUT) {
// @fixme: Doesn't find properly entries closed by stop losses?
return (datetime)HistoryDealGetInteger(_ticket, DEAL_TIME);
}
}
}
}
return 0;
#endif
}
datetime GetCloseTime() {
if (odata.time_close == 0 && Order::OrderSelect(oresult.order, SELECT_BY_TICKET, MODE_HISTORY)) {
odata.time_close = Order::OrderCloseTime(oresult.order);
}
return odata.time_close;
}
/**
* Returns comment of the currently selected order.
*
* @see:
* - https://docs.mql4.com/trading/ordercomment
* - https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
*/
static string OrderComment() {
#ifdef __MQL4__
return ::OrderComment();
#else // __MQL5__
return Order::OrderGetString(ORDER_COMMENT);
#endif
}
/**
* Returns calculated commission of the currently selected order.
*
* @see:
* - https://docs.mql4.com/trading/ordercommission
* - https://www.mql5.com/en/docs/standardlibrary/tradeclasses/cpositioninfo/cpositioninfocommission
*/
static double OrderCommission() {
#ifdef __MQL4__
return ::OrderCommission();
#else // __MQL5__
return ::PositionGetDouble(POSITION_COMMISSION);
#endif
}
/**
* Deletes previously opened pending order.
*
* @see: https://docs.mql4.com/trading/orderdelete
*/
static bool OrderDelete(unsigned long _ticket, color _color = NULL) {
#ifdef __MQL4__
return ::OrderDelete((int)_ticket, _color);
#else
if (::OrderSelect(_ticket)) {
MqlTradeRequest _request = {0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_REMOVE;
_request.order = _ticket;
return Order::OrderSend(_request, _result);
}
return false;
#endif
}
bool OrderDelete() { return Order::OrderDelete(GetTicket()); }
/**
* Returns expiration date of the selected pending order.
*
* @see
* - https://docs.mql4.com/trading/orderexpiration
* - https://www.mql5.com/en/docs/trading/ordergetinteger
*/
static datetime OrderExpiration() {
#ifdef __MQL4__
return ::OrderExpiration();
#else
return (datetime)Order::OrderGetInteger(ORDER_TIME_EXPIRATION);
#endif
}
/**
* Returns amount of lots of the selected order.
*
* @see:
* - https://docs.mql4.com/trading/orderlots
* - https://www.mql5.com/en/docs/trading/ordergetdouble
*/
static double OrderLots() {
#ifdef __MQL4__
return ::OrderLots();
#else
return Order::OrderGetDouble(ORDER_VOLUME_CURRENT);
#endif
}
double GetVolume() { return orequest.volume = IsSelected() ? OrderLots() : orequest.volume; }
/**
* Returns an identifying (magic) number of the currently selected order.
*
* @see
* - https://docs.mql4.com/trading/ordermagicnumber
* - https://www.mql5.com/en/docs/trading/ordergetinteger
*/
static long OrderMagicNumber() {
#ifdef __MQL4__
return (long)::OrderMagicNumber();
#else
return Order::OrderGetInteger(ORDER_MAGIC);
#endif
}
unsigned long GetMagicNumber() { return orequest.magic = IsSelected() ? OrderMagicNumber() : orequest.magic; }
/**
* Modification of characteristics of the previously opened or pending orders.
*
* @see https://docs.mql4.com/trading/ordermodify
*/
static bool OrderModify(unsigned long _ticket, // Ticket of the position.
double _price, // Price.
double _stoploss, // Stop loss.
double _takeprofit, // Take profit.
datetime _expiration, // Expiration.
color _arrow_color = clrNONE // Color of order.
) {
#ifdef __MQL4__
return ::OrderModify((unsigned int)_ticket, _price, _stoploss, _takeprofit, _expiration, _arrow_color);
#else
if (!::PositionSelectByTicket(_ticket)) {
return false;
}
MqlTradeRequest _request = {0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_SLTP;
//_request.type = PositionTypeToOrderType();
_request.position = _ticket; // Position ticket.
_request.symbol = ::PositionGetString(POSITION_SYMBOL);
_request.sl = _stoploss;
_request.tp = _takeprofit;
_request.expiration = _expiration;
return Order::OrderSend(_request, _result);
#endif
}
bool OrderModify(double _sl, double _tp, double _price = 0, datetime _expiration = 0) {
if (odata.time_close > 0) {
// Ignore change for already closed orders.
return false;
} else if (_sl == odata.sl && _tp == odata.tp && _expiration == odata.expiration) {
// Ignore change for the same values.
return false;
}
bool _result = Order::OrderModify(oresult.order, _price, _sl, _tp, _expiration);
if (_result) {
odata.sl = _sl;
odata.tp = _tp;
odata.expiration = _expiration;
} else if (Order::OrderSelect(oresult.order, SELECT_BY_TICKET, MODE_HISTORY)) {
odata.time_close = GetCloseTime();
_result = false;
} else {
_result = Order::OrderModify(oresult.order, _price, _sl, _tp, _expiration);
Logger().AddLastError(__FUNCTION_LINE__);
}
return _result;
}
/**
* Returns open price of the currently selected order.
*
* @see
* - https://docs.mql4.com/trading/orderopenprice
* - https://www.mql5.com/en/docs/trading/ordergetinteger
*/
static double OrderOpenPrice() {
#ifdef __MQL4__
return ::OrderOpenPrice();
#else
return Order::OrderGetDouble(ORDER_PRICE_OPEN);
#endif
}
double GetOpenPrice() {
Update(ORDER_PRICE_OPEN);
return odata.price_open;
}
/**
* Returns profit of the currently selected order.
*
* @return
* Returns the net profit value (without swaps or commissions) for the selected order.
* For open orders, it is the current unrealized profit. For closed orders, it is the fixed profit.
*
* @see https://docs.mql4.com/trading/orderprofit
*/
static double OrderProfit() {
#ifdef __MQL4__
return ::OrderProfit();
#else
return ::PositionGetDouble(POSITION_PROFIT);
#endif
}
double GetProfit() {
Update(ORDER_PRICE_CURRENT);
return odata.profit;
}
/**
* Executes trade operations by sending the request to a trade server.
*
* The main function used to open market or place a pending order.
*
* @see
* - https://docs.mql4.com/trading/ordersend
* - https://www.mql5.com/en/docs/trading/ordersend
*
* @return
* Returns number of the ticket assigned to the order by the trade server
* or -1 if it fails.
*/
static long OrderSend(string _symbol, // Symbol.
int _cmd, // Operation.
double _volume, // Volume.
double _price, // Price.
unsigned long _deviation, // Deviation.
double _stoploss, // Stop loss.
double _takeprofit, // Take profit.
string _comment = NULL, // Comment.
unsigned long _magic = 0, // Magic number.
datetime _expiration = 0, // Pending order expiration.
color _arrow_color = clrNONE // Color.
) {
#ifdef __MQL4__
return ::OrderSend(_symbol, _cmd, _volume, _price, (int)_deviation, _stoploss, _takeprofit, _comment,
(unsigned int)_magic, _expiration, _arrow_color);
#else
// @docs
// - https://www.mql5.com/en/articles/211
// - https://www.mql5.com/en/docs/constants/tradingconstants/enum_trade_request_actions
MqlTradeRequest _request = {0}; // Query structure.
MqlTradeResult _result = {0}; // Structure of the result.
_request.action = TRADE_ACTION_DEAL;
_request.symbol = _symbol;
_request.volume = _volume;
_request.price = _price;
_request.sl = _stoploss;
_request.tp = _takeprofit;
_request.deviation = _deviation;
_request.comment = _comment;
_request.magic = _magic;
_request.expiration = _expiration;
_request.type = (ENUM_ORDER_TYPE)_cmd;
_request.type_filling = _request.type_filling ? _request.type_filling : GetOrderFilling(_symbol);
return Order::OrderSend(_request, _result) > 0;
#endif
}
static bool OrderSend(const MqlTradeRequest &_request, MqlTradeResult &_result, MqlTradeCheckResult &_check_result,
color _color = clrNONE) {
#ifdef __MQL4__
// Convert Trade Request Structure to function parameters.
_result.retcode = TRADE_RETCODE_ERROR;
if (_request.position > 0) {
if (_request.action == TRADE_ACTION_SLTP) {
if (Order::OrderModify(_request.position, _request.price, _request.sl, _request.tp, _request.expiration,
_color)) {
// @see: https://www.mql5.com/en/docs/constants/structures/mqltraderesult
_result.ask = SymbolInfo::GetAsk(_request.symbol); // The current market Bid price (requote price).
_result.bid = SymbolInfo::GetBid(_request.symbol); // The current market Ask price (requote price).
_result.order = _request.position; // Order ticket.
_result.price = _request.price; // Deal price, confirmed by broker.
_result.volume = _request.volume; // Deal volume, confirmed by broker (@fixme?).
_result.retcode = TRADE_RETCODE_DONE;
//_result.comment = TODO; // The broker comment to operation (by default it is filled by description of trade
// server return code).
}
} else if (_request.action == TRADE_ACTION_CLOSE_BY) {
if (Order::OrderCloseBy(_request.position, _request.position_by, _color)) {
// @see: https://www.mql5.com/en/docs/constants/structures/mqltraderesult
_result.ask = SymbolInfo::GetAsk(_request.symbol); // The current market Bid price (requote price).
_result.bid = SymbolInfo::GetBid(_request.symbol); // The current market Ask price (requote price).
_result.retcode = TRADE_RETCODE_DONE;
}
} else if (_request.action == TRADE_ACTION_DEAL || _request.action == TRADE_ACTION_REMOVE) {
// @see: https://docs.mql4.com/trading/orderclose
if (Order::OrderClose(_request.position, _request.volume, _request.price, (int)_request.deviation, _color)) {
// @see: https://www.mql5.com/en/docs/constants/structures/mqltraderesult
_result.ask = SymbolInfo::GetAsk(_request.symbol); // The current market Bid price (requote price).
_result.bid = SymbolInfo::GetBid(_request.symbol); // The current market Ask price (requote price).
_result.order = _request.position; // Order ticket.
_result.price = _request.price; // Deal price, confirmed by broker.
_result.volume = _request.volume; // Deal volume, confirmed by broker (@fixme?).
_result.retcode = TRADE_RETCODE_DONE;
//_result.comment = TODO; // The broker comment to operation (by default it is filled by description of trade
// server return code).
}
}
} else if (_request.action == TRADE_ACTION_DEAL) {
// @see: https://docs.mql4.com/trading/ordersend
_result.order = Order::OrderSend(_request.symbol, // Symbol.
_request.type, // Operation.
_request.volume, // Volume.
_request.price, // Price.
_request.deviation, // Deviation.
_request.sl, // Stop loss.
_request.tp, // Take profit.
_request.comment, // Comment.
_request.magic, // Magic number.
_request.expiration, // Pending order expiration.
_color // Color.
);
_result.retcode = _result.order > 0 ? TRADE_RETCODE_DONE : GetLastError();
if (_request.order > 0) {
// @see: https://www.mql5.com/en/docs/constants/structures/mqltraderesult
_result.ask = SymbolInfo::GetAsk(_request.symbol); // The current market Bid price (requote price).
_result.bid = SymbolInfo::GetBid(_request.symbol); // The current market Ask price (requote price).
_result.price = _request.price; // Deal price, confirmed by broker.
_result.volume = _request.volume; // Deal volume, confirmed by broker (@fixme?).
//_result.comment = TODO; // The broker comment to operation (by default it is filled by description of trade
// server return code).
}
}
return _result.retcode == TRADE_RETCODE_DONE;
#else
// The trade requests go through several stages of checking on a trade server.
// First of all, it checks if all the required fields of the request parameter are filled out correctly.
if (!OrderCheck(_request, _check_result)) {
// If funds are not enough for the operation,
// or parameters are filled out incorrectly, the function returns false.
// In order to obtain information about the error, call the GetLastError() function.
// @docs
// - https://www.mql5.com/en/docs/trading/ordercheck
// - https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes
// - https://www.mql5.com/en/docs/constants/structures/mqltradecheckresult
#ifdef __debug__
PrintFormat("%s: Error %d: %s", __FUNCTION_LINE__, _check_result.retcode,
Terminal::GetErrorText(_check_result.retcode));
#endif
_result.retcode = _check_result.retcode;
return false;
}
// In case of a successful basic check of structures (index checking) returns true.
// However, this is not a sign of successful execution of a trade operation.
// If there are no errors, the server accepts the order for further processing.
// The check results are placed to the fields of the MqlTradeCheckResult structure.
// For a more detailed description of the function execution result,
// analyze the fields of the result structure.
// In order to obtain information about the error, call the GetLastError() function.
// --
// @docs
// - https://www.mql5.com/en/docs/trading/ordersend
// - https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes
// --
// Sends trade requests to a server.
return ::OrderSend(_request, _result);
// The function execution result is placed to structure MqlTradeResult,
// whose retcode field contains the trade server return code.
// In order to obtain information about the error, call the GetLastError() function.
#endif
}
static bool OrderSend(const MqlTradeRequest &_request, MqlTradeResult &_result) {