-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathTerminal.cs
More file actions
1319 lines (1181 loc) · 38.6 KB
/
Terminal.cs
File metadata and controls
1319 lines (1181 loc) · 38.6 KB
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
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Sockets;
using System.Text;
using System.Globalization;
namespace MTsocketAPI.MT5
{
public enum OrderType
{
ORDER_TYPE_BUY,
ORDER_TYPE_SELL,
ORDER_TYPE_BUY_LIMIT,
ORDER_TYPE_SELL_LIMIT,
ORDER_TYPE_BUY_STOP,
ORDER_TYPE_SELL_STOP
}
public enum TradeRetCode : long
{
TRADE_RETCODE_REQUOTE = 10004,
TRADE_RETCODE_REJECT = 1006,
TRADE_RETCODE_CANCEL = 10007,
TRADE_RETCODE_PLACED = 10008,
TRADE_RETCODE_DONE = 10009,
TRADE_RETCODE_DONE_PARTIAL = 10010,
TRADE_RETCODE_ERROR = 10011,
TRADE_RETCODE_TIMEOUT = 10012,
TRADE_RETCODE_INVALID = 10013,
TRADE_RETCODE_INVALID_VOLUME = 10014,
TRADE_RETCODE_INVALID_PRICE = 10015,
TRADE_RETCODE_INVALID_STOPS = 10016,
TRADE_RETCODE_TRADE_DISABLED = 10017,
TRADE_RETCODE_MARKET_CLOSED = 10018,
TRADE_RETCODE_NO_MONEY = 10019,
TRADE_RETCODE_PRICE_CHANGED = 10020,
TRADE_RETCODE_PRICE_OFF = 10021,
TRADE_RETCODE_INVALID_EXPIRATION = 10022,
TRADE_RETCODE_ORDER_CHANGED = 10023,
TRADE_RETCODE_TOO_MANY_REQUESTS = 10024,
TRADE_RETCODE_NO_CHANGES = 10025,
TRADE_RETCODE_SERVER_DISABLES_AT = 10026,
TRADE_RETCODE_CLIENT_DISABLES_AT = 10027,
TRADE_RETCODE_LOCKED = 10028,
TRADE_RETCODE_FROZEN = 10029,
TRADE_RETCODE_INVALID_FILL = 10030,
TRADE_RETCODE_CONNECTION = 10031,
TRADE_RETCODE_ONLY_REAL = 10032,
TRADE_RETCODE_LIMIT_ORDERS = 10033,
TRADE_RETCODE_LIMIT_VOLUME = 10034,
TRADE_RETCODE_INVALID_ORDER = 10035,
TRADE_RETCODE_POSITION_CLOSED = 10036,
TRADE_RETCODE_INVALID_CLOSE_VOLUME = 10038,
TRADE_RETCODE_CLOSE_ORDER_EXIST = 10039,
TRADE_RETCODE_LIMIT_POSITIONS = 10040,
TRADE_RETCODE_REJECT_CANCEL = 10041,
TRADE_RETCODE_LONG_ONLY = 10042,
TRADE_RETCODE_SHORT_ONLY = 10043,
TRADE_RETCODE_CLOSE_ONLY = 10044,
TRADE_RETCODE_FIFO_CLOSE = 10045,
TRADE_RETCODE_HEDGE_PROHIBITED = 10046
}
public enum TimeFrame
{
PERIOD_M1,
PERIOD_M2,
PERIOD_M3,
PERIOD_M4,
PERIOD_M5,
PERIOD_M6,
PERIOD_M10,
PERIOD_M12,
PERIOD_M15,
PERIOD_M20,
PERIOD_M30,
PERIOD_H1,
PERIOD_H2,
PERIOD_H3,
PERIOD_H4,
PERIOD_H6,
PERIOD_H8,
PERIOD_H12,
PERIOD_D1,
PERIOD_W1,
PERIOD_MN1
}
public enum TradeHistoryMode
{
POSITIONS,
DEALS,
ORDERS,
ORDERS_DEALS
}
public enum MA_Method
{
MODE_SMA,
MODE_EMA,
MODE_SMMA,
MODE_LWMA
}
public enum Applied_Price
{
PRICE_CLOSE,
PRICE_OPEN,
PRICE_HIGH,
PRICE_LOW,
PRICE_MEDIAN,
PRICE_TYPICAL,
PRICE_WEIGHTED
}
public class Terminal : ITerminal
{
public Terminal() { }
public string host = "127.0.0.1";
public int cmd_port = 77;
public int data_port = 78;
static int bufferLen = 65536;
TcpClient tcpClient_cmd;
TcpClient tcpClient_data;
public event EventHandler OnConnect;
public event EventHandler OnDisconnect;
public event EventHandler<Quote> OnPrice;
public event EventHandler<MarketDepth> OnMarketDepth;
public event EventHandler<OHLC_Msg> OnOHLC;
public event EventHandler<OrderEvent> OnOrderEvent;
/// <summary>
/// MTsocketAPI version
/// </summary>
public string Version { get; set; }
private object sendCmdLock = new object();
/// <summary>
/// Send RAW JSON command to MTsocketAPI
/// </summary>
/// <param name="cmd">JSON command</param>
/// <returns>JSON reply</returns>
public JObject SendCommand(JObject cmd)
{
lock (sendCmdLock)
{
try
{
byte[] data = Encoding.ASCII.GetBytes(cmd.ToString(Formatting.None) + "\r\n");
NetworkStream stream = tcpClient_cmd.GetStream();
stream.ReadTimeout = 3000;
stream.Write(data, 0, data.Length);
data = new byte[bufferLen];
string responseData = string.Empty;
int bytes;
do
{
bytes = stream.Read(data, 0, bufferLen);
responseData += Encoding.ASCII.GetString(data, 0, bytes);
} while (stream.DataAvailable || !responseData.EndsWith("\r\n"));
JObject? jresult = JsonConvert.DeserializeObject<JObject>(responseData);
if (jresult != null)
return jresult;
else
throw new Exception("Error with deserialization in SendCommand");
}
catch (Exception)
{
throw;
}
}
}
public async Task<JObject> SendCommandAsync(string host, int port, JObject cmd)
{
try
{
byte[] data = Encoding.ASCII.GetBytes(cmd.ToString(Formatting.None) + "\r\n");
if (tcpClient_cmd == null || tcpClient_cmd.Connected == false)
{
tcpClient_cmd = new TcpClient();
await tcpClient_cmd.ConnectAsync(host, port);
}
NetworkStream stream = tcpClient_cmd.GetStream();
stream.ReadTimeout = 3000;
await stream.WriteAsync(data, 0, data.Length);
data = new byte[bufferLen];
string responseData = string.Empty;
int bytes;
do
{
bytes = await stream.ReadAsync(data, 0, bufferLen);
responseData += Encoding.ASCII.GetString(data, 0, bytes);
} while (stream.DataAvailable || !responseData.EndsWith("\r\n"));
JObject? jresult = JsonConvert.DeserializeObject<JObject>(responseData);
tcpClient_cmd.Close();
if (jresult != null)
return jresult;
else
throw new Exception("Error with deserialization in SendCommand");
}
catch (Exception)
{
throw;
}
}
private void ListenMTData()
{
Thread listen = new Thread(() => ListenMTDataStream());
listen.IsBackground = true;
listen.Start();
}
private void ListenMTDataStream()
{
int bytes;
byte[] data = new byte[bufferLen];
NetworkStream stream = tcpClient_data.GetStream();
do
{
string responseData = string.Empty;
do
{
try
{
bytes = stream.Read(data, 0, data.Length);
responseData += Encoding.ASCII.GetString(data, 0, bytes);
}
catch (Exception ex)
{
}
} while (stream.DataAvailable);
try
{
responseData.Split(new string[] { "\n", "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList().ForEach(
line =>
{
JObject jresult = JObject.Parse(line);
if (jresult["MSG"].ToString() == "TRACK_PRICES")
{
Quote price = JsonConvert.DeserializeObject<Quote>(line);
if (OnPrice != null) OnPrice(this, price);
}
if (jresult["MSG"].ToString() == "TRACK_MBOOK")
{
MarketDepth domdata = JsonConvert.DeserializeObject<MarketDepth>(line);
if (OnMarketDepth != null) OnMarketDepth(this, domdata);
}
else if (jresult["MSG"].ToString() == "TRACK_OHLC")
{
OHLC_Msg price = JsonConvert.DeserializeObject<OHLC_Msg>(line);
if (OnOHLC != null) OnOHLC(this, price);
}
else if (jresult["MSG"].ToString() == "TRACK_TRADE_EVENTS")
{
OrderEvent ordEvent = JsonConvert.DeserializeObject<OrderEvent>(line);
if (OnOrderEvent != null) OnOrderEvent(this, ordEvent);
}
});
}
catch (Exception ex)
{
}
} while (true);
}
/// <summary>
/// Connect to MTsocketAPI
/// </summary>
/// <param name="host">Hostname or IP Address</param>
/// <param name="cmd_port">MTsocketAPI command port</param>
/// <param name="data_port">MTsocketAPI data port</param>
/// <returns>True = connect successful, False = connect fail</returns>
public bool Connect(string host = "127.0.0.1", int cmd_port = 77, int data_port = 78)
{
try
{
tcpClient_cmd = new TcpClient(host, cmd_port);
tcpClient_data = new TcpClient(host, data_port);
ListenMTData();
//JObject json_cmd = new JObject();
//json_cmd["MSG"] = "VERSION";
//JObject res = SendCommand(json_cmd);
//if (res["ERROR_ID"].ToString() == "0")
//{
// Version = res["NUMBER"].ToString();
// if (Convert.ToDouble(Version,CultureInfo.InvariantCulture) < 5.21)
// {
// throw new Exception("This API version needs at least MTsocketAPI 5.21 version");
// }
//}
//else
//{
// throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
//}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
if (OnConnect != null) OnConnect(this, new EventArgs());
return true;
}
/// <summary>
/// Get MT5 Terminal Information
/// </summary>
/// <returns>Terminal Info object</returns>
public TerminalInfo GetTerminalInfo()
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "TERMINAL_INFO";
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<TerminalInfo>(res.ToString());
}
else
{
throw new Exception("Error with the GetTerminalInfo command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get MT5 Account Status Info
/// </summary>
/// <returns>AccountStatus object</returns>
public AccountStatus GetAccountStatus()
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ACCOUNT_STATUS";
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<AccountStatus>(res.ToString());
}
else
{
throw new Exception("Error with the GetAccountStatus command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get Pending Orders
/// </summary>
/// <returns>List of pending orders</returns>
public List<Position> GetPendingOrders()
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_LIST";
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
List<Position> pending = JsonConvert.DeserializeObject<List<Position>>(res["PENDING"].ToString());
return pending;
}
else
{
throw new Exception("Error with the GetPendingOrders command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get Information from an opened order
/// </summary>
/// <returns>Opened order</returns>
public Position getOrderInfo(long ticket)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_INFO";
json_cmd["TICKET"] = ticket;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
List<Position> opened = JsonConvert.DeserializeObject<List<Position>>(res["OPENED"].ToString());
if (opened.Count > 0)
{
return opened.First();
}
else return new Position();
}
else
{
throw new Exception("Error with the GetOpenedOrders command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get Opened Positions
/// </summary>
/// <returns>List of opened positions</returns>
public List<Position> GetOpenedOrders()
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_LIST";
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
List<Position> opened = JsonConvert.DeserializeObject<List<Position>>(res["OPENED"].ToString());
return opened;
}
else
{
throw new Exception("Error with the GetOpenedOrders command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get Moving Average values
/// </summary>
/// <param name="Symbol">Symbol</param>
/// <param name="tf">TimeFrame</param>
/// <param name="MA_Period">Moving Average period</param>
/// <param name="MA_Shift">Moving Average shift</param>
/// <param name="MA_Method">Moving Average method</param>
/// <param name="Applied_Price">Appliced Price</param>
/// <param name="Shift">Shift</param>
/// <param name="Num">Number of elements</param>
/// <returns>List of MA values</returns>
/// <exception cref="Exception"></exception>
public List<double> MA_Indicator(string Symbol, TimeFrame tf, int MA_Period, int MA_Shift, MA_Method MA_Method, Applied_Price Applied_Price, int Shift, int Num = 1)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "MA_INDICATOR";
json_cmd["SYMBOL"] = Symbol;
json_cmd["TIMEFRAME"] = tf.ToString();
json_cmd["MA_PERIOD"] = MA_Period;
json_cmd["MA_SHIFT"] = MA_Shift;
json_cmd["MA_METHOD"] = MA_Method.ToString();
json_cmd["APPLIED_PRICE"] = Applied_Price.ToString();
json_cmd["SHIFT"] = Shift;
json_cmd["NUM"] = Num;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<double>>(res["DATA_VALUES"].ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get data from a the ATR indicator using the iATR function. More info: <see href="https://docs.mql4.com/indicators/iatr"/>
/// </summary>
/// <param name="Symbol">Symbol name</param>
/// <param name="tf">TimeFrame</param>
/// <param name="Period">ATR Period</param>
/// <param name="Shift">Shift</param>
/// <param name="Num">Number of elements</param>
public List<double> ATR_Indicator(string Symbol, TimeFrame tf, int Period, int Shift, int Num = 1)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ATR_INDICATOR";
json_cmd["SYMBOL"] = Symbol;
json_cmd["TIMEFRAME"] = tf.ToString();
json_cmd["PERIOD"] = Period;
json_cmd["SHIFT"] = Shift;
json_cmd["NUM"] = Num;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<double>>(res["DATA_VALUES"].ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get data from a custom indicator using the Metatrader iCustom function. More Info: <see href="https://www.mql5.com/es/docs/indicators/icustom"/>
/// </summary>
/// <param name="Symbol">Symbol name</param>
/// <param name="tf">TimeFrame</param>
/// <param name="Indicator_Name">Indicator Name</param>
/// <param name="Index">Buffer Index</param>
/// <param name="Num">Number of elements</param>
/// <param name="Params">Parameters</param>
public List<double> Custom_Indicator(string Symbol, TimeFrame tf, string Indicator_Name, int Index, int Num = 1, List<string> Params = null)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "CUSTOM_INDICATOR";
json_cmd["SYMBOL"] = Symbol;
json_cmd["TIMEFRAME"] = tf.ToString();
json_cmd["INDICATOR_NAME"] = Indicator_Name;
json_cmd["INDEX"] = Index;
json_cmd["NUM"] = Num;
int i = 1;
foreach (var param in Params)
{
double valorD;
int valorI;
if (int.TryParse(param, out valorI))
json_cmd["PARAM" + i.ToString()] = valorI;
else if (double.TryParse(param, out valorD))
json_cmd["PARAM" + i.ToString()] = valorD;
else
json_cmd["PARAM" + i.ToString()] = param.ToString();
i++;
}
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<double>>(res["DATA_VALUES"].ToString());
}
else
{
throw new Exception("Error with the Custom_Indicator command. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get Position History
/// </summary>
/// <param name="FromDate">From date</param>
/// <param name="ToDate">To date</param>
/// <returns>List of positions</returns>
public List<Position> GetTradeHistoryPositions(DateTime FromDate, DateTime ToDate)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "TRADE_HISTORY";
json_cmd["MODE"] = TradeHistoryMode.POSITIONS.ToString();
json_cmd["FROM_DATE"] = FromDate.ToString("yyyy.MM.dd HH:mm:ss");
json_cmd["TO_DATE"] = ToDate.ToString("yyyy.MM.dd HH:mm:ss");
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<Position>>(res[TradeHistoryMode.POSITIONS.ToString()].ToString());
}
else
{
throw new Exception("Error with the command TRADE_HISTORY. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get the Deals History
/// </summary>
/// <param name="FromDate"></param>
/// <param name="ToDate"></param>
/// <returns>List of deals</returns>
public List<Deal> GetTradeHistoryDeals(DateTime FromDate, DateTime ToDate)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "TRADE_HISTORY";
json_cmd["MODE"] = TradeHistoryMode.DEALS.ToString();
json_cmd["FROM_DATE"] = FromDate.ToString("yyyy.MM.dd HH:mm:ss");
json_cmd["TO_DATE"] = ToDate.ToString("yyyy.MM.dd HH:mm:ss");
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<Deal>>(res[TradeHistoryMode.DEALS.ToString()].ToString());
}
else
{
throw new Exception("Error with the command TRADE_HISTORY. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get the Order History
/// </summary>
/// <param name="FromDate">From date</param>
/// <param name="ToDate">To date</param>
/// <returns>List of orders</returns>
public List<Order> GetTradeHistoryOrders(DateTime FromDate, DateTime ToDate)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "TRADE_HISTORY";
json_cmd["MODE"] = TradeHistoryMode.ORDERS.ToString();
json_cmd["FROM_DATE"] = FromDate.ToString("yyyy.MM.dd HH:mm:ss");
json_cmd["TO_DATE"] = ToDate.ToString("yyyy.MM.dd HH:mm:ss");
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<Order>>(res[TradeHistoryMode.ORDERS.ToString()].ToString());
}
else
{
throw new Exception("Error with the command TRADE_HISTORY. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get the Orders & Deals History
/// </summary>
/// <param name="FromDate">From date</param>
/// <param name="ToDate">To date</param>
/// <returns>List of Orders & Deals</returns>
public List<OrderDeal> GetTradeHistoryOrdersDeals(DateTime FromDate, DateTime ToDate)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "TRADE_HISTORY";
json_cmd["MODE"] = TradeHistoryMode.ORDERS_DEALS.ToString();
json_cmd["FROM_DATE"] = FromDate.ToString("yyyy.MM.dd HH:mm:ss");
json_cmd["TO_DATE"] = ToDate.ToString("yyyy.MM.dd HH:mm:ss");
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<OrderDeal>>(res[TradeHistoryMode.ORDERS_DEALS.ToString()].ToString());
}
else
{
throw new Exception("Error with the command TRADE_HISTORY. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get the price history (Open, High, Low, Close) for a specified Symbol and TimeFrame.
/// </summary>
/// <param name="Symbol">Symbol</param>
/// <param name="tf">TimeFrame</param>
/// <param name="From">From date</param>
/// <param name="To">To date</param>
public List<Rates> PriceHistory(string Symbol, TimeFrame tf, DateTime FromDate, DateTime ToDate)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "PRICE_HISTORY";
json_cmd["SYMBOL"] = Symbol;
json_cmd["TIMEFRAME"] = tf.ToString();
json_cmd["FROM_DATE"] = FromDate.ToString("yyyy.MM.dd HH:mm");
json_cmd["TO_DATE"] = ToDate.ToString("yyyy.MM.dd HH:mm");
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<Rates>>(res["RATES"].ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Send market or limit orders.
/// </summary>
/// <param name="Symbol">Symbol</param>
/// <param name="Volume">Volume size</param>
/// <param name="Type">OrderType enum</param>
/// <param name="Price">Desired price. 0 for broker's best price (optional)</param>
/// <param name="SL">Stop Loss price. 0 for no Stop Loss (optional)</param>
/// <param name="TP">Take Profit price. 0 for no Take Profit (optional)</param>
/// <param name="Slippage">Slippage. 0 for default broker's Slippage (optional)</param>
/// <param name="Comment">Order Comment (optional)</param>
/// <param name="MagicNr">Magic Number (optional)</param>
/// <param name="Expiration">Order Expiration Date. Only for limit or stop orders (optional)</param>
public TradeResult SendOrder(string Symbol, double Volume, OrderType Type, double Price = 0, double SL = 0, double TP = 0, double Slippage = 0, string Comment = "", int MagicNr = 0, string Expiration = "1970/01/01 00:00", bool Async = false)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_SEND";
json_cmd["SYMBOL"] = Symbol;
json_cmd["VOLUME"] = Volume;
json_cmd["TYPE"] = Type.ToString();
if (SL > 0) json_cmd["SL"] = SL;
if (TP > 0) json_cmd["TP"] = TP;
if (Price > 0) json_cmd["PRICE"] = Price;
if (Slippage > 0) json_cmd["SLIPPAGE"] = Slippage;
if (Comment != "") json_cmd["COMMENT"] = Comment;
if (MagicNr > 0) json_cmd["MAGICNR"] = MagicNr;
if (Expiration != "1970/01/01 00:00") json_cmd["EXPIRATION"] = Expiration;
if (Async != false) json_cmd["ASYNC"] = true;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<TradeResult>(res.ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Change SL or TP for market or limit orders. More Info: <see href="https://www.mtsocketapi.com/doc5/API/ORDER_MODIFY.html"/>
/// </summary>
/// <param name="Ticket">Ticket Number</param>
/// <param name="SL">Stop loss price (optional)</param>
/// <param name="TP">Take profit price (optional)</param>
public TradeResult OrderModify(long Ticket, double SL = 0, double TP = 0, bool Async = false)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_MODIFY";
json_cmd["TICKET"] = Ticket;
if (SL > 0) json_cmd["SL"] = SL;
if (TP != 0) json_cmd["TP"] = TP;
if (Async != false) json_cmd["ASYNC"] = true;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<TradeResult>(res.ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Close partially or fully an order using the ticket number.
/// Also it closes stop or limit orders. More Info: <see href="https://www.mtsocketapi.com/doc5/API/ORDER_CLOSE.html"/>
/// </summary>
/// <param name="Ticket">Ticket Number</param>
/// <param name="Volume">Volume size (optional)</param>
/// <param name="Price">Desired Price (optional)</param>
/// <param name="Slippage">Max lippage (optional)</param>
public TradeResult OrderClose(long Ticket, double Volume = 0, double Price = 0, double Slippage = 0, bool Async = false)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "ORDER_CLOSE";
json_cmd["TICKET"] = Ticket;
if (Volume > 0) json_cmd["VOLUME"] = Volume;
if (Price != 0) json_cmd["PRICE"] = Price;
if (Slippage != 0) json_cmd["SLIPPAGE"] = Slippage;
if (Async != false) json_cmd["ASYNC"] = true;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<TradeResult>(res.ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get MT5 Symbol List
/// </summary>
/// <returns>Asset List</returns>
public List<Asset> GetSymbolList()
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "SYMBOL_LIST";
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<List<Asset>>(res["SYMBOLS"].ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get detailed information from a symbol
/// </summary>
/// <param name="Symbol">Symbol</param>
/// <returns>Asset object</returns>
/// <exception cref="Exception"></exception>
public Asset GetSymbolInfo(string Symbol)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "SYMBOL_INFO";
json_cmd["SYMBOL"] = Symbol;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<Asset>(res.ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
/// Get last quote from a symbol
/// </summary>
/// <param name="Symbol">Symbol</param>
/// <returns>Quote object</returns>
/// <exception cref="Exception"></exception>
public Quote GetQuote(string Symbol)
{
try
{
JObject json_cmd = new JObject();
json_cmd["MSG"] = "QUOTE";
json_cmd["SYMBOL"] = Symbol;
JObject res = SendCommand(json_cmd);
if (res["ERROR_ID"].ToString() == "0")
{
return JsonConvert.DeserializeObject<Quote>(res.ToString());
}
else
{
throw new Exception("Error with the command sent. ERROR_ID: " + res["ERROR_ID"] + " ERROR_DESCRIPTION: " + res["ERROR_DESCRIPTION"]);
}
}
catch (Exception)
{
throw;
}
}
/// <summary>
///
/// </summary>
/// <param name="FromDate">The date from which you want to request news</param>
/// <param name="ToDate">The date to which you want to request news</param>
/// <param name="Currency">(Optional) Country currency code name. For example: EUR, USD and so on</param>
/// <param name="Country_code">(Optional) Country code name (ISO 3166-1 alpha-2). “US”, “FR” and so on.</param>
/// <returns></returns>
public CalendarList CalendarList(DateTime FromDate, DateTime ToDate, string Currency = "", string Country_code = "")
{