-
Notifications
You must be signed in to change notification settings - Fork 69
/
ForecastExpert.mq5
428 lines (347 loc) · 13.3 KB
/
ForecastExpert.mq5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
//+------------------------------------------------------------------+
//| _HPCS_RNNPredict_MT5_EA_V01_WE.mq5 |
//| HPCS |
//| https://www.mql5.com |
//+------------------------------------------------------------------+
#property copyright "HPCS"
#property link "https://www.mql5.com"
#property version "1.00"
//+------------------------------------------------------------------+
//| Enumerated Parameters |
//+------------------------------------------------------------------+
enum Optimizer {
RMSProp,
SGD,
Adam,
Adagrad,
};
enum Architecture {
LSTM,
GRU,
BidirectionalLSTM,
BidirectionalGRU,
};
enum Loss {
MSE,
R2,
};
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
// Header file for JSON Serialization and Deserialization
#include <JAson.mqh>
//+------------------------------------------------------------------+
//| Input Parameters |
//+------------------------------------------------------------------+
input Architecture architecture = LSTM; // RNN Architecture
input Optimizer optimizer = RMSProp; // Optimizer
input Loss loss = MSE; // Loss Function
input bool gpu = true; // Allow GPU Computations ?
input bool train = true; // Train ?
//Train size must be greater than window_size = 60
input int trainingSize = 500; // Train Size
input int epochs = 5; // Epochs
input int scale = 100; // Scale
input string fileName = "model1"; // File Name to export model
input double momentum = 0.9; // Momentum (for SGD)
input double learningRate = 0.001; // Learning Rate
input double testingPart = 10; // Percentage of Train/Test Split
input double testingWeight = 50; // Percentage of Train/Test Score Weights
input int retrain = 10; // Retrain bar
input int bars = 5; // Future bars to predict
int socket = -2; // Socket Variable
int count = 0;
datetime previousTime;
string previousPred;
//+------------------------------------------------------------------+
//| Retrain Bar Detect Function |
//+------------------------------------------------------------------+
bool onRetrainBar(void){
if(previousTime != iTime(ChartSymbol(ChartID()),Period(),0)){
previousTime = iTime(ChartSymbol(ChartID()),Period(),0);
count++;
}
if(count == retrain){
count = 0;
return true;
}
return false;
}
// Socket Send Function
bool socksend(int sock,string request) {
char req[];
int len=StringToCharArray(request,req)-1;
if(len<0)
return(false);
return(SocketSend(sock,req,len)==len);
}
// Socket Receive Function
string socketreceive(int sock,int timeout) {
char rsp[];
string result="";
uint len;
uint timeout_check=GetTickCount()+timeout;
do
{
len=SocketIsReadable(sock);
if(len)
{
int rsp_len;
rsp_len=SocketRead(sock,rsp,len,timeout);
if(rsp_len>0)
{
result+=CharArrayToString(rsp,0,rsp_len);
}
}
}
while((GetTickCount()<timeout_check) && !IsStopped());
return result;
}
void drawpred(string res)
{
CJAVal json;
if(!json.Deserialize(res)) {
Print("BAD RESPONSE !!");
return;
}
double predictions[];
ArrayResize(predictions, bars);
for(int i=0;i<bars;i++){
ObjectDelete(ChartID(),"pred" + IntegerToString(i + 1));
}
for(int i=0;i<bars;i++)
{
predictions[i] = NormalizeDouble(StringToDouble(json["Pred"][i].ToStr()), Digits());
//Print(predictions[i]);
//Print(TimeCurrent() + ChartPeriod(0)*60*(i+1));
ObjectCreate(0, "pred" + IntegerToString(i + 1),OBJ_ARROW, 0, TimeCurrent() + ChartPeriod(0)*60*(i+1), predictions[i]);
ObjectSetInteger(0, "pred" + IntegerToString(i + 1),OBJPROP_COLOR,clrRed);
ObjectSetInteger(ChartID(), "pred" + IntegerToString(i + 1),OBJPROP_WIDTH,3);
ObjectSetInteger(0, "pred" + IntegerToString(i + 1),OBJPROP_ARROWCODE,159);
}
}
int OnInit()
{
//---
previousPred = "";
if(train == true){
ObjectCreate(ChartID(),"Trainbutton",OBJ_BUTTON,0,0,0);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_XSIZE,140);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_YSIZE,30);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_XDISTANCE,40);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_YDISTANCE,10);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_COLOR,clrBlue);
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_BGCOLOR,clrWhite);
ObjectSetString(ChartID(),"Trainbutton",OBJPROP_TEXT,"TRAIN MODEL");
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_STATE,false);
ObjectCreate(ChartID(),"Predbutton",OBJ_BUTTON,0,0,0);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_XSIZE,140);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_YSIZE,30);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_XDISTANCE,40);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_YDISTANCE,50);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_COLOR,clrBlue);
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_BGCOLOR,clrWhite);
ObjectSetString(ChartID(),"Predbutton",OBJPROP_TEXT,"PREDICT");
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_STATE,false);
if(!EventChartCustom(ChartID(),0,0,0,"Trainbutton")){
Print("Error : ",GetLastError());
}
if(!EventChartCustom(ChartID(),0,0,0,"Predbutton")){
Print("Error : ",GetLastError());
}
}
else{
socket = SocketCreate();
if(socket!=INVALID_HANDLE) {
if(SocketConnect(socket,"localhost",9090,1000)) {
Print("Connected to "," localhost",":",9090);
CJAVal json;
json["FileName"] = fileName;
json["Train"] = train;
json["GPU"] = gpu;
json["Bars"] = bars;
string jsonString = json.Serialize();
bool send = socksend(socket, jsonString);
if(send)
Print("Data Sent Successfully For Prediction.");
string strMessage;
do{
strMessage = socketreceive(socket,10);
if (strMessage != "") {
previousPred = strMessage;
Print(strMessage);
drawpred(strMessage);
SocketClose(socket);
socket = -2;
}
}while(strMessage == "");
}
else{
socket = -2;
Print("Error in connecting to ","localhost",":",9090," Error : ",GetLastError());
}
}
else{
socket = -2;
Print("Socket creation error ",GetLastError());
}
}
//---
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
//---
SocketClose(socket);
ObjectsDeleteAll(ChartID(),-1,-1);
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
//---
if(onRetrainBar()){
//Print("Inside onRetrainBar.");
if(socket == -2){
socket = SocketCreate();
if(socket!=INVALID_HANDLE) {
if(SocketConnect(socket,"localhost",9090,1000)) {
Print("Connected to "," localhost",":",9090);
double clpr[];
int copyClose = CopyClose(ChartSymbol(ChartID()),PERIOD_CURRENT,0,trainingSize,clpr);
datetime time[];
int copyTime = CopyTime(ChartSymbol(ChartID()),PERIOD_CURRENT,0,trainingSize,time);
CJAVal json;
for (int i = 0; i < ArraySize(clpr); i++)
{
json["Data"].Add(DoubleToString(clpr[i], 6));
json["Time"].Add((string)time[i]);
}
json["FileName"] = fileName;
json["Train"] = train;
json["GPU"] = gpu;
json["Architecture"] = (int)architecture;
json["Optimizer"] = (int)optimizer;
json["Loss"] = (int)loss;
json["LearningRate"] = learningRate;
json["Epochs"] = epochs;
json["Scale"] = scale;
json["Momentum"] = momentum;
json["TestingPart"] = testingPart;
json["TestingWeight"] = testingWeight;
json["Bars"] = bars;
string jsonString = json.Serialize();
bool send = socksend(socket, jsonString);
if(send)
Print("Data Sent Successfully For Retrain.");
}
else{
socket = -2;
Print("Error in connecting to ","localhost",":",9090," Error : ",GetLastError());
}
}
else{
socket = -2;
Print("Socket creation error ",GetLastError());
}
}
else{
Print("Socket Is Busy.");
}
}
}
//+------------------------------------------------------------------+
void OnTimer(){
}
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam){
if(id == CHARTEVENT_OBJECT_CLICK && sparam == "Trainbutton"){
if(socket == -2){
previousTime = iTime(ChartSymbol(ChartID()),Period(),0);
socket = SocketCreate();
if(socket!=INVALID_HANDLE) {
if(SocketConnect(socket,"localhost",9090,1000)) {
Print("Connected to "," localhost",":",9090);
double clpr[];
int copyClose = CopyClose(_Symbol,PERIOD_CURRENT,0,trainingSize,clpr);
datetime time[];
int copyTime= CopyTime(_Symbol,PERIOD_CURRENT,0,trainingSize,time);
CJAVal json;
for (int i = 0; i < ArraySize(clpr); i++)
{
json["Data"].Add(DoubleToString(clpr[i], 6));
json["Time"].Add((string)time[i]);
}
json["FileName"] = fileName;
json["Train"] = train;
json["GPU"] = gpu;
json["Architecture"] = (int)architecture;
json["Optimizer"] = (int)optimizer;
json["Loss"] = (int)loss;
json["LearningRate"] = learningRate;
json["Epochs"] = epochs;
json["Scale"] = scale;
json["Momentum"] = momentum;
json["TestingPart"] = testingPart;
json["TestingWeight"] = testingWeight;
json["Bars"] = bars;
string jsonString = json.Serialize();
//Print(jsonString);
bool send = socksend(socket, jsonString);
if(send)
Print("Data Sent Successfully.");
}
else{
socket = -2;
Print("Error in connecting to ","localhost",":",9090," Error : ",GetLastError());
}
}
else{
socket = -2;
Print("Socket creation error ",GetLastError());
}
}
else{
Print("Socket Is Busy In Training.");
}
ObjectSetInteger(ChartID(),"Trainbutton",OBJPROP_STATE,false);
}
if(id == CHARTEVENT_OBJECT_CLICK && sparam == "Predbutton"){
if(socket==-2){
if(previousPred != ""){
Print("Based on previously trained model, Prediction are : ",previousPred);
drawpred(previousPred);
}
else{
Print("No predicted data is available or Model is still getting trained.");
}
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_STATE,false);
return;
}
string strMessage;
do{
strMessage = socketreceive(socket,10);
if (strMessage != "") {
previousPred = strMessage;
Print(strMessage);
drawpred(strMessage);
SocketClose(socket);
socket = -2;
}
else{
if(previousPred != ""){
Print("Based on previously trained model, Prediction are : ",previousPred);
drawpred(previousPred);
}
else{
Print("No predicted data available or Model is still getting trained.");
}
}
}while(socket != -2 && strMessage != "");
ObjectSetInteger(ChartID(),"Predbutton",OBJPROP_STATE,false);
}
}
//+------------------------------------------------------------------+