Compare commits
33 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 1c47fc12d1 | |||
| 1a0ce7af3a | |||
| 08b83713af | |||
| 775a962d38 | |||
| b17e82d99d | |||
| d423745c93 | |||
| 1b2beab4c4 | |||
| ae6a2367b1 | |||
| b550a423a1 | |||
| de6b4f0546 | |||
| 2c77099430 | |||
| 99ea77ebfe | |||
| 4b2297fbfb | |||
| 37cb0fe738 | |||
| cc0f9b7575 | |||
| 7099ac1cac | |||
| 820329307f | |||
| 1bad67048f | |||
| f27bc3d1d9 | |||
| c1e136d64e | |||
| dc60a0a0c9 | |||
| 34af70c043 | |||
| 036c2d4cfd | |||
| 7deedb72c5 | |||
| 126c669c62 | |||
| 03088ea2ec | |||
| e14b83e023 | |||
| 598253cfc3 | |||
| aee89843da | |||
| 9457e57890 | |||
| 01ac1bbc11 | |||
| 081fdfbdfe | |||
| 4d06d0e060 |
@@ -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
|
||||
@@ -1,5 +1,2 @@
|
||||
|
||||
.DS_Store
|
||||
|
||||
|
||||
update_from_mt5\.sh
|
||||
|
||||
Binary file not shown.
@@ -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);
|
||||
}
|
||||
Binary file not shown.
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
//+----------------------------------------------------
|
||||
@@ -1,12 +1,12 @@
|
||||
# Metaquotes MQL5 - JSON - API
|
||||
|
||||
### Development state: first stable release
|
||||
### Development state: stable release version 2.0
|
||||
|
||||
Tested on macOS Mojave / Windows 10 in Parallels Desktop container.
|
||||
|
||||
Working in production on Debian 10 / Wine 4.
|
||||
Tested on Manjaro Linux / Windows 10 in VirtualBox
|
||||
|
||||
An issue was found because of REP/REQ socket. Architecture changes are in development.
|
||||
Working in production on Debian 10 / Wine 4.
|
||||
|
||||
## Table of Contents
|
||||
|
||||
@@ -15,6 +15,9 @@ An issue was found because of REP/REQ socket. Architecture changes are in develo
|
||||
- [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)
|
||||
|
||||
@@ -24,29 +27,50 @@ This project was developed to work as a server for the Backtrader Python trading
|
||||
|
||||
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 `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`)
|
||||
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 four ZeroMQ sockets:
|
||||
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.
|
||||
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.
|
||||
|
||||
@@ -68,34 +92,43 @@ The idea is to send requests via `System socket` and recieve results/errors via
|
||||
"takeprofit": null,
|
||||
"expiration": null,
|
||||
"deviation": null,
|
||||
"comment": 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 |
|
||||
| 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 |
|
||||
| HISTORY | WRITE | Downlaod 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 |
|
||||
| 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:
|
||||
|
||||
@@ -109,6 +142,8 @@ class MTraderAPI:
|
||||
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
|
||||
@@ -128,6 +163,20 @@ class MTraderAPI:
|
||||
# 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")
|
||||
|
||||
@@ -151,6 +200,16 @@ class MTraderAPI:
|
||||
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:
|
||||
@@ -171,6 +230,15 @@ class MTraderAPI:
|
||||
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"""
|
||||
|
||||
@@ -190,7 +258,11 @@ class MTraderAPI:
|
||||
"takeprofit": None,
|
||||
"expiration": None,
|
||||
"deviation": None,
|
||||
"comment": None
|
||||
"comment": None,
|
||||
"chartId": None,
|
||||
"indicatorChartId": None,
|
||||
"chartIndicatorSubWindow": None,
|
||||
"style": None,
|
||||
}
|
||||
|
||||
# update dict values if exist
|
||||
@@ -205,6 +277,58 @@ class MTraderAPI:
|
||||
|
||||
# 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
|
||||
@@ -215,10 +339,25 @@ All examples will be on Python 3. Lets create an instance of MetaTrader API clas
|
||||
api = MTraderAPI()
|
||||
```
|
||||
|
||||
First of all we should configure the script `symbol` and `timeframe`. Live data stream will be configured to the same params.
|
||||
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
|
||||
rep = api.construct_and_send(action="CONFIG", symbol="EURUSD", chartTF="M5")
|
||||
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)
|
||||
```
|
||||
|
||||
@@ -315,10 +454,11 @@ while True:
|
||||
pass
|
||||
```
|
||||
|
||||
There are only two variants of `Live socket` data. When everything is ok, the script sends data on candle close:
|
||||
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","data":[1560780120,1.12186,1.12194,1.12186,1.12191,15.00000]}
|
||||
{"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:
|
||||
@@ -370,6 +510,99 @@ When the terminal reconnects to the market, it sends the last closed candle agai
|
||||
}
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
+11
-1
@@ -1,3 +1,14 @@
|
||||
### 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
|
||||
@@ -5,4 +16,3 @@
|
||||
- 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
|
||||
- add testing mode with fake tick data
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user