This repository has been archived by the owner on Mar 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathAIVTester.mq5
507 lines (417 loc) · 14.3 KB
/
AIVTester.mq5
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
#include <Trade/Trade.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/OrderInfo.mqh>
#include <Trade/DealInfo.mqh>
#include <Files/FilePipe.mqh>
input string InpAddress = "AIV"; // Custom connection name
input bool InpUseBestPrice = true; // Find best price without spread
input int InpTrailingStep = 0; // Step for Trailing Stop in pips
input int InpBreakeven = 0; // Level in pips which start trailing from
// *** Structures *** //
ENUM_TRADE_REQUEST_ACTIONS iActions[5] =
{
TRADE_ACTION_DEAL,
TRADE_ACTION_PENDING,
TRADE_ACTION_SLTP,
TRADE_ACTION_MODIFY,
TRADE_ACTION_REMOVE
};
ENUM_ORDER_TYPE iOrderTypes[8] =
{
ORDER_TYPE_BUY,
ORDER_TYPE_SELL,
ORDER_TYPE_BUY_LIMIT,
ORDER_TYPE_SELL_LIMIT,
ORDER_TYPE_BUY_STOP,
ORDER_TYPE_SELL_STOP,
ORDER_TYPE_BUY_STOP_LIMIT,
ORDER_TYPE_SELL_STOP_LIMIT
};
ENUM_ORDER_TYPE_FILLING iFillTypes[3] =
{
ORDER_FILLING_FOK,
ORDER_FILLING_IOC,
ORDER_FILLING_RETURN
};
ENUM_ORDER_TYPE_TIME iTimeTypes[4] =
{
ORDER_TIME_GTC,
ORDER_TIME_DAY,
ORDER_TIME_SPECIFIED,
ORDER_TIME_SPECIFIED_DAY
};
struct PriceData
{
double StopLevel;
double Open;
double High;
double Low;
double Close;
double Ask;
double Bid;
double Spread;
double Capacity;
datetime Time;
};
struct OrderData
{
double SL;
double TP;
double Price;
double Volume;
double StopLevel;
ulong Magic;
ulong Ticket;
ulong Deviation;
ulong Expiration;
ulong OrderStatus;
ulong Type;
ulong TypeTime;
ulong Action;
ulong TypeFilling;
char Currency[50];
char Comments[250];
};
struct OperationData
{
ulong RequestId;
ulong ReturnCode;
ulong Deal;
ulong Order;
ulong DealStatus;
double Volume;
double Price;
double Bid;
double Ask;
char Message[250];
};
struct CountData
{
long OrdersCount;
long PositionsCount;
};
struct PositionData
{
double Volume;
double Opening;
double SL;
double TP;
double Price;
double Profit;
ulong Id;
datetime Time;
char Type[50];
char Currency[50];
};
// *** Classes *** //
class CClient : public CObject
{
public:
int Magic;
string Address;
CFilePipe iPipe;
CClient(string address)
{
Address = address;
Magic = int(TimeLocal());
};
void Open()
{
while(IsStopped() == false)
{
if (iPipe.Open(Address, FILE_READ | FILE_WRITE | FILE_BIN) != INVALID_HANDLE) break;
}
};
void Close()
{
iPipe.Close();
};
void SetOperation(OperationData &operation)
{
iPipe.WriteStruct(operation);
};
void SetPrice(PriceData &price)
{
iPipe.WriteStruct(price);
};
void SetPosition(PositionData &position)
{
iPipe.WriteStruct(position);
};
void GetOrder(OrderData &trade)
{
iPipe.ReadStruct(trade);
};
void SetCount(CountData &count)
{
iPipe.WriteStruct(count);
};
};
// *** Variables *** //
CClient * iClient;
// *** Implementation *** //
int OnInit()
{
iClient = new CClient("\\\\.\\pipe\\" + InpAddress);
iClient.Open();
if (MQL5InfoInteger(MQL5_TESTER) == 0)
{
EventSetTimer(1);
}
return(0);
}
void OnDeinit(const int reason)
{
EventKillTimer();
iClient.Close();
delete(iClient);
}
void OnTick()
{
Communication();
}
void OnTimer()
{
Communication();
}
void Communication()
{
CSymbolInfo symbolClass;
// Price
symbolClass.Name(_Symbol);
symbolClass.RefreshRates();
PriceData price = {0};
double close[], open[], high[], low[];
CopyClose(_Symbol, _Period, 0, 1, close);
CopyOpen(_Symbol, _Period, 0, 1, open);
CopyHigh(_Symbol, _Period, 0, 1, high);
CopyLow(_Symbol, _Period, 0, 1, low);
PositionTrailing();
price.StopLevel = symbolClass.StopsLevel();
price.Spread = symbolClass.Spread();
price.Time = symbolClass.Time();
price.Ask = symbolClass.Ask();
price.Bid = symbolClass.Bid();
price.Capacity = _Point;
price.Close = close[0];
price.Open = open[0];
price.High = high[0];
price.Low = low[0];
iClient.SetPrice(price);
// Order
OrderData order;
iClient.GetOrder(order);
MqlTradeResult result = {0};
MqlTradeRequest query = {0};
OperationData operation = {0};
if (order.OrderStatus > 0)
{
query.magic = iClient.Magic;
query.volume = NormalizeDouble(order.Volume, _Digits);
query.tp = NormalizeDouble(order.TP, _Digits);
query.sl = NormalizeDouble(order.SL, _Digits);
query.order = order.Ticket;
query.deviation = order.Deviation;
query.type = iOrderTypes[int(order.Type)];
query.action = iActions[int(order.Action)];
query.type_time = iTimeTypes[int(order.TypeTime)];
query.type_filling = iFillTypes[int(order.TypeFilling)];
query.symbol = Trim(CharArrayToString(order.Currency, 0, sizeof(order.Currency)));
query.comment = CharArrayToString(order.Comments, 0, sizeof(order.Comments));
if (StringLen(query.symbol) < 1)
{
query.symbol = _Symbol;
}
// Find best price
bool success = FindBestPrice(query, result, symbolClass);
if (success == false)
{
if (order.Price)
{
query.price = NormalizeDouble(order.Price, _Digits);
}
success = OrderSend(query, result);
}
operation.RequestId = result.request_id;
operation.ReturnCode = result.retcode;
operation.Deal = result.deal;
operation.Order = result.order;
operation.Volume = result.volume;
operation.Price = result.price;
operation.Bid = result.bid;
operation.Ask = result.ask;
operation.DealStatus = success ? 1 : 0;
StringToCharArray(GetErrorDescription(result.retcode), operation.Message, 0, sizeof(operation.Message));
}
iClient.SetOperation(operation);
// Orders and positions count
CountData countData = {0};
HistorySelect(0, TimeCurrent());
countData.OrdersCount = OrdersTotal();
countData.PositionsCount = PositionsTotal();
iClient.SetCount(countData);
// List orders
HistorySelect(0, TimeCurrent());
for (int i = 0; i < countData.OrdersCount; i++)
{
string orderType;
COrderInfo currentOrder;
PositionData positionData = {0};
currentOrder.SelectByIndex(i);
positionData.Profit = 0;
positionData.Time = currentOrder.TimeSetup();
positionData.Opening = currentOrder.PriceOpen();
positionData.Price = currentOrder.PriceCurrent();
positionData.Volume = currentOrder.VolumeCurrent();
positionData.SL = currentOrder.StopLoss();
positionData.TP = currentOrder.TakeProfit();
positionData.Id = currentOrder.Ticket();
currentOrder.FormatType(orderType, currentOrder.OrderType());
StringToCharArray(orderType, positionData.Type, 0, sizeof(positionData.Type));
StringToCharArray(currentOrder.Symbol(), positionData.Currency, 0, sizeof(positionData.Currency));
iClient.SetPosition(positionData);
}
// List positions
HistorySelect(0, TimeCurrent());
for (int i = 0; i < countData.PositionsCount; i++)
{
string positionType;
CPositionInfo currentPosition;
PositionData positionData = {0};
currentPosition.SelectByIndex(i);
positionData.Profit = currentPosition.Profit();
positionData.Time = currentPosition.Time();
positionData.Opening = currentPosition.PriceOpen();
positionData.Price = currentPosition.PriceCurrent();
positionData.Volume = currentPosition.Volume();
positionData.SL = currentPosition.StopLoss();
positionData.TP = currentPosition.TakeProfit();
positionData.Id = currentPosition.Identifier();
currentPosition.FormatType(positionType, currentPosition.PositionType());
StringToCharArray(positionType, positionData.Type, 0, sizeof(positionData.Type));
StringToCharArray(currentPosition.Symbol(), positionData.Currency, 0, sizeof(positionData.Currency));
iClient.SetPosition(positionData);
}
}
bool FindBestPrice(MqlTradeRequest &query, MqlTradeResult &result, CSymbolInfo &symbolClass)
{
bool success = false;
if (query.action == TRADE_ACTION_DEAL)
{
if (InpUseBestPrice)
{
if (query.type == ORDER_TYPE_BUY)
{
double price = symbolClass.Bid();
while (success == false && price <= symbolClass.Ask())
{
query.price = NormalizeDouble(price, _Digits);
success = OrderSend(query, result);
price += _Point;
}
}
if (query.type == ORDER_TYPE_SELL)
{
double price = symbolClass.Ask();
while (success == false && price >= symbolClass.Bid())
{
query.price = NormalizeDouble(price, _Digits);
success = OrderSend(query, result);
price -= _Point;
}
}
}
else
{
query.price = query.type == ORDER_TYPE_BUY ? NormalizeDouble(symbolClass.Ask(), _Digits) : NormalizeDouble(symbolClass.Bid(), _Digits);
}
}
return success;
}
bool PositionTrailing()
{
CTrade sTrade;
CSymbolInfo sSym;
COrderInfo sOrder;
CPositionInfo sPos;
sSym.Name(_Symbol);
sSym.RefreshRates();
double mAsk = sSym.Ask();
double mBid = sSym.Bid();
double mSpread = sSym.Spread() * _Point;
double mStopLevel = sSym.StopsLevel() * _Point;
for (int i = 0; i < PositionsTotal() && InpTrailingStep; i++)
{
if (_Symbol == PositionGetSymbol(i))
{
if (sPos.PositionType() == POSITION_TYPE_BUY)
{
double sl = MathMax(sPos.PriceOpen() + InpBreakeven * _Point, sPos.StopLoss()) + InpTrailingStep * _Point;
if (mBid - mStopLevel > sl)
{
sTrade.PositionModify(_Symbol, sl, sPos.TakeProfit());
}
}
if (sPos.PositionType() == POSITION_TYPE_SELL)
{
double sl = MathMin(sPos.PriceOpen() - InpBreakeven * _Point, sPos.StopLoss()) - InpTrailingStep * _Point;
if (mAsk + mStopLevel < sl)
{
sTrade.PositionModify(_Symbol, sl, sPos.TakeProfit());
}
}
}
}
return true;
}
string GetErrorDescription(int code)
{
string str = "Unknown error";
switch (code)
{
case TRADE_RETCODE_REQUOTE: str = "Requote"; break;
case TRADE_RETCODE_REJECT: str = "Request rejected"; break;
case TRADE_RETCODE_CANCEL: str = "Request canceled by trader"; break;
case TRADE_RETCODE_PLACED: str = "Order placed"; break;
case TRADE_RETCODE_DONE: str = "Request completed"; break;
case TRADE_RETCODE_DONE_PARTIAL: str = "Only part of the request was completed"; break;
case TRADE_RETCODE_ERROR: str = "Request processing error"; break;
case TRADE_RETCODE_TIMEOUT: str = "Request canceled by timeout"; break;
case TRADE_RETCODE_INVALID: str = "Invalid request"; break;
case TRADE_RETCODE_INVALID_VOLUME: str = "Invalid volume in the request"; break;
case TRADE_RETCODE_INVALID_PRICE: str = "Invalid price in the request"; break;
case TRADE_RETCODE_INVALID_STOPS: str = "Invalid stops in the request"; break;
case TRADE_RETCODE_TRADE_DISABLED: str = "Trade is disabled"; break;
case TRADE_RETCODE_MARKET_CLOSED: str = "Market is closed"; break;
case TRADE_RETCODE_NO_MONEY: str = "There is not enough money to complete the request"; break;
case TRADE_RETCODE_PRICE_CHANGED: str = "Prices changed"; break;
case TRADE_RETCODE_PRICE_OFF: str = "There are no quotes to process the request"; break;
case TRADE_RETCODE_INVALID_EXPIRATION: str = "Invalid order expiration date in the request"; break;
case TRADE_RETCODE_ORDER_CHANGED: str = "Order state changed"; break;
case TRADE_RETCODE_TOO_MANY_REQUESTS: str = "Too frequent requests"; break;
case TRADE_RETCODE_NO_CHANGES: str = "No changes in request"; break;
case TRADE_RETCODE_SERVER_DISABLES_AT: str = "Autotrading disabled by server"; break;
case TRADE_RETCODE_CLIENT_DISABLES_AT: str = "Autotrading disabled by client terminal"; break;
case TRADE_RETCODE_LOCKED: str = "Request locked for processing"; break;
case TRADE_RETCODE_FROZEN: str = "Order or position frozen"; break;
case TRADE_RETCODE_INVALID_FILL: str = "Invalid order filling type"; break;
case TRADE_RETCODE_CONNECTION: str = "No connection with the trade server"; break;
case TRADE_RETCODE_ONLY_REAL: str = "Operation is allowed only for live accounts"; break;
case TRADE_RETCODE_LIMIT_ORDERS: str = "The number of pending orders has reached the limit"; break;
case TRADE_RETCODE_LIMIT_VOLUME: str = "The volume of orders and positions for the symbol has reached the limit"; break;
case TRADE_RETCODE_INVALID_ORDER: str = "Incorrect or prohibited order type"; break;
case TRADE_RETCODE_POSITION_CLOSED: str = "Position with the specified POSITION_IDENTIFIER has already been closed"; break;
}
return (str);
}
void CustomLog(const string message)
{
Print(message);
}
string Trim(string content)
{
StringTrimLeft(content);
StringTrimRight(content);
return(content);
}