-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathSAM.mq5
More file actions
3100 lines (2634 loc) · 252 KB
/
Copy pathSAM.mq5
File metadata and controls
3100 lines (2634 loc) · 252 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#property copyright "Jason.W.Rusk@gmail.com"
#property version "3.00" // HTTP Communication Update
#include <Trade/Trade.mqh>
#include <Files/File.mqh>
#include <stdlib.mqh>
#include <Math/Stat/Math.mqh>
// --- TYPE DEFINITIONS ---
enum ENUM_TRADING_MODE { MODE_TRADING_DISABLED, MODE_REGRESSION_ONLY, MODE_COMBINED };
enum ENUM_STOP_LOSS_MODE { SL_ATR_BASED, SL_STATIC_PIPS };
enum ENUM_TAKE_PROFIT_MODE { TP_REGRESSION_TARGET, TP_ATR_MULTIPLE, TP_STATIC_PIPS };
enum ENUM_TARGET_BAR { H_PLUS_1=0, H_PLUS_2, H_PLUS_3, H_PLUS_4, H_PLUS_5 };
enum ENUM_ADAPTIVE_MODE { ADAPTIVE_DISABLED, ADAPTIVE_CONSERVATIVE, ADAPTIVE_AGGRESSIVE };
// --- HTTP COMMUNICATION SETTINGS ---
input group "=== HTTP DAEMON COMMUNICATION ===";
input string DaemonHost = "127.0.0.1"; // Daemon server host
input int DaemonPort = 8888; // Daemon server port
input int HttpTimeoutMs = 15000; // HTTP request timeout (ms)
input int MaxRetryAttempts = 3; // Max retry attempts for failed requests
input int RetryDelayMs = 1000; // Delay between retries (ms)
input bool EnableHttpLogging = true; // Enable detailed HTTP logging
input bool TestDaemonOnStart = false; // Test daemon communication on startup
// --- KELLY CRITERION INPUTS ---
input group "=== KELLY CRITERION POSITION SIZING ===";
input bool EnableKellyCriterion = true; // Enable Kelly Criterion position sizing
input double MaxKellyFraction = 0.25; // Maximum Kelly fraction (25% recommended)
input double MinKellyFraction = 0.01; // Minimum Kelly fraction (1% minimum)
input int KellyLookbackTrades = 30; // Number of recent trades for Kelly calculation
input double KellyMultiplier = 0.5; // Kelly fraction multiplier (0.5 = Half-Kelly)
input bool UseConfidenceScaling = true; // Scale Kelly by prediction confidence
input double BaseRiskWhenNoHistory = 2.0; // Risk % when insufficient trade history
input bool EnableKellySmoothing = true; // Smooth Kelly changes to prevent whipsawing
input double KellySmoothingFactor = 0.3; // Smoothing factor (0.1-0.5 recommended)
// --- TRADING HOURS INPUTS ---
input group "=== TRADING HOURS CONTROL ===";
input bool EnableTradingHours = false; // Enable/disable trading hours filter
input int TradingStartHour = 8; // Start trading hour (0-23)
input int TradingEndHour = 18; // End trading hour (0-23)
input bool TradingMonday = true; // Trade on Monday
input bool TradingTuesday = true; // Trade on Tuesday
input bool TradingWednesday = true; // Trade on Wednesday
input bool TradingThursday = true; // Trade on Thursday
input bool TradingFriday = true; // Trade on Friday
input bool TradingSaturday = false; // Trade on Saturday
input bool TradingSunday = true; // Trade on Sunday
input bool AvoidNewsHours = false; // Avoid major news hours
input string NewsAvoidanceHours = "14:30-15:30"; // Hours to avoid (format: HH:MM-HH:MM)
input bool ClosePositionsOutsideHours = false; // Close positions when outside trading hours
// --- SCALPING STRATEGY INPUTS ---
input group "=== SCALPING STRATEGY ===";
input bool EnableScalpingStrategy = true; // Enable/disable scalping
input double BaseScalpingPips = 10.0; // Base pip threshold for scalping
input int ScalpingTimeoutBars = 3; // Bars to hold scalping position
input double ScalpingRiskPercent = 1; // Risk % for scalping (separate from main)
input bool AdaptiveScalpingThreshold = true; // Make pip threshold adaptive
input double MinScalpingAccuracy = 0; // Minimum accuracy required for scalping
input bool ScalpingOverridesMain = false; // If true, scalping replaces main strategy
// --- ADAPTIVE LEARNING INPUTS ---
input group "=== ADAPTIVE LEARNING SYSTEM ===";
input ENUM_ADAPTIVE_MODE AdaptiveLearningMode = ADAPTIVE_CONSERVATIVE;
input bool EnableDynamicConfidence = true;
input bool EnableAdaptivePositionSizing = true;
input bool EnableStepWeighting = true;
input bool EnableMarketConditionAdaptation = true;
input bool EnableTesterLearning = true; // Learn from strategy tester results
input int AdaptiveLearningPeriod = 50; // Trades to analyze for adaptation
input double AdaptiveConfidenceRange = 0.30; // Max confidence adjustment range
input double AdaptiveRiskRange = 2.0; // Max risk adjustment range
input int MinTradesForAdaptation = 20; // Minimum trades before adaptation kicks in
input double TesterLearningWeight = 0.7; // Weight for tester vs live learning (0.0-1.0)
// --- ORIGINAL INPUT PARAMETERS ---
input group "Main Settings";
input ENUM_TRADING_MODE TradingLogicMode = MODE_COMBINED;
input bool EnablePricePredictionDisplay = true;
input bool EnableDailyPredictionDisplay = true; // Display D1 prediction on chart
input ENUM_TARGET_BAR TakeProfitTargetBar = H_PLUS_5;
input group "Risk & Position Management";
input ENUM_STOP_LOSS_MODE StopLossMode = SL_ATR_BASED;
input ENUM_TAKE_PROFIT_MODE TakeProfitMode = TP_REGRESSION_TARGET;
input bool UseMarketOrderForTP = false;
input double RiskPercent = 2.0;
input double MinimumRiskRewardRatio = 1.1;
input int StaticStopLossPips = 300;
input int StaticTakeProfitPips = 200;
input int ATR_Period = 14;
input double ATR_SL_Multiplier = 1.5;
input double ATR_TP_Multiplier = 2.0;
input double MinProfitPips = 10.0;
input bool EnableTimeBasedExit = false;
input int MaxPositionHoldBars = 12;
input int InpExitBarMinute = 58;
input bool EnableTrailingStop = true;
input double TrailingStartPips = 9.0;
input double TrailingStopPips = 2.0;
input group "Confidence & Filters";
input double MinimumModelConfidence = 0.40;
input double MinimumSignalConfidence = 0.30;
input double ClassificationSignalThreshold = 0.30;
input int RequiredConsistentSteps = 5;
input bool EnableADXFilter = true;
input int ADX_Period = 14;
input int ADX_Threshold = 25;
input group "Model & Data Settings";
input int AccuracyLookaheadBars = 5;
input int AccuracyLookbackOnInit = 60;
input int AccuracyWindowBars = 12;
input string Symbol_EURJPY = "EURJPY", Symbol_USDJPY = "USDJPY", Symbol_GBPUSD = "GBPUSD";
input string Symbol_EURGBP = "EURGBP", Symbol_USDCAD = "USDCAD", Symbol_USDCHF = "USDCHF";
input int PredictionUpdateMinutes = 1;
// --- Constants ---
#define PREDICTION_STEPS 5
#define SEQ_LEN 20
#define FEATURE_COUNT 15
#define GUI_PREFIX "GGTHGUI_"
#define BACKTEST_PREDICTIONS_FILE "backtest_predictions.csv"
#define ADAPTIVE_LEARNING_FILE "adaptive_learning_data.csv"
#define TESTER_RESULTS_FILE "tester_results.csv"
// --- KELLY CRITERION STRUCTURES ---
struct KellyTradeRecord {
datetime trade_time;
bool was_profitable;
double profit_pips;
double loss_pips;
double r_multiple; // Profit/Risk ratio
double confidence_used;
ENUM_ORDER_TYPE trade_type;
};
struct KellyMetrics {
double win_rate;
double avg_win_pips;
double avg_loss_pips;
double avg_r_multiple;
double profit_factor;
int total_trades;
int winning_trades;
double kelly_fraction;
double confidence_adjusted_kelly;
};
// --- ADAPTIVE LEARNING STRUCTURES ---
struct TradeRecord
{
datetime trade_time;
double entry_price;
double exit_price;
double profit;
double confidence_used;
double risk_used;
int prediction_step_used;
double accuracy_at_trade;
bool was_profitable;
double market_volatility;
int hour_of_day;
double drawdown_at_entry;
double prediction_error;
bool from_tester;
};
struct AdaptiveMetrics
{
double avg_accuracy[PREDICTION_STEPS];
double step_weights[PREDICTION_STEPS];
double dynamic_confidence_threshold;
double dynamic_risk_multiplier;
double success_rate_last_n_trades;
double avg_profit_per_trade;
double volatility_factor;
int trades_analyzed;
double max_drawdown_experienced;
double best_performing_step;
double worst_performing_step;
};
struct MarketCondition
{
double volatility_level;
int trend_direction; // -1=bear, 0=sideways, 1=bull
int session_hour;
double recent_accuracy;
double correlation_strength;
};
struct TesterResult
{
datetime test_date;
string symbol;
string timeframe;
double total_profit;
double max_drawdown;
int total_trades;
double success_rate;
double sharpe_ratio;
double best_confidence_threshold;
double best_risk_multiplier;
double avg_step_weight[PREDICTION_STEPS];
double market_conditions_score;
};
// --- Global Handles & Variables ---
int atr_handle, macd_handle, rsi_handle, stoch_handle, cci_handle, adx_handle, bb_handle;
CTrade trade;
enum ENUM_PREDICTION_DIRECTION { DIR_BULLISH, DIR_BEARISH, DIR_NEUTRAL };
struct StepPrediction
{
double target_price;
datetime prediction_bar_time;
datetime window_end_time;
ENUM_PREDICTION_DIRECTION direction;
int step;
bool evaluated;
bool hit_within_window;
};
struct DaemonResponse { double prices[PREDICTION_STEPS]; double confidence_score; double buy_prob; double sell_prob; };
// --- SCALPING STRATEGY STRUCTURES ---
struct ScalpingPosition
{
bool is_active;
datetime entry_time;
double entry_price;
double target_price;
int target_step;
ENUM_ORDER_TYPE order_type;
double lot_size;
ulong ticket;
datetime timeout_time; // This is now a reference time, not the definitive trigger
string comment;
};
// --- HTTP COMMUNICATION GLOBALS ---
string g_daemon_base_url = "";
int g_http_requests_sent = 0;
int g_http_successful_responses = 0;
int g_http_failed_responses = 0;
datetime g_last_http_request_time = 0;
string g_last_http_error = "";
bool g_daemon_health_checked = false;
// --- KELLY CRITERION GLOBAL VARIABLES ---
KellyTradeRecord g_kelly_trade_history[];
KellyMetrics g_kelly_metrics;
double g_current_kelly_fraction = 0.02; // Current Kelly fraction
double g_smoothed_kelly_fraction = 0.02; // Smoothed Kelly fraction
double g_last_calculated_kelly = 0.02; // Last raw Kelly calculation
datetime g_last_kelly_update = 0; // Last Kelly update time
// --- ADAPTIVE LEARNING GLOBAL VARIABLES ---
TradeRecord g_trade_history[];
AdaptiveMetrics g_adaptive_metrics;
MarketCondition g_current_market_condition;
TesterResult g_tester_results[];
ScalpingPosition g_scalping_position; // Current scalping position
datetime g_last_adaptation_time = 0;
bool g_adaptive_system_initialized = false;
bool g_is_tester_mode = false;
double g_tester_start_balance = 0;
double g_max_equity_peak = 0;
double g_current_drawdown = 0;
// Original global variables
StepPrediction g_step_predictions[];
double g_last_predictions[PREDICTION_STEPS];
double g_last_confidence_score = 0.0;
double g_accuracy_pct[PREDICTION_STEPS];
int g_total_hits[PREDICTION_STEPS], g_total_predictions[PREDICTION_STEPS];
double g_active_trade_target_price = 0;
// NEW: Daily Prediction Globals
double g_last_daily_prediction_price = 0;
ENUM_PREDICTION_DIRECTION g_last_daily_prediction_direction = DIR_NEUTRAL;
datetime g_last_daily_prediction_time = 0;
struct BacktestPrediction { datetime timestamp; double buy_prob, sell_prob, hold_prob, confidence_score; double predicted_prices[PREDICTION_STEPS]; };
BacktestPrediction g_backtest_predictions[];
int g_backtest_prediction_idx = 0;
double g_RiskPercent, g_MinimumRiskRewardRatio, g_ATR_SL_Multiplier, g_ATR_TP_Multiplier, g_MinProfitPips, g_TrailingStartPips, g_TrailingStopPips, g_MinimumModelConfidence, g_MinimumSignalConfidence, g_ClassificationSignalThreshold;
int g_RequiredConsistentSteps, g_StaticStopLossPips, g_StaticTakeProfitPips, g_ATR_Period, g_MaxPositionHoldBars, g_ExitBarMinute, g_ADX_Period, g_ADX_Threshold, g_AccuracyLookbackOnInit, g_AccuracyWindowBars, g_PredictionUpdateMinutes;
bool g_EnableTimeBasedExit, g_EnableTrailingStop, g_EnableADXFilter;
ENUM_TRADING_MODE g_TradingLogicMode;
ENUM_STOP_LOSS_MODE g_StopLossMode;
ENUM_TAKE_PROFIT_MODE g_TakeProfitMode;
datetime g_last_successful_request = 0;
datetime g_last_request_attempt = 0;
datetime g_last_prediction_time = 0;
int g_total_requests_sent = 0;
int g_successful_responses = 0;
string g_connection_status = "Not Connected";
string g_last_error = "";
//+------------------------------------------------------------------+
//| HTTP COMMUNICATION FUNCTIONS
//+------------------------------------------------------------------+
string BuildDaemonUrl(string endpoint = "predict")
{
return StringFormat("http://%s:%d/%s", DaemonHost, DaemonPort, endpoint);
}
//+------------------------------------------------------------------+
//| PROPERLY FIXED HTTP COMMUNICATION FUNCTIONS
//+------------------------------------------------------------------+
bool CheckDaemonHealth()
{
if(g_daemon_health_checked) return true;
string health_url = BuildDaemonUrl("health");
string headers = "Content-Type: application/json\r\n";
uchar response_data[];
string response_headers;
int timeout = 5000; // 5 second timeout for health check
if(EnableHttpLogging)
PrintFormat("🏥 Checking daemon health: %s", health_url);
// FIXED: Correct WebRequest signature with uchar[] arrays
uchar empty_data[];
int result = WebRequest("GET", health_url, headers, timeout, empty_data, response_data, response_headers);
if(result == 200)
{
string response_text = CharArrayToString(response_data);
if(EnableHttpLogging)
PrintFormat("✅ Daemon health check successful: %s", response_text);
// Parse health response to check model status
if(StringFind(response_text, "\"status\": \"healthy\"") >= 0 &&
StringFind(response_text, "\"model_loaded\": true") >= 0)
{
g_daemon_health_checked = true;
return true;
}
else
{
PrintFormat("❌ Daemon not fully ready: %s", response_text);
return false;
}
}
else
{
g_last_http_error = StringFormat("Health check failed: HTTP %d", result);
if(EnableHttpLogging)
PrintFormat("❌ %s", g_last_http_error);
return false;
}
}
bool SendHttpRequest(const double &features[], double current_price, double atr_val, DaemonResponse &response)
{
if(!CheckDaemonHealth()) return false;
g_http_requests_sent++;
g_last_http_request_time = TimeCurrent();
// Build JSON request
string request_id = GenerateRequestID();
string json_request = StringFormat("{\n \"request_id\": \"%s\",\n", request_id);
json_request += StringFormat(" \"current_price\": %.8f,\n", current_price);
json_request += StringFormat(" \"atr\": %.8f,\n", atr_val);
json_request += " \"features\": [";
for(int i = 0; i < ArraySize(features); i++)
{
json_request += DoubleToString(features[i], 8);
if(i < ArraySize(features) - 1) json_request += ", ";
}
json_request += "]\n}";
// Prepare HTTP request
string url = BuildDaemonUrl("predict");
string headers = "Content-Type: application/json\r\n";
uchar post_data[];
StringToCharArray(json_request, post_data, 0, StringLen(json_request));
uchar response_data[];
string response_headers;
if(EnableHttpLogging)
PrintFormat("📤 Sending HTTP request to: %s (%.2f KB)", url, ArraySize(post_data) / 1024.0);
// Attempt request with retries
for(int attempt = 1; attempt <= MaxRetryAttempts; attempt++)
{
// FIXED: Correct WebRequest signature with uchar[] arrays
int result = WebRequest("POST", url, headers, HttpTimeoutMs, post_data, response_data, response_headers);
if(result == 200)
{
// Successful response
string response_text = CharArrayToString(response_data);
if(EnableHttpLogging)
PrintFormat("✅ HTTP response received (attempt %d): %.2f KB", attempt, ArraySize(response_data) / 1024.0);
// Parse response
if(ParsePredictionResponse(response_text, response))
{
g_http_successful_responses++;
g_connection_status = "Connected";
g_last_error = "";
return true;
}
else
{
g_last_http_error = "Failed to parse response JSON";
if(EnableHttpLogging)
PrintFormat("❌ JSON parsing failed: %s", response_text);
break;
}
}
else
{
// HTTP error
string error_response = CharArrayToString(response_data);
g_last_http_error = StringFormat("HTTP %d: %s", result, error_response);
if(EnableHttpLogging)
PrintFormat("❌ HTTP error (attempt %d/%d): %s", attempt, MaxRetryAttempts, g_last_http_error);
// Check if we should retry
if(attempt < MaxRetryAttempts)
{
if(result == -1) // Network error
{
Sleep(RetryDelayMs * attempt); // Exponential backoff
continue;
}
else if(result >= 500) // Server error
{
Sleep(RetryDelayMs);
continue;
}
else // Client error (4xx) - don't retry
{
break;
}
}
}
}
// All attempts failed
g_http_failed_responses++;
g_connection_status = "Error";
g_last_error = g_last_http_error;
return false;
}
bool ParsePredictionResponse(string response_text, DaemonResponse &response)
{
// Check for error status
if(StringFind(response_text, "\"status\": \"error\"") >= 0)
{
// Extract error message
int msg_start = StringFind(response_text, "\"message\": \"");
if(msg_start >= 0)
{
msg_start += 12; // Length of "\"message\": \""
int msg_end = StringFind(response_text, "\"", msg_start);
if(msg_end > msg_start)
{
g_last_http_error = "Daemon error: " + StringSubstr(response_text, msg_start, msg_end - msg_start);
}
}
return false;
}
// Parse predicted prices array
int prices_start = StringFind(response_text, "\"predicted_prices\"");
if(prices_start < 0) return false;
int bracket_start = StringFind(response_text, "[", prices_start);
int bracket_end = StringFind(response_text, "]", bracket_start);
if(bracket_start < 0 || bracket_end < 0) return false;
string prices_str = StringSubstr(response_text, bracket_start + 1, bracket_end - bracket_start - 1);
string price_values[];
if(StringSplit(prices_str, ',', price_values) != PREDICTION_STEPS) return false;
// Convert to double array
for(int i = 0; i < PREDICTION_STEPS; i++)
{
string clean_price = price_values[i];
StringTrimLeft(clean_price);
StringTrimRight(clean_price);
response.prices[i] = StringToDouble(clean_price);
}
// Parse other fields
if(!JsonGetValue(response_text, "confidence_score", response.confidence_score)) return false;
if(!JsonGetValue(response_text, "buy_probability", response.buy_prob)) return false;
if(!JsonGetValue(response_text, "sell_probability", response.sell_prob)) return false;
return true;
}
bool TestDaemonCommunication()
{
PrintFormat("🧪 TESTING HTTP DAEMON COMMUNICATION...");
PrintFormat(" Target: %s", BuildDaemonUrl());
// Test health endpoint first
if(!CheckDaemonHealth())
{
PrintFormat("❌ DAEMON HEALTH CHECK FAILED!");
PrintFormat(" Make sure the daemon is running: python daemon_http.py");
PrintFormat(" Check if URL '%s' is in allowed URLs list", BuildDaemonUrl("health"));
return false;
}
PrintFormat("✅ Daemon health check passed!");
// Test prediction endpoint
double test_features[FEATURE_COUNT * SEQ_LEN];
for(int i = 0; i < ArraySize(test_features); i++)
{
test_features[i] = 0.001 * (i % 20); // Simple test data
}
MqlTick tick;
if(!SymbolInfoTick(_Symbol, tick))
{
PrintFormat("❌ Could not get current tick for test");
return false;
}
DaemonResponse test_response;
PrintFormat("📤 Sending test prediction request...");
if(SendHttpRequest(test_features, tick.ask, 0.0010, test_response))
{
PrintFormat("✅✅✅ HTTP DAEMON TEST SUCCESSFUL! ✅✅✅");
PrintFormat(" Confidence: %.3f", test_response.confidence_score);
PrintFormat(" Buy Probability: %.3f", test_response.buy_prob);
PrintFormat(" Sell Probability: %.3f", test_response.sell_prob);
PrintFormat(" First Predicted Price: %.5f", test_response.prices[0]);
PrintFormat(" HTTP Requests: %d successful, %d failed", g_http_successful_responses, g_http_failed_responses);
return true;
}
else
{
PrintFormat("❌❌❌ HTTP DAEMON TEST FAILED! ❌❌❌");
PrintFormat(" Error: %s", g_last_http_error);
PrintFormat(" Connection Status: %s", g_connection_status);
PrintFormat("\n🔧 TROUBLESHOOTING STEPS:");
PrintFormat("1. Ensure daemon is running: python daemon_http.py");
PrintFormat("2. Check daemon console for errors");
PrintFormat("3. Verify daemon host:port: %s:%d", DaemonHost, DaemonPort);
PrintFormat("4. Add daemon URL to MT5 allowed URLs:");
PrintFormat(" Tools → Options → Expert Advisors → Allow WebRequest for URL:");
PrintFormat(" %s", BuildDaemonUrl());
PrintFormat("5. Check Windows Firewall settings");
PrintFormat("6. Test daemon manually: curl -X GET %s", BuildDaemonUrl("health"));
return false;
}
}
string GetHttpConnectionStats()
{
if(g_http_requests_sent == 0) return "No requests sent";
double success_rate = (double)g_http_successful_responses / g_http_requests_sent * 100.0;
return StringFormat("%d/%d (%.1f%%)", g_http_successful_responses, g_http_requests_sent, success_rate);
}
//+------------------------------------------------------------------+
//| KELLY CRITERION FUNCTIONS
//+------------------------------------------------------------------+
void InitializeKellySystem()
{
ArrayResize(g_kelly_trade_history, 0);
// Initialize Kelly metrics
g_kelly_metrics.win_rate = 0.5; // Start with 50% assumption
g_kelly_metrics.avg_win_pips = 20.0; // Conservative estimates
g_kelly_metrics.avg_loss_pips = 15.0;
g_kelly_metrics.avg_r_multiple = 1.33;
g_kelly_metrics.profit_factor = 1.33;
g_kelly_metrics.total_trades = 0;
g_kelly_metrics.winning_trades = 0;
g_kelly_metrics.kelly_fraction = BaseRiskWhenNoHistory / 100.0;
g_kelly_metrics.confidence_adjusted_kelly = g_kelly_metrics.kelly_fraction;
g_current_kelly_fraction = BaseRiskWhenNoHistory / 100.0;
g_smoothed_kelly_fraction = g_current_kelly_fraction;
LoadKellyTradeHistory(); // Load from file if exists
PrintFormat("🎯 KELLY CRITERION INITIALIZED:");
PrintFormat(" Enabled: %s", EnableKellyCriterion ? "YES" : "NO");
PrintFormat(" Max Kelly Fraction: %.1f%%", MaxKellyFraction * 100);
PrintFormat(" Kelly Multiplier: %.2f (Half-Kelly)", KellyMultiplier);
PrintFormat(" Lookback Trades: %d", KellyLookbackTrades);
PrintFormat(" Initial Kelly Fraction: %.2f%%", g_current_kelly_fraction * 100);
}
void LoadKellyTradeHistory()
{
string filename = "kelly_trade_history.csv";
if(!FileIsExist(filename, FILE_COMMON)) return;
int file = FileOpen(filename, FILE_READ | FILE_CSV | FILE_COMMON);
if(file == INVALID_HANDLE) return;
// Skip header
if(!FileIsEnding(file)) FileReadString(file);
ArrayResize(g_kelly_trade_history, 0);
while(!FileIsEnding(file) && ArraySize(g_kelly_trade_history) < KellyLookbackTrades * 2)
{
KellyTradeRecord record;
record.trade_time = StringToTime(FileReadString(file));
record.was_profitable = (FileReadNumber(file) > 0.5);
record.profit_pips = FileReadNumber(file);
record.loss_pips = FileReadNumber(file);
record.r_multiple = FileReadNumber(file);
record.confidence_used = FileReadNumber(file);
record.trade_type = (ENUM_ORDER_TYPE)FileReadNumber(file);
int size = ArraySize(g_kelly_trade_history);
ArrayResize(g_kelly_trade_history, size + 1);
g_kelly_trade_history[size] = record;
}
FileClose(file);
if(ArraySize(g_kelly_trade_history) > 0)
{
CalculateKellyMetrics();
PrintFormat("📊 Loaded %d Kelly trade records from history", ArraySize(g_kelly_trade_history));
}
}
void SaveKellyTradeHistory()
{
string filename = "kelly_trade_history.csv";
int file = FileOpen(filename, FILE_WRITE | FILE_CSV | FILE_COMMON);
if(file == INVALID_HANDLE) return;
// Write header
FileWrite(file, "TradeTime,WasProfitable,ProfitPips,LossPips,RMultiple,ConfidenceUsed,TradeType");
// Keep only recent trades
int start_idx = MathMax(0, ArraySize(g_kelly_trade_history) - KellyLookbackTrades * 2);
for(int i = start_idx; i < ArraySize(g_kelly_trade_history); i++)
{
FileWrite(file, TimeToString(g_kelly_trade_history[i].trade_time),
g_kelly_trade_history[i].was_profitable ? 1 : 0,
g_kelly_trade_history[i].profit_pips,
g_kelly_trade_history[i].loss_pips,
g_kelly_trade_history[i].r_multiple,
g_kelly_trade_history[i].confidence_used,
(int)g_kelly_trade_history[i].trade_type);
}
FileClose(file);
}
void RecordKellyTrade(bool was_profitable, double profit_pips, double loss_pips,
double confidence_used, ENUM_ORDER_TYPE trade_type)
{
KellyTradeRecord new_record;
new_record.trade_time = TimeCurrent();
new_record.was_profitable = was_profitable;
new_record.profit_pips = profit_pips;
new_record.loss_pips = loss_pips;
new_record.r_multiple = (loss_pips > 0) ? (profit_pips / loss_pips) : 0;
new_record.confidence_used = confidence_used;
new_record.trade_type = trade_type;
// Add to history array
int size = ArraySize(g_kelly_trade_history);
ArrayResize(g_kelly_trade_history, size + 1);
g_kelly_trade_history[size] = new_record;
// Keep only recent trades
if(ArraySize(g_kelly_trade_history) > KellyLookbackTrades * 2)
{
int excess = ArraySize(g_kelly_trade_history) - KellyLookbackTrades * 2;
for(int i = 0; i < ArraySize(g_kelly_trade_history) - excess; i++)
g_kelly_trade_history[i] = g_kelly_trade_history[i + excess];
ArrayResize(g_kelly_trade_history, ArraySize(g_kelly_trade_history) - excess);
}
// Recalculate Kelly metrics
CalculateKellyMetrics();
SaveKellyTradeHistory();
PrintFormat("📝 KELLY TRADE RECORDED: %s, %.1f pips, R=%.2f, New Kelly=%.2f%%",
was_profitable ? "WIN" : "LOSS",
was_profitable ? profit_pips : -loss_pips,
new_record.r_multiple, g_current_kelly_fraction * 100);
}
void CalculateKellyMetrics()
{
if(ArraySize(g_kelly_trade_history) < 5)
{
// Not enough data, use conservative defaults
g_kelly_metrics.win_rate = 0.5;
g_kelly_metrics.avg_win_pips = 20.0;
g_kelly_metrics.avg_loss_pips = 15.0;
g_kelly_metrics.avg_r_multiple = 1.33;
g_kelly_metrics.profit_factor = 1.33;
g_kelly_metrics.total_trades = ArraySize(g_kelly_trade_history);
g_kelly_metrics.winning_trades = 0;
// Count actual wins for small sample
for(int i = 0; i < ArraySize(g_kelly_trade_history); i++)
if(g_kelly_trade_history[i].was_profitable) g_kelly_metrics.winning_trades++;
g_kelly_metrics.kelly_fraction = BaseRiskWhenNoHistory / 100.0;
g_current_kelly_fraction = g_kelly_metrics.kelly_fraction;
return;
}
// Use recent trades for calculation
int analyze_count = MathMin(ArraySize(g_kelly_trade_history), KellyLookbackTrades);
int start_idx = ArraySize(g_kelly_trade_history) - analyze_count;
// Calculate win rate and averages
int wins = 0;
double total_win_pips = 0, total_loss_pips = 0;
double total_win_r = 0, total_loss_r = 0;
int win_count = 0, loss_count = 0;
for(int i = start_idx; i < ArraySize(g_kelly_trade_history); i++)
{
if(g_kelly_trade_history[i].was_profitable)
{
wins++;
win_count++;
total_win_pips += g_kelly_trade_history[i].profit_pips;
total_win_r += g_kelly_trade_history[i].r_multiple;
}
else
{
loss_count++;
total_loss_pips += g_kelly_trade_history[i].loss_pips;
}
}
g_kelly_metrics.total_trades = analyze_count;
g_kelly_metrics.winning_trades = wins;
g_kelly_metrics.win_rate = (double)wins / analyze_count;
g_kelly_metrics.avg_win_pips = (win_count > 0) ? total_win_pips / win_count : 20.0;
g_kelly_metrics.avg_loss_pips = (loss_count > 0) ? total_loss_pips / loss_count : 15.0;
g_kelly_metrics.avg_r_multiple = (win_count > 0) ? total_win_r / win_count : 1.0;
// Calculate profit factor
g_kelly_metrics.profit_factor = (total_loss_pips > 0) ? total_win_pips / total_loss_pips : 1.0;
// Calculate Kelly fraction using the standard formula
// Kelly% = (Win_Rate * Avg_R_Multiple - Loss_Rate) / Avg_R_Multiple
double loss_rate = 1.0 - g_kelly_metrics.win_rate;
double avg_r = g_kelly_metrics.avg_r_multiple;
if(avg_r > 0)
{
g_kelly_metrics.kelly_fraction = (g_kelly_metrics.win_rate * avg_r - loss_rate) / avg_r;
}
else
{
g_kelly_metrics.kelly_fraction = 0.02; // Fallback
}
// Apply Kelly multiplier (Half-Kelly is common)
g_kelly_metrics.kelly_fraction *= KellyMultiplier;
// Apply bounds
g_kelly_metrics.kelly_fraction = MathMax(MinKellyFraction,
MathMin(MaxKellyFraction, g_kelly_metrics.kelly_fraction));
// Store raw calculation
g_last_calculated_kelly = g_kelly_metrics.kelly_fraction;
// Apply smoothing if enabled
if(EnableKellySmoothing && g_current_kelly_fraction > 0)
{
g_smoothed_kelly_fraction = g_current_kelly_fraction * (1.0 - KellySmoothingFactor) +
g_kelly_metrics.kelly_fraction * KellySmoothingFactor;
}
else
{
g_smoothed_kelly_fraction = g_kelly_metrics.kelly_fraction;
}
g_current_kelly_fraction = g_smoothed_kelly_fraction;
g_last_kelly_update = TimeCurrent();
PrintFormat("📊 KELLY METRICS UPDATE (%d trades):", analyze_count);
PrintFormat(" Win Rate: %.1f%% (%d/%d)", g_kelly_metrics.win_rate * 100, wins, analyze_count);
PrintFormat(" Avg Win: %.1f pips | Avg Loss: %.1f pips",
g_kelly_metrics.avg_win_pips, g_kelly_metrics.avg_loss_pips);
PrintFormat(" Avg R-Multiple: %.2f | Profit Factor: %.2f",
g_kelly_metrics.avg_r_multiple, g_kelly_metrics.profit_factor);
PrintFormat(" Raw Kelly: %.2f%% | Smoothed Kelly: %.2f%%",
g_kelly_metrics.kelly_fraction * 100, g_current_kelly_fraction * 100);
}
double GetConfidenceAdjustedKelly(double prediction_confidence)
{
if(!UseConfidenceScaling) return g_current_kelly_fraction;
// Scale Kelly fraction by prediction confidence
// Higher confidence = larger position, lower confidence = smaller position
double confidence_multiplier = prediction_confidence / 0.5; // 0.5 = neutral confidence
confidence_multiplier = MathMax(0.3, MathMin(2.0, confidence_multiplier)); // Bounds
double adjusted_kelly = g_current_kelly_fraction * confidence_multiplier;
// Apply final bounds
adjusted_kelly = MathMax(MinKellyFraction, MathMin(MaxKellyFraction, adjusted_kelly));
g_kelly_metrics.confidence_adjusted_kelly = adjusted_kelly;
return adjusted_kelly;
}
//+------------------------------------------------------------------+
//| STRATEGY TESTER LEARNING FUNCTIONS
//+------------------------------------------------------------------+
void InitializeTesterLearning()
{
g_is_tester_mode = MQLInfoInteger(MQL_TESTER);
if(g_is_tester_mode)
{
g_tester_start_balance = AccountInfoDouble(ACCOUNT_BALANCE);
g_max_equity_peak = g_tester_start_balance;
PrintFormat("🧪 Strategy Tester Learning Mode - Start Balance: %.2f", g_tester_start_balance);
}
LoadTesterResults();
}
void LoadTesterResults()
{
if(!EnableTesterLearning || !FileIsExist(TESTER_RESULTS_FILE, FILE_COMMON)) return;
int file = FileOpen(TESTER_RESULTS_FILE, FILE_READ | FILE_CSV | FILE_COMMON);
if(file == INVALID_HANDLE) return;
// Skip header
if(!FileIsEnding(file)) FileReadString(file);
ArrayResize(g_tester_results, 0);
while(!FileIsEnding(file))
{
TesterResult result;
result.test_date = StringToTime(FileReadString(file));
result.symbol = FileReadString(file);
result.timeframe = FileReadString(file);
result.total_profit = FileReadNumber(file);
result.max_drawdown = FileReadNumber(file);
result.total_trades = (int)FileReadNumber(file);
result.success_rate = FileReadNumber(file);
result.sharpe_ratio = FileReadNumber(file);
result.best_confidence_threshold = FileReadNumber(file);
result.best_risk_multiplier = FileReadNumber(file);
for(int i = 0; i < PREDICTION_STEPS; i++)
result.avg_step_weight[i] = FileReadNumber(file);
result.market_conditions_score = FileReadNumber(file);
int size = ArraySize(g_tester_results);
ArrayResize(g_tester_results, size + 1);
g_tester_results[size] = result;
}
FileClose(file);
PrintFormat("📊 Loaded %d tester results for learning", ArraySize(g_tester_results));
}
void SaveTesterResults()
{
if(!EnableTesterLearning) return;
int file = FileOpen(TESTER_RESULTS_FILE, FILE_WRITE | FILE_CSV | FILE_COMMON);
if(file == INVALID_HANDLE) return;
// Write header
string header = "TestDate,Symbol,Timeframe,TotalProfit,MaxDrawdown,TotalTrades,SuccessRate,SharpeRatio,BestConfidence,BestRiskMultiplier";
for(int i = 0; i < PREDICTION_STEPS; i++)
header += ",StepWeight" + IntegerToString(i);
header += ",MarketConditionsScore";
FileWrite(file, header);
for(int i = 0; i < ArraySize(g_tester_results); i++)
{
string line = TimeToString(g_tester_results[i].test_date) + "," +
g_tester_results[i].symbol + "," +
g_tester_results[i].timeframe + "," +
DoubleToString(g_tester_results[i].total_profit, 2) + "," +
DoubleToString(g_tester_results[i].max_drawdown, 2) + "," +
IntegerToString(g_tester_results[i].total_trades) + "," +
DoubleToString(g_tester_results[i].success_rate, 3) + "," +
DoubleToString(g_tester_results[i].sharpe_ratio, 3) + "," +
DoubleToString(g_tester_results[i].best_confidence_threshold, 3) + "," +
DoubleToString(g_tester_results[i].best_risk_multiplier, 3);
for(int j = 0; j < PREDICTION_STEPS; j++)
line += "," + DoubleToString(g_tester_results[i].avg_step_weight[j], 3);
line += "," + DoubleToString(g_tester_results[i].market_conditions_score, 3);
FileWrite(file, line);
}
FileClose(file);
}
void RecordTesterResult()
{
if(!g_is_tester_mode || !EnableTesterLearning) return;
// Calculate test results
HistorySelect(0, TimeCurrent());
int total_deals = HistoryDealsTotal();
double total_profit = 0;
int profitable_trades = 0;
int total_trades = 0;
double max_dd = 0;
for(int i = 0; i < total_deals; i++)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0 && HistoryDealGetString(ticket, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
{
double profit = HistoryDealGetDouble(ticket, DEAL_PROFIT);
total_profit += profit;
total_trades++;
if(profit > 0) profitable_trades++;
}
}
// Calculate Sharpe ratio
double profits[];
ArrayResize(profits, total_trades);
int profit_idx = 0;
for(int i = 0; i < total_deals; i++)
{
ulong ticket = HistoryDealGetTicket(i);
if(ticket > 0 && HistoryDealGetString(ticket, DEAL_SYMBOL) == _Symbol &&
HistoryDealGetInteger(ticket, DEAL_ENTRY) == DEAL_ENTRY_OUT)
{
profits[profit_idx++] = HistoryDealGetDouble(ticket, DEAL_PROFIT);
}
}
double sharpe = 0;
if(total_trades > 1)
{
double mean_profit = MathMean(profits);
double std_dev = MathStandardDeviation(profits);
if(std_dev > 0) sharpe = mean_profit / std_dev;
}
// Create tester result record
TesterResult result;
result.test_date = TimeCurrent();
result.symbol = _Symbol;
result.timeframe = "H1";
result.total_profit = total_profit;
result.max_drawdown = g_current_drawdown;
result.total_trades = total_trades;
result.success_rate = (total_trades > 0) ? (double)profitable_trades / total_trades * 100.0 : 0;
result.sharpe_ratio = sharpe;
result.best_confidence_threshold = g_adaptive_metrics.dynamic_confidence_threshold;
result.best_risk_multiplier = g_adaptive_metrics.dynamic_risk_multiplier;
for(int i = 0; i < PREDICTION_STEPS; i++)
result.avg_step_weight[i] = g_adaptive_metrics.step_weights[i];
result.market_conditions_score = CalculateMarketConditionScore();