-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathOrder.mqh
2804 lines (2635 loc) · 96.6 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-2021, EA31337 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
* Implements class for managing orders.
*/
// Prevents processing this includes file for the second time.
#ifndef ORDER_MQH
#define ORDER_MQH
// Includes.
#include "Action.enum.h"
#include "Convert.mqh"
#include "Data.define.h"
#include "Data.struct.h"
#include "Log.mqh"
#include "Order.define.h"
#include "Order.enum.h"
#include "Order.struct.h"
#include "Serializer.mqh"
#include "SerializerJson.mqh"
#include "Std.h"
#include "String.mqh"
#include "SymbolInfo.mqh"
/* Defines for backward compatibility. */
// 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 ORDER_EXTERNAL_ID
// Order identifier in an external trading system (on the Exchange).
// Note: Required for backward compatibility in MQL4.
// @see: https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties#enum_order_property_string
#define ORDER_EXTERNAL_ID ((ENUM_ORDER_PROPERTY_STRING)20)
#endif
#ifndef ORDER_REASON
// The reason or source for placing an order.
// Note: Required for backward compatibility in MQL4.
// @see: https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
#define ORDER_REASON ((ENUM_ORDER_PROPERTY_INTEGER)23)
#endif
#ifndef __MQLBUILD__
// Defines.
// Mode constants.
// @see: https://docs.mql4.com/trading/orderselect
#define MODE_TRADES 0
#define MODE_HISTORY 1
#endif
/**
* 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.
Log ologger; // Logger.
MqlTradeRequest orequest; // Trade Request Structure.
MqlTradeCheckResult oresult_check; // Results of a Trade Request Check.
MqlTradeResult oresult; // Trade Request Result.
OrderParams oparams;
OrderData odata;
#ifndef __MQL4__
// Used for order selection in MQL5 & C++.
static unsigned long selected_ticket_id;
static ENUM_ORDER_SELECT_TYPE selected_ticket_type;
#endif
public:
/**
* Class constructors.
*/
Order() {}
Order(long _ticket_no) {
odata.Set(ORDER_PROP_TICKET, _ticket_no);
Refresh(true);
}
Order(const MqlTradeRequest &_request, bool _send = true) {
orequest = _request;
if (_send) {
if (!IsDummy()) {
OrderSend();
} else {
OrderSendDummy();
}
}
}
Order(const MqlTradeRequest &_request, const OrderParams &_oparams, bool _send = true) {
orequest = _request;
oparams = _oparams;
if (_send) {
if (!IsDummy()) {
OrderSend();
} else {
OrderSendDummy();
}
}
}
/**
* Loads order based on OrderData struct.
*/
Order(OrderData &_odata) : odata(_odata) {}
/**
* Class copy constructors.
*/
Order(const Order &_order) {
oparams = _order.oparams;
odata = _order.odata;
orequest = _order.orequest;
oresult_check = _order.oresult_check;
oresult = _order.oresult;
}
/**
* Class deconstructor.
*/
~Order() {}
Log *GetLogger() { return GetPointer(ologger); }
/* Getters */
/**
* Gets an order property custom value.
*/
template <typename T>
T Get(ENUM_ORDER_PARAM _param) {
return oparams.Get<T>(_param);
}
/**
* Gets an order property custom value.
*/
template <typename T>
T Get(ENUM_ORDER_PROPERTY_CUSTOM _prop) {
return odata.Get<T>(_prop);
}
/**
* Gets an order property double value.
*/
template <typename T>
double Get(ENUM_ORDER_PROPERTY_DOUBLE _prop) {
return odata.Get<T>(_prop);
}
/**
* Gets an order property integer value.
*/
template <typename T>
T Get(ENUM_ORDER_PROPERTY_INTEGER _prop) {
return odata.Get<T>(_prop);
}
/**
* Gets an order property string value.
*/
string Get(ENUM_ORDER_PROPERTY_STRING _prop) { return odata.Get(_prop); }
/**
* 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 */
/**
* Sets an order property custom value.
*/
template <typename T>
void Set(ENUM_ORDER_PARAM _param, T _value, int _index1 = 0, int _index2 = 0) {
oparams.Set<T>(_param, _value, _index1, _index2);
}
/**
* Sets an order property custom value.
*/
template <typename T>
void Set(ENUM_ORDER_PROPERTY_CUSTOM _prop, T _value) {
odata.Set<T>(_prop, _value);
}
/**
* Sets an order property double value.
*/
void Set(ENUM_ORDER_PROPERTY_DOUBLE _prop, double _value) { odata.Set(_prop, _value); }
/**
* Sets an order property integer value.
*/
void Set(ENUM_ORDER_PROPERTY_INTEGER _prop, long _value) { odata.Set(_prop, _value); }
/**
* Sets an order property string value.
*/
void Set(ENUM_ORDER_PROPERTY_STRING _prop, string _value) { odata.Set(_prop, _value); }
/* State checkers */
/**
* Is order is open.
*/
bool IsClosed(bool _refresh = false) {
if (odata.Get<long>(ORDER_PROP_TIME_CLOSED) == 0) {
if (_refresh || ShouldRefresh()) {
if (Order::TryOrderSelect(odata.Get<long>(ORDER_PROP_TICKET), SELECT_BY_TICKET, MODE_HISTORY)) {
odata.Set<long>(ORDER_PROP_TIME_CLOSED, Order::OrderCloseTime());
odata.Set<int>(ORDER_PROP_REASON_CLOSE, ORDER_REASON_CLOSED_UNKNOWN);
}
}
}
return odata.Get<long>(ORDER_PROP_TIME_CLOSED) > 0;
}
/**
* Is order closed.
*/
bool IsOpen(bool _refresh = false) { return !IsClosed(_refresh); }
/**
* Should order be closed.
*
* @return
* Returns true when order should be closed, otherwise false.
*/
bool ShouldCloseOrder() {
bool _result = false;
if (oparams.HasCloseCondition()) {
int _num = oparams.Get<int>(ORDER_PARAM_COND_CLOSE_NUM);
for (int _ci = 0; _ci < _num; _ci++) {
ENUM_ORDER_CONDITION _cond = oparams.Get<ENUM_ORDER_CONDITION>(ORDER_PARAM_COND_CLOSE, _ci);
DataParamEntry _cond_args[1];
_cond_args[0] = oparams.Get<long>(ORDER_PARAM_COND_CLOSE_ARG_VALUE, _ci);
_result |= _result || Order::CheckCondition(_cond, _cond_args);
}
}
return _result;
}
/**
* Should order be refreshed.
*
* @return
* Returns true when order values can be refreshed, otherwise false.
*/
bool ShouldRefresh() {
return odata.Get<long>(ORDER_PROP_TIME_LAST_REFRESH) + oparams.Get<ushort>(ORDER_PARAM_REFRESH_FREQ) <=
TimeCurrent();
}
/**
* Should order be updated.
*
* @return
* Returns true when order stops can be updated, otherwise false.
*/
bool ShouldUpdate() {
return odata.Get<long>(ORDER_PROP_TIME_LAST_UPDATE) + oparams.Get<ushort>(ORDER_PARAM_UPDATE_FREQ) <= TimeCurrent();
}
/* State checking */
/**
* Check whether order is selected and it is same as the class one.
*/
bool IsSelected() {
unsigned long ticket_id = Order::OrderTicket();
bool is_selected;
if (IsDummy()) {
is_selected = true;
} else {
is_selected = (odata.Get<long>(ORDER_PROP_TICKET) > 0 && ticket_id == odata.Get<long>(ORDER_PROP_TICKET));
}
ResetLastError();
return is_selected;
}
bool IsSelectedDummy() {
// @todo
return false;
}
bool IsDummy() { return oparams.dummy; }
/* 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 = SymbolInfoStatic::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() {
Refresh(ORDER_TYPE_FILLING);
return odata.Get<ENUM_ORDER_TYPE_FILLING>(ORDER_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)SymbolInfoStatic::SymbolInfoInteger(_symbol, SYMBOL_TRADE_EXEMODE);
const long _filling_mode = SymbolInfoStatic::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 */
/* Order getters */
/**
* Returns close price of the currently selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/ordercloseprice
*/
static double OrderClosePrice() {
#ifdef __MQL4__
return ::OrderClosePrice();
#else // __MQL5__
// @docs https://www.mql5.com/en/docs/trading/HistoryDealGetDouble
double _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
const ENUM_DEAL_ENTRY _deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(_deal_ticket, DEAL_ENTRY);
if (_deal_entry == DEAL_ENTRY_OUT || _deal_entry == DEAL_ENTRY_OUT_BY) {
_result = HistoryDealGetDouble(_deal_ticket, DEAL_PRICE);
break;
}
}
}
return _result;
#endif
}
double GetClosePrice() { return IsClosed() ? odata.Get<double>(ORDER_PROP_PRICE_CLOSE) : 0; }
/**
* Returns open time of the currently selected order/position.
*
* @see
* - http://docs.mql4.com/trading/orderopentime
* - https://www.mql5.com/en/docs/constants/tradingconstants/positionproperties
*/
static datetime OrderOpenTime() {
#ifdef __MQL4__
// http://docs.mql4.com/trading/orderopentime
return (datetime)Order::OrderGetInteger(ORDER_TIME_SETUP);
#else
long _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
const ENUM_DEAL_ENTRY _deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(_deal_ticket, DEAL_ENTRY);
if (_deal_entry == DEAL_ENTRY_IN) {
_result = HistoryDealGetInteger(_deal_ticket, DEAL_TIME);
break;
}
}
}
return (datetime)_result;
#endif
}
datetime GetOpenTime() {
if (odata.Get<datetime>(ORDER_PROP_TIME_OPENED) == 0) {
OrderSelect();
odata.Set<datetime>(ORDER_PROP_TIME_OPENED, Order::OrderOpenTime());
}
return odata.Get<datetime>(ORDER_PROP_TIME_OPENED);
}
/*
* Returns close time of the currently selected order/position.
*
* @see:
* - https://docs.mql4.com/trading/orderclosetime
*/
static datetime OrderCloseTime() {
#ifdef __MQL4__
return ::OrderCloseTime();
#else // __MQL5__
// @docs https://www.mql5.com/en/docs/trading/historydealgetinteger
long _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
const ENUM_DEAL_ENTRY _deal_entry = (ENUM_DEAL_ENTRY)HistoryDealGetInteger(_deal_ticket, DEAL_ENTRY);
if (_deal_entry == DEAL_ENTRY_OUT || _deal_entry == DEAL_ENTRY_OUT_BY) {
_result = HistoryDealGetInteger(_deal_ticket, DEAL_TIME);
break;
}
}
}
return (datetime)_result;
#endif
}
datetime GetCloseTime() { return IsClosed() ? odata.Get<datetime>(ORDER_PROP_TIME_CLOSED) : 0; }
/**
* Returns comment of the currently selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/ordercomment
* - https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
*/
static string OrderComment() { return Order::OrderGetString(ORDER_COMMENT); }
/**
* Returns calculated commission of the currently selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/ordercommission
*/
static double OrderCommission() {
#ifdef __MQL4__
// https://docs.mql4.com/trading/ordercommission
return ::OrderCommission();
#else // __MQL5__
double _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
_result += _deal_ticket > 0 ? HistoryDealGetDouble(_deal_ticket, DEAL_COMMISSION) : 0;
}
}
return _result;
#endif
}
/* @todo
double GetCommission() {
if (IsSelected()) {
odata.Set<double>(ORDER_PROP_COMMISSION, Order::OrderCommission());
}
return odata.Get<double>(ORDER_PROP_COMMISSION);
}
*/
/**
* Returns total fees of the currently selected order.
*
*/
static double OrderTotalFees() {
#ifdef __MQL4__
return Order::OrderCommission() - Order::OrderSwap();
#else // __MQL5__
double _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
if (_deal_ticket > 0) {
_result += HistoryDealGetDouble(_deal_ticket, DEAL_COMMISSION);
_result += HistoryDealGetDouble(_deal_ticket, DEAL_FEE);
_result += HistoryDealGetDouble(_deal_ticket, DEAL_SWAP);
}
}
}
return _result;
#endif
}
double GetTotalFees() {
if (!IsClosed()) {
OrderSelect();
odata.Set<double>(ORDER_PROP_TOTAL_FEES, Order::OrderTotalFees());
}
return odata.Get<double>(ORDER_PROP_TOTAL_FEES);
}
/**
* Selects an order/position for further processing.
*
* @docs
* - https://docs.mql4.com/trading/orderselect
* - https://www.mql5.com/en/docs/trading/positiongetticket
*/
static datetime OrderExpiration() { return (datetime)Order::OrderGetInteger(ORDER_TIME_EXPIRATION); }
datetime GetExpiration() { return (datetime)odata.Get<datetime>(ORDER_TIME_EXPIRATION); }
/**
* Returns amount of lots/volume of the selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/orderlots
* - https://www.mql5.com/en/docs/constants/tradingconstants/positionproperties
*/
static double OrderLots() {
#ifdef __MQL4__
return ::OrderLots();
#else
// @fixme: It returns 0.
// @fixme: Error 69639.
return Order::OrderGetDouble(ORDER_VOLUME_CURRENT);
#endif
}
double GetVolume() { return orequest.volume; }
/**
* Returns an identifying (magic) number of the currently selected order.
*
* @see
* - http://docs.mql4.com/trading/ordermagicnumber
* - https://www.mql5.com/en/docs/trading/ordergetinteger
*/
static long OrderMagicNumber() { return Order::OrderGetInteger(ORDER_MAGIC); }
unsigned long GetMagicNumber() { return orequest.magic; }
/**
* Returns open price of the currently selected order/position.
*
* @docs
* - http://docs.mql4.com/trading/orderopenprice
* - https://www.mql5.com/en/docs/trading/ordergetdouble
*/
static double OrderOpenPrice() { return Order::OrderGetDouble(ORDER_PRICE_OPEN); }
double GetOpenPrice() { return odata.Get<double>(ORDER_PRICE_OPEN); }
/**
* Returns profit of the currently selected order/position.
*
* @docs
* - http://docs.mql4.com/trading/orderprofit
*
* @return
* Returns the order's net profit value (without swaps or commissions).
*/
static double OrderProfit() {
#ifdef __MQL4__
// 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.
return ::OrderProfit();
#else
double _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
_result += _deal_ticket > 0 ? HistoryDealGetDouble(_deal_ticket, DEAL_PROFIT) : 0;
}
}
return _result;
#endif
}
/**
* Returns stop loss value of the currently selected order.
*
* @docs
* - http://docs.mql4.com/trading/orderstoploss
* - https://www.mql5.com/en/docs/trading/ordergetdouble
*/
static double OrderStopLoss() { return Order::OrderGetDouble(ORDER_SL); }
double GetStopLoss(bool _refresh = true) {
if (ShouldRefresh() || _refresh) {
Refresh(ORDER_SL);
}
return odata.Get<double>(ORDER_SL);
}
/**
* Returns take profit value of the currently selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/ordertakeprofit
* - https://www.mql5.com/en/docs/constants/tradingconstants/positionproperties
*
* @return
* Returns take profit value of the currently selected order/position.
*/
static double OrderTakeProfit() { return Order::OrderGetDouble(ORDER_TP); }
double GetTakeProfit(bool _refresh = true) {
if (ShouldRefresh() || _refresh) {
Refresh(ORDER_TP);
}
return odata.Get<double>(ORDER_TP);
}
/**
* Returns SL/TP value of the currently selected order.
*/
static double GetOrderSLTP(ENUM_ORDER_PROPERTY_DOUBLE _mode) {
switch (_mode) {
case ORDER_SL:
return OrderStopLoss();
case ORDER_TP:
return OrderTakeProfit();
}
return NULL;
}
/**
* Returns cumulative swap of the currently selected order.
*/
static double OrderSwap() {
#ifdef __MQL4__
// https://docs.mql4.com/trading/orderswap
return ::OrderSwap();
#else
double _result = 0;
unsigned long _ticket = Order::OrderTicket();
if (HistorySelectByPosition(_ticket)) {
for (int i = HistoryDealsTotal() - 1; i >= 0; i--) {
// https://www.mql5.com/en/docs/trading/historydealgetticket
const unsigned long _deal_ticket = HistoryDealGetTicket(i);
_result += _deal_ticket > 0 ? HistoryDealGetDouble(_deal_ticket, DEAL_SWAP) : 0;
}
}
return _result;
#endif
}
/* @fixme
double GetSwap() {
if (!IsClosed()) {
OrderSelect();
odata.swap = Order::OrderSwap();
}
return odata.swap;
}
*/
/**
* Returns symbol name of the currently selected order/position.
*
* @docs
* - https://docs.mql4.com/trading/ordersymbol
* - https://www.mql5.com/en/docs/trading/positiongetstring
*/
static string OrderSymbol() {
#ifdef __MQL4__
return ::OrderSymbol();
#else
return Order::OrderGetString(ORDER_SYMBOL);
#endif
}
string GetSymbol() { return orequest.symbol; }
/**
* Returns a ticket number of the currently selected order.
*
* It is a unique number assigned to each order.
*
* @see https://docs.mql4.com/trading/orderticket
* @see https://www.mql5.com/en/docs/trading/ordergetticket
*/
static unsigned long OrderTicket() {
#ifdef __MQL4__
return ::OrderTicket();
#else
return selected_ticket_id;
#endif
}
// unsigned long GetTicket() const { return odata.Get<unsigned long>(ORDER_PROP_TICKET); }
/**
* Returns order operation type of the currently selected order/position.
*
* @docs
* - http://docs.mql4.com/trading/ordertype
* - https://www.mql5.com/en/docs/constants/tradingconstants/positionproperties
*
* @return
* Order/position operation type.
*/
static ENUM_ORDER_TYPE OrderType() { return (ENUM_ORDER_TYPE)Order::OrderGetInteger(ORDER_TYPE); }
ENUM_ORDER_TYPE GetType() {
if (odata.Get<int>(ORDER_TYPE) < 0 && Select()) {
Refresh(ORDER_TYPE);
}
return odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE);
}
/**
* Returns order operation type of the currently selected order.
*
* Limit and stop orders are on a GTC basis unless an expiry time is set explicitly.
*
* @see https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
*/
static ENUM_ORDER_TYPE_TIME OrderTypeTime() { return (ENUM_ORDER_TYPE_TIME)Order::OrderGetInteger(ORDER_TYPE_TIME); }
/**
* Returns the order position based on the ticket.
*
* It is set to an order as soon as it is executed.
* Each executed order results in a deal that opens or modifies an already existing position.
* The identifier of exactly this position is set to the executed order at this moment.
*/
static unsigned long OrderGetPositionID() {
#ifdef __MQL4__
unsigned long _ticket = ::OrderTicket();
for (int _pos = 0; _pos < OrdersTotal(); _pos++) {
if (::OrderSelect(_pos, SELECT_BY_POS, MODE_TRADES) && ::OrderTicket() == _ticket) {
return _pos;
}
}
return -1;
#else // __MQL5__
return Order::OrderGetInteger(ORDER_POSITION_ID);
#endif
}
/* @todo
unsigned long GetPositionID() {
#ifdef ORDER_POSITION_ID
if (odata.position_id == 0) {
OrderSelect();
Refresh(ORDER_POSITION_ID);
}
#endif
return odata.Get<unsigned long>(ORDER_POSITION_ID);
}
*/
/**
* Returns the ticket of an opposite position.
*
* Used when a position is closed by an opposite one open for the same symbol in the opposite direction.
*
* @see:
* - https://www.mql5.com/en/docs/constants/structures/mqltraderequest
* - https://www.mql5.com/en/docs/constants/tradingconstants/orderproperties
*/
static unsigned long OrderGetPositionBy() {
#ifdef __MQL4__
// @todo
/*
for (int _pos = 0; _pos < OrdersTotal(); _pos++) {
if (OrderSelect(_pos, SELECT_BY_POS, MODE_TRADES) && OrderTicket() == _ticket) {
return _pos;
}
}
*/
return -1;
#else // __MQL5__
return Order::OrderGetInteger(ORDER_POSITION_BY_ID);
#endif
}
/* @todo
unsigned long GetOrderPositionBy() {
#ifdef ORDER_POSITION_BY_ID
if (odata.position_by_id == 0) {
OrderSelect();
Refresh(ORDER_POSITION_BY_ID);
}
#endif
return odata.Get<unsigned long>(ORDER_POSITION_BY_ID);
}
*/
/**
* Returns the ticket of a position in the list of open positions.
*
* @see https://www.mql5.com/en/docs/trading/positiongetticket
*/
unsigned long PositionGetTicket(int _index) {
#ifdef __MQL4__
if (::OrderSelect(_index, SELECT_BY_POS, MODE_TRADES)) {
return ::OrderTicket();
}
return -1;
#else // __MQL5__
return ::PositionGetTicket(_index);
#endif
}
/* Order manipulation */
/**
* 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 = {(ENUM_TRADE_REQUEST_ACTIONS)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(ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_UNKNOWN, string _comment = "") {
odata.ResetError();
odata.Set(ORDER_PROP_REASON_CLOSE, _reason);
if (!OrderSelect()) {
if (!OrderSelectHistory()) {
odata.ProcessLastError();
return false;
}
}
MqlTradeRequest _request = {(ENUM_TRADE_REQUEST_ACTIONS)0};
MqlTradeResult _result = {0};
_request.action = TRADE_ACTION_DEAL;
_request.comment = _comment != "" ? _comment : odata.GetReasonCloseText();
_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) {
// For now, sets the current time.
odata.Set(ORDER_PROP_TIME_CLOSED, DateTimeStatic::TimeTradeServer());
// For now, sets using the actual close price.
odata.Set(ORDER_PROP_PRICE_CLOSE, SymbolInfo::GetCloseOffer(odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE)));
odata.Set(ORDER_PROP_LAST_ERROR, ERR_NO_ERROR);
odata.Set(ORDER_PROP_REASON_CLOSE, _reason);
Refresh();
return true;
} else {
odata.Set<unsigned int>(ORDER_PROP_LAST_ERROR, oresult.retcode);
if (OrderSelect()) {
if (IsClosed()) {
Refresh();
}
}
}
return false;
}
/**
* Closes dummy order.
*
* @return
* Returns true if successful.
*/
bool OrderCloseDummy(ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_UNKNOWN, string _comment = "") {
odata.Set(ORDER_PROP_LAST_ERROR, ERR_NO_ERROR);
odata.Set(ORDER_PROP_PRICE_CLOSE, SymbolInfoStatic::GetCloseOffer(symbol, odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE)));
odata.Set(ORDER_PROP_REASON_CLOSE, _reason);
odata.Set(ORDER_PROP_TIME_CLOSED, DateTimeStatic::TimeTradeServer());
Refresh();
return true;
}
/**
* 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 = {(ENUM_TRADE_REQUEST_ACTIONS)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
}
/**
* Closes a position by an opposite one.
*/
bool OrderCloseBy(long _opposite, color _color) {
bool _result = OrderCloseBy(odata.Get<long>(ORDER_PROP_TICKET), _opposite, _color);
if (_result) {
odata.Set(ORDER_PROP_REASON_CLOSE, ORDER_REASON_CLOSED_BY_OPPOSITE);
}
return _result;
}