G7 FVG OB Confluence AutoTrader
Сообщите нам, если считаете, что материал размещён без разрешения.
Сообщить о материале
Обращение по товару «g7_fvg_ob_confluence_autotrader.mq5» отправится на рассмотрение. Укажите контакт для ответа и опишите причину.
О программе
G7 FVG OB Confluence AutoTrader — торговый советник для MetaTrader 5, предназначенный для автоматического анализа рыночных данных на заданном таймфрейме и выполнения сделок при возникновении условий, связанных с зонами Order Block и Fair Value Gap. Советник использует пользовательские настройки для определения параметров сканирования, управления рисками и визуализации на графике. В коде присутствуют обработчики событий и вызовы торговых функций, что подтверждает его способность совершать торговые операции. Однако конкретные алгоритмы и торговые правила не раскрываются в описании.
Настройки программы
| Настройка | Описание |
|---|---|
| InpSmcTimeframe | Таймфрейм для сканирования зон Smart Money Concepts. |
| InpLookbackBars | Количество баров истории для анализа. |
| InpSwingLookback | Количество баров для определения силы свинговых максимумов и минимумов. |
| InpMinFvgPips | Минимальный размер имбаланса FVG в пипсах. |
| InpObDisplacementMult | Множитель импульса для определения Order Block относительно ATR. |
| InpRemoveMitigated | Удаляет с графика зоны, которые уже были перекрыты ценой. |
| InpRequireOverlap | Требует строгого физического перекрытия зон Order Block и FVG. |
| InpOverlapTolerancePips | Допуск в пипсах для определения близости зон при совпадении. |
| InpTriggerMode | Режим входа в сделку при касании зоны. |
| InpCooldownBarsM15 | Количество баров M15, в течение которых новые сигналы не обрабатываются после сделки. |
| InpMinConfidenceToTrade | Минимальный уровень уверенности (в процентах) для выполнения сделки. |
| InpDefaultAutoTrade | Включает автоматическое выполнение сделок при обнаружении совпадения зон. |
| InpDefaultLot | Базовый размер лота для сделок. |
| InpDefaultSL_Pips | Размер защитного стоп-лосса в пипсах (0 — использовать границы зоны). |
| InpDefaultTP_Pips | Размер тейк-профита в пипсах. |
| InpMagicNumber | Уникальный номер эксперта для идентификации сделок. |
| InpEnableAutoBE | Включает автоматический перевод позиций в безубыток. |
| InpBETriggerPips | Прибыль в пипсах, при достижении которой активируется перевод в безубыток. |
| InpBELockPips | Количество пунктов, фиксируемых в прибыли при переводе в безубыток. |
| InpEnableTrailing | Включает динамический трейлинг-стоп. |
| InpTrailingStartPips | Прибыль в пипсах, при которой активируется трейлинг-стоп. |
| InpTrailingDistPips | Расстояние трейлинг-стопа в пипсах. |
| InpEnablePropGuard | Включает защиту от дневной просадки для проп-фирм. |
| InpMaxDailyLossPct | Максимальный процент дневного убытка, при котором срабатывает защита. |
| InpMaxDailyProfitPct | Максимальный процент дневной прибыли, при котором фиксируется результат. |
| InpMaxSpreadAllowed | Максимально допустимый спред в пипсах для совершения сделки. |
| InpShowDashboard | Включает отображение информационной панели на графике. |
| InpApplyChartTheme | Включает автоматическое применение цветовой темы графика (золото/красный). |
| InpShowWatermark | Включает отображение водяного знака G7 на графике. |
| InpPanelCorner | Угол привязки панели на графике. |
| InpPanelX | Смещение панели по горизонтали в пикселях. |
| InpPanelY | Смещение панели по вертикали в пикселях. |
| InpDrawZonesOnChart | Включает отрисовку прямоугольников зон Order Block и FVG на графике. |
| InpBullObColor | Цвет отображения бычьих Order Block. |
| InpBearObColor | Цвет отображения медвежьих Order Block. |
| InpBullFvgColor | Цвет отображения бычьих зон FVG. |
| InpBearFvgColor | Цвет отображения медвежьих зон FVG. |
| InpConfluenceColor | Цвет границы зон совпадения (confluence). |
Поиск по коду файла
#property version "2.00"
#property description "G7 High-Frequency Institutional SMC Dashboard & Auto-Execution Engine"
#property description "M15 Order Block + FVG Confluence, AI Confidence Radar & Interactive Control Deck"
#include <Trade\Trade.mqh>
#include <Trade\PositionInfo.mqh>
#include <Trade\AccountInfo.mqh>
#include <Trade\SymbolInfo.mqh>
#define UI_PREFIX "G7AI_"
#define MAX_SMC_ZONES 60
#define MAX_HIST_BARS 300
enum ENUM_SMC_ZONE_TYPE
{
ZONE_NONE = 0,
ZONE_BULLISH_OB = 1,
ZONE_BEARISH_OB = 2,
ZONE_BULLISH_FVG = 3,
ZONE_BEARISH_FVG = 4,
ZONE_GOLDEN_CONFLUENCE_BULL = 5,
ZONE_GOLDEN_CONFLUENCE_BEAR = 6
};
enum ENUM_EXECUTION_TRIGGER
{
TRIGGER_ZONE_TOUCH = 0, // Execute on Immediate Zone Entry Touch
TRIGGER_50_PERCENT_EQ = 1, // Execute at 50% Equilibrium Retest
TRIGGER_REJECTION_CONFIRM = 2 // Execute on Candle Rejection Close
};
struct SMC_Zone
{
ulong id;
ENUM_SMC_ZONE_TYPE type;
datetime time_start;
datetime time_end;
double price_high;
double price_low;
double price_mid;
bool is_mitigated;
datetime mitigation_time;
bool trade_triggered;
string box_name;
string label_name;
color box_color;
};
#define GRP_SMC "=== 1. SMART MONEY CONCEPTS (M15 SCANNER) ==="
#define GRP_CONF "=== 2. M15 OB + FVG CONFLUENCE ENGINE ==="
#define GRP_EXEC "=== 3. AUTO-EXECUTION & RISK SIZING ==="
#define GRP_PROTECT "=== 4. PROP FIRM & PROTECTION ENGINE ==="
#define GRP_UI "=== 5. ON-CHART OBSIDIAN HUD DASHBOARD ==="
input group GRP_SMC
input ENUM_TIMEFRAMES InpSmcTimeframe = PERIOD_M15; // SMC Timeframe (M15 Recommended)
input int InpLookbackBars = 150; // Analysis Bar History Depth
input int InpSwingLookback = 5; // Swing High/Low Strength (BOS Pivot)
input double InpMinFvgPips = 3.0; // Minimum FVG Imbalance Size (Pips)
input double InpObDisplacementMult = 1.6; // Order Block Impulse Multiplier (vs ATR)
input bool InpRemoveMitigated = true; // Clean Mitigated Zones From Chart
input group GRP_CONF
input bool InpRequireOverlap = true; // Require Strict Physical OB+FVG Overlap
input double InpOverlapTolerancePips= 2.0; // Confluence Proximity Tolerance (Pips)
input ENUM_EXECUTION_TRIGGER InpTriggerMode = TRIGGER_ZONE_TOUCH; // Execution Entry Mode
input int InpCooldownBarsM15 = 3; // Signal Cooldown Between Entries (M15 Bars)
input int InpMinConfidenceToTrade= 70; // Minimum AI Confidence % To Execute (e.g. 70%)
input group GRP_EXEC
input bool InpDefaultAutoTrade = true; // Auto-Execute Trades On Confluence Match
input double InpDefaultLot = 0.01; // Base Trade Lot Size
input double InpDefaultSL_Pips = 25.0; // Protective Stop Loss (Pips, 0=Zone High/Low)
input double InpDefaultTP_Pips = 50.0; // Target Take Profit (Pips)
input ulong InpMagicNumber = 777715; // Expert Magic Number
input bool InpEnableAutoBE = true; // Auto Breakeven Shield
input double InpBETriggerPips = 15.0; // Breakeven Activation Pips
input double InpBELockPips = 3.0; // Breakeven Profit Locked Pips
input bool InpEnableTrailing = true; // Dynamic Trailing Stop
input double InpTrailingStartPips = 20.0; // Trailing Start Activation (Pips)
input double InpTrailingDistPips = 15.0; // Trailing Distance (Pips)
input group GRP_PROTECT
input bool InpEnablePropGuard = true; // Enable Prop Firm Daily Drawdown Shield
input double InpMaxDailyLossPct = 4.0; // Max Daily Loss % (Circuit Breaker)
input double InpMaxDailyProfitPct = 8.0; // Max Daily Profit % (Target Lock)
input double InpMaxSpreadAllowed = 4.0; // Max Allowed Spread (Pips)
input group GRP_UI
input bool InpShowDashboard = true; // Show On-Chart Glassmorphism Panel
input bool InpApplyChartTheme = true; // Auto-Apply Luxury Gold/Red Theme
input bool InpShowWatermark = true; // Show G7 Luxury Watermark
input ENUM_BASE_CORNER InpPanelCorner = CORNER_LEFT_UPPER; // Panel Corner Anchor
input int InpPanelX = 20; // Panel X Offset (Pixels)
input int InpPanelY = 50; // Panel Y Offset (Clean Upper Offset)
input bool InpDrawZonesOnChart = true; // Draw Visual OB & FVG Boxes
input color InpBullObColor = C'16,80,60'; // Bullish Order Block Color
input color InpBearObColor = C'90,25,35'; // Bearish Order Block Color
input color InpBullFvgColor = C'10,60,90'; // Bullish FVG Color
input color InpBearFvgColor = C'85,45,20'; // Bearish FVG Color
input color InpConfluenceColor = C'212,175,55'; // Golden Confluence Border Color
CTrade m_trade;
CPositionInfo m_position;
CAccountInfo m_account;
CSymbolInfo m_symbol;
SMC_Zone g_obZones[];
SMC_Zone g_fvgZones[];
SMC_Zone g_confZones[];
int g_obCount = 0;
int g_fvgCount = 0;
int g_confCount = 0;
ulong g_zoneIdCounter = 1000;
double g_currentLot = 0.01;
double g_currentSL_Pips = 25.0;
double g_currentTP_Pips = 50.0;
bool g_autoTradeActive = true;
bool g_autoBEActive = true;
bool g_trailingActive = true;
datetime g_lastDayReset = 0;
double g_dayStartBalance = 0.0;
double g_dayStartEquity = 0.0;
bool g_circuitBreakerHit = false;
string g_circuitReason = "";
datetime g_lastLongEntryTime = 0;
datetime g_lastShortEntryTime = 0;
ulong g_lastExecutedZoneId = 0;
int g_aiConfidencePct = 50;
string g_newsStatus = "No High-Impact USD News";
string g_newsBiasBadge = "SAFE ● [+20%]";
color g_newsBiasColor = C'0,230,118';
string g_dxyStatus = "UNAVAILABLE | XAUUSD SELL";
string g_dxyAlignmentBadge = "STANDBY [+0%]";
color g_dxyAlignmentColor = C'150,170,195';
string g_fvgStatusBadge = "✔ BEARISH FVG (SELL) [+20%]";
color g_fvgStatusColor = C'255,75,85';
string g_sweepStatusBadge = "▲ TARGETING SSL (NO SWEEP) [+0%]";
color g_sweepStatusColor = C'255,200,50';
string g_obStatusBadge = "✔ BULLISH OB (BUY) [+0%]";
color g_obStatusColor = C'0,230,118';
string g_confLine1 = "▲ CONFLUENCE CONFLICT: FVG and Order Block are";
string g_confLine2 = "showing opposing signals. Score capped at 60%.";
string g_bannerBottomText = "AI CONFIDENCE (50%) IS BELOW 70% THRESHOLD";
string g_bannerSubText = "Market in consolidation or conflicting institutional alignment. Manual trade execution withheld to safeguard capital.";
string g_bannerStatusText = "STATUS: PATIENCE STANDBY";
color g_bannerBorderColor = C'180,140,35';
color g_bannerTextColor = C'255,190,30';
double GetPipSize(const string sym)
{
double pt = SymbolInfoDouble(sym, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
if(digits == 3 || digits == 5) return pt * 10.0;
if(digits == 2) return pt * 10.0; // Institutional standard: 1 pip = 10 points ($0.10 on XAUUSD Gold)
return pt;
}
void CheckDailyReset()
{
MqlDateTime dt;
TimeCurrent(dt);
datetime todayStart = StringToTime(StringFormat("%04d.%02d.%02d 00:00", dt.year, dt.mon, dt.day));
if(g_lastDayReset != todayStart)
{
g_lastDayReset = todayStart;
g_dayStartBalance = AccountInfoDouble(ACCOUNT_BALANCE);
g_dayStartEquity = AccountInfoDouble(ACCOUNT_EQUITY);
g_circuitBreakerHit = false;
g_circuitReason = "";
}
}
void CheckPropFirmGuard()
{
if(!InpEnablePropGuard || g_circuitBreakerHit) return;
double currentEquity = AccountInfoDouble(ACCOUNT_EQUITY);
double baseline = (g_dayStartBalance > 0.0) ? g_dayStartBalance : currentEquity;
if(baseline <= 0.0) return;
double dailyNetChange = currentEquity - baseline;
double dailyNetPct = (dailyNetChange / baseline) * 100.0;
if(dailyNetPct <= -MathAbs(InpMaxDailyLossPct))
{
g_circuitBreakerHit = true;
g_circuitReason = StringFormat("DAILY LOSS LIMIT REACHED: %.2f%% (Limit: -%.2f%%)", dailyNetPct, InpMaxDailyLossPct);
Alert(StringFormat("[G7 SMC PROTECT] EMERGENCY LOCK: %s", g_circuitReason));
CloseAllPositions();
return;
}
if(InpMaxDailyProfitPct > 0.0 && dailyNetPct >= InpMaxDailyProfitPct)
{
g_circuitBreakerHit = true;
g_circuitReason = StringFormat("DAILY TARGET ACHIEVED: +%.2f%% (Target: +%.2f%%)", dailyNetPct, InpMaxDailyProfitPct);
Alert(StringFormat("[G7 SMC PROTECT] TARGET SECURED: %s", g_circuitReason));
CloseAllPositions();
}
}
double GetFloatingPnL(const string sym, int &openCount)
{
double totalFloating = 0.0;
openCount = 0;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
if(sym != "" && m_position.Symbol() != sym) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
totalFloating += m_position.Profit() + m_position.Swap();
openCount++;
}
}
return totalFloating;
}
void CloseAllPositions(const string sym = "")
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
if(sym != "" && m_position.Symbol() != sym) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
m_trade.PositionClose(m_position.Ticket());
}
}
}
void CloseProfitablePositions(const string sym = "")
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
if(sym != "" && m_position.Symbol() != sym) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
if(m_position.Profit() > 0.0)
{
m_trade.PositionClose(m_position.Ticket());
}
}
}
}
void ClosePartialFiftyPercent(const string sym = "")
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
if(sym != "" && m_position.Symbol() != sym) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
double currentVol = m_position.Volume();
string pSym = m_position.Symbol();
double minLot = SymbolInfoDouble(pSym, SYMBOL_VOLUME_MIN);
double lotStep = SymbolInfoDouble(pSym, SYMBOL_VOLUME_STEP);
double halfVol = MathFloor((currentVol * 0.5) / lotStep) * lotStep;
if(halfVol >= minLot && halfVol < currentVol)
{
m_trade.PositionClosePartial(m_position.Ticket(), halfVol);
}
}
}
}
void BreakevenAllPositions(bool forceNow = false)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
string sym = m_position.Symbol();
if(sym != _Symbol) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
double pip = GetPipSize(sym);
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double openPrice = m_position.PriceOpen();
double currentSL = m_position.StopLoss();
ENUM_POSITION_TYPE pType = m_position.PositionType();
double stopLevelPts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL);
double freezePts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_FREEZE_LEVEL);
double spreadPts = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD);
double minSafeDist = MathMax(stopLevelPts, MathMax(spreadPts, freezePts)) * point + 15.0 * point;
if(pType == POSITION_TYPE_BUY)
{
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
double profitPips = (bid - openPrice) / pip;
if(forceNow || profitPips >= InpBETriggerPips)
{
double newSL = NormalizeDouble(openPrice + (InpBELockPips * pip), digits);
if((currentSL < newSL || currentSL == 0.0) && (bid - newSL >= minSafeDist))
{
m_trade.PositionModify(m_position.Ticket(), newSL, m_position.TakeProfit());
}
}
}
else if(pType == POSITION_TYPE_SELL)
{
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double profitPips = (openPrice - ask) / pip;
if(forceNow || profitPips >= InpBETriggerPips)
{
double newSL = NormalizeDouble(openPrice - (InpBELockPips * pip), digits);
if((currentSL > newSL || currentSL == 0.0) && (newSL - ask >= minSafeDist))
{
m_trade.PositionModify(m_position.Ticket(), newSL, m_position.TakeProfit());
}
}
}
}
}
}
void ProcessTrailingStop()
{
if(!g_trailingActive) return;
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
if(m_position.SelectByIndex(i))
{
string sym = m_position.Symbol();
if(sym != _Symbol) continue;
if(m_position.Magic() != InpMagicNumber && InpMagicNumber > 0) continue;
double pip = GetPipSize(sym);
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double openPrice = m_position.PriceOpen();
double currentSL = m_position.StopLoss();
ENUM_POSITION_TYPE pType = m_position.PositionType();
double stopLevelPts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL);
double freezePts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_FREEZE_LEVEL);
double spreadPts = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD);
double minSafeDist = MathMax(stopLevelPts, MathMax(spreadPts, freezePts)) * point + 15.0 * point;
if(pType == POSITION_TYPE_BUY)
{
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
double profitPips = (bid - openPrice) / pip;
if(profitPips >= InpTrailingStartPips)
{
double proposedSL = NormalizeDouble(bid - (InpTrailingDistPips * pip), digits);
if(proposedSL > currentSL + (2.0 * pip) || currentSL == 0.0)
{
if(proposedSL > openPrice && (bid - proposedSL >= minSafeDist))
{
m_trade.PositionModify(m_position.Ticket(), proposedSL, m_position.TakeProfit());
}
}
}
}
else if(pType == POSITION_TYPE_SELL)
{
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double profitPips = (openPrice - ask) / pip;
if(profitPips >= InpTrailingStartPips)
{
double proposedSL = NormalizeDouble(ask + (InpTrailingDistPips * pip), digits);
if(proposedSL < currentSL - (2.0 * pip) || currentSL == 0.0)
{
if(proposedSL < openPrice && (proposedSL - ask >= minSafeDist))
{
m_trade.PositionModify(m_position.Ticket(), proposedSL, m_position.TakeProfit());
}
}
}
}
}
}
}
double NormalizeTradeVolume(const string sym, double requestedLot)
{
double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
double stepLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
if(stepLot <= 0.0) stepLot = 0.01;
if(minLot <= 0.0) minLot = 0.01;
if(maxLot <= 0.0) maxLot = 100.0;
double lot = requestedLot;
if(lot < minLot) lot = minLot;
if(lot > maxLot) lot = maxLot;
lot = minLot + MathFloor((lot - minLot) / stepLot + 0.00001) * stepLot;
int volDigits = 2;
if(stepLot >= 1.0) volDigits = 0;
else if(stepLot >= 0.1) volDigits = 1;
else if(stepLot >= 0.01) volDigits = 2;
else volDigits = 3;
lot = NormalizeDouble(lot, volDigits);
if(lot < minLot) lot = minLot;
if(lot > maxLot) lot = maxLot;
return lot;
}
double CalculateSafeTradeLot(const string sym, ENUM_ORDER_TYPE orderType, double targetLot)
{
double minLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_MAX);
double stepLot = SymbolInfoDouble(sym, SYMBOL_VOLUME_STEP);
if(stepLot <= 0.0) stepLot = 0.01;
if(minLot <= 0.0) minLot = 0.01;
if(maxLot <= 0.0) maxLot = 100.0;
double lot = NormalizeTradeVolume(sym, targetLot);
double freeMargin = AccountInfoDouble(ACCOUNT_MARGIN_FREE);
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
double price = (orderType == ORDER_TYPE_SELL) ? bid : ask;
if(price <= 0.0 || freeMargin <= 0.0) return 0.0;
double singleLotMargin = 0.0;
if(OrderCalcMargin(orderType, sym, 1.0, price, singleLotMargin) && singleLotMargin > 0.0)
{
double maxAffordableLot = (freeMargin * 0.90) / singleLotMargin;
if(lot > maxAffordableLot)
{
lot = MathFloor(maxAffordableLot / stepLot) * stepLot;
int volDigits = (stepLot >= 1.0) ? 0 : ((stepLot >= 0.1) ? 1 : 2);
lot = NormalizeDouble(lot, volDigits);
}
}
if(lot < minLot) return 0.0; // Cannot afford even minimum broker lot size
if(lot > maxLot) lot = maxLot;
return lot;
}
void CalculateValidStops(const string sym,
ENUM_ORDER_TYPE orderType,
double requestedSLPips,
double requestedTPPips,
double customSL,
double &outSL,
double &outTP)
{
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(sym, SYMBOL_DIGITS);
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
double spreadPts = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD);
double stopLevelPts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_STOPS_LEVEL);
double freezePts = (double)SymbolInfoInteger(sym, SYMBOL_TRADE_FREEZE_LEVEL);
double pip = GetPipSize(sym);
if(point <= 0.0) point = 0.00001;
if(pip <= 0.0) pip = point * 10.0;
double maxConstraintPts = MathMax(stopLevelPts, MathMax(spreadPts, freezePts));
double safeBufferPts = MathMax(maxConstraintPts + 25.0, 50.0);
double safeBufferPrice = safeBufferPts * point;
outSL = 0.0;
outTP = 0.0;
if(orderType == ORDER_TYPE_BUY)
{
double minSLDist = safeBufferPrice;
if(requestedSLPips > 0.0)
{
double slDist = MathMax(requestedSLPips * pip, minSLDist);
outSL = NormalizeDouble(bid - slDist, digits);
}
if(customSL > 0.0)
{
if(customSL <= bid - minSLDist)
outSL = NormalizeDouble(customSL, digits);
else
outSL = NormalizeDouble(bid - minSLDist, digits);
}
if(requestedTPPips > 0.0)
{
double tpDist = MathMax(requestedTPPips * pip, minSLDist);
outTP = NormalizeDouble(ask + tpDist, digits);
}
}
else if(orderType == ORDER_TYPE_SELL)
{
double minSLDist = safeBufferPrice;
if(requestedSLPips > 0.0)
{
double slDist = MathMax(requestedSLPips * pip, minSLDist);
outSL = NormalizeDouble(ask + slDist, digits);
}
if(customSL > 0.0)
{
if(customSL >= ask + minSLDist)
outSL = NormalizeDouble(customSL, digits);
else
outSL = NormalizeDouble(ask + minSLDist, digits);
}
if(requestedTPPips > 0.0)
{
double tpDist = MathMax(requestedTPPips * pip, minSLDist);
outTP = NormalizeDouble(bid - tpDist, digits);
}
}
}
bool ExecuteSMCAutoTrade(ENUM_ORDER_TYPE orderType, double customSL = 0.0, string comment = "G7 SMC M15 Confluence")
{
if(g_circuitBreakerHit)
{
Print("[G7 SMC] Execution blocked: Prop Firm Circuit Breaker is active!");
return false;
}
string sym = _Symbol;
double point = SymbolInfoDouble(sym, SYMBOL_POINT);
double pip = GetPipSize(sym);
if(point <= 0.0 || pip <= 0.0) return false;
double currentSpread = (double)SymbolInfoInteger(sym, SYMBOL_SPREAD) * point / pip;
if(currentSpread > InpMaxSpreadAllowed && !MQLInfoInteger(MQL_TESTER))
{
PrintFormat("[G7 SMC] Spread too high: %.1f pips (Max: %.1f pips)", currentSpread, InpMaxSpreadAllowed);
return false;
}
double lot = CalculateSafeTradeLot(sym, orderType, g_currentLot);
if(lot <= 0.0)
{
PrintFormat("[G7 SMC] Free margin (%.2f) insufficient for minimum lot. Trade safely withheld.", AccountInfoDouble(ACCOUNT_MARGIN_FREE));
return false;
}
m_trade.SetExpertMagicNumber(InpMagicNumber);
m_trade.SetDeviationInPoints(30);
if(!m_trade.SetTypeFillingBySymbol(sym))
{
uint filling = (uint)SymbolInfoInteger(sym, SYMBOL_FILLING_MODE);
if((filling & SYMBOL_FILLING_FOK) != 0)
m_trade.SetTypeFilling(ORDER_FILLING_FOK);
else if((filling & SYMBOL_FILLING_IOC) != 0)
m_trade.SetTypeFilling(ORDER_FILLING_IOC);
else
m_trade.SetTypeFilling(ORDER_FILLING_RETURN);
}
double sl = 0.0, tp = 0.0;
CalculateValidStops(sym, orderType, g_currentSL_Pips, g_currentTP_Pips, customSL, sl, tp);
double ask = SymbolInfoDouble(sym, SYMBOL_ASK);
double bid = SymbolInfoDouble(sym, SYMBOL_BID);
if(orderType == ORDER_TYPE_BUY)
{
if(ask <= 0.0) return false;
return m_trade.Buy(lot, sym, ask, sl, tp, comment);
}
else if(orderType == ORDER_TYPE_SELL)
{
if(bid <= 0.0) return false;
return m_trade.Sell(lot, sym, bid, sl, tp, comment);
}
return false;
}
void ScanM15OrderBlocks()
{
MqlRates rates[];
ArraySetAsSeries(rates, true);
int copied = CopyRates(_Symbol, InpSmcTimeframe, 0, InpLookbackBars, rates);
if(copied < InpSwingLookback * 4 + 10) return;
double pip = GetPipSize(_Symbol);
g_obCount = 0;
ArrayResize(g_obZones, MAX_SMC_ZONES);
double sumRange = 0.0;
int checkBars = MathMin(20, copied - 1);
if(checkBars < 5) return;
for(int k = 1; k <= checkBars; k++)
{
sumRange += (rates[k].high - rates[k].low);
}
double avgRange = (sumRange / (double)checkBars);
if(avgRange <= 0.0) avgRange = 10.0 * pip;
int maxLoop = copied - InpSwingLookback - 3;
for(int i = InpSwingLookback + 1; i < maxLoop; i++)
{
if(g_obCount >= MAX_SMC_ZONES - 2) break;
bool isBearCandle = (rates[i].close < rates[i].open);
bool isStrongExpansionUp = (rates[i-1].close > rates[i-1].open) &&
((rates[i-1].close - rates[i-1].open) >= avgRange * InpObDisplacementMult);
if(isBearCandle && isStrongExpansionUp)
{
double highestPrior = rates[i+1].high;
for(int s = 1; s <= InpSwingLookback; s++)
{
int checkIdx = i + s;
if(checkIdx < copied)
{
if(rates[checkIdx].high > highestPrior) highestPrior = rates[checkIdx].high;
}
}
if(rates[i-1].high > highestPrior)
{
SMC_Zone ob;
ob.id = ++g_zoneIdCounter;
ob.type = ZONE_BULLISH_OB;
ob.time_start = rates[i].time;
ob.time_end = TimeCurrent() + PeriodSeconds(InpSmcTimeframe) * 12;
ob.price_high = rates[i].high;
ob.price_low = rates[i].low;
ob.price_mid = (ob.price_high + ob.price_low) * 0.5;
ob.is_mitigated = false;
ob.trade_triggered = false;
ob.box_color = InpBullObColor;
ob.box_name = StringFormat("%sOB_BULL_%I64u", UI_PREFIX, ob.id);
ob.label_name = StringFormat("%sLBL_OB_BULL_%I64u", UI_PREFIX, ob.id);
for(int m = i - 2; m >= 0; m--)
{
if(rates[m].low <= ob.price_high)
{
ob.is_mitigated = true;
ob.mitigation_time = rates[m].time;
break;
}
}
g_obZones[g_obCount++] = ob;
}
}
bool isBullCandle = (rates[i].close > rates[i].open);
bool isStrongExpansionDown = (rates[i-1].close < rates[i-1].open) &&
((rates[i-1].open - rates[i-1].close) >= avgRange * InpObDisplacementMult);
if(isBullCandle && isStrongExpansionDown)
{
double lowestPrior = rates[i+1].low;
for(int s = 1; s <= InpSwingLookback; s++)
{
int checkIdx = i + s;
if(checkIdx < copied)
{
if(rates[checkIdx].low < lowestPrior) lowestPrior = rates[checkIdx].low;
}
}
if(rates[i-1].low < lowestPrior)
{
SMC_Zone ob;
ob.id = ++g_zoneIdCounter;
ob.type = ZONE_BEARISH_OB;
ob.time_start = rates[i].time;
ob.time_end = TimeCurrent() + PeriodSeconds(InpSmcTimeframe) * 12;
ob.price_high = rates[i].high;
ob.price_low = rates[i].low;
ob.price_mid = (ob.price_high + ob.price_low) * 0.5;
ob.is_mitigated = false;
ob.trade_triggered = false;
ob.box_color = InpBearObColor;
ob.box_name = StringFormat("%sOB_BEAR_%I64u", UI_PREFIX, ob.id);
ob.label_name = StringFormat("%sLBL_OB_BEAR_%I64u", UI_PREFIX, ob.id);
for(int m = i - 2; m >= 0; m--)
{
if(rates[m].high >= ob.price_low)
{
ob.is_mitigated = true;
ob.mitigation_time = rates[m].time;
break;
}
}
g_obZones[g_obCount++] = ob;
}
}
}
}
void ScanM15FairValueGaps()
{
MqlRates rates[];
ArraySetAsSeries(rates, true);
int copied = CopyRates(_Symbol, InpSmcTimeframe, 0, InpLookbackBars, rates);
if(copied < 10) return;
double pip = GetPipSize(_Symbol);
g_fvgCount = 0;
ArrayResize(g_fvgZones, MAX_SMC_ZONES);
for(int i = 1; i < copied - 2; i++)
{
if(g_fvgCount >= MAX_SMC_ZONES - 2) break;
double gapTopBull = rates[i-1].low;
double gapBottomBull = rates[i+1].high;
double gapSizeBull = (gapTopBull - gapBottomBull) / pip;
if(gapTopBull > gapBottomBull && gapSizeBull >= InpMinFvgPips)
{
SMC_Zone fvg;
fvg.id = ++g_zoneIdCounter;
fvg.type = ZONE_BULLISH_FVG;
fvg.time_start = rates[i].time;
fvg.time_end = TimeCurrent() + PeriodSeconds(InpSmcTimeframe) * 12;
fvg.price_high = gapTopBull;
fvg.price_low = gapBottomBull;
fvg.price_mid = (gapTopBull + gapBottomBull) * 0.5;
fvg.is_mitigated = false;
fvg.trade_triggered = false;
fvg.box_color = InpBullFvgColor;
fvg.box_name = StringFormat("%sFVG_BULL_%I64u", UI_PREFIX, fvg.id);
fvg.label_name = StringFormat("%sLBL_FVG_BULL_%I64u", UI_PREFIX, fvg.id);
for(int m = i - 2; m >= 0; m--)
{
if(rates[m].low <= fvg.price_low)
{
fvg.is_mitigated = true;
fvg.mitigation_time = rates[m].time;
break;
}
}
g_fvgZones[g_fvgCount++] = fvg;
}
double gapTopBear = rates[i+1].low;
double gapBottomBear = rates[i-1].high;
double gapSizeBear = (gapTopBear - gapBottomBear) / pip;
if(gapTopBear > gapBottomBear && gapSizeBear >= InpMinFvgPips)
{
SMC_Zone fvg;
fvg.id = ++g_zoneIdCounter;
fvg.type = ZONE_BEARISH_FVG;
fvg.time_start = rates[i].time;
fvg.time_end = TimeCurrent() + PeriodSeconds(InpSmcTimeframe) * 12;
fvg.price_high = gapTopBear;
fvg.price_low = gapBottomBear;
fvg.price_mid = (gapTopBear + gapBottomBear) * 0.5;
fvg.is_mitigated = false;
fvg.trade_triggered = false;
fvg.box_color = InpBearFvgColor;
fvg.box_name = StringFormat("%sFVG_BEAR_%I64u", UI_PREFIX, fvg.id);
fvg.label_name = StringFormat("%sLBL_FVG_BEAR_%I64u", UI_PREFIX, fvg.id);
for(int m = i - 2; m >= 0; m--)
{
if(rates[m].high >= fvg.price_high)
{
fvg.is_mitigated = true;
fvg.mitigation_time = rates[m].time;
break;
}
}
g_fvgZones[g_fvgCount++] = fvg;
}
}
}
void MatchObFvgConfluence()
{
double pip = GetPipSize(_Symbol);
double tol = InpOverlapTolerancePips * pip;
g_confCount = 0;
ArrayResize(g_confZones, MAX_SMC_ZONES);Показано первые 50% кода (символов: 44028)