34 Commits

Author SHA1 Message Date
Gunther Schulz 1c47fc12d1 fix bug tthat every second tick was dropped
Every other tick used to be dropped before this fix, because of incrementing the counter twice in a loop
2020-11-22 13:24:09 +01:00
Gunther Schulz 1a0ce7af3a fix incorrect setting of high water mark
Socket settings need to be set before connecting to the socket
Also, increase high water mark
2020-11-22 13:21:39 +01:00
Gunther Schulz 08b83713af fix compiler failure 2020-11-22 13:15:51 +01:00
Gunther Schulz 775a962d38 format code with new MT5 code styler 2020-11-22 13:14:33 +01:00
Nikolai b17e82d99d Merge pull request #9 from Gunther-Schulz/indicator
Drawing custom indicator data to charts
2020-10-12 10:25:50 +03:00
Gunther Schulz d423745c93 some fixes 2020-10-10 17:20:08 +02:00
Gunther Schulz 1b2beab4c4 update README and changelog
minor update to JsonAPIIndicator
2020-06-13 17:34:11 +02:00
Gunther Schulz ae6a2367b1 fix formating 2020-04-30 19:03:23 +02:00
Gunther Schulz b550a423a1 changelog 2020-04-30 18:58:17 +02:00
Gunther Schulz de6b4f0546 add support for plot labels for chart indicator lines
cleanup
2020-04-30 18:55:49 +02:00
Gunther Schulz 2c77099430 update changelog 2020-04-30 16:26:36 +02:00
Gunther Schulz 99ea77ebfe cleanup 2020-04-30 10:49:01 +02:00
Gunther Schulz 4b2297fbfb allow ENUM as string as parameters for indicators
minor code optimization
2020-03-04 12:32:48 +01:00
Gunther Schulz 37cb0fe738 cleanup 2020-03-03 12:52:46 +01:00
Gunther Schulz cc0f9b7575 change error handling to utilize MQL5 standard error handling 2020-03-02 22:11:32 +01:00
Gunther Schulz 7099ac1cac add chart control
open and draw indicator lines on chart
2020-03-01 18:06:24 +01:00
Gunther Schulz 820329307f add indicator control 2020-02-23 14:03:25 +01:00
Gunther Schulz 1bad67048f add spread support for price candle data 2020-02-16 22:17:37 +01:00
Gunther Schulz f27bc3d1d9 add indicator
control any mt5 indicator
2020-02-16 12:51:36 +01:00
Gunther Schulz c1e136d64e minor README.md formating cleanup 2020-02-16 12:51:14 +01:00
Gunther Schulz dc60a0a0c9 update .gitattributes for Metatrader 5 file types 2020-02-16 12:22:02 +01:00
Gunther Schulz 34af70c043 add script to remove binary characters and add BOM 2020-02-16 12:00:27 +01:00
Nikolai 036c2d4cfd Update JsonAPI.mq5 2020-02-16 11:03:50 +03:00
Nikolai 7deedb72c5 Update JsonAPI.mq5 2020-02-16 11:01:55 +03:00
Nikolai 126c669c62 Bug fix 2020-02-16 11:01:49 +03:00
Nikolai 03088ea2ec Update README.md 2020-02-13 18:16:35 +03:00
Nikolai e14b83e023 v 2.0 2020-02-13 18:15:23 +03:00
Nikolai 598253cfc3 Update JsonAPI.mq5 2020-02-12 20:41:03 +03:00
Nikolai aee89843da Update JsonAPI.mq5 2020-02-12 20:34:41 +03:00
Nikolai 9457e57890 Update JsonAPI.mq5
Reconnect loop
2020-02-12 20:19:22 +03:00
Nikolai 01ac1bbc11 Merge pull request #6 from freedumb2000/ticks-support
Support for tick data
2020-01-28 23:30:33 +03:00
Gunther Schulz 081fdfbdfe add support for higher tick timestamp resolution 2020-01-15 10:21:18 +01:00
Gunther Schulz 4d06d0e060 remove all Lizar contrib files and dependencies
add changelog
2020-01-12 20:22:06 +01:00
Gunther Schulz bc594e97e7 free symbol hooks, cvs write support 2020-01-09 22:04:38 +01:00
13 changed files with 1840 additions and 1036 deletions
+3
View File
@@ -1,2 +1,5 @@
# Auto detect text files and perform LF normalization
* text=auto
text *.mq5 eol=CRLF diff=c
text *.mqh eol=CRLF diff=c
-3
View File
@@ -1,5 +1,2 @@
.DS_Store
update_from_mt5\.sh
Binary file not shown.
-210
View File
@@ -1,210 +0,0 @@
//+------------------------------------------------------------------+
//| OnTick(string symbol).mqh |
//| Copyright 2010, Lizar |
//| https://login.mql5.com/ru/users/Lizar |
//| Revision 2011.01.30 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, Lizar"
#property link "https://login.mql5.com/ru/users/Lizar"
//+------------------------------------------------------------------+
//| The events enumeration is implemented as flags |
//| the events can be combined using the OR ("|") logical operation |
//+------------------------------------------------------------------+
enum ENUM_CHART_EVENT_SYMBOL
{
CHARTEVENT_NO =0, // Events disabled
CHARTEVENT_INIT =0, // "Initialization" event
CHARTEVENT_NEWBAR_M1 =0x00000001, // "New bar" event on M1 chart
CHARTEVENT_NEWBAR_M2 =0x00000002, // "New bar" event on M2 chart
CHARTEVENT_NEWBAR_M3 =0x00000004, // "New bar" event on M3 chart
CHARTEVENT_NEWBAR_M4 =0x00000008, // "New bar" event on M4 chart
CHARTEVENT_NEWBAR_M5 =0x00000010, // "New bar" event on M5 chart
CHARTEVENT_NEWBAR_M6 =0x00000020, // "New bar" event on M6 chart
CHARTEVENT_NEWBAR_M10=0x00000040, // "New bar" event on M10 chart
CHARTEVENT_NEWBAR_M12=0x00000080, // "New bar" event on M12 chart
CHARTEVENT_NEWBAR_M15=0x00000100, // "New bar" event on M15 chart
CHARTEVENT_NEWBAR_M20=0x00000200, // "New bar" event on M20 chart
CHARTEVENT_NEWBAR_M30=0x00000400, // "New bar" event on M30 chart
CHARTEVENT_NEWBAR_H1 =0x00000800, // "New bar" event on H1 chart
CHARTEVENT_NEWBAR_H2 =0x00001000, // "New bar" event on H2 chart
CHARTEVENT_NEWBAR_H3 =0x00002000, // "New bar" event on H3 chart
CHARTEVENT_NEWBAR_H4 =0x00004000, // "New bar" event on H4 chart
CHARTEVENT_NEWBAR_H6 =0x00008000, // "New bar" event on H6 chart
CHARTEVENT_NEWBAR_H8 =0x00010000, // "New bar" event on H8 chart
CHARTEVENT_NEWBAR_H12=0x00020000, // "New bar" event on H12 chart
CHARTEVENT_NEWBAR_D1 =0x00040000, // "New bar" event on D1 chart
CHARTEVENT_NEWBAR_W1 =0x00080000, // "New bar" event on W1 chart
CHARTEVENT_NEWBAR_MN1=0x00100000, // "New bar" event on MN1 chart
CHARTEVENT_TICK =0x00200000, // "New tick" event
CHARTEVENT_ALL =0xFFFFFFFF, // All events enabled
};
//---
#define CHART_EVENT_SYMBOL CHARTEVENT_TICK // frequency of calling OnTick()
int _handle_[];
int _symbols_total_ = 0; // total symbols
int _symbols_market_ = 0; // number of symbols in Market Watch
bool _market_watch_ = false; // use symbols from Market Watch
bool _testing_ = false; // In testing mode
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int LoadSymbol(string symbol)
// TODO only load when not already exists
{
//--- check if we work in Strategy Tester:
_testing_=((bool)MQL5InfoInteger(MQL5_TESTING) ||
(bool)MQL5InfoInteger(MQL5_OPTIMIZATION) ||
(bool)MQL5InfoInteger(MQL5_VISUAL_MODE));
//--- check settings
if(_testing_ )
{
Print("Error: Strategy Tester is not working. ");
return(1);
}
//--- Initialization of variables and arrays:
_symbols_total_=SymbolsTotal(false); // total symbols
ArrayResize(_handle_,_symbols_total_); // resize array for handles of "spys"
ArrayInitialize(_handle_,INVALID_HANDLE); // initalizae array for handles of "spys"
Print(_symbols_total_, symbol);
_symbols_total_=ArraySize(tickSymbols);
for(int i=0;i<_symbols_total_;i++)
if(!LoadAgent(i, symbol)) return(1);
Print(_symbols_total_, symbol);
//--- Execute OnInit function of Expert Advisor
//_OnInit();
return(0);
}
int UnloadAllSymbols()
{
//--- check if we work in Strategy Tester:
_testing_=((bool)MQL5InfoInteger(MQL5_TESTING) ||
(bool)MQL5InfoInteger(MQL5_OPTIMIZATION) ||
(bool)MQL5InfoInteger(MQL5_VISUAL_MODE));
//--- check settings
if(_testing_ )
{
Print("Error: Strategy Tester is not working. ");
return(1);
}
_symbols_total_=ArraySize(tickSymbols);
for(int i=0;i<_symbols_total_;i++)
if(!DeLoadAgent(i, tickSymbols[i])) return(1);
//--- Execute OnInit function of Expert Advisor
//_OnInit();
return(0);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//| Used only in Strategy Tester |
//+------------------------------------------------------------------+
void OnTick()
{
if(_testing_)
{
for(int i=0;i<_symbols_total_;i++)
{
Print("a");
string __symbol__=tickSymbols[i];
if(MathAbs(GlobalVariableGet(__symbol__+"_flag")-2)<0.1)
{
Print("b");
GlobalVariableSet(__symbol__+"_flag",1);
OnTick(__symbol__);
}
}
}
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long& lparam,const double& dparam,const string& sparam)
{
//--- Call of OnTick(string symbol) or OnChartEvent event handler:
if(id==CHARTEVENT_CUSTOM_LAST)
{
OnTick(sparam);
//--- synchronize "agents" with Market Watch if necessary:
}
else _OnChartEvent(id,lparam,dparam,sparam);
}
#define OnChartEvent _OnChartEvent // rendefine of OnChartEvent function
//+------------------------------------------------------------------+
//| Function for loading of "spys" |
//| INPUT: __id__ - id, corresponds to the symbol index in |
//| the list of symbols |
//| __symbol__ - symbol name |
//| OUTPUT: true - if successful |
//| false - if error |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool LoadAgent(int __id__, string __symbol__)
{
_handle_[__id__]=iCustom(__symbol__,_Period,"Spy Control panel MCM",ChartID(),65534,CHART_EVENT_SYMBOL);
if(_handle_[__id__]==INVALID_HANDLE)
{
Print("Error in setting of agent for ",__symbol__);
return(false);
}
Print("The agent for ",__symbol__," is set.");
return(true);
}
//+------------------------------------------------------------------+
//| Function for release of the "spys" |
//| INPUT: __id__ - id, corresponds to the symbol index in |
//| the list of symbols |
//| __symbol__ - symbol name |
//| OUTPUT: true - if successful |
//| false - if error |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool DeLoadAgent(int __id__, string __symbol__)
{
if(_handle_[__id__]!=INVALID_HANDLE)
{
if(!IndicatorRelease(_handle_[__id__]))
{
Print("Error deletion of agent for ",__symbol__);
return(false);
}
Print("The agent for ",__symbol__," is deleted.");
_handle_[__id__]=INVALID_HANDLE;
}
return(true);
}
//+------------------------------ end -------------------------------+
+382
View File
@@ -0,0 +1,382 @@
#define MIN_ENUM_VALUES 0
#define MAX_ENUM_VALUES 255
//+------------------------------------------------------------------+
//| StringToEnum : Convert a string to an ENUM value, |
//| it loops between min(0) and max(255), adjustable if needed. |
//| Non existing enum value defined as -1. If -1 is used as an |
//| enum value, code need to be adjusted to an other default. |
//| Parameters : |
//| in - string to convert |
//| out - ENUM value |
//| @return - int if conversion succeeded, false otherwise |
//| |
//| Based on: |
//| https://www.mql5.com/en/forum/61741/page3#comment_5491344 |
//+------------------------------------------------------------------+
template<typename ENUM>
int StringToEnum(string in,ENUM &out)
{
out=-1;
//---
for(int i=MIN_ENUM_VALUES;i<=MAX_ENUM_VALUES;i++)
{
ENUM enumValue=(ENUM)i;
if(in==EnumToString(enumValue))
{
out=enumValue;
break;
}
}
//---
return(out);
}
int StringToEnumInt(string indicatorConstantString)
{
int r = -1;
ENUM_ACCOUNT_INFO_DOUBLE a1;
r = StringToEnum(indicatorConstantString,a1);
//if(debug) Print("ENUM type: ENUM_ACCOUNT_INFO_DOUBLE");
if(r>=0)return r;
ENUM_ACCOUNT_INFO_INTEGER a2;
r = StringToEnum(indicatorConstantString,a2);
if(r>=0)return r;
ENUM_ACCOUNT_INFO_STRING a3;
r = StringToEnum(indicatorConstantString,a3);
if(r>=0)return r;
ENUM_ACCOUNT_MARGIN_MODE a4;
r = StringToEnum(indicatorConstantString,a4);
if(r>=0)return r;
ENUM_ACCOUNT_STOPOUT_MODE a5;
r = StringToEnum(indicatorConstantString,a5);
if(r>=0)return r;
ENUM_ACCOUNT_TRADE_MODE a6;
r = StringToEnum(indicatorConstantString,a6);
if(r>=0)return r;
ENUM_ALIGN_MODE a7;
r = StringToEnum(indicatorConstantString,a7);
if(r>=0)return r;
ENUM_ANCHOR_POINT a8;
r = StringToEnum(indicatorConstantString,a8);
if(r>=0)return r;
ENUM_APPLIED_PRICE a9;
r = StringToEnum(indicatorConstantString,a9);
if(r>=0)return r;
ENUM_APPLIED_PRICE a10;
r = StringToEnum(indicatorConstantString,a10);
if(r>=0)return r;
ENUM_APPLIED_VOLUME a11;
r = StringToEnum(indicatorConstantString,a11);
if(r>=0)return r;
ENUM_ARROW_ANCHOR a12;
r = StringToEnum(indicatorConstantString,a12);
if(r>=0)return r;
ENUM_BASE_CORNER a13;
r = StringToEnum(indicatorConstantString,a13);
if(r>=0)return r;
ENUM_BOOK_TYPE a14;
r = StringToEnum(indicatorConstantString,a14);
if(r>=0)return r;
ENUM_BORDER_TYPE a15;
r = StringToEnum(indicatorConstantString,a15);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_FREQUENCY a16;
r = StringToEnum(indicatorConstantString,a16);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_IMPACT a17;
r = StringToEnum(indicatorConstantString,a17);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_IMPORTANCE a18;
r = StringToEnum(indicatorConstantString,a18);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_MULTIPLIER a19;
r = StringToEnum(indicatorConstantString,a19);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_SECTOR a20;
r = StringToEnum(indicatorConstantString,a20);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_TIMEMODE a21;
r = StringToEnum(indicatorConstantString,a21);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_TYPE a22;
r = StringToEnum(indicatorConstantString,a22);
if(r>=0)return r;
ENUM_CALENDAR_EVENT_UNIT a23;
r = StringToEnum(indicatorConstantString,a23);
if(r>=0)return r;
ENUM_CHART_EVENT a24;
r = StringToEnum(indicatorConstantString,a24);
if(r>=0)return r;
ENUM_CHART_MODE a25;
r = StringToEnum(indicatorConstantString,a25);
if(r>=0)return r;
ENUM_CHART_POSITION a26;
r = StringToEnum(indicatorConstantString,a26);
if(r>=0)return r;
ENUM_CHART_PROPERTY_DOUBLE a27;
r = StringToEnum(indicatorConstantString,a27);
if(r>=0)return r;
ENUM_CHART_PROPERTY_INTEGER a28;
r = StringToEnum(indicatorConstantString,a28);
if(r>=0)return r;
ENUM_CHART_PROPERTY_STRING a29;
r = StringToEnum(indicatorConstantString,a29);
if(r>=0)return r;
ENUM_CHART_VOLUME_MODE a30;
r = StringToEnum(indicatorConstantString,a30);
if(r>=0)return r;
ENUM_CL_DEVICE_TYPE a31;
r = StringToEnum(indicatorConstantString,a31);
if(r>=0)return r;
ENUM_COLOR_FORMAT a32;
r = StringToEnum(indicatorConstantString,a32);
if(r>=0)return r;
ENUM_CRYPT_METHOD a33;
r = StringToEnum(indicatorConstantString,a33);
if(r>=0)return r;
ENUM_CUSTOMIND_PROPERTY_DOUBLE a34;
r = StringToEnum(indicatorConstantString,a34);
if(r>=0)return r;
ENUM_CHART_PROPERTY_INTEGER a35;
r = StringToEnum(indicatorConstantString,a35);
if(r>=0)return r;
ENUM_CUSTOMIND_PROPERTY_STRING a36;
r = StringToEnum(indicatorConstantString,a36);
if(r>=0)return r;
ENUM_DATABASE_EXPORT_FLAGS a37;
r = StringToEnum(indicatorConstantString,a37);
if(r>=0)return r;
ENUM_DATABASE_FIELD_TYPE a38;
r = StringToEnum(indicatorConstantString,a38);
if(r>=0)return r;
ENUM_DATABASE_OPEN_FLAGS a39;
r = StringToEnum(indicatorConstantString,a39);
if(r>=0)return r;
ENUM_DATABASE_PRINT_FLAGS a40;
r = StringToEnum(indicatorConstantString,a40);
if(r>=0)return r;
ENUM_DATATYPE a41;
r = StringToEnum(indicatorConstantString,a41);
if(r>=0)return r;
ENUM_DAY_OF_WEEK a42;
r = StringToEnum(indicatorConstantString,a42);
if(r>=0)return r;
ENUM_DEAL_ENTRY a43;
r = StringToEnum(indicatorConstantString,a43);
if(r>=0)return r;
ENUM_DEAL_PROPERTY_DOUBLE a44;
r = StringToEnum(indicatorConstantString,a44);
if(r>=0)return r;
ENUM_DEAL_PROPERTY_INTEGER a45;
r = StringToEnum(indicatorConstantString,a45);
if(r>=0)return r;
ENUM_DEAL_PROPERTY_STRING a46;
r = StringToEnum(indicatorConstantString,a46);
if(r>=0)return r;
ENUM_DEAL_REASON a47;
r = StringToEnum(indicatorConstantString,a47);
if(r>=0)return r;
ENUM_DEAL_TYPE a48;
r = StringToEnum(indicatorConstantString,a48);
if(r>=0)return r;
ENUM_DRAW_TYPE a49;
r = StringToEnum(indicatorConstantString,a49);
if(r>=0)return r;
ENUM_DX_BUFFER_TYPE a50;
r = StringToEnum(indicatorConstantString,a50);
if(r>=0)return r;
ENUM_DX_FORMAT a51;
r = StringToEnum(indicatorConstantString,a51);
if(r>=0)return r;
ENUM_DX_HANDLE_TYPE a52;
r = StringToEnum(indicatorConstantString,a52);
if(r>=0)return r;
ENUM_DX_PRIMITIVE_TOPOLOGY a53;
r = StringToEnum(indicatorConstantString,a53);
if(r>=0)return r;
ENUM_DX_SHADER_TYPE a54;
r = StringToEnum(indicatorConstantString,a54);
if(r>=0)return r;
ENUM_ELLIOT_WAVE_DEGREE a55;
r = StringToEnum(indicatorConstantString,a55);
if(r>=0)return r;
ENUM_FILESELECT_FLAGS a56;
r = StringToEnum(indicatorConstantString,a56);
if(r>=0)return r;
ENUM_FILE_POSITION a57;
r = StringToEnum(indicatorConstantString,a57);
if(r>=0)return r;
ENUM_FILE_PROPERTY_INTEGER a58;
r = StringToEnum(indicatorConstantString,a58);
if(r>=0)return r;
ENUM_GANN_DIRECTION a59;
r = StringToEnum(indicatorConstantString,a59);
if(r>=0)return r;
ENUM_INDEXBUFFER_TYPE a60;
r = StringToEnum(indicatorConstantString,a60);
if(r>=0)return r;
ENUM_INDICATOR a61;
r = StringToEnum(indicatorConstantString,a61);
if(r>=0)return r;
ENUM_INIT_RETCODE a62;
r = StringToEnum(indicatorConstantString,a62);
if(r>=0)return r;
ENUM_LICENSE_TYPE a63;
r = StringToEnum(indicatorConstantString,a63);
if(r>=0)return r;
ENUM_LINE_STYLE a64;
r = StringToEnum(indicatorConstantString,a64);
if(r>=0)return r;
ENUM_MA_METHOD a65;
r = StringToEnum(indicatorConstantString,a65);
if(r>=0)return r;
ENUM_MQL_INFO_INTEGER a66;
r = StringToEnum(indicatorConstantString,a66);
if(r>=0)return r;
ENUM_MQL_INFO_STRING a67;
r = StringToEnum(indicatorConstantString,a67);
if(r>=0)return r;
ENUM_OBJECT a68;
r = StringToEnum(indicatorConstantString,a68);
if(r>=0)return r;
ENUM_OBJECT_PROPERTY_DOUBLE a69;
r = StringToEnum(indicatorConstantString,a69);
if(r>=0)return r;
ENUM_OBJECT_PROPERTY_INTEGER a70;
r = StringToEnum(indicatorConstantString,a70);
if(r>=0)return r;
ENUM_OBJECT_PROPERTY_STRING a71;
r = StringToEnum(indicatorConstantString,a71);
if(r>=0)return r;
ENUM_OPENCL_HANDLE_TYPE a72;
r = StringToEnum(indicatorConstantString,a72);
if(r>=0)return r;
ENUM_OPENCL_PROPERTY_INTEGER a73;
r = StringToEnum(indicatorConstantString,a73);
if(r>=0)return r;
ENUM_PLOT_PROPERTY_STRING a74;
r = StringToEnum(indicatorConstantString,a74);
if(r>=0)return r;
ENUM_POINTER_TYPE a75;
r = StringToEnum(indicatorConstantString,a75);
if(r>=0)return r;
ENUM_POSITION_PROPERTY_DOUBLE a76;
r = StringToEnum(indicatorConstantString,a76);
if(r>=0)return r;
ENUM_ORDER_PROPERTY_INTEGER a77;
r = StringToEnum(indicatorConstantString,a77);
if(r>=0)return r;
ENUM_PLOT_PROPERTY_STRING a78;
r = StringToEnum(indicatorConstantString,a78);
if(r>=0)return r;
ENUM_PROGRAM_TYPE a79;
r = StringToEnum(indicatorConstantString,a79);
if(r>=0)return r;
ENUM_SERIESMODE a80;
r = StringToEnum(indicatorConstantString,a80);
if(r>=0)return r;
ENUM_SERIES_INFO_INTEGER a81;
r = StringToEnum(indicatorConstantString,a81);
if(r>=0)return r;
ENUM_SIGNAL_BASE_DOUBLE a82;
r = StringToEnum(indicatorConstantString,a82);
if(r>=0)return r;
ENUM_SIGNAL_BASE_INTEGER a83;
r = StringToEnum(indicatorConstantString,a83);
if(r>=0)return r;
ENUM_SIGNAL_BASE_STRING a84;
r = StringToEnum(indicatorConstantString,a84);
if(r>=0)return r;
ENUM_SIGNAL_INFO_DOUBLE a85;
r = StringToEnum(indicatorConstantString,a85);
if(r>=0)return r;
ENUM_SIGNAL_INFO_INTEGER a86;
r = StringToEnum(indicatorConstantString,a86);
if(r>=0)return r;
ENUM_SIGNAL_INFO_STRING a87;
r = StringToEnum(indicatorConstantString,a87);
if(r>=0)return r;
ENUM_STATISTICS a88;
r = StringToEnum(indicatorConstantString,a88);
if(r>=0)return r;
ENUM_STO_PRICE a89;
r = StringToEnum(indicatorConstantString,a89);
if(r>=0)return r;
ENUM_SYMBOL_CALC_MODE a90;
r = StringToEnum(indicatorConstantString,a90);
if(r>=0)return r;
ENUM_SYMBOL_CHART_MODE a91;
r = StringToEnum(indicatorConstantString,a91);
if(r>=0)return r;
ENUM_SYMBOL_INFO_DOUBLE a92;
r = StringToEnum(indicatorConstantString,a92);
if(r>=0)return r;
ENUM_SYMBOL_INFO_INTEGER a93;
r = StringToEnum(indicatorConstantString,a93);
if(r>=0)return r;
ENUM_SYMBOL_INFO_STRING a94;
r = StringToEnum(indicatorConstantString,a94);
if(r>=0)return r;
ENUM_STATISTICS a95;
r = StringToEnum(indicatorConstantString,a95);
if(r>=0)return r;
ENUM_STO_PRICE a96;
r = StringToEnum(indicatorConstantString,a96);
if(r>=0)return r;
ENUM_SYMBOL_CALC_MODE a97;
r = StringToEnum(indicatorConstantString,a97);
if(r>=0)return r;
ENUM_SYMBOL_CHART_MODE a98;
r = StringToEnum(indicatorConstantString,a98);
if(r>=0)return r;
ENUM_SYMBOL_INFO_DOUBLE a99;
r = StringToEnum(indicatorConstantString,a99);
if(r>=0)return r;
ENUM_SYMBOL_INFO_INTEGER a100;
r = StringToEnum(indicatorConstantString,a100);
if(r>=0)return r;
ENUM_SYMBOL_INFO_STRING a101;
r = StringToEnum(indicatorConstantString,a101);
if(r>=0)return r;
ENUM_SYMBOL_OPTION_MODE a102;
r = StringToEnum(indicatorConstantString,a102);
if(r>=0)return r;
ENUM_SYMBOL_OPTION_RIGHT a103;
r = StringToEnum(indicatorConstantString,a103);
if(r>=0)return r;
ENUM_SYMBOL_ORDER_GTC_MODE a104;
r = StringToEnum(indicatorConstantString,a104);
if(r>=0)return r;
ENUM_SYMBOL_SWAP_MODE a105;
r = StringToEnum(indicatorConstantString,a105);
if(r>=0)return r;
ENUM_SYMBOL_TRADE_EXECUTION a106;
r = StringToEnum(indicatorConstantString,a106);
if(r>=0)return r;
ENUM_SYMBOL_TRADE_MODE a107;
r = StringToEnum(indicatorConstantString,a107);
if(r>=0)return r;
ENUM_TERMINAL_INFO_DOUBLE a108;
r = StringToEnum(indicatorConstantString,a108);
if(r>=0)return r;
ENUM_TERMINAL_INFO_INTEGER a109;
r = StringToEnum(indicatorConstantString,a109);
if(r>=0)return r;
ENUM_TERMINAL_INFO_STRING a110;
r = StringToEnum(indicatorConstantString,a110);
if(r>=0)return r;
ENUM_TIMEFRAMES a111;
r = StringToEnum(indicatorConstantString,a111);
if(r>=0)return r;
ENUM_TRADE_REQUEST_ACTIONS a112;
r = StringToEnum(indicatorConstantString,a112);
if(r>=0)return r;
ENUM_TRADE_TRANSACTION_TYPE a113;
r = StringToEnum(indicatorConstantString,a113);
if(r>=0)return r;
return(-1);
}
+449
View File
@@ -0,0 +1,449 @@
//+------------------------------------------------------------------+
//| ControlErrors.mqh |
//| Copyright KlimMalgin |
//| The library should be located in directory: |
//| MetaTrader 5/MQL5/Include/ |
//| https://www.mql5.com/en/articles/70 |
//+------------------------------------------------------------------+
#property copyright "KlimMalgin"
#property link ""
class ControlErrors
{
private:
// Flags that define what types of reports need to be enabled
bool _PlaySound; // Play or don't play a sound when an error occurs.
bool _PrintInfo; // Add error details to the journal of Expert Advisors
bool _AlertInfo; // Generate Alert with error details
bool _WriteFile; // Record reports on errors into a file or not
// A structure for storing error data elements that use this structure
struct Code
{
int code; // Error code
string desc; // Description of the error code
};
Code Errors[]; // Array that contains error codes and their descriptions
Code _UserError; // Stores information about a custome error
Code _Error; // Stores information about the last error of any type
// Different service properties
short _CountErrors; // Number of errors stored in array Errors[]
string _PlaySoundFile; // File that will be played for an alert sound
string _DataPath; // Path to the log storing directory
public:
// Constructor
ControlErrors(void);
// Methods for setting flags
void SetSound(bool value); // Play or don't play a sound when an error occurs
void SetPrint(bool value); // Enter error data the the journal of Expert Advisors or not
void SetAlert(bool value); // Generate an Alert message or not
void SetWriteFlag(bool flag); // Set the writing flag. true - keep logs, false - do not keep
// Methods for working with errors
int mGetLastError(); // Returns contents of the system variable _LastError
int mGetError(); // Returns code of the last obtained error
int mGetTypeError(); // Returns error type (Custom = 1 ore predefined = 0)
void mResetLastError(); // Resets the contents of the system variable _LastError
void mSetUserError(ushort value, string desc = ""); // Sets the custom error
void mResetUserError(); // Resets class fields that contain information about the custom error
void mResetError(); // Resets the structure that contains information about the last error
string mGetDesc(int nErr = 0); // Returns error description by the number, or that of the current error of no number
int Check(string st = ""); // Method to check the current system state for errors
// Alert methods (Alert, Print, Sound)
void mAlert(string message = "");
void mPrint(string message = "");
void mSound();
// Various service methods
void SetPlaySoundFile(string file); // Method sets the file name to play an sound
void SetWritePath(string path); // Set the path to store logs
int mFileWrite(string message = "");// Record into a file the available information about the last error
};
void ControlErrors::ControlErrors(void)
{
SetAlert(false);
SetPrint(false);
SetSound(false);
SetWriteFlag(false);
SetPlaySoundFile("alert.wav");
SetWritePath("LogErrors.txt");
_CountErrors = 150;
ArrayResize(Errors, _CountErrors);
// Return codes of a trade server
Errors[0].code = 10004;Errors[0].desc = "Requote";
Errors[1].code = 10006;Errors[1].desc = "Request rejected";
Errors[2].code = 10007;Errors[2].desc = "Request canceled by trader";
Errors[3].code = 10008;Errors[3].desc = "Order placed";
Errors[4].code = 10009;Errors[4].desc = "Request is completed";
Errors[5].code = 10010;Errors[5].desc = "Request is partially completed";
Errors[6].code = 10011;Errors[6].desc = "Request processing error";
Errors[7].code = 10012;Errors[7].desc = "Request canceled by timeout";
Errors[8].code = 10013;Errors[8].desc = "Invalid request";
Errors[9].code = 10014;Errors[9].desc = "Invalid volume in the request";
Errors[10].code = 10015;Errors[10].desc = "Invalid price in the request";
Errors[11].code = 10016;Errors[11].desc = "Invalid stops in the request";
Errors[12].code = 10017;Errors[12].desc = "Trade is disabled";
Errors[13].code = 10018;Errors[13].desc = "Market is closed";
Errors[14].code = 10019;Errors[14].desc = "There is not enough money to fulfill the request";
Errors[15].code = 10020;Errors[15].desc = "Prices changed";
Errors[16].code = 10021;Errors[16].desc = "There are no quotes to process the request";
Errors[17].code = 10022;Errors[17].desc = "Invalid order expiration date in the request";
Errors[18].code = 10023;Errors[18].desc = "Order state changed";
Errors[19].code = 10024;Errors[19].desc = "Too frequent requests";
Errors[20].code = 10025;Errors[20].desc = "No changes in request";
Errors[21].code = 10026;Errors[21].desc = "Autotrading disabled by server";
Errors[22].code = 10027;Errors[22].desc = "Autotrading disabled by client terminal";
Errors[23].code = 10028;Errors[23].desc = "Request locked for processing";
Errors[24].code = 10029;Errors[24].desc = "Order or position frozen";
Errors[25].code = 10030;Errors[25].desc = "Invalid order filling type";
// Common Errors
Errors[26].code = 4001;Errors[26].desc = "Unexpected internal error";
Errors[27].code = 4002;Errors[27].desc = "Wrong parameter in the inner call of the client terminal function";
Errors[28].code = 4003;Errors[28].desc = "Wrong parameter when calling the system function";
Errors[29].code = 4004;Errors[29].desc = "Not enough memory to perform the system function";
Errors[30].code = 4005;Errors[30].desc = "The structure contains objects of strings and/or dynamic arrays and/or structure of such objects and/or classes";
Errors[31].code = 4006;Errors[31].desc = "Array of a wrong type, wrong size, or a damaged object of a dynamic array";
Errors[32].code = 4007;Errors[32].desc = "Not enough memory for the relocation of an array, or an attempt to change the size of a static array";
Errors[33].code = 4008;Errors[33].desc = "Not enough memory for the relocation of string";
Errors[34].code = 4009;Errors[34].desc = "Not initialized string";
Errors[35].code = 4010;Errors[35].desc = "Invalid date and/or time";
Errors[36].code = 4011;Errors[36].desc = "Requested array size exceeds 2 GB";
Errors[37].code = 4012;Errors[37].desc = "Wrong pointer";
Errors[38].code = 4013;Errors[38].desc = "Wrong type of pointer";
Errors[39].code = 4014;Errors[39].desc = "System function is not allowed to call";
// Charts
Errors[40].code = 4101;Errors[40].desc = "Wrong chart ID";
Errors[41].code = 4102;Errors[41].desc = "Chart does not respond";
Errors[42].code = 4103;Errors[42].desc = "Chart not found";
Errors[43].code = 4104;Errors[43].desc = "No Expert Advisor in the chart that could handle the event";
Errors[44].code = 4105;Errors[44].desc = "Chart opening error";
Errors[45].code = 4106;Errors[45].desc = "Failed to change chart symbol and period";
Errors[46].code = 4107;Errors[46].desc = "Wrong parameter for timer";
Errors[47].code = 4108;Errors[47].desc = "Failed to create timer";
Errors[48].code = 4109;Errors[48].desc = "Wrong chart property ID";
Errors[49].code = 4110;Errors[49].desc = "Error creating screenshots";
Errors[50].code = 4111;Errors[50].desc = "Error navigating through chart";
Errors[51].code = 4112;Errors[51].desc = "Error applying template";
Errors[52].code = 4113;Errors[52].desc = "Subwindow containing the indicator was not found";
// Graphical Objects
Errors[53].code = 4201;Errors[53].desc = "Error working with a graphical object";
Errors[54].code = 4202;Errors[54].desc = "Graphical object was not found";
Errors[55].code = 4203;Errors[55].desc = "Wrong ID of a graphical object property";
Errors[56].code = 4204;Errors[56].desc = "Unable to get date corresponding to the value";
Errors[57].code = 4205;Errors[57].desc = "Unable to get value corresponding to the date";
// MarketInfo
Errors[58].code = 4301;Errors[58].desc = "Unknown symbol";
Errors[59].code = 4302;Errors[59].desc = "Symbol is not selected in MarketWatch";
Errors[60].code = 4303;Errors[60].desc = "Wrong identifier of a symbol property";
Errors[61].code = 4304;Errors[61].desc = "Time of the last tick is not known (no ticks)";
// History Access
Errors[62].code = 4401;Errors[62].desc = "Requested history not found";
Errors[63].code = 4402;Errors[63].desc = "Wrong ID of the history property";
// Global_Variables
Errors[64].code = 4501;Errors[64].desc = "Global variable of the client terminal is not found";
Errors[65].code = 4502;Errors[65].desc = "Global variable of the client terminal with the same name already exists";
Errors[66].code = 4510;Errors[66].desc = "Email sending failed";
Errors[67].code = 4511;Errors[67].desc = "Sound playing failed";
Errors[68].code = 4512;Errors[68].desc = "Wrong identifier of the program property";
Errors[69].code = 4513;Errors[69].desc = "Wrong identifier of the terminal property";
Errors[70].code = 4514;Errors[70].desc = "File sending via ftp failed";
// Custom Indicator Buffers
Errors[71].code = 4601;Errors[71].desc = "Not enough memory for the distribution of indicator buffers";
Errors[72].code = 4602;Errors[72].desc = "Wrong indicator buffer index";
// Custom Indicator Properties
Errors[73].code = 4603;Errors[73].desc = "Wrong ID of the custom indicator property";
// Account
Errors[74].code = 4701;Errors[74].desc = "Wrong account property ID";
Errors[75].code = 4751;Errors[75].desc = "Wrong trade property ID;";
Errors[76].code = 4752;Errors[76].desc = "Trading by Expert Advisors prohibited";
Errors[77].code = 4753;Errors[77].desc = "Position not found";
Errors[78].code = 4754;Errors[78].desc = "Order not found";
Errors[79].code = 4755;Errors[79].desc = "Deal not found";
Errors[80].code = 4756;Errors[80].desc = "Trade request sending failed";
Errors[81].code = 4757;Errors[81].desc = "Timeout exceeded when selecting (searching) specified data";
// Indicators
Errors[82].code = 4801;Errors[82].desc = "Unknown symbol";
Errors[83].code = 4802;Errors[83].desc = "Indicator cannot be created";
Errors[84].code = 4803;Errors[84].desc = "Not enough memory to add the indicator";
Errors[85].code = 4804;Errors[85].desc = "The indicator cannot be applied to another indicator";
Errors[86].code = 4805;Errors[86].desc = "Error applying an indicator to chart";
Errors[87].code = 4806;Errors[87].desc = "Requested data not found";
Errors[88].code = 4807;Errors[88].desc = "Wrong index of the requested indicator buffer";
Errors[89].code = 4808;Errors[89].desc = "Wrong number of parameters when creating an indicator";
Errors[90].code = 4809;Errors[90].desc = "No parameters when creating an indicator";
Errors[91].code = 4810;Errors[91].desc = "The first parameter in the array must be the name of the custom indicator";
Errors[92].code = 4811;Errors[92].desc = "Invalid parameter type in the array when creating an indicator";
// Depth of Market
Errors[93].code = 4901;Errors[93].desc = "Depth Of Market can not be added";
Errors[94].code = 4902;Errors[94].desc = "Depth Of Market can not be removed";
Errors[95].code = 4903;Errors[95].desc = "The data from Depth Of Market can not be obtained";
Errors[96].code = 4904;Errors[96].desc = "Error in subscribing to receive new data from Depth Of Market";
// File Operations
Errors[97].code = 5001;Errors[97].desc = "More than 64 files cannot be opened at the same time";
Errors[98].code = 5002;Errors[98].desc = "Invalid file name";
Errors[99].code = 5003;Errors[99].desc = "Too long file name";
Errors[100].code = 5004;Errors[100].desc = "File opening error";
Errors[101].code = 5005;Errors[101].desc = "Not enough memory for cache to read";
Errors[102].code = 5006;Errors[102].desc = "File deleting error";
Errors[103].code = 5007;Errors[103].desc = "A file with this handle was closed, or was not opened at all";
Errors[104].code = 5008;Errors[104].desc = "Wrong file handle";
Errors[105].code = 5009;Errors[105].desc = "The file must be opened for writing";
Errors[106].code = 5010;Errors[106].desc = "The file must be opened for reading";
Errors[107].code = 5011;Errors[107].desc = "The file must be opened as a binary one";
Errors[108].code = 5012;Errors[108].desc = "The file must be opened as a text";
Errors[109].code = 5013;Errors[109].desc = "The file must be opened as a text or CSV";
Errors[110].code = 5014;Errors[110].desc = "The file must be opened as CSV";
Errors[111].code = 5015;Errors[111].desc = "File reading error";
Errors[112].code = 5016;Errors[112].desc = "String size must be specified, because the file is opened as binary";
Errors[113].code = 5017;Errors[113].desc = "A text file must be for string arrays, for other arrays - binary";
Errors[114].code = 5018;Errors[114].desc = "This is not a file, this is a directory";
Errors[115].code = 5019;Errors[115].desc = "File does not exist";
Errors[116].code = 5020;Errors[116].desc = "File can not be rewritten";
Errors[117].code = 5021;Errors[117].desc = "Wrong directory name";
Errors[118].code = 5022;Errors[118].desc = "Directory does not exist";
Errors[119].code = 5023;Errors[119].desc = "This is a file, not a directory";
Errors[120].code = 5024;Errors[120].desc = "The directory cannot be removed";
// String Casting
Errors[121].code = 5030;Errors[121].desc = "No date in the string";
Errors[122].code = 5031;Errors[122].desc = "Wrong date in the string";
Errors[123].code = 5032;Errors[123].desc = "Wrong time in the string";
Errors[124].code = 5033;Errors[124].desc = "Error converting string to date";
Errors[125].code = 5034;Errors[125].desc = "Not enough memory for the string";
Errors[126].code = 5035;Errors[126].desc = "The string length is less than expected";
Errors[127].code = 5036;Errors[127].desc = "Too large number, more than ULONG_MAX";
Errors[128].code = 5037;Errors[128].desc = "Invalid format string";
Errors[129].code = 5038;Errors[129].desc = "Amount of format specifiers more than the parameters";
Errors[130].code = 5039;Errors[130].desc = "Amount of parameters more than the format specifiers";
Errors[131].code = 5040;Errors[131].desc = "Damaged parameter of string type";
Errors[132].code = 5041;Errors[132].desc = "Position outside the string";
Errors[133].code = 5042;Errors[133].desc = "0 added to the string end, a useless operation";
Errors[134].code = 5043;Errors[134].desc = "Unknown data type when converting to a string";
Errors[135].code = 5044;Errors[135].desc = "Damaged string object";
// Operations with Arrays
Errors[136].code = 5050;Errors[136].desc = "Copying incompatible arrays. String array can be copied only to a string array, and a numeric array - in numeric array only";
Errors[137].code = 5051;Errors[137].desc = "The receiving array is declared as AS_SERIES, and it is of insufficient size";
Errors[138].code = 5052;Errors[138].desc = "Too small array, the starting position is outside the array";
Errors[139].code = 5053;Errors[139].desc = "An array of zero length";
Errors[140].code = 5054;Errors[140].desc = "Must be a numeric array";
Errors[141].code = 5055;Errors[141].desc = "Must be a one-dimensional array";
Errors[142].code = 5056;Errors[142].desc = "Timeseries cannot be used";
Errors[143].code = 5057;Errors[143].desc = "Must be an array of type double";
Errors[144].code = 5058;Errors[144].desc = "Must be an array of type float";
Errors[145].code = 5059;Errors[145].desc = "Must be an array of type long";
Errors[146].code = 5060;Errors[146].desc = "Must be an array of type int";
Errors[147].code = 5061;Errors[147].desc = "Must be an array of type short";
Errors[148].code = 5062;Errors[148].desc = "Must be an array of type char";
}
void ControlErrors::SetAlert(bool value)
{
_AlertInfo = value;
}
void ControlErrors::SetPrint(bool value)
{
_PrintInfo = value;
}
void ControlErrors::SetSound(bool value)
{
_PlaySound = value;
}
void ControlErrors::SetWriteFlag(bool flag)
{
_WriteFile = flag;
}
void ControlErrors::SetWritePath(string path)
{
_DataPath = path;
}
void ControlErrors::SetPlaySoundFile(string file)
{
_PlaySoundFile = file;
}
int ControlErrors::mGetLastError(void)
{
_Error.code = GetLastError();
_Error.desc = mGetDesc(_Error.code);
return _Error.code;
}
void ControlErrors::mResetLastError(void)
{
ResetLastError();
}
int ControlErrors::mGetError(void)
{
return _Error.code;
}
void ControlErrors::mResetError(void)
{
_Error.code = 0;
_Error.desc = "";
}
int ControlErrors::mGetTypeError(void)
{
if (mGetError() < ERR_USER_ERROR_FIRST)
{
return 0;
}
else if (mGetError() >= ERR_USER_ERROR_FIRST)
{
return 1;
}
return -1;
}
void ControlErrors::mSetUserError(ushort value, string desc = "")
{
SetUserError(value);
_UserError.code = value;
_UserError.desc = desc;
}
void ControlErrors::mResetUserError(void)
{
_UserError.code = 0;
_UserError.desc = "";
}
string ControlErrors::mGetDesc(int nErr=0)
{
int ErrorNumber = 0;
string ReturnDesc = "";
ErrorNumber = (mGetError()>0)?mGetError():ErrorNumber;
ErrorNumber = (nErr>0)?nErr:ErrorNumber;
if ((ErrorNumber > 0) && (ErrorNumber < ERR_USER_ERROR_FIRST))
{
for (int i = 0;i<_CountErrors;i++)
{
if (Errors[i].code == ErrorNumber)
{
ReturnDesc = Errors[i].desc;
break;
}
}
}
else if (ErrorNumber > ERR_USER_ERROR_FIRST)
{
ReturnDesc = (_UserError.desc=="")?"Custom error":_UserError.desc;
}
if (ReturnDesc == ""){return "Unknown error code: "+(string)ErrorNumber;}
return ReturnDesc;
}
void ControlErrors::mAlert(string message="")
{
if (_AlertInfo == true)
{
if (message == "")
{
if (mGetError() > 0)
{
Alert("Error ",mGetError()," - ",mGetDesc());
}
}
else
{
Alert(message);
}
}
}
void ControlErrors::mPrint(string message="")
{
if (_PrintInfo == true)
{
if (message == "")
{
if (mGetError() > 0)
{
Print("Error ",mGetError()," - ",mGetDesc());
}
}
else
{
Print(message);
}
}
}
void ControlErrors::mSound(void)
{
if (_PlaySound == true)
{
PlaySound(_PlaySoundFile);
}
}
int ControlErrors::Check(string st="")
{
int errNum = 0;
errNum = mGetLastError();
mFileWrite();
mAlert(st);
mPrint(st);
mSound();
mResetError();
mResetLastError();
mResetUserError();
return errNum;
}
int ControlErrors::mFileWrite(string message = "")
{
int handle = 0,
_return = 0;
datetime time = TimeCurrent();
string text = (message != "")?message:time+" - Error "+mGetError()+" "+mGetDesc();
if (_WriteFile == true)
{
handle = FileOpen(_DataPath,FILE_READ|FILE_WRITE|FILE_TXT|FILE_ANSI);
if (handle != INVALID_HANDLE)
{
ulong size = FileSize(handle);
FileSeek(handle,size,SEEK_SET);
_return = FileWrite(handle,text);
FileClose(handle);
}
}
return _return;
}
+342
View File
@@ -0,0 +1,342 @@
//+------------------------------------------------------------------+
//| JsonAPIIndicator.mq5 |
//| Copyright 2020, Gunther Schulz |
//| https://www.guntherschulz.de |
//+------------------------------------------------------------------+
#property copyright "2020 Gunther Schulz"
#property link "https://www.guntherschulz.de"
#property version "1.00"
#include <StringToEnumInt.mqh>
#include <Zmq/Zmq.mqh>
#include <Json.mqh>
// Set ports and host for ZeroMQ
string HOST="localhost";
int CHART_SUB_PORT=15562;
// ZeroMQ Cnnections
Context context("MQL5 JSON API");
Socket chartSubscriptionSocket(context,ZMQ_SUB);
//--- input parameters
#property indicator_buffers 21
#property indicator_plots 20
#property indicator_label1 "JsonAPI"
#property indicator_type1 DRAW_NONE
#property indicator_type2 DRAW_NONE
#property indicator_type3 DRAW_NONE
//#property indicator_color3 CLR_NONE
#property indicator_type4 DRAW_NONE
#property indicator_type5 DRAW_NONE
input string IndicatorId="";
input string ShortName="JsonAPI";
//--- indicator settings
double B0[], B1[], B2[], B3[], B4[], B5[], B6[], B7[], B8[], B9[], B10[], B11[], B12[], B13[], B14[], B15[], B16[], B17[], B18[], B19[], alive[];
bool debug = true;
bool first = false;
int activeBufferCount = 0;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// TODO subscribe only to own IndicatorId topic
// Subscribe to all topics
chartSubscriptionSocket.setSubscribe("");
chartSubscriptionSocket.setLinger(1000);
// Number of messages to buffer in RAM.
chartSubscriptionSocket.setReceiveHighWaterMark(1000); // TODO confirm settings
bool result = chartSubscriptionSocket.connect(StringFormat("tcp://%s:%d", HOST, CHART_SUB_PORT));
if(result == false)
{
Print("Failed to subscrbe on port ", CHART_SUB_PORT);
}
else
{
Print("Accepting Chart Indicator data on port ", CHART_SUB_PORT);
}
//--- indicator buffers mapping;
ArraySetAsSeries(B0,true);
ArraySetAsSeries(B1,true);
ArraySetAsSeries(B2,true);
ArraySetAsSeries(B3,true);
ArraySetAsSeries(B4,true);
ArraySetAsSeries(B5,true);
ArraySetAsSeries(B6,true);
ArraySetAsSeries(B7,true);
ArraySetAsSeries(B8,true);
ArraySetAsSeries(B9,true);
ArraySetAsSeries(B10,true);
ArraySetAsSeries(B11,true);
ArraySetAsSeries(B12,true);
ArraySetAsSeries(B13,true);
ArraySetAsSeries(B14,true);
ArraySetAsSeries(B15,true);
ArraySetAsSeries(B16,true);
ArraySetAsSeries(B17,true);
ArraySetAsSeries(B18,true);
ArraySetAsSeries(B19,true);
ArraySetAsSeries(alive,true);
SetIndexBuffer(0,B0,INDICATOR_DATA);
SetIndexBuffer(1,B1,INDICATOR_DATA);
SetIndexBuffer(2,B2,INDICATOR_DATA);
SetIndexBuffer(3,B3,INDICATOR_DATA);
SetIndexBuffer(4,B4,INDICATOR_DATA);
SetIndexBuffer(5,B5,INDICATOR_DATA);
SetIndexBuffer(6,B6,INDICATOR_DATA);
SetIndexBuffer(7,B7,INDICATOR_DATA);
SetIndexBuffer(8,B8,INDICATOR_DATA);
SetIndexBuffer(9,B9,INDICATOR_DATA);
SetIndexBuffer(10,B10,INDICATOR_DATA);
SetIndexBuffer(11,B11,INDICATOR_DATA);
SetIndexBuffer(12,B12,INDICATOR_DATA);
SetIndexBuffer(13,B13,INDICATOR_DATA);
SetIndexBuffer(14,B14,INDICATOR_DATA);
SetIndexBuffer(15,B15,INDICATOR_DATA);
SetIndexBuffer(16,B16,INDICATOR_DATA);
SetIndexBuffer(17,B17,INDICATOR_DATA);
SetIndexBuffer(18,B18,INDICATOR_DATA);
SetIndexBuffer(19,B19,INDICATOR_DATA);
SetIndexBuffer(20,alive,INDICATOR_CALCULATIONS); // If the buffer index changes, the line starting with "CopyBuffer(chartWindowIndicators[i].indicatorHandle," in JsonAPI.mq5 has to be updated
//---
IndicatorSetString(INDICATOR_SHORTNAME,ShortName);
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void SetStyle(int bufferIdx, string linelabel, color colorstyle, int linetype, int linestyle, int linewidth)
{
PlotIndexSetString(bufferIdx,PLOT_LABEL,linelabel);
PlotIndexSetInteger(bufferIdx,PLOT_LINE_COLOR,0,colorstyle);
PlotIndexSetInteger(bufferIdx,PLOT_DRAW_TYPE,linetype);
PlotIndexSetInteger(bufferIdx,PLOT_LINE_STYLE,linestyle);
PlotIndexSetInteger(bufferIdx,PLOT_LINE_WIDTH,linewidth);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate(const int rates_total,
const int prev_calculated,
const datetime &time[],
const double &open[],
const double &high[],
const double &low[],
const double &close[],
const long &tick_volume[],
const long &volume[],
const int &spread[])
{
// While a new candle is forming, set the current value to be empty
if(rates_total>prev_calculated)
{
B0[0] = EMPTY_VALUE;
B1[0] = EMPTY_VALUE;
B2[0] = EMPTY_VALUE;
B3[0] = EMPTY_VALUE;
B4[0] = EMPTY_VALUE;
B5[0] = EMPTY_VALUE;
B6[0] = EMPTY_VALUE;
B7[0] = EMPTY_VALUE;
B8[0] = EMPTY_VALUE;
B9[0] = EMPTY_VALUE;
B10[0] = EMPTY_VALUE;
B11[0] = EMPTY_VALUE;
B12[0] = EMPTY_VALUE;
B13[0] = EMPTY_VALUE;
B14[0] = EMPTY_VALUE;
B15[0] = EMPTY_VALUE;
B16[0] = EMPTY_VALUE;
B17[0] = EMPTY_VALUE;
B18[0] = EMPTY_VALUE;
B19[0] = EMPTY_VALUE;
}
if(first==false)
alive[0] = 1;
// ChartRedraw(0);
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
//| |
//+------------------------------------------------------------------+
void SubscriptionHandler(ZmqMsg &chartMsg)
{
CJAVal message;
// Get data from request
string msg=chartMsg.getData();
if(debug)
Print("Processing:"+msg);
// Deserialize msg to CJAVal array
if(!message.Deserialize(msg))
{
Alert("Deserialization Error");
ExpertRemove();
}
if(message["indicatorChartId"]==IndicatorId)
{
if(message["action"]=="PLOT" && message["actionType"]=="DATA")
{
int bufferIdx = message["indicatorBufferId"].ToInt();
if(bufferIdx == 0)
WriteToBuffer(message, B0);
if(bufferIdx == 1)
WriteToBuffer(message, B1);
if(bufferIdx == 2)
WriteToBuffer(message, B2);
if(bufferIdx == 3)
WriteToBuffer(message, B3);
if(bufferIdx == 4)
WriteToBuffer(message, B4);
if(bufferIdx == 5)
WriteToBuffer(message, B5);
if(bufferIdx == 6)
WriteToBuffer(message, B6);
if(bufferIdx == 7)
WriteToBuffer(message, B7);
if(bufferIdx == 8)
WriteToBuffer(message, B8);
if(bufferIdx == 9)
WriteToBuffer(message, B9);
if(bufferIdx == 10)
WriteToBuffer(message, B10);
if(bufferIdx == 11)
WriteToBuffer(message, B11);
if(bufferIdx == 12)
WriteToBuffer(message, B12);
if(bufferIdx == 13)
WriteToBuffer(message, B13);
if(bufferIdx == 14)
WriteToBuffer(message, B14);
if(bufferIdx == 15)
WriteToBuffer(message, B15);
if(bufferIdx == 16)
WriteToBuffer(message, B16);
if(bufferIdx == 17)
WriteToBuffer(message, B17);
if(bufferIdx == 18)
WriteToBuffer(message, B18);
if(bufferIdx == 19)
WriteToBuffer(message, B19);
}
else
if(message["action"]=="PLOT" && message["actionType"]=="ADDBUFFER")
{
string linelabel = message["style"]["linelabel"].ToStr();
string colorstyleStr = message["style"]["color"].ToStr();
string linetypeStr = message["style"]["linetype"].ToStr();
string linestyleStr = message["style"]["linestyle"].ToStr();
int linewidth = message["style"]["linewidth"].ToInt();
color colorstyle = StringToColor(colorstyleStr);
int linetype = StringToEnumInt(linetypeStr);
int linestyle = StringToEnumInt(linestyleStr);
/*
//if (aa == false) {
Print("SETBUFF ActCount ",activeBufferCount);
if (activeBufferCount == 0) {SetIndexBuffer(0,B1,INDICATOR_DATA);} // Two semicolons ar required! No idea why. Seems to be a timing problem, better to keep it in init()
if (activeBufferCount == 1) {SetIndexBuffer(1,B2,INDICATOR_DATA);;}
if (activeBufferCount == 2) {SetIndexBuffer(2,B3,INDICATOR_DATA);;}
if (activeBufferCount == 3) {SetIndexBuffer(3,B4,INDICATOR_DATA);;}
if (activeBufferCount == 4) {SetIndexBuffer(4,B5,INDICATOR_DATA);;}
//aa = true;}
*/
SetStyle(activeBufferCount, linelabel, colorstyle, linetype, linestyle, linewidth);
activeBufferCount = activeBufferCount + 1;
}
}
}
//+------------------------------------------------------------------+
//| Update indicator buffer function |
//+------------------------------------------------------------------+
void WriteToBuffer(CJAVal &message, double &buffer[])
{
int bufferSize = ArraySize(buffer);
int messageDataSize = message["data"].Size();
// TODO check if this is working as expected. Seems to
if(first==false)
{
for(int i=0; i<activeBufferCount; i++)
{
//Print("BUFF ",bufferSize-messageDataSize, " ",ArraySize(B2)," ", ArraySize(B3), " ",messageDataSize);
PlotIndexSetInteger(i,PLOT_DRAW_BEGIN,bufferSize-messageDataSize);
}
first = true;
}
for(int i=0; i<messageDataSize; i++)
{
// don't add more elements than the automatically sized buffer array can hold
if(i+1<bufferSize)
{
// the first element is the current unformed candle, so we start at index 1
// we reverse the order of the incoming values, which are expected to be ascending
//buffer[i+1] = message["data"][messageDataSize-1-i].ToDbl();
buffer[i+1] = message["data"][messageDataSize-1-i].ToDbl();
}
}
// Set the most recent plotted value to nothing, as we do not have any data for yet unformed candles
buffer[0] = EMPTY_VALUE;
}
//+------------------------------------------------------------------+
//| Check for new indicator data function |
//+------------------------------------------------------------------+
void CheckMessages()
{
// This is a workaround for Timer(). It is needed, because OnTimer() works if the indicator is manually added to a chart, but not with ChartIndicatorAdd()
ZmqMsg chartMsg;
// Recieve chart instructions stream from client via live Chart socket.
chartSubscriptionSocket.recv(chartMsg,true);
// Request recieved
if(chartMsg.size()>0)
{
// Handle subscription SubscriptionHandler()
SubscriptionHandler(chartMsg);
ChartRedraw(ChartID());
}
}
//+------------------------------------------------------------------+
//| OnTimer() workaround function |
//+------------------------------------------------------------------+
// Gets triggered by the OnTimer() function of the JsonAPI Expert script
void OnChartEvent(const int id,
const long &lparam,
const double &dparam,
const string &sparam)
{
if(id==CHARTEVENT_CUSTOM+222)
CheckMessages();
}
//+----------------------------------------------------
+618 -376
View File
@@ -1,376 +1,618 @@
# Metaquotes MQL5 - JSON - API
### Development state: first stable release
Tested on macOS Mojave / Windows 10 in Parallels Desktop container.
Working in production on Debian 10 / Wine 4.
An issue was found because of REP/REQ socket. Architecture changes are in development.
## Table of Contents
* [About the Project](#about-the-project)
* [Installation](#installation)
* [Documentation](#documentation)
* [Usage](#usage)
* [Live data and streaming events](#live-data-and-streaming-events)
* [Error handling](#error-handling)
* [License](#license)
## About the Project
This project was developed to work as a server for the Backtrader Python trading framework. It is based on ZeroMQ sockets and uses JSON format to communicate. But now it has grown to the independent project. You can use it with any programming language that has [ZeroMQ binding](http://zeromq.org/bindings:_start).
Backtrader Python client is located here: [Python Backtrader - Metaquotes MQL5 ](https://github.com/khramkov/Backtrader-MQL5-API)
In development:
* Devitation
* Stop limit orders
## Installation
1. Install ZeroMQ for MQL5 [https://github.com/dingmaotu/mql-zmq](https://github.com/dingmaotu/mql-zmq)
2. Put `include/Json.mqh` from this repo to your MetaEditor `include` directoty.
3. Download and compile `experts/JsonAPI.mq5` script.
4. Check if Metatrader 5 automatic trading is allowed.
5. Attach the script to a chart in Metatrader 5.
6. Allow DLL import in dialog window.
7. Check if the ports are free to use. (default:`15555`,`15556`, `15557`,`15558`)
## Documentation
The script uses four ZeroMQ sockets:
1. `System socket` - recives requests from client and replies 'OK'
2. `Data socket` - pushes data to client depending on the request via System socket.
3. `Live socket` - automatically pushes last candle when it closes.
4. `Streaming socket` - automatically pushes last transaction info every time it happens.
The idea is to send requests via `System socket` and recieve results/errors via `Data socket`. Event handlers should be created for `Live socket` and `Streaming socket` because the server sends data to theese sockets automatically. See examples in [Live data and streaming events](#live-data-and-streaming-events) section.
`System socket` request uses default JSON dictionary:
```
{
"action": null,
"actionType": null,
"symbol": null,
"chartTF": null,
"fromDate": null,
"toDate": null,
"id": null,
"magic": null,
"volume": null,
"price": null,
"stoploss": null,
"takeprofit": null,
"expiration": null,
"deviation": null,
"comment": null
}
```
Check out the available combinations of `action` and `actionType`:
action | actionType | Description |
-----------|----------------------|----------------------------|
CONFIG | null | Set script configuration |
ACCOUNT | null | Get account settings |
BALANCE | null | Get current balance |
POSITIONS | null | Get current open positions |
ORDERS | null | Get current open orders |
HISTORY | DATA | Get data history |
HISTORY | TRADES | Get trades history |
TRADE | ORDER_TYPE_BUY | Buy market |
TRADE | ORDER_TYPE_SELL | Sell market |
TRADE | ORDER_TYPE_BUY_LIMIT | Buy limit |
TRADE | ORDER_TYPE_SELL_LIMIT| Sell limit |
TRADE | ORDER_TYPE_BUY_STOP | Buy stop |
TRADE | ORDER_TYPE_SELL_STOP | Sell stop |
TRADE | POSITION_MODIFY | Position modify |
TRADE | POSITION_PARTIAL | Position close partial |
TRADE | POSITION_CLOSE_ID | Position close by id |
TRADE | POSITION_CLOSE_SYMBOL| Positions close by symbol |
TRADE | ORDER_MODIFY | Order modify |
TRADE | ORDER_CANCEL | Order cancel |
Python 3 API class example:
``` python
import zmq
class MTraderAPI:
def __init__(self, host=None):
self.HOST = host or 'localhost'
self.SYS_PORT = 15555 # REP/REQ port
self.DATA_PORT = 15556 # PUSH/PULL port
self.LIVE_PORT = 15557 # PUSH/PULL port
self.EVENTS_PORT = 15558 # PUSH/PULL port
# ZeroMQ timeout in seconds
sys_timeout = 1
data_timeout = 10
# initialise ZMQ context
context = zmq.Context()
# connect to server sockets
try:
self.sys_socket = context.socket(zmq.REQ)
# set port timeout
self.sys_socket.RCVTIMEO = sys_timeout * 1000
self.sys_socket.connect('tcp://{}:{}'.format(self.HOST, self.SYS_PORT))
self.data_socket = context.socket(zmq.PULL)
# set port timeout
self.data_socket.RCVTIMEO = data_timeout * 1000
self.data_socket.connect('tcp://{}:{}'.format(self.HOST, self.DATA_PORT))
except zmq.ZMQError:
raise zmq.ZMQBindError("Binding ports ERROR")
def _send_request(self, data: dict) -> None:
"""Send request to server via ZeroMQ System socket"""
try:
self.sys_socket.send_json(data)
msg = self.sys_socket.recv_string()
# terminal received the request
assert msg == 'OK', 'Something wrong on server side'
except AssertionError as err:
raise zmq.NotDone(err)
except zmq.ZMQError:
raise zmq.NotDone("Sending request ERROR")
def _pull_reply(self):
"""Get reply from server via Data socket with timeout"""
try:
msg = self.data_socket.recv_json()
except zmq.ZMQError:
raise zmq.NotDone('Data socket timeout ERROR')
return msg
def live_socket(self, context=None):
"""Connect to socket in a ZMQ context"""
try:
context = context or zmq.Context.instance()
socket = context.socket(zmq.PULL)
socket.connect('tcp://{}:{}'.format(self.HOST, self.LIVE_PORT))
except zmq.ZMQError:
raise zmq.ZMQBindError("Live port connection ERROR")
return socket
def streaming_socket(self, context=None):
"""Connect to socket in a ZMQ context"""
try:
context = context or zmq.Context.instance()
socket = context.socket(zmq.PULL)
socket.connect('tcp://{}:{}'.format(self.HOST, self.EVENTS_PORT))
except zmq.ZMQError:
raise zmq.ZMQBindError("Data port connection ERROR")
return socket
def construct_and_send(self, **kwargs) -> dict:
"""Construct a request dictionary from default and send it to server"""
# default dictionary
request = {
"action": None,
"actionType": None,
"symbol": None,
"chartTF": None,
"fromDate": None,
"toDate": None,
"id": None,
"magic": None,
"volume": None,
"price": None,
"stoploss": None,
"takeprofit": None,
"expiration": None,
"deviation": None,
"comment": None
}
# update dict values if exist
for key, value in kwargs.items():
if key in request:
request[key] = value
else:
raise KeyError('Unknown key in **kwargs ERROR')
# send dict to server
self._send_request(request)
# return server reply
return self._pull_reply()
```
## Usage
All examples will be on Python 3. Lets create an instance of MetaTrader API class:
``` python
api = MTraderAPI()
```
First of all we should configure the script `symbol` and `timeframe`. Live data stream will be configured to the seme params.
``` python
rep = api.construct_and_send(action="CONFIG", symbol="EURUSD", chartTF="M5")
print(rep)
```
Get information about the trading account.
``` python
rep = api.construct_and_send(action="ACCOUNT")
print(rep)
```
Get historical data. `fromDate` should be in timestamp format. The data will be loaded to the last candle if `toDate` is `None`. Notice, that the script sends the last unclosed candle too. You should delete it manually.
There are some issues:
- MetaTrader keeps historical data in cache. But when you make a request for the first time, MetaTrader downloads the data from a broker. This operation can exceed `Data socket` timeout. It depends on your broker. Second request will be handeled quickly.
- It takes 6-7 seconds to process `50000` M1 candles. It was tested on Windows 10 in Parallels Desktop container with 4 cores and 4GB RAM. So if you need more data there are three ways to handle it. 1) Increase `Data socket` timeout. 2) You can load data partially using `fromDate` and `toDate`. 3) You can use more powerfull hardware.
``` python
rep = api.construct_and_send(action="HISTORY", actionType="DATA", symbol="EURUSD", chartTF="M5", fromDate=1555555555)
print(rep)
```
History data reply example:
```
{'data': [[1560782340, 1.12271, 1.12288, 1.12269, 1.12277, 46.0],[1560782400, 1.12278, 1.12299, 1.12276, 1.12297, 43.0],[1560782460, 1.12296, 1.12302, 1.12293, 1.123, 23.0]]}
```
Buy market order.
``` python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_BUY", symbol="EURUSD", "volume"=0.1, "stoploss"=1.1, "takeprofit"=1.3)
print(rep)
```
Sell limit order. Remember to switch SL/TP depending on BUY/SELL, or you will get `invalid stops` error.
- BUY: SL < price < TP
- SELL: SL > price > TP
``` python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_SELL_LIMIT", symbol="EURUSD", "volume"=0.1, "price"=1.2, "stoploss"=1.3, "takeprofit"=1.1)
print(rep)
```
All pending orders are set to `Good till cancel` by default. If you want to set an expiration date, pass the date in timestamp format to `expiration` param.
``` python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_SELL_LIMIT", symbol="EURUSD", "volume"=0.1, "price"=1.2, "expiration"=1560782460)
print(rep)
```
## Live data and streaming events
Event handler example for `Live socket` and `Data socket`.
``` python
import zmq
import threading
api = MTraderAPI()
def _t_livedata():
socket = api.live_socket()
while True:
try:
last_candle = socket.recv_json()
except zmq.ZMQError:
raise zmq.NotDone("Live data ERROR")
print(last_candle)
def _t_streaming_events():
socket = api.streaming_socket()
while True:
try:
trans = socket.recv_json()
request, reply = trans.values()
except zmq.ZMQError:
raise zmq.NotDone("Streaming data ERROR")
print(request)
print(reply)
t = threading.Thread(target=_t_livedata, daemon=True)
t.start()
t = threading.Thread(target=_t_streaming_events, daemon=True)
t.start()
while True:
pass
```
There are only two variants of `Live socket` data. When everything is ok, the script sends data on candle close:
```
{"status":"CONNECTED","data":[1560780120,1.12186,1.12194,1.12186,1.12191,15.00000]}
```
If the terminal has lost connection to the market:
```
{"status":"DISCONNECTED"}
```
When the terminal reconnects to the market, it sends the last closed candle again. So you should update your historical data. Make the `action="HISTORY"` request with `fromDate` equal to your last candle timestamp before disconnect.
`OnTradeTransaction` function is called when a trade transaction event occurs. `Streaming socket` sends `TRADE_TRANSACTION_REQUEST` data every time it happens. Try to create and modify orders in the MQL5 terminal manually and check the expert logging tab for better understanding. Also see [MQL5 docs](https://www.mql5.com/en/docs/event_handlers/ontradetransaction).
`TRADE_TRANSACTION_REQUEST` request data:
```
{
'action': 'TRADE_ACTION_DEAL',
'order': 501700843,
'symbol': 'EURUSD',
'volume': 0.1,
'price': 1.12181,
'stoplimit': 0.0,
'sl': 1.1,
'tp': 1.13,
'deviation': 10,
'type': 'ORDER_TYPE_BUY',
'type_filling': 'ORDER_FILLING_FOK',
'type_time': 'ORDER_TIME_GTC',
'expiration': 0,
'comment': None,
'position': 0,
'position_by': 0
}
```
`TRADE_TRANSACTION_REQUEST` result data:
```
{
'retcode': 10009,
'result': 'TRADE_RETCODE_DONE',
'deal': 501700843,
'order': 501700843,
'volume': 0.1,
'price': 1.12181,
'comment': None,
'request_id': 8,
'retcode_external': 0
}
```
## Error handling
First of all, when you send a command via `System socket`, you should always receive back `"OK"` message via `System socket`. It means that your command was received and deserialized.
All data that come through `Data socket` have an `error` param. This param will have `true` key if somethng goes wrong. Also, there will be `description` and `function` params. They will hold information about error and the name of the function with error.
This information also applies to the trade commannds. See [MQL5 docs](https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes) for possible server answers.
## License
This program 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 `LICENSE` for more information.
# Metaquotes MQL5 - JSON - API
### Development state: stable release version 2.0
Tested on macOS Mojave / Windows 10 in Parallels Desktop container.
Tested on Manjaro Linux / Windows 10 in VirtualBox
Working in production on Debian 10 / Wine 4.
## Table of Contents
- [About the Project](#about-the-project)
- [Installation](#installation)
- [Documentation](#documentation)
- [Usage](#usage)
- [Live data and streaming events](#live-data-and-streaming-events)
- [Streaming MT5 indicator data](#streaming-mt5-indicator-data)
- [Plot values to MT5 charts](#plot-values-to-mt5-charts)
- [The JsonAPIIndicator](#the-jsonapiindicator)
- [Error handling](#error-handling)
- [License](#license)
## About the Project
This project was developed to work as a server for the Backtrader Python trading framework. It is based on ZeroMQ sockets and uses JSON format to communicate. But now it has grown to the independent project. You can use it with any programming language that has [ZeroMQ binding](http://zeromq.org/bindings:_start).
Backtrader Python client is located here: [Python Backtrader - Metaquotes MQL5 ](https://github.com/khramkov/Backtrader-MQL5-API)
Thanks to the participation of [Gunther Schulz](https://github.com/Gunther-Schulz), the project moved to a new level.
New features:
- Support for multiple datastreams in parallel for any combination of symbols and timeframes independently of the timeframe and symbol of the attached chart
- Support for tick data
- Support for direct download as CSV files
- Automatic retry binding to sockets. When running under Wine in Linux, sockets will be blocked for 60 seconds if closed uncleanly. This can happen if the client is still connected while the EA gets reloaded.
- Skip re-initialization on chart timeframe change
- Support for spread data (ask/bid)
- Support for plotting to charts in MT5 by streaming values from the client
- Support for processing client data with MT5 indicators
In development:
- Devitation
- Stop limit orders
- Drawing of chart objects
## Installation
1. Install ZeroMQ for MQL5 [https://github.com/dingmaotu/mql-zmq](https://github.com/dingmaotu/mql-zmq)
2. Put the following files from this repo to your MetaEditor Iinclude` directory
- `Include/Json.mqh`
- `Include/controlerrors.mqh`
- `Include/StringToEnumInt.mqh`
3. Put the `Indicators/JsonAPIIndicator.mq5` file from this repo to your MetaEditor `Indicators` directory
4. Download and compile `experts/JsonAPI.mq5` script.
5. Check if Metatrader 5 automatic trading is allowed.
6. Attach the `JsonAPI.mq5` script to a chart in Metatrader 5.
7. Allow DLL import in dialog window.
8. Check if the ports are free to use. (default:`15555`,`15556`, `15557`,`15558`, `15559`, `15560`,`15562`)
## Documentation
The script uses seven ZeroMQ sockets:
1. `System socket` - Recives requests from client and replies 'OK'.
2. `Data socket` - Pushes data to client depending on the request via System socket.
3. `Live socket` - Automatically pushes last candle when it closes.
4. `Streaming socket` - Automatically pushes last transaction info every time it happens.
5. `Indicator data socket` - automatically pushes indicator result values to the client.
6. `Chart Data Socket` - Recieves values to be plotted to a specific chart.
7. `Chart Indicator Socket` - Only for internal communication. Passes values to be plotted TO the supplied JsonAPIIndicator indicator
The idea is to send requests via `System socket` and recieve results/errors via `Data socket`. Event handlers should be created for `Live socket` and `Streaming socket` because the server sends data to theese sockets automatically. See examples in [Live data and streaming events](#live-data-and-streaming-events) section.
`System socket` request uses default JSON dictionary:
```
{
"action": null,
"actionType": null,
"symbol": null,
"chartTF": null,
"fromDate": null,
"toDate": null,
"id": null,
"magic": null,
"volume": null,
"price": null,
"stoploss": null,
"takeprofit": null,
"expiration": null,
"deviation": null,
"comment": null,
"chartId": None,
"indicatorChartId": None,
"chartIndicatorSubWindow": None,
"style": None,
}
```
Check out the available combinations of `action` and `actionType`:
| action | actionType | Description |
| --------- | --------------------- | --------------------------------- |
| CONFIG | null | Set script configuration |
| RESET | null | Reset subscribed symbols |
| ACCOUNT | null | Get account settings |
| BALANCE | null | Get current balance |
| POSITIONS | null | Get current open positions |
| ORDERS | null | Get current open orders |
| INDICATOR | ATTACH | Attach an indicator and return ID |
| INDICATOR | REQUEST | Get indicator data |
| CHART | OPEN | Open a new chart window |
| CHART | ADDINDICATOR | Attach JsonAPIIndicator indicator |
| HISTORY | DATA | Get data history |
| HISTORY | TRADES | Get trades history |
| HISTORY | WRITE | Download history data as CSV |
| TRADE | ORDER_TYPE_BUY | Buy market |
| TRADE | ORDER_TYPE_SELL | Sell market |
| TRADE | ORDER_TYPE_BUY_LIMIT | Buy limit |
| TRADE | ORDER_TYPE_SELL_LIMIT | Sell limit |
| TRADE | ORDER_TYPE_BUY_STOP | Buy stop |
| TRADE | ORDER_TYPE_SELL_STOP | Sell stop |
| TRADE | POSITION_MODIFY | Position modify |
| TRADE | POSITION_PARTIAL | Position close partial |
| TRADE | POSITION_CLOSE_ID | Position close by id |
| TRADE | POSITION_CLOSE_SYMBOL | Positions close by symbol |
| TRADE | ORDER_MODIFY | Order modify |
| TRADE | ORDER_CANCEL | Order cancel |
Python 3 API class example:
```python
import zmq
class MTraderAPI:
def __init__(self, host=None):
self.HOST = host or 'localhost'
self.SYS_PORT = 15555 # REP/REQ port
self.DATA_PORT = 15556 # PUSH/PULL port
self.LIVE_PORT = 15557 # PUSH/PULL port
self.EVENTS_PORT = 15558 # PUSH/PULL port
self.INDICATOR_DATA_PORT = 15559 # REP/REQ port
self.CHART_DATA_PORT = 15560 # PUSH port
# ZeroMQ timeout in seconds
sys_timeout = 1
data_timeout = 10
# initialise ZMQ context
context = zmq.Context()
# connect to server sockets
try:
self.sys_socket = context.socket(zmq.REQ)
# set port timeout
self.sys_socket.RCVTIMEO = sys_timeout * 1000
self.sys_socket.connect('tcp://{}:{}'.format(self.HOST, self.SYS_PORT))
self.data_socket = context.socket(zmq.PULL)
# set port timeout
self.data_socket.RCVTIMEO = data_timeout * 1000
self.data_socket.connect('tcp://{}:{}'.format(self.HOST, self.DATA_PORT))
self.indicator_data_socket = context.socket(zmq.PULL)
# set port timeout
self.indicator_data_socket.RCVTIMEO = data_timeout * 1000
self.indicator_data_socket.connect(
"tcp://{}:{}".format(self.HOST, self.INDICATOR_DATA_PORT)
)
self.chart_data_socket = context.socket(zmq.PUSH)
# set port timeout
# TODO check if port is listening and error handling
self.chart_data_socket.connect(
"tcp://{}:{}".format(self.HOST, self.CHART_DATA_PORT)
)
except zmq.ZMQError:
raise zmq.ZMQBindError("Binding ports ERROR")
def _send_request(self, data: dict) -> None:
"""Send request to server via ZeroMQ System socket"""
try:
self.sys_socket.send_json(data)
msg = self.sys_socket.recv_string()
# terminal received the request
assert msg == 'OK', 'Something wrong on server side'
except AssertionError as err:
raise zmq.NotDone(err)
except zmq.ZMQError:
raise zmq.NotDone("Sending request ERROR")
def _pull_reply(self):
"""Get reply from server via Data socket with timeout"""
try:
msg = self.data_socket.recv_json()
except zmq.ZMQError:
raise zmq.NotDone('Data socket timeout ERROR')
return msg
def _indicator_pull_reply(self):
"""Get reply from server via Data socket with timeout"""
try:
msg = self.indicator_data_socket.recv_json()
except zmq.ZMQError:
raise zmq.NotDone("Indicator Data socket timeout ERROR")
if self.debug:
print("ZMQ INDICATOR DATA REPLY: ", msg)
return msg
def live_socket(self, context=None):
"""Connect to socket in a ZMQ context"""
try:
context = context or zmq.Context.instance()
socket = context.socket(zmq.PULL)
socket.connect('tcp://{}:{}'.format(self.HOST, self.LIVE_PORT))
except zmq.ZMQError:
raise zmq.ZMQBindError("Live port connection ERROR")
return socket
def streaming_socket(self, context=None):
"""Connect to socket in a ZMQ context"""
try:
context = context or zmq.Context.instance()
socket = context.socket(zmq.PULL)
socket.connect('tcp://{}:{}'.format(self.HOST, self.EVENTS_PORT))
except zmq.ZMQError:
raise zmq.ZMQBindError("Data port connection ERROR")
return socket
def _push_chart_data(self, data: dict) -> None:
"""Send message for chart control to server via ZeroMQ chart data socket"""
try:
if self.debug:
print("ZMQ PUSH CHART DATA: ", data, " -> ", data)
self.chart_data_socket.send_json(data)
except zmq.ZMQError:
raise zmq.NotDone("Sending request ERROR")
def construct_and_send(self, **kwargs) -> dict:
"""Construct a request dictionary from default and send it to server"""
# default dictionary
request = {
"action": None,
"actionType": None,
"symbol": None,
"chartTF": None,
"fromDate": None,
"toDate": None,
"id": None,
"magic": None,
"volume": None,
"price": None,
"stoploss": None,
"takeprofit": None,
"expiration": None,
"deviation": None,
"comment": None,
"chartId": None,
"indicatorChartId": None,
"chartIndicatorSubWindow": None,
"style": None,
}
# update dict values if exist
for key, value in kwargs.items():
if key in request:
request[key] = value
else:
raise KeyError('Unknown key in **kwargs ERROR')
# send dict to server
self._send_request(request)
# return server reply
return self._pull_reply()
def indicator_construct_and_send(self, **kwargs) -> dict:
"""Construct a request dictionary from default and send it to server"""
# default dictionary
request = {
"action": None,
"actionType": None,
"id": None,
"symbol": None,
"chartTF": None,
"fromDate": None,
"toDate": None,
"name": None,
"params": None,
"linecount": None,
}
# update dict values if exist
for key, value in kwargs.items():
if key in request:
request[key] = value
else:
raise KeyError("Unknown key in **kwargs ERROR")
# send dict to server
self._send_request(request)
# return server reply
return self._indicator_pull_reply()
def chart_data_construct_and_send(self, **kwargs) -> dict:
"""Construct a request dictionary from default and send it to server"""
# default dictionary
message = {
"action": None,
"actionType": None,
"chartId": None,
"indicatorChartId": None,
"data": None,
}
# update dict values if exist
for key, value in kwargs.items():
if key in message:
message[key] = value
else:
raise KeyError("Unknown key in **kwargs ERROR")
# send dict to server
self._push_chart_data(message)
```
## Usage
All examples will be on Python 3. Lets create an instance of MetaTrader API class:
```python
api = MTraderAPI()
```
First of all we should configure the script `symbol` and `timeframe`. Live data stream will be configured to the same params. You can use any number of `symbols` and `timeframes`. The server subscribes to these sembols and will transmit them through the `Live data` socket
```python
print(api.construct_and_send(action="CONFIG", symbol="EURUSD", chartTF="M5"))
print(api.construct_and_send(action="CONFIG", symbol="AUDUSD", chartTF="M1"))
...
```
There is also `tick` data. You can subscribe for `tick` and `candle` data at the same `symbol`.
```python
print(api.construct_and_send(action="CONFIG", symbol="EURUSD", chartTF="TICK"))
print(api.construct_and_send(action="CONFIG", symbol="EURUSD", chartTF="M1"))
```
If you want to stop `Live data`, you should reset server subscriptions.
```python
rep = api.construct_and_send(action="RESET")
print(rep)
```
Get information about the trading account.
```python
rep = api.construct_and_send(action="ACCOUNT")
print(rep)
```
Get historical data. `fromDate` should be in timestamp format. The data will be loaded to the last candle if `toDate` is `None`. Notice, that the script sends the last unclosed candle too. You should delete it manually.
There are some issues:
- MetaTrader keeps historical data in cache. But when you make a request for the first time, MetaTrader downloads the data from a broker. This operation can exceed `Data socket` timeout. It depends on your broker. Second request will be handeled quickly.
- It takes 6-7 seconds to process `50000` M1 candles. It was tested on Windows 10 in Parallels Desktop container with 4 cores and 4GB RAM. So if you need more data there are three ways to handle it. 1) Increase `Data socket` timeout. 2) You can load data partially using `fromDate` and `toDate`. 3) You can use more powerfull hardware.
```python
rep = api.construct_and_send(action="HISTORY", actionType="DATA", symbol="EURUSD", chartTF="M5", fromDate=1555555555)
print(rep)
```
History data reply example:
```
{'data': [[1560782340, 1.12271, 1.12288, 1.12269, 1.12277, 46.0],[1560782400, 1.12278, 1.12299, 1.12276, 1.12297, 43.0],[1560782460, 1.12296, 1.12302, 1.12293, 1.123, 23.0]]}
```
Buy market order.
```python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_BUY", symbol="EURUSD", "volume"=0.1, "stoploss"=1.1, "takeprofit"=1.3)
print(rep)
```
Sell limit order. Remember to switch SL/TP depending on BUY/SELL, or you will get `invalid stops` error.
- BUY: SL < price < TP
- SELL: SL > price > TP
```python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_SELL_LIMIT", symbol="EURUSD", "volume"=0.1, "price"=1.2, "stoploss"=1.3, "takeprofit"=1.1)
print(rep)
```
All pending orders are set to `Good till cancel` by default. If you want to set an expiration date, pass the date in timestamp format to `expiration` param.
```python
rep = api.construct_and_send(action="TRADE", actionType="ORDER_TYPE_SELL_LIMIT", symbol="EURUSD", "volume"=0.1, "price"=1.2, "expiration"=1560782460)
print(rep)
```
## Live data and streaming events
Event handler example for `Live socket` and `Data socket`.
```python
import zmq
import threading
api = MTraderAPI()
def _t_livedata():
socket = api.live_socket()
while True:
try:
last_candle = socket.recv_json()
except zmq.ZMQError:
raise zmq.NotDone("Live data ERROR")
print(last_candle)
def _t_streaming_events():
socket = api.streaming_socket()
while True:
try:
trans = socket.recv_json()
request, reply = trans.values()
except zmq.ZMQError:
raise zmq.NotDone("Streaming data ERROR")
print(request)
print(reply)
t = threading.Thread(target=_t_livedata, daemon=True)
t.start()
t = threading.Thread(target=_t_streaming_events, daemon=True)
t.start()
while True:
pass
```
There are only two variants of `Live socket` data. When everything is ok, the script sends subscribed data on new even. You can divide streams by symbol and timeframe names:
```
{"status":"CONNECTED","symbol":"EURUSD","timeframe":"TICK","data":[1581611172734,1.08515,1.08521]}
{"status":"CONNECTED","symbol":"EURUSD","timeframe":"M1","data":[1581611100,1.08525,1.08525,1.08520,1.08520,10.00000]}
```
If the terminal has lost connection to the market:
```
{"status":"DISCONNECTED"}
```
When the terminal reconnects to the market, it sends the last closed candle again. So you should update your historical data. Make the `action="HISTORY"` request with `fromDate` equal to your last candle timestamp before disconnect.
`OnTradeTransaction` function is called when a trade transaction event occurs. `Streaming socket` sends `TRADE_TRANSACTION_REQUEST` data every time it happens. Try to create and modify orders in the MQL5 terminal manually and check the expert logging tab for better understanding. Also see [MQL5 docs](https://www.mql5.com/en/docs/event_handlers/ontradetransaction).
`TRADE_TRANSACTION_REQUEST` request data:
```
{
'action': 'TRADE_ACTION_DEAL',
'order': 501700843,
'symbol': 'EURUSD',
'volume': 0.1,
'price': 1.12181,
'stoplimit': 0.0,
'sl': 1.1,
'tp': 1.13,
'deviation': 10,
'type': 'ORDER_TYPE_BUY',
'type_filling': 'ORDER_FILLING_FOK',
'type_time': 'ORDER_TIME_GTC',
'expiration': 0,
'comment': None,
'position': 0,
'position_by': 0
}
```
`TRADE_TRANSACTION_REQUEST` result data:
```
{
'retcode': 10009,
'result': 'TRADE_RETCODE_DONE',
'deal': 501700843,
'order': 501700843,
'volume': 0.1,
'price': 1.12181,
'comment': None,
'request_id': 8,
'retcode_external': 0
}
```
## Streaming MT5 indicator data
Open a chart window and attach a MT5 indicator.
Parameters:
- `id` - a unique id string.
- `symbol` - chart symbol to open and atatch the indicator to.
- `chartTF` - timeframe to set the chart at.
- `name` - the name of the MT5 indicator to attach.
- `params` - the initialisation paramaters that the specified indicator expects.
- `linecount` - the number of buffers the indicator returns. In the example below MACD is used and it return the values for "macd" and "signal".
```python
print(api.indicator_construct_and_send(action='INDICATOR', actionType='ATTACH', id='4df306ea-e8e6-439b-8004-b86ba4bcc8c3', symbol='EURUSD', chartTF='M1', name='Examples/MACD', 'params'=['12', '26', '9', 'PRICE_CLOSE'], 'linecount'=2))
```
Stream the calculated result values of a previously attached indicator.
Parameters:
- `id` - id string of a previously attached indicator.
- `fromDate` - timestamp for which a result value is requested.
```python
print(api.indicator_construct_and_send(action='INDICATOR', actionType='REQUEST', id='4df306ea-e8e6-439b-8004-b86ba4bcc8c3', 'fromDate'=1591993860))
```
Example of the result:
```python
{'error': False, 'id': '4df306ea-e8e6-439b-8004-b86ba4bcc8c3', 'data': ['0.00008204', '0.00001132']}
```
The data field holds a list with results of the calculated indicator buffers.
## Plot values to MT5 charts
Open a new chart window to plot values to.
Parameters:
- `chartId` - a unique id string to reference the new chart window.
- `fromDate` - timestamp for which a result value is requested.
- `symbol` - chart symbol to open and atatch the indicator to.
- `chartTF` - timeframe to set the chart at.
```python
print(api.construct_and_send(action='CHART', actionType='OPEN', symbol='EURUSD', chartTF='M1', chartId='cbb82988-3193-4dda-9cea-c27faaf7835b'))
```
A common scenario would be to stream vlaues calculated by the client indictor to be plotted in MT5. This is done by attaching the supplied MT5 indicator `JsonAPIIndicator` and passing values to be plotted to it.
Initialize a plot line object by attaching a new instance of `JsonAPIIndicator`, ready to recieve values to be plotted.
Parameters:
- `chartId` - id string of a previously opened chart.
- `indicatorChartId`: a unique id string to reference the new plot line object.
- `chartIndicatorSubWindow`: chart sub window to plot to (https://www.mql5.c.om/en/docs/chart_operations/chartindicatoradd)
- `style`: style settings for the plot. `shortname` and `linelabel` can be any string value. `linewidth` expects an int. All other paramters require constants supported by MQL5.
Supported are the following style paramers (with the corresponding MQL5 constants in braces): `color` (PLOT_LINE_COLOR), `linetype` (PLOT_DRAW_TYPE), `linestyle` (PLOT_LINE_STYLE).
```python
print(api.construct_and_send(action='CHART', actionType='ADDINDICATOR', chartId='cbb82988-3193-4dda-9cea-c27faaf7835b', indicatorChartId='5f2c1ab5-6b36-498f-96ac-3982a4a3551a', chartIndicatorSubWindow=1, style={shortname='BT-BollingerBands', linelabel='Middle', color='clrYellow', linetype='DRAW_LINE', linestyle='STYLE_SOLID', linewidth=1))
```
Stream values to a plot line object (draw a line).
Parameters:
- `chartId` - id string of a previously opened chart.
- `indicatorChartId`: id string of a previously initialized plot line object.
- `data`: list of values to plot. The last value in a list (`values[-1]`) corresponds to the most recent candle. If the size of the list of values passsed is >= 1, and the number of historic candles to plot is `n` then `values[n-1]` is the most recent candle and `values[0]` is the oldest candle.
```python
# Plot line with historic data
values=[1.1225948211353751, 1.1226243406054506, 1.1226266123404378]
print(api.chart_data_construct_and_send(action='PLOT', chartId='cbb82988-3193-4dda-9cea-c27faaf7835b', indicatorChartId='5f2c1ab5-6b36-498f-96ac-3982a4a3551a', chartIndicatorSubWindow=1, data=values))
n=len(values)
print(f'The value for the oldest candle: {values[0]} - The value for the most recent candle: {values[n-1]}')
# Extend the plotted line with the most recent values as new candles are created
print(api.chart_data_construct_and_send(action='PLOT', chartId='cbb82988-3193-4dda-9cea-c27faaf7835b', indicatorChartId='5f2c1ab5-6b36-498f-96ac-3982a4a3551a', chartIndicatorSubWindow=1, data=[1.122618120966847]))
print(api.chart_data_construct_and_send(action='PLOT', chartId='cbb82988-3193-4dda-9cea-c27faaf7835b', indicatorChartId='5f2c1ab5-6b36-498f-96ac-3982a4a3551a', chartIndicatorSubWindow=1, data=[1.1226254106923093]))
```
## The JsonAPIIndicator
The supplied indicator `JsonAPIIndicator` does not do any calculations by itself. It simply plots
incoming data to a chart which can be passed by via JSON interface to the `Chart Data Socket`. The indicator is controlled by the expert script `JsonAPI.mq5` locally via port `15562`.
## Error handling
First of all, when you send a command via `System socket`, you should always receive back `"OK"` message via `System socket`. It means that your command was received and deserialized.
All data that come through `Data socket` have an `error` param. This param will have `true` key if somethng goes wrong. Also, there will be `description` and `function` params. They will hold information about error and the name of the function with error.
This information also applies to the trade commannds. See [MQL5 docs](https://www.mql5.com/en/docs/constants/errorswarnings/enum_trade_return_codes) for possible server answers.
## License
This program 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 `LICENSE` for more information.
+18
View File
@@ -0,0 +1,18 @@
### 30th April 2020
- add support for spreads
- add support for plotting custom indicator data to charts
- add support for streaming MT5 indicator data
- new error reporting
### 16th February 2020
- add support for candle ask/bid price spread
### 11th January 2020
- add support for multiple datastreams in parallel for any combination of symbols and timeframes independently of the timeframe and symbol of the attached chart
- add support for tick data
- add support for direct download as CSV files
- add one automatic retry binding to sockets. When running under Wine in Linux, sockets will be blocked for 60 seconds if closed uncleanly. This can happen if the client is still connected while the EA gets reloaded.
- skip re-initialization on chart timeframe change
Executable
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# https://www.commandlinefu.com/commands/view/11560/delete-all-non-printing-characters-from-a-file
# http://www.skybert.net/bash/adding-utf-8-bom-from-the-command-line/
# Remove non-printable ASCII characters
tr -cd '[:print:]\n\r' < ./Experts/JsonAPI.mq5 > ./Experts/JsonAPI.clean.mq5
# Add UTF-8 BOM
sed -i '1s/^/\xef\xbb\xbf/' ./Experts/JsonAPI.clean.mq5
mv ./Experts/JsonAPI.clean.mq5 ./Experts/JsonAPI.mq5
# Remove non-printable ASCII characters
tr -cd '[:print:]\n\r' < ./Indicators/JsonAPIIndicator.mq5 > ./Indicators/JsonAPIIndicator.clean.mq5
# Add UTF-8 BOM
sed -i '1s/^/\xef\xbb\xbf/' ./Indicators/JsonAPIIndicator.clean.mq5
mv ./Indicators/JsonAPIIndicator.clean.mq5 ./Indicators/JsonAPIIndicator.mq5
# Remove non-printable ASCII characters
tr -cd '[:print:]\n\r' < ./Include/StringToEnumInt.mqh > ./Include/StringToEnumInt.clean.mqh
# Add UTF-8 BOM
sed -i '1s/^/\xef\xbb\xbf/' ./Include/StringToEnumInt.clean.mqh
mv ./Include/StringToEnumInt.clean.mqh ./Include/StringToEnumInt.mqh
# Remove non-printable ASCII characters
tr -cd '[:print:]\n\r' < ./Include/controlerrors.mqh > ./Include/controlerrors.clean.mqh
# Add UTF-8 BOM
sed -i '1s/^/\xef\xbb\xbf/' ./Include/controlerrors.clean.mqh
mv ./Include/controlerrors.clean.mqh ./Include/controlerrors.mqh
@@ -1,73 +0,0 @@
//+------------------------------------------------------------------+
//| OnTick(string symbol).mq5 |
//| Copyright 2010, Lizar |
//| https://login.mql5.com/ru/users/Lizar |
//+------------------------------------------------------------------+
#define VERSION "1.00 Build 1 (01 Fab 2011)"
#property copyright "Copyright 2010, Lizar"
#property link "https://login.mql5.com/ru/users/Lizar"
#property version VERSION
#property description "Template of the Expert Advisor"
#property description "with multicurrency OnTick(string symbol) event handler"
//+------------------------------------------------------------------+
//| MULTICURRENCY MODE SETTINGS |
//| of OnTick(string symbol) event handler |
//| |
//| 1.1 List of symbols needed to proceed in the events: |
#define SYMBOLS_TRADING "EURUSD","GBPUSD","USDJPY","USDCHF"
//| 1.2 If you want all symbols from Market Watch, use this: |
//#define SYMBOLS_TRADING "MARKET_WATCH"
//| Note: Select only one way from 1.1 or 1.2. |
//| |
//| 2. Event type for OnTick(string symbol): |
#define CHART_EVENT_SYMBOL CHARTEVENT_TICK
//| Note: the event type must corresponds to the |
//| ENUM_CHART_EVENT_SYMBOL enumeration. |
//| |
//| 3. Include file: |
#include <OnTick(string symbol).mqh>
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Expert initialization function |
//| This function must be declared, even if it empty. |
//+------------------------------------------------------------------+
int OnInit()
{
//--- Add your code here...
return(0);
}
//+------------------------------------------------------------------+
//| Expert multi tick function |
//| Use this function instead of the standard OnTick() function |
//+------------------------------------------------------------------+
void OnTick(string symbol)
{
//--- Add your code here...
Print("New event on symbol: ",symbol);
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//| This function must be declared, even if it empty. |
//+------------------------------------------------------------------+
void OnChartEvent(const int id, // event id
const long& lparam, // event param of long type
const double& dparam, // event param of double type
const string& sparam) // event param of string type
{
//--- Add your code here...
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//--- Add your code here...
}
//+------------------------------ end -------------------------------+
@@ -1,214 +0,0 @@
//+------------------------------------------------------------------+
//| OnTick(string symbol).mqh |
//| Copyright 2010, Lizar |
//| https://login.mql5.com/ru/users/Lizar |
//| Revision 2011.01.30 |
//+------------------------------------------------------------------+
#property copyright "Copyright 2010, Lizar"
#property link "https://login.mql5.com/ru/users/Lizar"
//+------------------------------------------------------------------+
//| The events enumeration is implemented as flags |
//| the events can be combined using the OR ("|") logical operation |
//+------------------------------------------------------------------+
enum ENUM_CHART_EVENT_SYMBOL
{
CHARTEVENT_NO =0, // Events disabled
CHARTEVENT_INIT =0, // "Initialization" event
CHARTEVENT_NEWBAR_M1 =0x00000001, // "New bar" event on M1 chart
CHARTEVENT_NEWBAR_M2 =0x00000002, // "New bar" event on M2 chart
CHARTEVENT_NEWBAR_M3 =0x00000004, // "New bar" event on M3 chart
CHARTEVENT_NEWBAR_M4 =0x00000008, // "New bar" event on M4 chart
CHARTEVENT_NEWBAR_M5 =0x00000010, // "New bar" event on M5 chart
CHARTEVENT_NEWBAR_M6 =0x00000020, // "New bar" event on M6 chart
CHARTEVENT_NEWBAR_M10=0x00000040, // "New bar" event on M10 chart
CHARTEVENT_NEWBAR_M12=0x00000080, // "New bar" event on M12 chart
CHARTEVENT_NEWBAR_M15=0x00000100, // "New bar" event on M15 chart
CHARTEVENT_NEWBAR_M20=0x00000200, // "New bar" event on M20 chart
CHARTEVENT_NEWBAR_M30=0x00000400, // "New bar" event on M30 chart
CHARTEVENT_NEWBAR_H1 =0x00000800, // "New bar" event on H1 chart
CHARTEVENT_NEWBAR_H2 =0x00001000, // "New bar" event on H2 chart
CHARTEVENT_NEWBAR_H3 =0x00002000, // "New bar" event on H3 chart
CHARTEVENT_NEWBAR_H4 =0x00004000, // "New bar" event on H4 chart
CHARTEVENT_NEWBAR_H6 =0x00008000, // "New bar" event on H6 chart
CHARTEVENT_NEWBAR_H8 =0x00010000, // "New bar" event on H8 chart
CHARTEVENT_NEWBAR_H12=0x00020000, // "New bar" event on H12 chart
CHARTEVENT_NEWBAR_D1 =0x00040000, // "New bar" event on D1 chart
CHARTEVENT_NEWBAR_W1 =0x00080000, // "New bar" event on W1 chart
CHARTEVENT_NEWBAR_MN1=0x00100000, // "New bar" event on MN1 chart
CHARTEVENT_TICK =0x00200000, // "New tick" event
CHARTEVENT_ALL =0xFFFFFFFF, // All events enabled
};
//---
string _symbol_[]={SYMBOLS_TRADING};
int _handle_[];
int _symbols_total_ = 0; // total symbols
int _symbols_market_ = 0; // number of symbols in Market Watch
bool _market_watch_ = false; // use symbols from Market Watch
bool _testing_ = false; // In testing mode
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
//--- check if we work in Strategy Tester:
_testing_=((bool)MQL5InfoInteger(MQL5_TESTING) ||
(bool)MQL5InfoInteger(MQL5_OPTIMIZATION) ||
(bool)MQL5InfoInteger(MQL5_VISUAL_MODE));
//--- Check do we need to use the symbols from Market Watch
if(_symbol_[0]=="MARKET_WATCH") _market_watch_=true;
//--- check settings
if(_testing_ && _market_watch_)
{
Print("Error: Please specify list of symbols in SYMBOLS_TRADING for use in Strategy Tester ");
return(1);
}
//--- Initialization of variables and arrays:
_symbols_total_=SymbolsTotal(false); // total symbols
ArrayResize(_handle_,_symbols_total_); // resize array for handles of "spys"
ArrayInitialize(_handle_,INVALID_HANDLE); // initalizae array for handles of "spys"
//--- Load "spys":
if(_market_watch_) SynchronizationTradingTools();
else
{
_symbols_total_=ArraySize(_symbol_);
for(int i=0;i<_symbols_total_;i++)
if(!LoadAgent(i, _symbol_[i])) return(1);
}
//--- Execute OnInit function of Expert Advisor
_OnInit();
return(0);
}
#define OnInit _OnInit // rendefine of OnInit function
//+------------------------------------------------------------------+
//| Expert tick function |
//| Used only in Strategy Tester |
//+------------------------------------------------------------------+
void OnTick()
{
if(_testing_)
{
for(int i=0;i<_symbols_total_;i++)
{
string __symbol__=_symbol_[i];
if(MathAbs(GlobalVariableGet(__symbol__+"_flag")-2)<0.1)
{
GlobalVariableSet(__symbol__+"_flag",1);
OnTick(__symbol__);
}
}
}
}
//+------------------------------------------------------------------+
//| ChartEvent function |
//+------------------------------------------------------------------+
void OnChartEvent(const int id,const long& lparam,const double& dparam,const string& sparam)
{
//--- Call of OnTick(string symbol) or OnChartEvent event handler:
if(id==CHARTEVENT_CUSTOM_LAST)
{
OnTick(sparam);
//--- synchronize "agents" with Market Watch if necessary:
if(_market_watch_) SynchronizationTradingTools();
}
else _OnChartEvent(id,lparam,dparam,sparam);
}
#define OnChartEvent _OnChartEvent // rendefine of OnChartEvent function
//+------------------------------------------------------------------+
//| Function for synchronization of "spys" with symbols |
//| from "Market Watch" |
//| INPUT: no. |
//| OUTPUT: no. |
//| REMARK: no. |
//+------------------------------------------------------------------+
void SynchronizationTradingTools()
{
if(_symbols_market_!=SymbolsTotal(true))
{
_symbols_market_=0;
for(int i=0;i<_symbols_total_;i++)
{
long __symbol_select__;
string __symbol__=SymbolName(i,false);
if(!SymbolInfoInteger(__symbol__,SYMBOL_SELECT,__symbol_select__)) return;
if(_handle_[i]==INVALID_HANDLE && __symbol_select__)
{
if(!LoadAgent(i,__symbol__)) return;
}
else if(_handle_[i]!=INVALID_HANDLE && !__symbol_select__)
{
if(!DeLoadAgent(i,__symbol__)) return;
}
}
_symbols_market_=SymbolsTotal(true);
}
}
//+------------------------------------------------------------------+
//| Function for loading of "spys" |
//| INPUT: __id__ - id, corresponds to the symbol index in |
//| the list of symbols |
//| __symbol__ - symbol name |
//| OUTPUT: true - if successful |
//| false - if error |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool LoadAgent(int __id__, string __symbol__)
{
_handle_[__id__]=iCustom(__symbol__,_Period,"Spy Control panel MCM",ChartID(),65534,CHART_EVENT_SYMBOL);
if(_handle_[__id__]==INVALID_HANDLE)
{
Print("Error in setting of agent for ",__symbol__);
return(false);
}
Print("The agent for ",__symbol__," is set.");
return(true);
}
//+------------------------------------------------------------------+
//| Function for release of the "spys" |
//| INPUT: __id__ - id, corresponds to the symbol index in |
//| the list of symbols |
//| __symbol__ - symbol name |
//| OUTPUT: true - if successful |
//| false - if error |
//| REMARK: no. |
//+------------------------------------------------------------------+
bool DeLoadAgent(int __id__, string __symbol__)
{
if(_handle_[__id__]!=INVALID_HANDLE)
{
if(!IndicatorRelease(_handle_[__id__]))
{
Print("Error deletion of agent for ",__symbol__);
return(false);
}
Print("The agent for ",__symbol__," is deleted.");
_handle_[__id__]=INVALID_HANDLE;
}
return(true);
}
//+------------------------------ end -------------------------------+
@@ -1,160 +0,0 @@
//+------------------------------------------------------------------+
//| Spy Control panel MCM.mq5 |
//| Copyright 2010, Lizar |
//| https://login.mql5.com/ru/users/Lizar |
//+------------------------------------------------------------------+
#define VERSION "1.00 Build 4 (30 Jan 2011)"
#property copyright "Copyright 2010, Lizar"
#property link "https://login.mql5.com/ru/users/Lizar"
#property version VERSION
#property description "MCM Control panel agent."
#property description "It can be attached to the chart (any timeframe) of the symbol needed"
#property description "and generate the NewBar and/or NewTick custom events for the chart"
#property indicator_chart_window
//+------------------------------------------------------------------+
//| The events enumeration is implemented as flags |
//| the events can be combined using the OR ("|") logical operation |
//+------------------------------------------------------------------+
enum ENUM_CHART_EVENT_SYMBOL
{
CHARTEVENT_INIT =0, // "Initialization" event
CHARTEVENT_NO =0, // Events disabled
CHARTEVENT_NEWBAR_M1 =0x00000001, // "New bar" event on 1-m chart
CHARTEVENT_NEWBAR_M2 =0x00000002, // "New bar" event on 2-m chart
CHARTEVENT_NEWBAR_M3 =0x00000004, // "New bar" event on 3-m chart
CHARTEVENT_NEWBAR_M4 =0x00000008, // "New bar" event on 4-m chart
CHARTEVENT_NEWBAR_M5 =0x00000010, // "New bar" event on 5-m chart
CHARTEVENT_NEWBAR_M6 =0x00000020, // "New bar" event on 6-m chart
CHARTEVENT_NEWBAR_M10=0x00000040, // "New bar" event on 10-m chart
CHARTEVENT_NEWBAR_M12=0x00000080, // "New bar" event on 12-m chart
CHARTEVENT_NEWBAR_M15=0x00000100, // "New bar" event on 15-m chart
CHARTEVENT_NEWBAR_M20=0x00000200, // "New bar" event on 20-m chart
CHARTEVENT_NEWBAR_M30=0x00000400, // "New bar" event on 30-m chart
CHARTEVENT_NEWBAR_H1 =0x00000800, // "New bar" event on hourly chart
CHARTEVENT_NEWBAR_H2 =0x00001000, // "New bar" event on H2 chart
CHARTEVENT_NEWBAR_H3 =0x00002000, // "New bar" event on H3 chart
CHARTEVENT_NEWBAR_H4 =0x00004000, // "New bar" event on H4 chart
CHARTEVENT_NEWBAR_H6 =0x00008000, // "New bar" event on H6 chart
CHARTEVENT_NEWBAR_H8 =0x00010000, // "New bar" event on H8 chart
CHARTEVENT_NEWBAR_H12=0x00020000, // "New bar" event on H12 chart
CHARTEVENT_NEWBAR_D1 =0x00040000, // "New bar" event on D1 chart
CHARTEVENT_NEWBAR_W1 =0x00080000, // "New bar" event on W1 chart
CHARTEVENT_NEWBAR_MN1=0x00100000, // "New bar" event on MN1 chart
CHARTEVENT_TICK =0x00200000, // "New tick" event
CHARTEVENT_ALL =0xFFFFFFFF, // All events enabled
};
input long chart_id; // chart id
input ushort custom_event_id; // event id
input ENUM_CHART_EVENT_SYMBOL flag_event=CHARTEVENT_NO; // event flag.
MqlDateTime time, prev_time;
bool testing=false;
//+------------------------------------------------------------------+
//| Custom indicator initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
testing=((bool)MQL5InfoInteger(MQL5_TESTING) ||
(bool)MQL5InfoInteger(MQL5_OPTIMIZATION) ||
(bool) MQL5InfoInteger(MQL5_VISUAL_MODE));
if(testing)
{
GlobalVariableTemp(_Symbol+"_flag");
GlobalVariableTemp(_Symbol+"_custom_id");
GlobalVariableTemp(_Symbol+"_event");
GlobalVariableTemp(_Symbol+"_price");
}
return(0);
}
//+------------------------------------------------------------------+
//| Custom indicator iteration function |
//+------------------------------------------------------------------+
int OnCalculate (const int rates_total, // size of price[] array
const int prev_calculated, // bars calculated at previous call
const int begin, // begin
const double& price[] // array for calculation
)
{
double price_current=price[rates_total-1];
TimeCurrent(time);
if(prev_calculated==0)
{
EventCustom(CHARTEVENT_INIT,price_current);
prev_time=time;
return(rates_total);
}
//--- new tick
if((flag_event & CHARTEVENT_TICK)!=0) EventCustom(CHARTEVENT_TICK,price_current);
//--- check change time
if(time.min==prev_time.min &&
time.hour==prev_time.hour &&
time.day==prev_time.day &&
time.mon==prev_time.mon) return(rates_total);
//--- new minute
if((flag_event & CHARTEVENT_NEWBAR_M1)!=0) EventCustom(CHARTEVENT_NEWBAR_M1,price_current);
if(time.min%2 ==0 && (flag_event & CHARTEVENT_NEWBAR_M2)!=0) EventCustom(CHARTEVENT_NEWBAR_M2,price_current);
if(time.min%3 ==0 && (flag_event & CHARTEVENT_NEWBAR_M3)!=0) EventCustom(CHARTEVENT_NEWBAR_M3,price_current);
if(time.min%4 ==0 && (flag_event & CHARTEVENT_NEWBAR_M4)!=0) EventCustom(CHARTEVENT_NEWBAR_M4,price_current);
if(time.min%5 ==0 && (flag_event & CHARTEVENT_NEWBAR_M5)!=0) EventCustom(CHARTEVENT_NEWBAR_M5,price_current);
if(time.min%6 ==0 && (flag_event & CHARTEVENT_NEWBAR_M6)!=0) EventCustom(CHARTEVENT_NEWBAR_M6,price_current);
if(time.min%10==0 && (flag_event & CHARTEVENT_NEWBAR_M10)!=0) EventCustom(CHARTEVENT_NEWBAR_M10,price_current);
if(time.min%12==0 && (flag_event & CHARTEVENT_NEWBAR_M12)!=0) EventCustom(CHARTEVENT_NEWBAR_M12,price_current);
if(time.min%15==0 && (flag_event & CHARTEVENT_NEWBAR_M15)!=0) EventCustom(CHARTEVENT_NEWBAR_M15,price_current);
if(time.min%20==0 && (flag_event & CHARTEVENT_NEWBAR_M20)!=0) EventCustom(CHARTEVENT_NEWBAR_M20,price_current);
if(time.min%30==0 && (flag_event & CHARTEVENT_NEWBAR_M30)!=0) EventCustom(CHARTEVENT_NEWBAR_M30,price_current);
if(time.min!=0) {prev_time=time; return(rates_total);}
//--- new hour
if((flag_event & CHARTEVENT_NEWBAR_H1)!=0) EventCustom(CHARTEVENT_NEWBAR_H1,price_current);
if(time.hour%2 ==0 && (flag_event & CHARTEVENT_NEWBAR_H2)!=0) EventCustom(CHARTEVENT_NEWBAR_H2,price_current);
if(time.hour%3 ==0 && (flag_event & CHARTEVENT_NEWBAR_H3)!=0) EventCustom(CHARTEVENT_NEWBAR_H3,price_current);
if(time.hour%4 ==0 && (flag_event & CHARTEVENT_NEWBAR_H4)!=0) EventCustom(CHARTEVENT_NEWBAR_H4,price_current);
if(time.hour%6 ==0 && (flag_event & CHARTEVENT_NEWBAR_H6)!=0) EventCustom(CHARTEVENT_NEWBAR_H6,price_current);
if(time.hour%8 ==0 && (flag_event & CHARTEVENT_NEWBAR_H8)!=0) EventCustom(CHARTEVENT_NEWBAR_H8,price_current);
if(time.hour%12==0 && (flag_event & CHARTEVENT_NEWBAR_H12)!=0) EventCustom(CHARTEVENT_NEWBAR_H12,price_current);
if(time.hour!=0) {prev_time=time; return(rates_total);}
//--- new day
if((flag_event & CHARTEVENT_NEWBAR_D1)!=0) EventCustom(CHARTEVENT_NEWBAR_D1,price_current);
//--- new week
if(time.day_of_week==1 && (flag_event & CHARTEVENT_NEWBAR_W1)!=0) EventCustom(CHARTEVENT_NEWBAR_W1,price_current);
//--- new month
if(time.day==1 && (flag_event & CHARTEVENT_NEWBAR_MN1)!=0) EventCustom(CHARTEVENT_NEWBAR_MN1,price_current);
prev_time=time;
//--- return value of prev_calculated for next call
return(rates_total);
}
//+------------------------------------------------------------------+
void EventCustom(ENUM_CHART_EVENT_SYMBOL event,double price)
{
if(!testing) EventChartCustom(chart_id,custom_event_id,(long)event,price,_Symbol);
else
{
if(GlobalVariableSet(_Symbol+"_custom_id",custom_event_id)==0) return;
if(GlobalVariableSet(_Symbol+"_event",event)==0) return;
if(GlobalVariableSet(_Symbol+"_price",price)==0) return;
GlobalVariableSet(_Symbol+"_flag",2);
}
return;
}