-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUltimate_Gold_Scalper.mq5
More file actions
534 lines (476 loc) · 19.5 KB
/
Copy pathUltimate_Gold_Scalper.mq5
File metadata and controls
534 lines (476 loc) · 19.5 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
//+------------------------------------------------------------------+
//| Ultimate_ICT_Gold_Scalper_v3.0.mq5 |
//| Professional Trading Systems |
//| Version 3.00 |
//+------------------------------------------------------------------+
#property copyright "Professional Trading Systems"
#property version "3.00"
#property description "Advanced ICT Gold Scalper with FVG, Order Blocks, Silver Bullet"
#property strict
#include <Trade/Trade.mqh>
#include <Trade/PositionInfo.mqh>
#include <Trade/SymbolInfo.mqh>
#include <Trade/AccountInfo.mqh>
#include <Trade/DealInfo.mqh>
#include <Math/Stat/Math.mqh>
//+------------------------------------------------------------------+
//| Input Parameters - Optimized for XAUUSD |
//+------------------------------------------------------------------+
input group "=== Risk Management ==="
input double RiskPercent = 1.0; // Risk per trade (%)
input double MaxDailyRiskPercent = 5.0; // Max daily loss (%)
input double MaxDailyProfitPercent = 8.0; // Daily profit target (%)
input int MaxPositions = 2; // Maximum concurrent positions
input int MaxDailyTrades = 10; // Maximum trades per day
input group "=== XAUUSD Specific Settings ==="
input double MinATR_Points = 100.0; // Minimum ATR for Gold (points)
input double MaxSpreadPoints = 50.0; // Maximum spread (points)
input double ATR_SL_Multiplier = 2.0; // Stop Loss ATR multiplier
input double ATR_TP_Multiplier = 3.0; // Take Profit ATR multiplier
input group "=== ICT Strategy Parameters ==="
input bool UseLiquiditySweeps = true; // Use liquidity sweeps
input bool UseFairValueGaps = true; // Use Fair Value Gaps
input bool UseOrderBlocks = true; // Use Order Blocks
input bool UseSilverBullet = true; // Use Silver Bullet
input int LiquidityLookback = 50; // Bars for liquidity lookback
input int FVG_Lookback = 20; // Bars for FVG lookback
input double FVG_MinSizeATR = 0.5; // Minimum FVG size (x ATR)
input group "=== Session Settings ==="
input bool TradeAsianSession = false; // Trade Asian session
input bool TradeLondonSession = true; // Trade London session
input bool TradeNewYorkSession = true; // Trade New York session
input int LondonStartHour = 7; // London session start (hour, broker time)
input int NewYorkStartHour = 13; // New York session start (hour, broker time)
input group "=== Silver Bullet Windows ==="
input bool LondonSilverBullet = true; // London Silver Bullet
input int LondonKillZoneStart = 8; // London Kill Zone start
input int LondonKillZoneEnd = 9; // London Kill Zone end
input bool NewYorkSilverBullet = true; // New York Silver Bullet
input int NYKillZoneStart = 15; // New York Kill Zone start
input int NYKillZoneEnd = 16; // New York Kill Zone end
input group "=== Position Management ==="
input bool UseBreakEven = true; // Move to breakeven
input double BE_TriggerATR = 1.0; // Breakeven trigger (x ATR)
input bool UseTrailingStop = true; // Use trailing stop
input double Trail_StartATR = 1.5; // Trailing start (x ATR)
input double Trail_StepATR = 0.5; // Trailing step (x ATR)
input bool UsePartialClose = true; // Use partial close
input double PartialClosePercent = 50.0; // Partial close percentage
input double PartialCloseTriggerATR = 1.0; // Partial close trigger (x ATR)
input group "=== Execution Settings ==="
input int SlippagePoints = 10; // Slippage in points
input int OrderRetryCount = 5; // Order retry count
input int OrderRetryDelayMs = 200; // Retry delay (ms)
input group "=== System Settings ==="
enum ENUM_LOG_LEVEL {
LOG_NONE = 0,
LOG_ERROR = 1,
LOG_WARNING = 2,
LOG_INFO = 3,
LOG_DEBUG = 4
};
input ENUM_LOG_LEVEL LogLevel = LOG_INFO; // Log level
input bool UseAsyncExecution = true; // Use async order execution
input bool EnablePerformanceMode = true; // Enable performance optimizations
//+------------------------------------------------------------------+
//| Structures and Classes |
//+------------------------------------------------------------------+
// Performance optimized market data storage
class CMarketData {
public:
datetime time[10000];
double high[10000];
double low[10000];
double close[10000];
double volume[10000];
int dataIndex;
CMarketData() : dataIndex(0) {}
void AddBar(datetime t, double h, double l, double c, double v) {
int idx = dataIndex % 10000;
time[idx] = t;
high[idx] = h;
low[idx] = l;
close[idx] = c;
volume[idx] = v;
dataIndex++;
}
};
// Liquidity Level Structure
struct LiquidityLevel {
double price;
datetime time;
int strength; // How many times tested
bool isHigh; // True for resistance, false for support
bool swept; // Has been swept?
double volume; // Volume at this level
};
// Fair Value Gap Structure
struct FairValueGap {
double topPrice;
double bottomPrice;
datetime time;
bool isBullish;
bool filled;
double size; // Gap size in points
};
// Order Block Structure
struct OrderBlock {
double topPrice;
double bottomPrice;
datetime time;
bool isBullish;
bool mitigated;
double volume;
};
// Advanced Position Tracker
class CPositionTracker {
public:
ulong ticket;
datetime openTime;
double openPrice;
double originalSL;
double originalTP;
bool partialClosed;
bool breakEvenSet;
bool trailingActive;
double peakProfit; // Track highest profit
double currentRR; // Current Risk-Reward
CPositionTracker() { Reset(); }
void Reset() {
ticket = 0;
openTime = 0;
openPrice = 0;
originalSL = 0;
originalTP = 0;
partialClosed = false;
breakEvenSet = false;
trailingActive = false;
peakProfit = 0;
currentRR = 0;
}
};
// Object Pool for Memory Efficiency
template<typename T>
class CObjectPool {
private:
T* m_pool[];
int m_poolSize;
int m_nextAvailable;
public:
CObjectPool(int size = 100) {
m_poolSize = size;
ArrayResize(m_pool, m_poolSize);
m_nextAvailable = 0;
for(int i = 0; i < m_poolSize; i++) {
m_pool[i] = new T();
}
}
~CObjectPool() {
for(int i = 0; i < m_poolSize; i++) {
delete m_pool[i];
}
}
T* Acquire() {
if(m_nextAvailable >= m_poolSize) {
int oldSize = m_poolSize;
m_poolSize *= 2;
ArrayResize(m_pool, m_poolSize);
for(int i = oldSize; i < m_poolSize; i++) {
m_pool[i] = new T();
}
}
return m_pool[m_nextAvailable++];
}
void Release(T* obj) {
obj.Reset();
m_nextAvailable--;
}
};
//+------------------------------------------------------------------+
//| Main EA Class |
//+------------------------------------------------------------------+
class CUltimateICTGoldScalper {
private:
// Core objects
CTrade m_trade;
CPositionInfo m_position;
CSymbolInfo m_symbol;
CAccountInfo m_account;
// Indicator handles
int m_atrHandle;
int m_emaFastHandle;
int m_emaSlowHandle;
int m_volumeHandle;
// Market structure
LiquidityLevel m_liquidityLevels[];
FairValueGap m_fairValueGaps[];
OrderBlock m_orderBlocks[];
CMarketData m_marketData;
// Position tracking
CObjectPool<CPositionTracker>* m_positionPool;
CPositionTracker* m_activePositions[];
// Performance metrics
double m_dayStartBalance;
int m_todayTradeCount;
datetime m_lastTradeTime;
double m_currentATR;
// System variables
long m_magicNumber;
bool m_initialized;
// Private methods
void LogError(string message) { if(LogLevel >= LOG_ERROR) Print("[ERROR] ", message); }
void LogWarning(string message) { if(LogLevel >= LOG_WARNING) Print("[WARN] ", message); }
void LogInfo(string message) { if(LogLevel >= LOG_INFO) Print("[INFO] ", message); }
void LogDebug(string message) { if(LogLevel >= LOG_DEBUG) Print("[DEBUG] ", message); }
long GenerateMagicNumber() {
string str = _Symbol + IntegerToString(Period());
uchar arr[];
StringToCharArray(str, arr);
long hash = 0;
for(int i = 0; i < ArraySize(arr); i++) {
hash = (hash * 31 + arr[i]) % 9999999;
}
return 100000 + hash;
}
bool IsRecoverableError(int errorCode) {
switch(errorCode) {
case TRADE_RETCODE_REQUOTE:
case TRADE_RETCODE_PRICE_CHANGED:
case TRADE_RETCODE_TIMEOUT:
case TRADE_RETCODE_CONNECTION:
return true;
default:
return false;
}
}
bool ExecuteWithRetry(MqlTradeRequest &request, MqlTradeResult &result) {
for(int attempt = 0; attempt < OrderRetryCount; attempt++) {
ZeroMemory(result);
if(OrderSend(request, result)) {
if(result.retcode == TRADE_RETCODE_DONE) return true;
}
if(!IsRecoverableError(result.retcode)) break;
Sleep(OrderRetryDelayMs * (int)pow(2, attempt));
}
return false;
}
double GetAverageVolume(int periods) {
long volumes[];
ArraySetAsSeries(volumes, true);
if(CopyTickVolume(_Symbol, PERIOD_M5, 0, periods, volumes) <= 0) return 0;
double sum = 0;
for(int i = 0; i < periods; i++) sum += volumes[i];
return sum / periods;
}
double GetCurrentVolumeRatio() {
long currentVolume = iVolume(_Symbol, PERIOD_M5, 0);
double avgVolume = GetAverageVolume(20);
if(avgVolume > 0) return currentVolume / avgVolume;
return 1.0;
}
bool IsInKillZone() {
if(!UseSilverBullet) return false;
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
int hour = dt.hour;
if(LondonSilverBullet && hour >= LondonKillZoneStart && hour < LondonKillZoneEnd) return true;
if(NewYorkSilverBullet && hour >= NYKillZoneStart && hour < NYKillZoneEnd) return true;
return false;
}
bool IsInTradingSession() {
MqlDateTime dt;
TimeToStruct(TimeCurrent(), dt);
int hour = dt.hour;
if(TradeAsianSession && hour >= 0 && hour < 6) return true;
if(TradeLondonSession && hour >= LondonStartHour && hour < LondonStartHour+4) return true;
if(TradeNewYorkSession && hour >= NewYorkStartHour && hour < NewYorkStartHour+4) return true;
return false;
}
ENUM_POSITION_TYPE GetMarketBias() {
double emaBuffer[];
ArraySetAsSeries(emaBuffer, true);
if(CopyBuffer(m_emaSlowHandle, 0, 0, 1, emaBuffer) <= 0) return -1;
double currentPrice = iClose(_Symbol, PERIOD_M5, 0);
if(currentPrice > emaBuffer[0]) return POSITION_TYPE_BUY;
if(currentPrice < emaBuffer[0]) return POSITION_TYPE_SELL;
return -1;
}
void AddLiquidityLevel(double price, bool isHigh, datetime time) {
int size = ArraySize(m_liquidityLevels);
ArrayResize(m_liquidityLevels, size + 1);
m_liquidityLevels[size].price = price;
m_liquidityLevels[size].isHigh = isHigh;
m_liquidityLevels[size].time = time;
m_liquidityLevels[size].swept = false;
m_liquidityLevels[size].strength = CalculateLevelStrength(price);
long volumes[1];
if(CopyTickVolume(_Symbol, PERIOD_M5, 0, 1, volumes) > 0)
m_liquidityLevels[size].volume = (double)volumes[0];
}
int CalculateLevelStrength(double price) {
int strength = 0;
double tolerance = m_currentATR * 0.1;
for(int i = 1; i < 100; i++) {
double high = iHigh(_Symbol, PERIOD_M5, i);
double low = iLow(_Symbol, PERIOD_M5, i);
if(MathAbs(high - price) < tolerance || MathAbs(low - price) < tolerance)
strength++;
}
return strength;
}
void UpdateLiquidityLevels() {
ArrayResize(m_liquidityLevels, 0);
// Swing highs and lows
for(int i = 3; i < LiquidityLookback; i++) {
// Swing high
if(iHigh(_Symbol, PERIOD_M5, i) > iHigh(_Symbol, PERIOD_M5, i-1) &&
iHigh(_Symbol, PERIOD_M5, i) > iHigh(_Symbol, PERIOD_M5, i-2) &&
iHigh(_Symbol, PERIOD_M5, i) > iHigh(_Symbol, PERIOD_M5, i+1) &&
iHigh(_Symbol, PERIOD_M5, i) > iHigh(_Symbol, PERIOD_M5, i+2)) {
AddLiquidityLevel(iHigh(_Symbol, PERIOD_M5, i), true, iTime(_Symbol, PERIOD_M5, i));
}
// Swing low
if(iLow(_Symbol, PERIOD_M5, i) < iLow(_Symbol, PERIOD_M5, i-1) &&
iLow(_Symbol, PERIOD_M5, i) < iLow(_Symbol, PERIOD_M5, i-2) &&
iLow(_Symbol, PERIOD_M5, i) < iLow(_Symbol, PERIOD_M5, i+1) &&
iLow(_Symbol, PERIOD_M5, i) < iLow(_Symbol, PERIOD_M5, i+2)) {
AddLiquidityLevel(iLow(_Symbol, PERIOD_M5, i), false, iTime(_Symbol, PERIOD_M5, i));
}
}
// Daily and weekly levels
AddLiquidityLevel(iHigh(_Symbol, PERIOD_D1, 0), true, 0);
AddLiquidityLevel(iLow(_Symbol, PERIOD_D1, 0), false, 0);
AddLiquidityLevel(iHigh(_Symbol, PERIOD_W1, 0), true, 0);
AddLiquidityLevel(iLow(_Symbol, PERIOD_W1, 0), false, 0);
}
void UpdateFairValueGaps() {
if(!UseFairValueGaps) return;
ArrayResize(m_fairValueGaps, 0);
for(int i = 2; i < FVG_Lookback; i++) {
// Bullish FVG: current low > previous high
double currentLow = iLow(_Symbol, PERIOD_M5, i);
double prevHigh = iHigh(_Symbol, PERIOD_M5, i-1);
if(currentLow > prevHigh) {
double gapSize = currentLow - prevHigh;
if(gapSize >= m_currentATR * FVG_MinSizeATR) {
int size = ArraySize(m_fairValueGaps);
ArrayResize(m_fairValueGaps, size + 1);
m_fairValueGaps[size].topPrice = currentLow;
m_fairValueGaps[size].bottomPrice = prevHigh;
m_fairValueGaps[size].time = iTime(_Symbol, PERIOD_M5, i);
m_fairValueGaps[size].isBullish = true;
m_fairValueGaps[size].filled = false;
m_fairValueGaps[size].size = gapSize;
}
}
// Bearish FVG: current high < previous low
double currentHigh = iHigh(_Symbol, PERIOD_M5, i);
double prevLow = iLow(_Symbol, PERIOD_M5, i-1);
if(currentHigh < prevLow) {
double gapSize = prevLow - currentHigh;
if(gapSize >= m_currentATR * FVG_MinSizeATR) {
int size = ArraySize(m_fairValueGaps);
ArrayResize(m_fairValueGaps, size + 1);
m_fairValueGaps[size].topPrice = currentHigh;
m_fairValueGaps[size].bottomPrice = prevLow;
m_fairValueGaps[size].time = iTime(_Symbol, PERIOD_M5, i);
m_fairValueGaps[size].isBullish = false;
m_fairValueGaps[size].filled = false;
m_fairValueGaps[size].size = gapSize;
}
}
}
}
void UpdateOrderBlocks() {
if(!UseOrderBlocks) return;
ArrayResize(m_orderBlocks, 0);
for(int i = 1; i < 50; i++) {
// Bullish Order Block: last bearish candle before bullish move
if(iClose(_Symbol, PERIOD_M5, i) < iOpen(_Symbol, PERIOD_M5, i)) { // bearish
if(iClose(_Symbol, PERIOD_M5, i-1) > iOpen(_Symbol, PERIOD_M5, i-1)) { // bullish next
int size = ArraySize(m_orderBlocks);
ArrayResize(m_orderBlocks, size + 1);
m_orderBlocks[size].topPrice = iHigh(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].bottomPrice = iLow(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].time = iTime(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].isBullish = true;
m_orderBlocks[size].mitigated = false;
long volumes[1];
if(CopyTickVolume(_Symbol, PERIOD_M5, i, 1, volumes) > 0)
m_orderBlocks[size].volume = (double)volumes[0];
}
}
// Bearish Order Block: last bullish candle before bearish move
if(iClose(_Symbol, PERIOD_M5, i) > iOpen(_Symbol, PERIOD_M5, i)) { // bullish
if(iClose(_Symbol, PERIOD_M5, i-1) < iOpen(_Symbol, PERIOD_M5, i-1)) { // bearish next
int size = ArraySize(m_orderBlocks);
ArrayResize(m_orderBlocks, size + 1);
m_orderBlocks[size].topPrice = iHigh(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].bottomPrice = iLow(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].time = iTime(_Symbol, PERIOD_M5, i);
m_orderBlocks[size].isBullish = false;
m_orderBlocks[size].mitigated = false;
long volumes[1];
if(CopyTickVolume(_Symbol, PERIOD_M5, i, 1, volumes) > 0)
m_orderBlocks[size].volume = (double)volumes[0];
}
}
}
}
void UpdateMarketData() {
double atrBuffer[];
ArraySetAsSeries(atrBuffer, true);
if(CopyBuffer(m_atrHandle, 0, 0, 1, atrBuffer) > 0)
m_currentATR = atrBuffer[0];
m_marketData.AddBar(
TimeCurrent(),
iHigh(_Symbol, PERIOD_M5, 0),
iLow(_Symbol, PERIOD_M5, 0),
iClose(_Symbol, PERIOD_M5, 0),
(double)iVolume(_Symbol, PERIOD_M5, 0)
);
}
bool CheckDailyLimits() {
if(m_todayTradeCount >= MaxDailyTrades) return true;
double currentEquity = m_account.Equity();
double dailyPL = (currentEquity - m_dayStartBalance) / m_dayStartBalance * 100;
if(dailyPL <= -MaxDailyRiskPercent) {
LogWarning("Daily loss limit reached");
return true;
}
if(dailyPL >= MaxDailyProfitPercent) {
LogInfo("Daily profit target reached");
return true;
}
return false;
}
void ResetDailyStats() {
m_todayTradeCount = 0;
m_dayStartBalance = m_account.Balance();
}
bool CanOpenNewPosition() {
// Max positions
int openPositions = 0;
for(int i = 0; i < PositionsTotal(); i++) {
if(m_position.SelectByIndex(i) && m_position.Magic() == m_magicNumber)
openPositions++;
}
if(openPositions >= MaxPositions) return false;
// Spread check
double spread = SymbolInfoInteger(_Symbol, SYMBOL_SPREAD);
if(spread > MaxSpreadPoints) return false;
// ATR check
if(m_currentATR / _Point < MinATR_Points) return false;
// Session check
if(!IsInTradingSession()) return false;
return true;
}
void CalculateBullishEntry(double &entry, double &sl, double &tp) {
entry = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
sl = entry - (m_currentATR * ATR_SL_Multiplier);
tp = entry + (m_currentATR * ATR_TP_Multiplier);
entry = NormalizeDouble(entry, _Digits);
sl = NormalizeDouble(sl, _Digits);
tp = NormalizeDouble(tp, _Digits);
}
void CalculateBearishEntry(double &entry, doubl