-
Notifications
You must be signed in to change notification settings - Fork 277
/
MtApi5Client.cs
executable file
·3614 lines (3160 loc) · 191 KB
/
MtApi5Client.cs
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
// ReSharper disable InconsistentNaming
using System;
using System.Collections.Generic;
using System.Linq;
using MTApiService;
using System.Collections;
using System.ServiceModel;
using MtApi5.Requests;
using Newtonsoft.Json;
using System.Threading.Tasks;
using MtApi5.Events;
namespace MtApi5
{
public class MtApi5Client
{
#region MT Constants
public const int SYMBOL_EXPIRATION_GTC = 1;
public const int SYMBOL_EXPIRATION_DAY = 2;
public const int SYMBOL_EXPIRATION_SPECIFIED = 4;
public const int SYMBOL_EXPIRATION_SPECIFIED_DAY = 8;
public const int SYMBOL_FILLING_ALL_OR_NONE = 1;
public const int SYMBOL_CANCEL_REMAIND = 1;
public const int SYMBOL_RETURN_REMAIND = 1;
#endregion
private const char ParamSeparator = ';';
private const string LogProfileName = "MtApi5Client";
public delegate void QuoteHandler(object sender, string symbol, double bid, double ask);
#region Private Fields
private static readonly MtLog Log = LogConfigurator.GetLogger(typeof(MtApi5Client));
private MtClient _client;
private readonly object _locker = new object();
private volatile bool _isBacktestingMode;
private Mt5ConnectionState _connectionState = Mt5ConnectionState.Disconnected;
private int _executorHandle;
private readonly Dictionary<Mt5EventTypes, Action<int, string>> _mtEventHandlers =
new Dictionary<Mt5EventTypes, Action<int, string>>();
#endregion
#region Public Methods
public MtApi5Client()
{
#if (DEBUG)
const LogLevel logLevel = LogLevel.Debug;
#else
const LogLevel logLevel = LogLevel.Info;
#endif
LogConfigurator.Setup(LogProfileName, logLevel);
_mtEventHandlers[Mt5EventTypes.OnBookEvent] = ReceivedOnBookEvent;
_mtEventHandlers[Mt5EventTypes.OnTick] = ReceivedOnTickEvent;
_mtEventHandlers[Mt5EventTypes.OnTradeTransaction] = ReceivedOnTradeTransactionEvent;
_mtEventHandlers[Mt5EventTypes.OnLastTimeBar] = ReceivedOnLastTimeBarEvent;
_mtEventHandlers[Mt5EventTypes.OnLockTicks] = ReceivedOnLockTicksEvent;
}
///<summary>
///Connect with MetaTrader API. Async method.
///</summary>
///<param name="host">Address of MetaTrader host (ex. 192.168.1.2)</param>
///<param name="port">Port of host connection (default 8222) </param>
public void BeginConnect(string host, int port)
{
Log.Info($"BeginConnect: host = {host}, port = {port}");
Task.Factory.StartNew(() => Connect(host, port));
}
///<summary>
///Connect with MetaTrader API. Async method.
///</summary>
///<param name="port">Port of host connection (default 8222) </param>
public void BeginConnect(int port)
{
Log.Info($"BeginConnect: port = {port}");
Task.Factory.StartNew(() => Connect(port));
}
///<summary>
///Disconnect from MetaTrader API. Async method.
///</summary>
public void BeginDisconnect()
{
Log.Info("BeginDisconnect called.");
Task.Factory.StartNew(() => Disconnect(false));
}
///<summary>
///Load quotes connected into MetaTrader API.
///</summary>
public IEnumerable<Mt5Quote> GetQuotes()
{
var client = Client;
var quotes = client?.GetQuotes();
return quotes?.Select(q => new Mt5Quote(q));
}
///<summary>
///Checks if the Expert Advisor runs in the testing mode..
///</summary>
public bool IsTesting()
{
return SendCommand<bool>(Mt5CommandType.IsTesting, null);
}
#region Trading functions
///<summary>
///Sends trade requests to a server
///</summary>
///<param name="request">Reference to a object of MqlTradeRequest type describing the trade activity of the client.</param>
///<param name="result">Reference to a object of MqlTradeResult type describing the result of trade operation in case of a successful completion (if true is returned).</param>
/// <returns>
/// 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.
/// For a more detailed description of the function execution result, analyze the fields of result structure.
/// </returns>
public bool OrderSend(MqlTradeRequest request, out MqlTradeResult result)
{
Log.Debug($"OrderSend: request = {request}");
if (request == null)
{
Log.Warn("OrderSend: request is not defined!");
result = null;
return false;
}
var response = SendRequest<OrderSendResult>(new OrderSendRequest
{
TradeRequest = request
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
///<summary>
///Function is used for conducting asynchronous trade operations without waiting for the trade server's response to a sent request.
///</summary>
///<param name="request">Reference to a object of MqlTradeRequest type describing the trade activity of the client.</param>
///<param name="result">Reference to a object of MqlTradeResult type describing the result of trade operation in case of a successful completion (if true is returned).</param>
/// <returns>
/// Returns true if the request is sent to a trade server. In case the request is not sent, it returns false.
/// In case the request is sent, in the result variable the response code contains TRADE_RETCODE_PLACED value (code 10008) – "order placed".
/// Successful execution means only the fact of sending, but does not give any guarantee that the request has reached the trade server and has been accepted for processing.
/// When processing the received request, a trade server sends a reply to a client terminal notifying of change in the current state of positions,
/// orders and deals, which leads to the generation of the Trade event.
/// </returns>
public bool OrderSendAsync(MqlTradeRequest request, out MqlTradeResult result)
{
Log.Debug($"OrderSend: request = {request}");
if (request == null)
{
Log.Warn("OrderSend: request is not defined!");
result = null;
return false;
}
var response = SendRequest<OrderSendResult>(new OrderSendAsyncRequest
{
TradeRequest = request
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
///<summary>
///The function calculates the margin required for the specified order type, on the current account
///, in the current market environment not taking into account current pending orders and open positions
///. It allows the evaluation of margin for the trade operation planned. The value is returned in the account currency.
///</summary>
///<param name="action">The order type, can be one of the values of the ENUM_ORDER_TYPE enumeration.</param>
///<param name="symbol">Symbol name.</param>
///<param name="volume">Volume of the trade operation.</param>
///<param name="price">Open price.</param>
///<param name="margin">The variable, to which the value of the required margin will be written in case the function is successfully executed
///. The calculation is performed as if there were no pending orders and open positions on the current account
///. The margin value depends on many factors, and can differ in different market environments.</param>
/// <returns>
/// The function returns true in case of success; otherwise it returns false.
/// </returns>
public bool OrderCalcMargin(ENUM_ORDER_TYPE action, string symbol, double volume, double price, out double margin)
{
var commandParameters = new ArrayList { (int)action, symbol, volume, price };
var strResult = SendCommand<string>(Mt5CommandType.OrderCalcMargin, commandParameters);
return strResult.ParseResult(ParamSeparator, out margin);
}
///<summary>
///The function calculates the profit for the current account,
///in the current market conditions, based on the parameters passed.
///The function is used for pre-evaluation of the result of a trade operation.
///The value is returned in the account currency.
///</summary>
///<param name="action">Type of the order, can be one of the two values of the ENUM_ORDER_TYPE enumeration: ORDER_TYPE_BUY or ORDER_TYPE_SELL.</param>
///<param name="symbol">Symbol name.</param>
///<param name="volume">Volume of the trade operation.</param>
///<param name="priceOpen">Open price.</param>
///<param name="priceClose">Close price.</param>
///<param name="profit">The variable, to which the calculated value of the profit will be written in case the function is successfully executed.
///The estimated profit value depends on many factors, and can differ in different market environments.</param>
/// <returns>
/// The function returns true in case of success; otherwise it returns false. If an invalid order type is specified, the function will return false.
/// </returns>
public bool OrderCalcProfit(ENUM_ORDER_TYPE action, string symbol, double volume, double priceOpen, double priceClose, out double profit)
{
var commandParameters = new ArrayList { (int)action, symbol, volume, priceOpen, priceClose };
var strResult = SendCommand<string>(Mt5CommandType.OrderCalcProfit, commandParameters);
return strResult.ParseResult(ParamSeparator, out profit);
}
///<summary>
///The OrderCheck() function checks if there are enough money to execute a required trade operation.
///The check results are placed to the fields of the MqlTradeCheckResult structure.
///</summary>
///<param name="request">Reference to a object of MqlTradeRequest type describing the trade activity of the client.</param>
///<param name="result"> Reference to the object of the MqlTradeCheckResult type, to which the check result will be placed.</param>
/// <returns>
/// If funds are not enough for the operation, or parameters are filled out incorrectly, the function returns false.
/// In case of a successful basic check of structures (check of pointers), it returns true.
/// However, this is not an indication that the requested trade operation is sure to be successfully executed.
/// For a more detailed description of the function execution result, analyze the fields of the result structure.
/// </returns>
public bool OrderCheck(MqlTradeRequest request, out MqlTradeCheckResult result)
{
Log.Debug($"OrderCheck: request = {request}");
if (request == null)
{
Log.Warn("OrderCheck: request is not defined!");
result = null;
return false;
}
var response = SendRequest<OrderCheckResult>(new OrderCheckRequest
{
TradeRequest = request
});
result = response?.TradeCheckResult;
return response != null && response.RetVal;
}
///<summary>
///Returns the number of open positions.
///</summary>
public int PositionsTotal()
{
return SendCommand<int>(Mt5CommandType.PositionsTotal, null);
}
///<summary>
///Returns the symbol corresponding to the open position and automatically selects the position for further working with it using functions PositionGetDouble, PositionGetInteger, PositionGetString.
///</summary>
///<param name="index">Number of the position in the list of open positions.</param>
public string PositionGetSymbol(int index)
{
var commandParameters = new ArrayList { index };
return SendCommand<string>(Mt5CommandType.PositionGetSymbol, commandParameters);
}
///<summary>
///Chooses an open position for further working with it. Returns true if the function is successfully completed. Returns false in case of failure.
///</summary>
///<param name="symbol">Name of the financial security.</param>
public bool PositionSelect(string symbol)
{
var commandParameters = new ArrayList { symbol };
return SendCommand<bool>(Mt5CommandType.PositionSelect, commandParameters);
}
///<summary>
///Selects an open position to work with based on the ticket number specified in the position. If successful, returns true. Returns false if the function failed.
///</summary>
///<param name="ticket">Position ticket.</param>
public bool PositionSelectByTicket(ulong ticket)
{
var commandParameters = new ArrayList { ticket };
return SendCommand<bool>(Mt5CommandType.PositionSelectByTicket, commandParameters);
}
///<summary>
///The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect.
///</summary>
///<param name="propertyId">Identifier of a position property.</param>
public double PositionGetDouble(ENUM_POSITION_PROPERTY_DOUBLE propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<double>(Mt5CommandType.PositionGetDouble, commandParameters);
}
///<summary>
///The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect.
///</summary>
///<param name="propertyId">Identifier of a position property.</param>
public long PositionGetInteger(ENUM_POSITION_PROPERTY_INTEGER propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<long>(Mt5CommandType.PositionGetInteger, commandParameters);
}
///<summary>
///The function returns the requested property of an open position, pre-selected using PositionGetSymbol or PositionSelect.
///</summary>
///<param name="propertyId">Identifier of a position property.</param>
public string PositionGetString(ENUM_POSITION_PROPERTY_STRING propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<string>(Mt5CommandType.PositionGetString, commandParameters);
}
///<summary>
///The function returns the ticket of a position with the specified index in the list of open positions and automatically selects the position to work with using functions PositionGetDouble, PositionGetInteger, PositionGetString.
///</summary>
///<param name="index">Identifier of a position property.</param>
public ulong PositionGetTicket(int index)
{
var commandParameters = new ArrayList { index };
return SendCommand<ulong>(Mt5CommandType.PositionGetTicket, commandParameters);
}
///<summary>
///Returns the number of current orders.
///</summary>
public int OrdersTotal()
{
return SendCommand<int>(Mt5CommandType.OrdersTotal, null);
}
///<summary>
///Returns the number of current orders.
///</summary>
///<param name="index">Number of an order in the list of current orders.</param>
public ulong OrderGetTicket(int index)
{
var commandParameters = new ArrayList { index };
return SendCommand<ulong>(Mt5CommandType.OrderGetTicket, commandParameters);
}
///<summary>
///Selects an order to work with. Returns true if the function has been successfully completed.
///</summary>
///<param name="ticket">Order ticket.</param>
public bool OrderSelect(ulong ticket)
{
var commandParameters = new ArrayList { ticket };
return SendCommand<bool>(Mt5CommandType.OrderSelect, commandParameters);
}
///<summary>
///Returns the requested property of an order, pre-selected using OrderGetTicket or OrderSelect.
///</summary>
///<param name="propertyId"> Identifier of the order property.</param>
public double OrderGetDouble(ENUM_ORDER_PROPERTY_DOUBLE propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<double>(Mt5CommandType.OrderGetDouble, commandParameters);
}
///<summary>
///Returns the requested property of an order, pre-selected using OrderGetTicket or OrderSelect.
///</summary>
///<param name="propertyId"> Identifier of the order property.</param>
public long OrderGetInteger(ENUM_ORDER_PROPERTY_INTEGER propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<long>(Mt5CommandType.OrderGetInteger, commandParameters);
}
///<summary>
///Returns the requested property of an order, pre-selected using OrderGetTicket or OrderSelect.
///</summary>
///<param name="propertyId"> Identifier of the order property.</param>
public string OrderGetString(ENUM_ORDER_PROPERTY_STRING propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<string>(Mt5CommandType.OrderGetString, commandParameters);
}
///<summary>
///Retrieves the history of deals and orders for the specified period of server time.
///</summary>
///<param name="fromDate">Start date of the request.</param>
///<param name="toDate">End date of the request.</param>
public bool HistorySelect(DateTime fromDate, DateTime toDate)
{
var commandParameters = new ArrayList { Mt5TimeConverter.ConvertToMtTime(fromDate), Mt5TimeConverter.ConvertToMtTime(toDate) };
return SendCommand<bool>(Mt5CommandType.HistorySelect, commandParameters);
}
///<summary>
///Retrieves the history of deals and orders having the specified position identifier.
///</summary>
///<param name="positionId">Position identifier that is set to every executed order and every deal.</param>
public bool HistorySelectByPosition(long positionId)
{
var commandParameters = new ArrayList { positionId };
return SendCommand<bool>(Mt5CommandType.HistorySelectByPosition, commandParameters);
}
///<summary>
///Selects an order from the history for further calling it through appropriate functions.
///</summary>
///<param name="ticket">Order ticket.</param>
public bool HistoryOrderSelect(ulong ticket)
{
var commandParameters = new ArrayList { ticket };
return SendCommand<bool>(Mt5CommandType.HistoryOrderSelect, commandParameters);
}
///<summary>
///Returns the number of orders in the history.
///</summary>
public int HistoryOrdersTotal()
{
return SendCommand<int>(Mt5CommandType.HistoryOrdersTotal, null);
}
///<summary>
///Return the ticket of a corresponding order in the history.
///</summary>
///<param name="index">Number of the order in the list of orders.</param>
public ulong HistoryOrderGetTicket(int index)
{
var commandParameters = new ArrayList { index };
return SendCommand<ulong>(Mt5CommandType.HistoryOrderGetTicket, commandParameters);
}
///<summary>
///Returns the requested order property.
///</summary>
///<param name="ticketNumber">Order ticket.</param>
///<param name="propertyId">Identifier of the order property.</param>
public double HistoryOrderGetDouble(ulong ticketNumber, ENUM_ORDER_PROPERTY_DOUBLE propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<double>(Mt5CommandType.HistoryOrderGetDouble, commandParameters);
}
///<summary>
///Returns the requested property of an order.
///</summary>
///<param name="ticketNumber">Order ticket.</param>
///<param name="propertyId">Identifier of the order property.</param>
public long HistoryOrderGetInteger(ulong ticketNumber, ENUM_ORDER_PROPERTY_INTEGER propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<long>(Mt5CommandType.HistoryOrderGetInteger, commandParameters);
}
///<summary>
///Returns the requested property of an order.
///</summary>
///<param name="ticketNumber">Order ticket.</param>
///<param name="propertyId">Identifier of the order property.</param>
public string HistoryOrderGetString(ulong ticketNumber, ENUM_ORDER_PROPERTY_STRING propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<string>(Mt5CommandType.HistoryOrderGetString, commandParameters);
}
///<summary>
///Selects a deal in the history for further calling it through appropriate functions.
///</summary>
///<param name="ticket">Deal ticket.</param>
public bool HistoryDealSelect(ulong ticket)
{
var commandParameters = new ArrayList { ticket };
return SendCommand<bool>(Mt5CommandType.HistoryDealSelect, commandParameters);
}
///<summary>
///Returns the number of deal in history.
///</summary>
public int HistoryDealsTotal()
{
return SendCommand<int>(Mt5CommandType.HistoryDealsTotal, null);
}
///<summary>
///The function selects a deal for further processing and returns the deal ticket in history.
///</summary>
///<param name="index">Number of a deal in the list of deals.</param>
public ulong HistoryDealGetTicket(int index)
{
var commandParameters = new ArrayList { index };
return SendCommand<ulong>(Mt5CommandType.HistoryDealGetTicket, commandParameters);
}
///<summary>
///Returns the requested property of a deal.
///</summary>
///<param name="ticketNumber">Deal ticket.</param>
///<param name="propertyId"> Identifier of a deal property.</param>
public double HistoryDealGetDouble(ulong ticketNumber, ENUM_DEAL_PROPERTY_DOUBLE propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<double>(Mt5CommandType.HistoryDealGetDouble, commandParameters);
}
///<summary>
///Returns the requested property of a deal.
///</summary>
///<param name="ticketNumber">Deal ticket.</param>
///<param name="propertyId"> Identifier of a deal property.</param>
public long HistoryDealGetInteger(ulong ticketNumber, ENUM_DEAL_PROPERTY_INTEGER propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<long>(Mt5CommandType.HistoryDealGetInteger, commandParameters);
}
///<summary>
///Returns the requested property of a deal.
///</summary>
///<param name="ticketNumber">Deal ticket.</param>
///<param name="propertyId"> Identifier of a deal property.</param>
public string HistoryDealGetString(ulong ticketNumber, ENUM_DEAL_PROPERTY_STRING propertyId)
{
var commandParameters = new ArrayList { ticketNumber, (int)propertyId };
return SendCommand<string>(Mt5CommandType.HistoryDealGetString, commandParameters);
}
///<summary>
///Close all open positions.
///</summary>
[Obsolete("OrderCloseAll is deprecated, please use PositionCloseAll instead.")]
public bool OrderCloseAll()
{
return SendCommand<bool>(Mt5CommandType.OrderCloseAll, null);
}
///<summary>
///Close all open positions. Returns count of closed positions.
///</summary>
public int PositionCloseAll()
{
return SendCommand<int>(Mt5CommandType.PositionCloseAll, null);
}
///<summary>
///Closes a position with the specified ticket.
///</summary>
///<param name="ticket">Ticket of the closed position.</param>
///<param name="deviation">Maximal deviation from the current price (in points).</param>
public bool PositionClose(ulong ticket, ulong deviation = ulong.MaxValue)
{
var commandParameters = new ArrayList { ticket, deviation };
return SendCommand<bool>(Mt5CommandType.PositionClose, commandParameters);
}
/// <summary>
/// Modifies existing position
/// </summary>
/// <param name="ticket">>Ticket of the position</param>
/// <param name="sl">Stop loss</param>
/// <param name="tp">Take profit</param>
/// <returns></returns>
public bool PositionModify(ulong ticket, double sl, double tp)
{
var commandParameters = new ArrayList { ticket, sl,tp };
return SendCommand<bool>(Mt5CommandType.PositionModify, commandParameters);
}
///<summary>
///Closes a position with the specified ticket.
///</summary>
///<param name="ticket">Ticket of the closed position.</param>
///<param name="deviation">Maximal deviation from the current price (in points).</param>
/// <param name="result">output result</param>
public bool PositionClose(ulong ticket, ulong deviation, out MqlTradeResult result)
{
Log.Debug($"PositionClose: ticket = {ticket}, deviation = {deviation}");
var response = SendRequest<PositionCloseResult>(new PositionCloseRequest
{
Ticket = ticket,
Deviation = deviation
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
///<summary>
///Closes a position with the specified ticket.
///</summary>
///<param name="ticket">Ticket of the closed position.</param>
/// <param name="result">output result</param>
public bool PositionClose(ulong ticket, out MqlTradeResult result)
{
return PositionClose(ticket, ulong.MaxValue, out result);
}
/// <summary>
/// Opens a position with the specified parameters.
/// </summary>
/// <param name="symbol">symbol</param>
/// <param name="orderType">order type to open position </param>
/// <param name="volume">position volume</param>
/// <param name="price">execution price</param>
/// <param name="sl">Stop Loss price</param>
/// <param name="tp">Take Profit price</param>
/// <param name="comment">comment</param>
/// <returns>true - successful check of the basic structures, otherwise - false.</returns>
public bool PositionOpen(string symbol, ENUM_ORDER_TYPE orderType, double volume, double price, double sl, double tp, string comment = "")
{
var commandParameters = new ArrayList { symbol, (int) orderType, volume, price, sl, tp, comment };
return SendCommand<bool>(Mt5CommandType.PositionOpen, commandParameters);
}
/// <summary>
/// Opens a position with the specified parameters.
/// </summary>
/// <param name="symbol">symbol</param>
/// <param name="orderType">order type to open position </param>
/// <param name="volume">position volume</param>
/// <param name="price">execution price</param>
/// <param name="sl">Stop Loss price</param>
/// <param name="tp">Take Profit price</param>
/// <param name="comment">comment</param>
/// <param name="result">output result</param>
/// <returns>true - successful check of the basic structures, otherwise - false.</returns>
public bool PositionOpen(string symbol, ENUM_ORDER_TYPE orderType, double volume, double price, double sl, double tp, string comment, out MqlTradeResult result)
{
Log.Debug($"PositionOpen: symbol = {symbol}, orderType = {orderType}, volume = {volume}, price = {price}, sl = {sl}, tp = {tp}, comment = {comment}");
var response = SendRequest<OrderSendResult>(new PositionOpenRequest
{
Symbol = symbol,
OrderType = orderType,
Volume = volume,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
/// <summary>
/// Opens a position with the specified parameters.
/// </summary>
/// <param name="symbol">symbol</param>
/// <param name="orderType">order type to open position </param>
/// <param name="volume">position volume</param>
/// <param name="price">execution price</param>
/// <param name="sl">Stop Loss price</param>
/// <param name="tp">Take Profit price</param>
/// <param name="result">output result</param>
/// <returns>true - successful check of the basic structures, otherwise - false.</returns>
public bool PositionOpen(string symbol, ENUM_ORDER_TYPE orderType, double volume, double price, double sl, double tp, out MqlTradeResult result)
{
return PositionOpen(symbol, orderType, volume, price, sl, tp, "", out result);
}
/// <summary>
/// Partially closes a position on a specified symbol in case of a "hedging" accounting.
/// </summary>
/// <param name="symbol">Name of a trading instrument, on which a position is closed partially.</param>
/// <param name="volume"> Volume, by which a position should be decreased. If the value exceeds the volume of a partially closed position, it is closed in full. No position in the opposite direction is opened.</param>
/// <param name="deviation">The maximum deviation from the current price (in points).</param>
/// <returns>true if the basic check of structures is successful, otherwise false.</returns>
public bool PositionClosePartial(string symbol, double volume, ulong deviation = ulong.MaxValue)
{
var commandParameters = new ArrayList { symbol, volume, deviation };
return SendCommand<bool>(Mt5CommandType.PositionClosePartial_bySymbol, commandParameters);
}
/// <summary>
/// Partially closes a position on a specified symbol in case of a "hedging" accounting.
/// </summary>
/// <param name="ticket">Closed position ticket.</param>
/// <param name="volume"> Volume, by which a position should be decreased. If the value exceeds the volume of a partially closed position, it is closed in full. No position in the opposite direction is opened.</param>
/// <param name="deviation">The maximum deviation from the current price (in points).</param>
/// <returns>true if the basic check of structures is successful, otherwise false.</returns>
public bool PositionClosePartial(ulong ticket, double volume, ulong deviation = ulong.MaxValue)
{
var commandParameters = new ArrayList { ticket, volume, deviation };
return SendCommand<bool>(Mt5CommandType.PositionClosePartial_byTicket, commandParameters);
}
/// <summary>
/// Opens a long position with specified parameters with current market Ask price
/// </summary>
/// <param name="result">output result</param>
/// <param name="volume">Requested position volume.</param>
/// <param name="symbol">Position symbol. If it is not specified, the current symbol will be used.</param>
/// <param name="price">Execution price.</param>
/// <param name="sl">Stop Loss price.</param>
/// <param name="tp">Take Profit price.</param>
/// <param name="comment">Comment.</param>
/// <returns>true - successful check of the structures, otherwise - false.</returns>
public bool Buy(out MqlTradeResult result, double volume, string symbol = null, double price = 0.0, double sl = 0.0, double tp = 0.0, string comment = null)
{
Log.Debug($"Buy: volume = {volume}, symbol = {symbol}, sl = {sl}, tp = {tp}, comment = {comment}");
var response = SendRequest<OrderSendResult>(new BuyRequest
{
Volume = volume,
Symbol = symbol,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
/// <summary>
/// Opens a short position with specified parameters with current market Bid price
/// </summary>
/// <param name="result">output result</param>
/// <param name="volume">Requested position volume.</param>
/// <param name="symbol">Position symbol. If it is not specified, the current symbol will be used.</param>
/// <param name="price">Execution price.</param>
/// <param name="sl">Stop Loss price.</param>
/// <param name="tp">Take Profit price.</param>
/// <param name="comment">Comment.</param>
/// <returns>true - successful check of the structures, otherwise - false.</returns>
public bool Sell(out MqlTradeResult result, double volume, string symbol = null, double price = 0.0, double sl = 0.0, double tp = 0.0, string comment = null)
{
Log.Debug($"Sell: volume = {volume}, symbol = {symbol}, sl = {sl}, tp = {tp}, comment = {comment}");
var response = SendRequest<OrderSendResult>(new SellRequest
{
Volume = volume,
Symbol = symbol,
Price = price,
Sl = sl,
Tp = tp,
Comment = comment
});
result = response?.TradeResult;
return response != null && response.RetVal;
}
#endregion
#region Account Information functions
///<summary>
///Returns the value of the corresponding account property.
///</summary>
///<param name="propertyId">Identifier of the property.</param>
public double AccountInfoDouble(ENUM_ACCOUNT_INFO_DOUBLE propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<double>(Mt5CommandType.AccountInfoDouble, commandParameters);
}
///<summary>
///Returns the value of the corresponding account property.
///</summary>
///<param name="propertyId">Identifier of the property.</param>
public long AccountInfoInteger(ENUM_ACCOUNT_INFO_INTEGER propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<long>(Mt5CommandType.AccountInfoInteger, commandParameters);
}
///<summary>
///Returns the value of the corresponding account property.
///</summary>
///<param name="propertyId">Identifier of the property.</param>
public string AccountInfoString(ENUM_ACCOUNT_INFO_STRING propertyId)
{
var commandParameters = new ArrayList { (int)propertyId };
return SendCommand<string>(Mt5CommandType.AccountInfoString, commandParameters);
}
#endregion
#region Timeseries and Indicators Access
///<summary>
///Returns information about the state of historical data.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe"> Period.</param>
///<param name="propId">Identifier of the requested property, value of the ENUM_SERIES_INFO_INTEGER enumeration.</param>
public long SeriesInfoInteger(string symbolName, ENUM_TIMEFRAMES timeframe, ENUM_SERIES_INFO_INTEGER propId)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe, (int)propId };
return SendCommand<long>(Mt5CommandType.SeriesInfoInteger, commandParameters);
}
///<summary>
///Returns the number of bars count in the history for a specified symbol and period.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe"> Period.</param>
public int Bars(string symbolName, ENUM_TIMEFRAMES timeframe)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe };
return SendCommand<int>(Mt5CommandType.Bars, commandParameters);
}
///<summary>
///Returns the number of bars count in the history for a specified symbol and period.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe">Period.</param>
///<param name="startTime">Bar time corresponding to the first element.</param>
///<param name="stopTime">Bar time corresponding to the last element.</param>
public int Bars(string symbolName, ENUM_TIMEFRAMES timeframe, DateTime startTime, DateTime stopTime)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe, Mt5TimeConverter.ConvertToMtTime(startTime), Mt5TimeConverter.ConvertToMtTime(stopTime) };
return SendCommand<int>(Mt5CommandType.Bars2, commandParameters);
}
///<summary>
///Returns the number of calculated data for the specified indicator.
///</summary>
///<param name="indicatorHandle">The indicator handle, returned by the corresponding indicator function.</param>
public int BarsCalculated(int indicatorHandle)
{
var commandParameters = new ArrayList { indicatorHandle };
return SendCommand<int>(Mt5CommandType.BarsCalculated, commandParameters);
}
///<summary>
///Gets data of a specified buffer of a certain indicator in the necessary quantity.
///</summary>
///<param name="indicatorHandle">The indicator handle, returned by the corresponding indicator function.</param>
///<param name="bufferNum">The indicator buffer number.</param>
///<param name="startPos">The position of the first element to copy.</param>
///<param name="count">Data count to copy.</param>
///<param name="buffer">Array of double type.</param>
public int CopyBuffer(int indicatorHandle, int bufferNum, int startPos, int count, out double[] buffer)
{
var commandParameters = new ArrayList { indicatorHandle, bufferNum, startPos, count };
buffer = SendCommand<double[]>(Mt5CommandType.CopyBuffer, commandParameters);
return buffer?.Length ?? 0;
}
///<summary>
///Gets data of a specified buffer of a certain indicator in the necessary quantity.
///</summary>
///<param name="indicatorHandle">The indicator handle, returned by the corresponding indicator function.</param>
///<param name="bufferNum">The indicator buffer number.</param>
///<param name="startTime">Bar time, corresponding to the first element.</param>
///<param name="count">Data count to copy.</param>
///<param name="buffer">Array of double type.</param>
public int CopyBuffer(int indicatorHandle, int bufferNum, DateTime startTime, int count, out double[] buffer)
{
var commandParameters = new ArrayList { indicatorHandle, bufferNum, Mt5TimeConverter.ConvertToMtTime(startTime), count };
buffer = SendCommand<double[]>(Mt5CommandType.CopyBuffer1, commandParameters);
return buffer?.Length ?? 0;
}
///<summary>
///Gets data of a specified buffer of a certain indicator in the necessary quantity.
///</summary>
///<param name="indicatorHandle">The indicator handle, returned by the corresponding indicator function.</param>
///<param name="bufferNum">The indicator buffer number.</param>
///<param name="startTime">Bar time, corresponding to the first element.</param>
///<param name="stopTime">Bar time, corresponding to the last element.</param>
///<param name="buffer">Array of double type.</param>
public int CopyBuffer(int indicatorHandle, int bufferNum, DateTime startTime, DateTime stopTime, out double[] buffer)
{
var commandParameters = new ArrayList { indicatorHandle, bufferNum, Mt5TimeConverter.ConvertToMtTime(startTime), Mt5TimeConverter.ConvertToMtTime(stopTime) };
buffer = SendCommand<double[]>(Mt5CommandType.CopyBuffer1, commandParameters);
return buffer?.Length ?? 0;
}
///<summary>
///Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the ratesArray array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe">Period.</param>
///<param name="startPos">The start position for the first element to copy.</param>
///<param name="count">Data count to copy.</param>
///<param name="ratesArray">Array of MqlRates type.</param>
public int CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, int startPos, int count, out MqlRates[] ratesArray)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe, startPos, count };
ratesArray = null;
var retVal = SendCommand<MtMqlRates[]>(Mt5CommandType.CopyRates, commandParameters);
if (retVal != null)
{
ratesArray = new MqlRates[retVal.Length];
for(var i = 0; i < retVal.Length; i++)
{
ratesArray[i] = new MqlRates(retVal[i].time
, retVal[i].open
, retVal[i].high
, retVal[i].low
, retVal[i].close
, retVal[i].tick_volume
, retVal[i].spread
, retVal[i].real_volume);
}
}
return ratesArray?.Length ?? 0;
}
///<summary>
///Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the ratesArray array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe">Period.</param>
///<param name="startTime">The start time for the first element to copy.</param>
///<param name="count">Data count to copy.</param>
///<param name="ratesArray">Array of MqlRates type.</param>
public int CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, DateTime startTime, int count, out MqlRates[] ratesArray)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe, Mt5TimeConverter.ConvertToMtTime(startTime), count };
ratesArray = null;
var retVal = SendCommand<MtMqlRates[]>(Mt5CommandType.CopyRates1, commandParameters);
if (retVal != null)
{
ratesArray = new MqlRates[retVal.Length];
for (var i = 0; i < retVal.Length; i++)
{
ratesArray[i] = new MqlRates(retVal[i].time
, retVal[i].open
, retVal[i].high
, retVal[i].low
, retVal[i].close
, retVal[i].tick_volume
, retVal[i].spread
, retVal[i].real_volume);
}
}
return ratesArray?.Length ?? 0;
}
///<summary>
///Gets history data of MqlRates structure of a specified symbol-period in specified quantity into the ratesArray array. The elements ordering of the copied data is from present to the past, i.e., starting position of 0 means the current bar.
///</summary>
///<param name="symbolName">Symbol name.</param>
///<param name="timeframe">Period.</param>
///<param name="startTime">The start time for the first element to copy.</param>
///<param name="stopTime">Bar time, corresponding to the last element to copy.</param>
///<param name="ratesArray">Array of MqlRates type.</param>
public int CopyRates(string symbolName, ENUM_TIMEFRAMES timeframe, DateTime startTime, DateTime stopTime, out MqlRates[] ratesArray)
{
var commandParameters = new ArrayList { symbolName, (int)timeframe, Mt5TimeConverter.ConvertToMtTime(startTime), Mt5TimeConverter.ConvertToMtTime(stopTime) };