-
-
Notifications
You must be signed in to change notification settings - Fork 102
/
Copy pathTrade.mqh
2078 lines (1955 loc) · 75.6 KB
/
Trade.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-2022, 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/>.
*
*/
// Forward declaration.
class Trade;
/**
* Trade class
*/
#ifndef TRADE_MQH
#define TRADE_MQH
// Includes.
#include "Account/AccountMt.h"
#include "Convert.mqh"
#include "Storage/Dict/DictStruct.h"
#include "Indicator/IndicatorData.h"
#include "Math.h"
#include "Storage/Object.h"
#include "Order.mqh"
#include "OrderQuery.h"
#include "Task/TaskManager.h"
#include "Task/Taskable.h"
#include "Trade.enum.h"
#include "Trade.struct.h"
class Trade : public Taskable<DataParamEntry> {
public:
AccountMt account;
Ref<IndicatorData> indi_candle;
DictStruct<long, Ref<Order>> orders_active;
DictStruct<long, Ref<Order>> orders_history;
DictStruct<long, Ref<Order>> orders_pending;
Log logger; // Trade logger.
TaskManager tasks; // Tasks.
TradeParams tparams; // Trade parameters.
TradeStates tstates; // Trade states.
TradeStats tstats; // Trade statistics.
protected:
string name;
Ref<Order> order_last;
// Strategy *strategy; // Optional pointer to Strategy class.
public:
/**
* Class constructor.
*/
Trade(IndicatorData *_indi_candle) : indi_candle(_indi_candle), order_last(NULL) {
SetName();
OrdersLoadByMagic(tparams.magic_no);
};
Trade(TradeParams &_tparams, IndicatorData *_indi_candle)
: indi_candle(_indi_candle), tparams(_tparams), order_last(NULL) {
SetName();
OrdersLoadByMagic(tparams.magic_no);
};
/**
* Default constructor.
*/
Trade() {}
/**
* Copy constructor.
*/
Trade(const Trade &_trade) {
tparams = _trade.tparams;
tstats = _trade.tstats;
tstates = _trade.tstates;
}
/**
* Class deconstructor.
*/
~Trade() {}
/* Getters simple */
/**
* Gets an account parameter value of double type.
*/
/*
template <typename T>
T Get(ENUM_ACCOUNT_INFO_DOUBLE _param) {
return account.Get<T>(_param);
}
*/
/**
* Gets a trade state value.
*/
template <typename T>
T Get(ENUM_TRADE_STATE _prop) {
return tstates.Get(_prop);
}
/**
* Gets a trade parameter value.
*/
template <typename T>
T Get(ENUM_TRADE_PARAM _param) {
return tparams.Get<T>(_param);
}
/**
* Gets a chart parameter value.
*/
template <typename T>
T Get(ENUM_CHART_PARAM _param) {
return GetSource() PTR_DEREF Get<T>(_param);
}
/**
* Gets name of trade instance.
*/
string GetName() const { return name; }
/**
* Gets the last order.
*/
Order *GetOrderLast() { return order_last.Ptr(); }
/**
* Gets copy of params.
*
* @return
* Returns structure for Trade's params.
*/
TradeParams GetParams() const { return tparams; }
/**
* Gets copy of states.
*
* @return
* Returns structure for Trade's states.
*/
TradeStates GetStates() const { return tstates; }
/**
* Gets copy of stats.
*
* @return
* Returns structure for Trade's stats.
*/
TradeStats GetStats() const { return tstats; }
/**
* Gets list of active orders.
*
* @return
* Returns DictStruct's of active orders.
*/
DictStruct<long, Ref<Order>> *GetOrdersActive() { return &orders_active; }
/**
* Gets list of history orders.
*
* @return
* Returns DictStruct's of orders from history.
*/
DictStruct<long, Ref<Order>> *GetOrdersHistory() { return &orders_history; }
/**
* Gets list of pending orders.
*
* @return
* Returns DictStruct's of pending orders.
*/
DictStruct<long, Ref<Order>> *GetOrdersPending() { return &orders_pending; }
/**
* Get a trade request.
*
* @return
* Returns true on successful request.
*/
MqlTradeRequest GetTradeOpenRequest(ENUM_ORDER_TYPE _type, float _volume = 0, long _magic = 0, string _comment = "") {
// Create a request.
MqlTradeRequest _request = {(ENUM_TRADE_REQUEST_ACTIONS)0};
_request.action = TRADE_ACTION_DEAL;
_request.comment = _comment;
_request.deviation = 10;
_request.magic = _magic > 0 ? _magic : tparams.Get<long>(TRADE_PARAM_MAGIC_NO);
_request.symbol = GetSource() PTR_DEREF GetSymbol();
_request.price = GetSource() PTR_DEREF GetOpenOffer(_type);
_request.type = _type;
#ifndef __MQL4__
// Filling modes not supported under MQL4.
_request.type_filling = Order::GetOrderFilling(_request.symbol);
#endif
_request.volume = _volume > 0 ? _volume : tparams.Get<float>(TRADE_PARAM_LOT_SIZE);
_request.volume = NormalizeLots(fmax(_request.volume, GetSource() PTR_DEREF GetSymbolProps().GetVolumeMin()));
#ifdef __debug__
MqlTick _tick; // Structure to get the latest prices.
SymbolInfoTick(GetSource() PTR_DEREF GetSymbol(), _tick);
Print("------------------------");
Print("C Price: ", GetSource() PTR_DEREF GetOpenOffer(_type));
Print("C Ask: ", GetSource() PTR_DEREF GetTick() PTR_DEREF GetAsk());
Print("C Bid: ", GetSource() PTR_DEREF GetTick() PTR_DEREF GetBid());
Print("R Ask: ", _tick.ask);
Print("R Bid: ", _tick.bid);
#endif
return _request;
}
/* Setters */
/**
* Sets a trade parameter value.
*/
template <typename T>
void Set(ENUM_TRADE_PARAM _param, T _value) {
tparams.Set<T>(_param, _value);
}
/**
* Sets default name of trade instance.
*/
void SetName() {
name = StringFormat("%s@%s", C_STR(GetSource() PTR_DEREF GetSymbol()),
C_STR(ChartTf::TfToString(GetSource() PTR_DEREF GetTf())));
}
/**
* Sets name of trade instance.
*/
void SetName(string _name) { name = _name; }
// void SetStrategy(Strategy *_strategy) { strategy = _strategy; }
/* State methods */
/**
* Check whether the price is in its peak for the current period.
*/
bool IsPeak(ENUM_ORDER_TYPE _cmd, int _shift = 0) {
bool _result = false;
double _high = GetSource() PTR_DEREF GetHigh(_shift + 1);
double _low = GetSource() PTR_DEREF GetLow(_shift + 1);
double _open = GetSource() PTR_DEREF GetOpenOffer(_cmd);
if (_low != _high) {
switch (_cmd) {
case ORDER_TYPE_BUY:
_result = _open > _high;
break;
case ORDER_TYPE_SELL:
_result = _open < _low;
break;
default:
RUNTIME_ERROR("Order type not supported!");
_result = false;
}
}
return _result;
}
/**
* Checks if the current price is in pivot point level given the order type.
*/
bool IsPivot(ENUM_ORDER_TYPE _cmd, int _shift = 0) {
bool _result = false;
double _high = GetSource() PTR_DEREF GetHigh(_shift + 1);
double _low = GetSource() PTR_DEREF GetLow(_shift + 1);
double _close = GetSource() PTR_DEREF GetClose(_shift + 1);
if (_close > 0 && _low != _high) {
float _pp = (float)(_high + _low + _close) / 3;
switch (_cmd) {
case ORDER_TYPE_BUY:
_result = GetSource() PTR_DEREF GetOpenOffer(_cmd) > _pp;
break;
case ORDER_TYPE_SELL:
_result = GetSource() PTR_DEREF GetOpenOffer(_cmd) < _pp;
break;
default:
RUNTIME_ERROR("Order type not supported!");
_result = false;
}
}
return _result;
}
/**
* Check if trading is allowed.
*/
bool IsTradeAllowed() {
UpdateStates();
return !tstates.CheckState(TRADE_STATE_TRADE_CANNOT);
}
/**
* Check if trading is recommended.
*/
bool IsTradeRecommended() {
UpdateStates();
return !tstates.CheckState(TRADE_STATE_TRADE_WONT);
}
/**
* Check if trading instance is valid.
*/
bool IsValid() { return GetSource() PTR_DEREF IsValid(); }
/**
* Check if this trade instance has active orders.
*/
bool HasActiveOrders() { return orders_active.Size() > 0; }
/**
* Check if current bar has active order.
*/
bool HasBarOrder(ENUM_ORDER_TYPE _cmd, int _shift = 0) {
bool _result = false;
Ref<Order> _order = order_last;
if (_order.IsSet() && _order REF_DEREF Get<ENUM_ORDER_TYPE>(ORDER_TYPE) == _cmd &&
_order REF_DEREF Get<long>(ORDER_TIME_SETUP) > GetSource() PTR_DEREF GetBarTime()) {
_result |= true;
}
if (!_result) {
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order REF_DEREF Get<ENUM_ORDER_TYPE>(ORDER_TYPE) == _cmd) {
long _time_opened = _order REF_DEREF Get<long>(ORDER_TIME_SETUP);
_result |= _shift > 0 && _time_opened < GetSource() PTR_DEREF GetBarTime(_shift - 1);
_result |= _time_opened >= GetSource() PTR_DEREF GetBarTime(_shift);
if (_result) {
break;
}
}
}
}
return _result;
}
/**
* Checks if we have already better priced opened order.
*/
bool HasOrderBetter(ENUM_ORDER_TYPE _cmd) {
bool _result = false;
Ref<Order> _order = order_last;
OrderData _odata;
double _price_curr = GetSource() PTR_DEREF GetOpenOffer(_cmd);
if (_order.IsSet() && _order REF_DEREF IsOpen()) {
if (_odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE) == _cmd) {
switch (_cmd) {
case ORDER_TYPE_BUY:
_result |= _odata.Get<float>(ORDER_PRICE_OPEN) <= _price_curr;
break;
case ORDER_TYPE_SELL:
_result |= _odata.Get<float>(ORDER_PRICE_OPEN) >= _price_curr;
break;
default:
RUNTIME_ERROR("Order type not supported!");
_result = false;
}
}
}
if (!_result) {
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid() && !_result; ++iter) {
_order = iter.Value();
if (_order.IsSet() && _order REF_DEREF IsOpen()) {
if (_odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE) == _cmd) {
switch (_cmd) {
case ORDER_TYPE_BUY:
_result |= _odata.Get<float>(ORDER_PRICE_OPEN) <= _price_curr;
break;
case ORDER_TYPE_SELL:
_result |= _odata.Get<float>(ORDER_PRICE_OPEN) >= _price_curr;
break;
default:
RUNTIME_ERROR("Order type not supported!");
_result = false;
}
}
} else if (_order.IsSet()) {
OrderMoveToHistory(_order.Ptr());
}
}
}
return _result;
}
/**
* Checks if we have already order with the opposite type.
*/
bool HasOrderOppositeType(ENUM_ORDER_TYPE _cmd) {
bool _result = false;
Ref<Order> _order = order_last;
OrderData _odata;
// double _price_curr = GetSource() PTR_DEREF GetOpenOffer(_cmd);
if (_order.IsSet()) {
_result = _odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE) != _cmd;
}
if (!_result) {
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid() && !_result; ++iter) {
_order = iter.Value();
if (_order.IsSet()) {
_result = _odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE) != _cmd;
if (_result) {
_result = _odata.Get<ENUM_ORDER_TYPE>(ORDER_TYPE) != _cmd;
break;
}
} else if (_order.IsSet()) {
OrderMoveToHistory(_order.Ptr());
}
}
}
return _result;
}
/**
* Checks if the trade has the given state.
*
* @param _state State to check.
*
* @return
* Returns true when in that state.
*/
bool HasState(ENUM_TRADE_STATE _state) { return tstates.CheckState(_state); }
/* Calculation methods */
/**
* Calculate the total profit from all active orders in base currency value.
*
* @param
* Returns profit in base currency value.
*/
float CalcActiveProfitInValue() {
float _result = 0.0f;
if (Get<bool>(TRADE_STATE_ORDERS_ACTIVE)) {
OrderQuery _oquery(orders_active);
RefreshActiveOrdersByProp(ORDER_PRICE_CURRENT);
_result = _oquery.CalcSumByProp<ENUM_ORDER_PROPERTY_CUSTOM, float>(ORDER_PROP_PROFIT_VALUE);
}
return _result;
}
/**
* Calculate equity based on all active orders in base currency value.
*
* Note: Equity is calculated only for this instance.
*
* @param
* Returns equity value in base currency value.
*/
float CalcActiveEquity() { return account.GetTotalBalance() + CalcActiveProfitInValue(); }
/**
* Calculate equity based on all active orders in percent.
*
* Note: Equity is calculated only for this instance.
*
* @param
* Returns equity in percent.
*/
float CalcActiveEquityInPct(bool _hundreds = true) {
float _result = (float)Math::ChangeInPct(account.GetTotalBalance(), CalcActiveEquity(), _hundreds);
return _result;
}
/**
* Calculates the margin required for the specified order type.
*
* Note: It not taking into account current pending orders and open positions.
*
* @return
* The function returns true in case of success; otherwise it returns false.
*
* @see: https://www.mql5.com/en/docs/trading/ordercalcmargin
*/
static bool OrderCalcMargin(ENUM_ORDER_TYPE _action, // type of order
string _symbol, // symbol name
double _volume, // volume
double _price, // open price
double &_margin // variable for obtaining the margin value
) {
#ifdef __MQL4__
// @todo: To test.
_margin = GetMarginRequired(_symbol, _action);
return _margin > 0;
#else // __MQL5__
return ::OrderCalcMargin(_action, _symbol, _volume, _price, _margin);
#endif
}
/**
* Free margin required for opening a position with the volume of one lot in the appropriate direction.
*/
static double GetMarginRequired(string _symbol, ENUM_ORDER_TYPE _cmd = ORDER_TYPE_BUY) {
#ifdef __MQL4__
return MarketInfo(_symbol, MODE_MARGINREQUIRED);
#else
// https://www.mql5.com/ru/forum/170952/page9#comment_4134898
// https://www.mql5.com/en/docs/trading/ordercalcmargin
double _margin_req;
bool _result = Trade::OrderCalcMargin(_cmd, _symbol, 1, SymbolInfoStatic::GetAsk(_symbol), _margin_req);
return _result ? _margin_req : 0;
#endif
}
float GetMarginRequired(ENUM_ORDER_TYPE _cmd = ORDER_TYPE_BUY) {
return (float)GetMarginRequired(GetSource() PTR_DEREF GetSymbol(), _cmd);
}
/* Lot size methods */
/**
* Calculate the maximal lot size for the given stop loss value and risk margin.
*
* @param double sl
* Stop loss to calculate the lot size for.
* @param string symbol
* Symbol pair.
*
* @return
* Returns maximum safe lot size value.
*
* @see: https://www.mql5.com/en/code/8568
*/
double GetMaxLotSize(double _sl, ENUM_ORDER_TYPE _cmd = ORDER_TYPE_UNSET) {
_cmd = _cmd == ORDER_TYPE_UNSET ? Order::OrderType() : _cmd;
double risk_amount = account.GetTotalBalance() / 100 * tparams.risk_margin;
double _ticks =
fabs(_sl - GetSource() PTR_DEREF GetOpenOffer(_cmd)) / GetSource() PTR_DEREF GetSymbolProps().GetTickSize();
double lot_size1 = fmin(_sl, _ticks) > 0 ? risk_amount / (_sl * (_ticks / 100.0)) : 1;
lot_size1 *= GetSource() PTR_DEREF GetSymbolProps().GetVolumeMin();
return NormalizeLots(lot_size1);
}
double GetMaxLotSize(unsigned int _pips, ENUM_ORDER_TYPE _cmd = ORDER_TYPE_UNSET) {
return GetMaxLotSize(CalcOrderSLTP(_pips, _cmd, ORDER_TYPE_SL));
}
/**
* Optimize lot size for open based on the consecutive wins and losses.
*
* @param
* lots (double)
* Base lot size.
* win_factor (double)
* Lot size increase factor (in %) multiplied by consecutive wins.
* loss_factor (double)
* Lot size increase factor (in %) multiplied by consecutive losses.
* ols_orders (double)
* Maximum number of recent orders to check for consecutive wins/losses.
* symbol (string)
* Optional symbol name if different than current.
*/
double OptimizeLotSize(double lots, double win_factor = 1.0, double loss_factor = 1.0, int ols_orders = 100,
string _symbol = NULL) {
double lotsize = lots;
int wins = 0, losses = 0; // Number of consequent losing orders.
int twins = 0, tlosses = 0; // Total number of consequent losing orders.
if (win_factor == 0 && loss_factor == 0) {
return lotsize;
}
// Calculate number of wins and losses orders without a break.
#ifdef __MQL5__
/* @fixme: Rewrite without using CDealInfo.
CDealInfo deal;
HistorySelect(0, TimeCurrent()); // Select history for access.
*/
#endif
int _orders = TradeHistoryStatic::HistoryOrdersTotal();
for (int i = _orders - 1; i >= fmax(0, _orders - ols_orders); i--) {
#ifdef __MQL5__
/* @fixme: Rewrite without using CDealInfo.
deal.Ticket(HistoryDealGetTicket(i));
if (deal.Ticket() == 0) {
Print(__FUNCTION__, ": Error in history!");
break;
}
if (deal.Symbol() != GetSource() PTR_DEREF GetSymbol()) continue;
double profit = deal.Profit();
*/
double profit = 0;
#else
if (Order::OrderSelect(i, SELECT_BY_POS, MODE_HISTORY) == false) {
Print(__FUNCTION__, ": Error in history!");
break;
}
if (Order::OrderSymbol() != Symbol() || Order::OrderType() > ORDER_TYPE_SELL) continue;
double profit = OrderStatic::Profit();
#endif
if (profit > 0.0) {
losses = 0;
wins++;
} else {
wins = 0;
losses++;
}
twins = fmax(wins, twins);
tlosses = fmax(losses, tlosses);
}
lotsize = twins > 1 ? lotsize + (lotsize / 100 * win_factor * twins) : lotsize;
lotsize = tlosses > 1 ? lotsize + (lotsize / 100 * loss_factor * tlosses) : lotsize;
return NormalizeLots(lotsize);
}
/**
* Calculate size of the lot based on the free margin or balance.
*
* @param
* _risk_margin (double) Risk margin in %.
* ...
*
* @return
* Returns calculated lot size (volume).
*/
float CalcLotSize(float _risk_margin = 1, // Risk margin in %.
float _risk_ratio = 1.0, // Risk ratio factor.
unsigned int _orders_avg = 10, // Number of orders to use for the calculation.
unsigned int _method = 0 // Method of calculation (0-3).
) {
float _avail_amount = _method % 2 == 0 ? account.GetMarginAvail() : account.GetTotalBalance();
float _lot_size_min = (float)GetSource() PTR_DEREF GetSymbolProps().GetVolumeMin();
float _lot_size = _lot_size_min;
float _risk_value = (float)account.GetLeverage();
if (_method == 0 || _method == 1) {
float _margin_req = GetMarginRequired();
if (_margin_req > 0) {
_lot_size = _avail_amount / _margin_req * _risk_ratio;
_lot_size /= _risk_value * _risk_ratio * _orders_avg;
}
} else {
float _risk_amount = _avail_amount / 100 * _risk_margin;
float _money_value = Convert::MoneyToValue(_risk_amount, _lot_size_min, GetSource() PTR_DEREF GetSymbol());
float _tick_value = (float)GetSource() PTR_DEREF GetSymbolProps().GetTickSize();
// @todo: Improves calculation logic.
_lot_size = _money_value * _tick_value * _risk_ratio / _risk_value / 100;
}
_lot_size = (float)fmin(_lot_size, GetSource() PTR_DEREF GetSymbolProps().GetVolumeMax());
return (float)NormalizeLots(_lot_size);
}
/* Orders methods */
/**
* Open an order.
*/
bool OrderAdd(Order *_order) {
bool _result = false;
unsigned int _last_error = _order PTR_DEREF Get<unsigned int>(ORDER_PROP_LAST_ERROR);
logger.Link(_order PTR_DEREF GetLogger());
Ref<Order> _ref_order = _order;
switch (_last_error) {
case 69539:
logger.Error("Error while opening an order!", __FUNCTION_LINE__,
StringFormat("Code: %d, Msg: %s", _last_error, C_STR(Terminal::GetErrorText(_last_error))));
tstats.Add(TRADE_STAT_ORDERS_ERRORS);
// Pass-through.
case ERR_NO_ERROR: // 0
orders_active.Set(_order PTR_DEREF Get<unsigned long>(ORDER_PROP_TICKET), _ref_order);
order_last = _order;
tstates.AddState(TRADE_STATE_ORDERS_ACTIVE);
tstats.Add(TRADE_STAT_ORDERS_OPENED);
// Trigger: OnOrder();
_result = true;
break;
case TRADE_RETCODE_INVALID: // 10013
logger.Error("Cannot process order!", __FUNCTION_LINE__, StringFormat("Code: %d", _last_error));
_result = false;
break;
case TRADE_RETCODE_NO_MONEY: // 10019
logger.Error("Not enough money to complete the request!", __FUNCTION_LINE__,
StringFormat("Code: %d", _last_error));
tstates.AddState(TRADE_STATE_MONEY_NOT_ENOUGH);
_result = false;
break;
default:
logger.Error("Cannot add order!", __FUNCTION_LINE__,
StringFormat("Code: %d, Msg: %s", _last_error, C_STR(Terminal::GetErrorText(_last_error))));
tstats.Add(TRADE_STAT_ORDERS_ERRORS);
_result = false;
break;
}
UpdateStates(_result);
return _result;
}
/**
* Moves active order to history.
*/
bool OrderMoveToHistory(Order *_order) {
_order PTR_DEREF Refresh(true);
orders_active.Unset(_order PTR_DEREF Get<unsigned long>(ORDER_PROP_TICKET));
Ref<Order> _ref_order = _order;
bool result = orders_history.Set(_order PTR_DEREF Get<unsigned long>(ORDER_PROP_TICKET), _ref_order);
/* @todo
if (strategy != NULL) {
strategy.OnOrderClose(_order);
}
*/
// Update stats.
tstats.Add(TRADE_STAT_ORDERS_CLOSED);
// Update states.
tstates.SetState(TRADE_STATE_ORDERS_ACTIVE, orders_active.Size() > 0);
tstates.RemoveState(TRADE_STATE_ORDERS_MAX_HARD);
tstates.RemoveState(TRADE_STATE_ORDERS_MAX_SOFT);
return result;
}
bool OrderMoveToHistory(unsigned long _ticket) {
Ref<Order> _order = orders_active.GetByKey(_ticket);
return OrderMoveToHistory(_order.Ptr());
}
/**
* Refresh active orders.
*/
bool RefreshActiveOrders(bool _force = false, bool _first_close = false) {
bool _result = true;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
Ref<Order> _order = iter.Value();
if (_order.IsSet() && _order REF_DEREF IsOpen(true)) {
_order REF_DEREF Refresh(_force);
} else if (_order.IsSet()) {
_result &= OrderMoveToHistory(_order.Ptr());
if (_first_close) {
break;
}
}
}
return _result;
}
/**
* Refresh active orders by given property.
*/
template <typename E>
bool RefreshActiveOrdersByProp(E _prop, bool _force = false) {
bool _result = true;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
Ref<Order> _order = iter.Value();
if (_order.IsSet() && _order REF_DEREF IsOpen(true)) {
if (_force || _order REF_DEREF ShouldRefresh()) {
_order REF_DEREF Refresh(_prop);
}
} else if (_order.IsSet()) {
_result &= OrderMoveToHistory(_order.Ptr());
}
}
return _result;
}
/**
* Sends a trade request.
*/
bool RequestSend(const MqlTradeRequest &_request, OrderParams &_oparams) {
bool _result = false;
switch (_request.action) {
case TRADE_ACTION_CLOSE_BY:
break;
case TRADE_ACTION_DEAL:
if (!IsTradeRecommended()) {
// logger.Warning("Trade not recommended!", __FUNCTION_LINE__, (string)tstates.GetStates());
return _result;
} else if (account.GetAccountFreeMarginCheck(_request.type, _request.volume) == 0) {
logger.Error("No free margin to open a new trade!", __FUNCTION_LINE__);
}
break;
case TRADE_ACTION_MODIFY:
break;
case TRADE_ACTION_PENDING:
break;
case TRADE_ACTION_REMOVE:
break;
case TRADE_ACTION_SLTP:
break;
}
Order *_order = new Order(_request, _oparams);
_result = OrderAdd(_order);
if (_result) {
OnOrderOpen(PTR_TO_REF(_order));
}
return _result;
}
bool RequestSend(const MqlTradeRequest &_request) {
OrderParams _oparams;
return RequestSend(_request, _oparams);
}
/**
* Loads an existing order.
*/
bool OrderLoad(Order *_order) {
bool _result = false;
Ref<Order> _order_ref = _order;
if (_order PTR_DEREF IsOpen()) {
// @todo: _order.IsPending()?
_result &= orders_active.Set(_order PTR_DEREF Get<long>(ORDER_PROP_TICKET), _order_ref);
} else {
_result &= orders_history.Set(_order PTR_DEREF Get<long>(ORDER_PROP_TICKET), _order_ref);
}
return _result && GetLastError() == ERR_NO_ERROR;
}
/**
* Loads active orders by magic number.
*/
bool OrdersLoadByMagic(unsigned long _magic_no) {
ResetLastError();
int _total_active = TradeStatic::TotalActive();
for (int pos = 0; pos < _total_active; pos++) {
if (OrderStatic::SelectByPosition(pos)) {
if (OrderStatic::MagicNumber() == _magic_no) {
unsigned long _ticket = OrderStatic::Ticket();
Ref<Order> _order = new Order(_ticket);
orders_active.Set(_ticket, _order);
}
}
}
return GetLastError() == ERR_NO_ERROR;
}
/**
* Returns the number of market and pending orders.
*
* @see:
* - https://www.mql5.com/en/docs/trading/orderstotal
* - https://www.mql5.com/en/docs/trading/positionstotal
*/
static int OrdersTotal() {
#ifdef __MQL4__
return ::OrdersTotal();
#else
return ::OrdersTotal() + ::PositionsTotal();
#endif
}
/* Orders close methods */
/**
* Close all orders.
*
* Note: It will only affect trades managed by this class instance.
*
* @return
* Returns number of successfully closed trades.
* On error, returns -1.
*/
int OrdersCloseAll(ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_ALL, string _comment = "") {
int _closed = 0;
Ref<Order> _order;
_comment = _comment != "" ? _comment : __FUNCTION__;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order REF_DEREF IsOpen(true)) {
if (_order REF_DEREF OrderClose(_reason, _comment)) {
_closed++;
OrderMoveToHistory(_order.Ptr());
order_last = _order;
} else {
logger.AddLastError(__FUNCTION_LINE__, _order REF_DEREF Get<unsigned long>(ORDER_PROP_LAST_ERROR));
return -1;
}
} else {
OrderMoveToHistory(_order.Ptr());
}
}
return _closed;
}
/**
* Close orders by order type.
*
* @return
* Returns number of successfully closed trades.
* On error, returns -1.
*/
int OrdersCloseViaCmd(ENUM_ORDER_TYPE _cmd, ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_UNKNOWN,
string _comment = "") {
int _closed = 0;
Ref<Order> _order;
_comment = _comment != "" ? _comment : __FUNCTION__;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order REF_DEREF IsOpen(true)) {
_order REF_DEREF Refresh();
if (_order REF_DEREF GetRequest().type == _cmd) {
if (_order REF_DEREF OrderClose(_reason, _comment)) {
_closed++;
OrderMoveToHistory(_order.Ptr());
order_last = _order;
} else {
logger.Error("Error while closing order!", __FUNCTION_LINE__,
StringFormat("Code: %d", _order REF_DEREF Get<unsigned long>(ORDER_PROP_LAST_ERROR)));
return -1;
}
order_last = _order;
}
} else {
OrderMoveToHistory(_order.Ptr());
}
}
return _closed;
}
/**
* Close orders based on the property value and math condition.
*
* Note: It will only affect trades managed by this class instance.
*
* @return
* Returns number of successfully closed trades.
* On error, returns -1.
*/
template <typename E, typename T>
int OrdersCloseViaProp(E _prop, T _value, ENUM_MATH_CONDITION _op,
ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_UNKNOWN, string _comment = "") {
int _closed = 0;
Ref<Order> _order;
_comment = _comment != "" ? _comment : __FUNCTION__;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order REF_DEREF IsOpen(true)) {
_order REF_DEREF Refresh((E)_prop);
if (Math::Compare(_order REF_DEREF Get<T>((E)_prop), _value, _op)) {
if (_order REF_DEREF OrderClose(_reason, _comment)) {
_closed++;
OrderMoveToHistory(_order.Ptr());
order_last = _order;
} else {
logger.AddLastError(__FUNCTION_LINE__, _order REF_DEREF Get<unsigned long>(ORDER_PROP_LAST_ERROR));
return -1;
}
}
} else {
OrderMoveToHistory(_order.Ptr());
}
}
return _closed;
}
/**
* Close orders based on the two property values of the same type and math condition.
*
* Note: It will only affect trades managed by this class instance.
*
* @return
* Returns number of successfully closed trades.
* On error, returns -1.
*/
template <typename E, typename T>
int OrdersCloseViaProp2(E _prop1, T _value1, E _prop2, T _value2, ENUM_MATH_CONDITION _op,
ENUM_ORDER_REASON_CLOSE _reason = ORDER_REASON_CLOSED_UNKNOWN, string _comment = "") {
int _closed = 0;
Ref<Order> _order;
_comment = _comment != "" ? _comment : __FUNCTION__;
for (DictStructIterator<long, Ref<Order>> iter = orders_active.Begin(); iter.IsValid(); ++iter) {
_order = iter.Value();
if (_order REF_DEREF IsOpen(true)) {
_order REF_DEREF Refresh();
if (Math::Compare(_order REF_DEREF Get<T>((E)_prop1), _value1, _op) &&
Math::Compare(_order REF_DEREF Get<T>((E)_prop2), _value2, _op)) {
if (!_order REF_DEREF OrderClose(_reason, _comment)) {
#ifndef __MQL4__
// @fixme: GH-571.
logger.Info(__FUNCTION_LINE__, _order REF_DEREF ToString());
#endif
// @fixme: GH-570.
// logger.AddLastError(__FUNCTION_LINE__, _order REF_DEREF Get<unsigned int>(ORDER_PROP_LAST_ERROR));
logger.Warning("Issue with closing the order!", __FUNCTION_LINE__);
ResetLastError();
return -1;
}
order_last = _order;
_closed++;
}
} else {
OrderMoveToHistory(_order.Ptr());
}
}