掌握公允价值缺口:形成机制、交易逻辑以及 Breaker 与市场结构转变在自动化交易中的应用
引言
公允价值缺口是当今非常普遍的现象,通常被视作“聪明钱”概念(SMC)体系的组成部分,或者更准确地说,是由该概念衍生而来。 在社交媒体上,交易者们也常在交易平台和在线图表讨论室中谈及这一现象,但大多数人只是将其视为一个参考点,而没有意识到它也可以帮助改善交易,更没有借助这套工具,根据公允价值缺口出现的时间和位置,判断交易方向偏好并据此进行交易。
我的目标不仅是探讨公允价值缺口,还包括如何利用这些缺口为交易者创造优势,从而确立交易方向偏好、构建市场叙事,甚至执行交易。 我还将分析这些公允价值缺口最可能出现在哪里、何时以及如何形成,以及如何确认它们可作为交易入场点或止盈点,在价格强劲扩张并出现回调后,如何将其作为再次入场点执行交易。
在理解公允价值缺口以及用于验证、确定和识别潜在交易方向偏好与市场叙事的交易逻辑之后,我将解释突破信号的形成以及市场结构转变,这些通常可为基于潜在交易方向偏好与市场叙事的交易提供确认。 这些突破信号和市场结构转变极具说服力,甚至往往能为长期交易提供确认。 本文将清晰地描述和阐释公允价值缺口与突破信号相结合的有效性,特别是考虑到它们在所有时间周期(无论是短期还是长期)中都会出现。
公允价值缺口简介
当价格向任一方向快速波动时,就会形成公允价值缺口,这表明存在强烈的买入或卖出压力,主要来自机构投资者。 简而言之,这种交易压力往往导致交易者无法获得同等的下单或执行交易的机会。在看涨公允价值缺口(FVG)中,价格从某一点迅猛上涨,卖方没有足够的时间或机会执行卖出订单;而在看跌公允价值缺口(FVG)中,价格从某一点迅猛下跌,买方没有足够的时间或机会执行买入订单。这样的区域被称为价格失衡区间,因为价格没有出现与扩张方向相反的运动。
用油漆工刷墙的道理最能解释这一点:油漆工刷墙时,需要朝相反方向以相同或相近的笔触来回涂刷,才能使油漆分布均匀、平衡,或者更准确地说,达到较高的涂刷质量。 同样的逻辑也适用于价格。 例如,当一根看涨 K 线扩张并突破某个价位(如从 1.3010 升至 1.3030)时,还必须有一根看跌 K 线突破该价位,才能使价格恢复平衡;否则,就会形成公允价值缺口。 通常情况下——即使不是每次——价格最终都会回到这个点位。 价格回到该点位时,正是我们应寻求利用这些公允价值缺口的位置和时机,因为它们提供了大量回报丰厚的机会。
下图展示了公允价值缺口的示例及其应用方式。

它们是如何形成的、何时形成的以及为什么形成的
既然我们已经定义了什么是公允价值缺口,那么就更容易理解它们是如何形成的。 公允价值缺口会在一些非常明确的情形下形成。 第一种情况是消息发布时,可能是高影响力经济消息(如 CPI、FOMC 或 NFP),也可能是其他类型的消息,具体取决于其影响力。
我认为,大多数情况下,在这类消息发布之前,市场中的大型参与者就已经设置了挂单,因而早已预期到随之而来的波动及其速度和力度;随后,市场迅速朝着有利于他们的方向运动,并留下我们希望从中获利的公允价值缺口。 按照行业惯例,在重大新闻发布前交易并不理想;通常,更明智的做法是等到新闻发布及其引发的市场波动出现后再执行交易。因此,理想情况下,我们应避免过早入场,因为此时交易形态大多甚至尚未形成。
它们还会在银行、对冲基金等大型机构下单时形成;这些机构的订单金额高达数十亿美元,因此能够影响市场走势。
即使没有新闻发布的影响,也能通过巨大的 K 线和价格向单一方向的突然剧烈波动,轻松识别出这些大额订单。 在本文中,我试图说明,在这些大幅波动发生后,我们应如何训练自己,留意识别在波动过程中形成的公允价值缺口。
下图展示了价格如何迅猛地突破某一区域,而下一根 K 线并未回撤至覆盖前一根看涨 K 线的位置,从而留下一段未被覆盖的区域,即公允价值缺口。

如何分析公允价值缺口
在本章中,我们将探讨如何分析公允价值缺口,此前各章已对公允价值缺口的定义、出现时机及其形成机制进行了说明。 现在,我们将重点探讨如何分析这些缺口,以确定应等待并执行哪些交易。
第一条基本规则是:在大多数情况下,我们应避免直接交易公允价值缺口,而应沿价格远离缺口的方向交易,因为当我们顺应趋势、交易方向偏好和市场叙事有效利用这些缺口时,它们就能起到推动作用。 那么,为什么要逆着这样一个推动价格的区域交易,眼看它转眼间就将价格全力推向对我们不利的方向呢? 这一点无论在较短还是较长的时间周期上都同样成立;这些缺口的作用方式都是一样的。 唯一的区别在于形成交易机会所需的时间,但在绝大多数情况下(约 90%),它们都会这样发挥作用。
理想情况下,第一步是进行自上而下分析,从最高时间周期逐步分析到最低时间周期,观察并标出所有公允价值缺口。 接下来,最重要的一步是分析当前的趋势方向、交易方向偏好和市场叙事。 例如,GOLD 在 MN、W1 和 D1 时间周期上的趋势、交易方向偏好和市场叙事均指向买入交易。 这可以通过以下三种主要方式来确认:价格位于移动平均线(简单移动平均线和指数移动平均线)之上;市场结构清晰地显示出买入动能;绿色(看涨)K 线的数量远多于红色(看跌)K 线。
一旦确定了当前的趋势和市场叙事,我们就必须考虑另一个重要方面。 价格不断波动,寻找可扫取的流动性,而市场叙事、走势方向和交易方向偏好则由较高时间周期决定。 流动性主要集中在此前的日线、周线和月线低点及高点附近,预计这些位置会出现显著的市场反应。 因此,一旦对流动性和趋势有了大致了解,我们就能更轻松地执行交易。
例如,我们目前已确定 GOLD 价格正逼近上周高点,这一判断得到了市场结构或移动平均线的确认。 在本周或同期交易时段内,价格继续向上周高点靠拢,且公允价值缺口持续形成。 这些缺口应标记为看涨公允价值缺口;如果它们出现在较高时间周期(例如 H4、D1、H1),则更为理想,同样应标记为看涨公允价值缺口。 交易者应始终做好在价格回到这些缺口时买入的准备,并据此寻找交易执行机会。
需要注意的是,即便并非每次如此,价格在大多数情况下也会回到公允价值缺口,使其恢复平衡。 然而,如果价格已接近上述目标位(例如周线、月线或日线高点),那么一旦触及目标位且流动性被扫取,相应公允价值缺口不再被用于新交易的可能性就会显著降低,而在该缺口处买入可能会失败。 因此,我们应该避免进行此类交易。
公允价值缺口如何影响交易及其应对方法
基本思路是:在确定趋势和方向(例如看跌)后,通过自上而下分析寻找并标记公允价值缺口。 需要注意的是,只要周线、日线或月线目标位保持不变,价格就会回到这些公允价值缺口对应的价位,从而提供交易和入场机会。 通常情况下,价格必须恢复平衡,并填补公允价值缺口。 因此,当价格返回并吸引第二波买盘时,公允价值缺口便会成为推动该货币对或资产走强的因素,因为此时会有更多交易者建立新仓位,这也解释了市场走势的速度和力度。 这会推动价格大幅向上波动。 此外,这还会强化趋势的方向、交易方向偏好和市场叙事。
如何成功利用公允价值缺口执行交易入场
这是本文最重要、最有价值的内容,因为在对所有判断标准进行充分验证和分析后,我们已了解如何确定公允价值缺口在何处、以何种方式失效或得到确认,以及它们如何形成、最可能出现在哪里。 这一部分比较简单,因为所有艰巨的工作都已经完成了。
现在需要的只是耐心、自律和专注。 我们将主要基于D1图表进行分析,因为它是参考图表,便于我们寻找公允价值缺口。 如果我们发现公允价值缺口,且价格回到该缺口内,就迅速切换到H4时间周期,寻找看涨吞没 K 线(如果趋势、交易方向偏好和市场叙事均指向买方)或看跌吞没 K 线(如果交易方向偏好、趋势和市场叙事均指向卖方)。 这种情况可能发生在公允价值缺口内的任何位置,但理想情况下,应出现在伦敦或纽约等交易时段开始前后。 发现吞没 K 线后,我们进一步下切至H1时间周期,在这里寻找市场结构的突破。
市场结构的突破,是指价格运行状态发生变化。例如,原先以卖出为主、随后转为买入时,意味着价格运行状态以及市场结构发生了变化。 因此,这就是你在H1时间周期上要寻找的信号。 止损应设在突破走势的另一端;可在H1突破时形成的、价格合适的小型缺口处,借助突破信号入场,也可在价格回撤至60%回撤位时入场(如果出现这种回撤)。
当市场结构转变前的最后一个高点或低点被突破时,就构成了突破。 在卖方主导的市场中,快速、有力地突破最后一个高点属于看涨突破;而在买方主导的市场中,快速、有力地跌破最后一个低点则属于看跌突破。
其他时间周期上也会出现同样的现象。 如果我们在H4图表上发现公允价值缺口,就在H1图表上寻找吞没 K 线,然后在M15图表上寻找市场结构转变。 采用较短时间周期的交易者也可以运用这一策略。 同样的现象会重复出现:H1时间周期上出现公允价值缺口,M15时间周期上出现吞没 K 线,随后M5时间周期上出现市场结构转变。 此外,对于剥头皮交易,可关注M15图表上出现的公允价值缺口。 我们可以在M5图表上寻找吞没 K 线,并在M1图表上寻找市场结构转变。
如何以及何时避免利用公允价值缺口进行交易
大多数公允价值缺口通常会带来交易机会,但如上所述,某些公允价值缺口并不适合交易。
1. 与趋势、交易方向偏好和市场叙事所指方向相反的公允价值缺口,完全不会对价格形成有效阻挡。例如,如果趋势或交易方向偏好为买入,而价格转而下跌并留下公允价值缺口,这可能只是一次回调;当价格恢复上涨趋势时,不要指望上方的公允价值缺口能够阻挡价格,价格会迅速穿过该缺口。
2. 这些公允价值缺口失效的第二种情况,是周线、日线或月线级别的整体目标已经达到。 公允价值缺口可能会失效,因为流动性被扫取后,价格便没有理由继续沿原方向运行;大型公司已经获利了结,因此价格不再具备继续运行的动能或速度。 因此,公允价值缺口可能会失效,因为价格可能会回调,甚至反转。
3. 第三种也是最后一种失效情形是:例如,较低时间周期上未出现上述吞没 K 线和市场结构转变。 此外,这些信号必须在交易非常活跃的时段内按上述顺序出现。
首先形成公允价值缺口,随后出现吞没 K 线,接着发生市场结构转变。 因此,只有在这些信号按此顺序出现后,我们才能依据优质的交易形态执行交易。 这清楚地表明,如果上述条件未全部满足,交易者就不应使用该方法或利用公允价值缺口进行交易,因为失败的可能性很高。
较高时间周期的公允价值缺口
较高时间周期的缺口是指 H4、D1 和 W1 上的公允价值缺口。这些缺口可轻松用于捕捉大幅或长期的价格波动,幅度甚至可达 200 至 500 点子,因为它们更稳定、变化更缓慢,不存在短期波动或单边走势,因此更适合能够耐心持仓、不感到紧张或恐惧的长期交易者。
较低时间周期中的公允价值缺口
较低时间周期的缺口指的是H1、M15和M5时间周期的公允价值缺口。 这些缺口主要适合短期交易者,而非长期交易者,包括剥头皮交易者,以及持仓数小时后便平仓的短期交易者。 这些缺口可能出现在趋势行情中,尤其是在 M15 时间周期上;在交易时段内加以利用时,它们非常可靠。 这些缺口适合快速执行交易,可轻松提供 100 至 150 点子的获利空间。 根据价格波动的强度和速度,它们呈现出短期价格波动和高波动性的特点。 这要求交易者能够迅速做出交易决策,并擅长在此类环境中交易。
使用 MQL5 实现基于公允价值缺口的自动化交易
为了实现该策略的自动化,我创建了
- 一个用于检测和标绘缺口的 FVG 指标。
- 一个根据检测结果进行交易、结合 MSS 确定入场时机的 FVG + MSS EA。
FVG 指标的源代码
该指标通过寻找幅度较大且互不重叠的 K 线来检测 FVG(imbalance > lows),根据下方代码,指标将缺口大小换算为点数并取整,当该结果大于 minPts 时,便将其识别为 FVG。 它通过绘制矩形来直观显示缺口。
#property copyright "Eugene Mmene" #property link "EMcapital" #property version "1.0" input int minPts = 100; // Minimum points for FVG gap to be valid input int FVG_Rec_Ext_Bars = 10; // Length of FVG rectangle in bars input bool DrawFVG = true; // Draw FVG rectangles on chart #define FVG_Prefix "FVG_REC_" #define CLR_UP clrLime #define CLR_DOWN clrRed struct TimeframeData { ENUM_TIMEFRAMES tf; datetime lastBar; }; TimeframeData tfs[]; string eaSymbol; void CreateRec(string objName, datetime time1, double price1, datetime time2, double price2, color clr) { Print("CreateRec called: objName=", objName, ", time1=", TimeToString(time1), ", price1=", DoubleToString(price1, _Digits)); if(DrawFVG && ObjectFind(0, objName) < 0) { if(ObjectCreate(0, objName, OBJ_RECTANGLE, 0, time1, price1, time2, price2)) { ObjectSetInteger(0, objName, OBJPROP_TIME, 0, time1); ObjectSetDouble(0, objName, OBJPROP_PRICE, 0, price1); ObjectSetInteger(0, objName, OBJPROP_TIME, 1, time2); ObjectSetDouble(0, objName, OBJPROP_PRICE, 1, price2); ObjectSetInteger(0, objName, OBJPROP_COLOR, clr); ObjectSetInteger(0, objName, OBJPROP_FILL, true); ObjectSetInteger(0, objName, OBJPROP_BACK, false); Print("CreateRec: Rectangle created successfully: ", objName); } else { Print("CreateRec: Failed to create rectangle: ", objName, ", Error=", GetLastError()); } } else { Print("CreateRec: Skipped - DrawFVG=", DrawFVG, ", Object exists=", ObjectFind(0, objName) >= 0); } } void DetectFVGs() { Print("DetectFVGs started"); int maxObjects = 100; // Limit total objects to prevent overload int currentObjects = ObjectsTotal(0, 0, OBJ_RECTANGLE); if(currentObjects >= maxObjects) { Print("DetectFVGs: Object limit reached (", currentObjects, "/", maxObjects, "), skipping FVG creation"); return; } for(int i = 0; i < ArraySize(tfs); i++) { if(!NewBar(tfs[i].tf)) continue; double low0 = iLow(eaSymbol, tfs[i].tf, 0); double high2 = iHigh(eaSymbol, tfs[i].tf, 2); double gap_L0_H2 = NormalizeDouble((low0 - high2) / _Point, 0); double high0 = iHigh(eaSymbol, tfs[i].tf, 0); double low2 = iLow(eaSymbol, tfs[i].tf, 2); double gap_H0_L2 = NormalizeDouble((low2 - high0) / _Point, 0); if(gap_L0_H2 > minPts) { string fvgName = FVG_Prefix + EnumToString(tfs[i].tf) + "_" + TimeToString(iTime(eaSymbol, tfs[i].tf, 0), TIME_DATE|TIME_MINUTES); Print(StringFormat("%s Bullish FVG detected: Low=%s, High[2]=%s, Gap=%s points", EnumToString(tfs[i].tf), DoubleToString(low0, _Digits), DoubleToString(high2, _Digits), DoubleToString(gap_L0_H2, 0))); CreateRec(fvgName, iTime(eaSymbol, tfs[i].tf, 0), high2, iTime(eaSymbol, tfs[i].tf, 0) + PeriodSeconds(tfs[i].tf) * FVG_Rec_Ext_Bars, low0, CLR_UP); } if(gap_H0_L2 > minPts) { string fvgName = FVG_Prefix + EnumToString(tfs[i].tf) + "_" + TimeToString(iTime(eaSymbol, tfs[i].tf, 0), TIME_DATE|TIME_MINUTES); Print(StringFormat("%s Bearish FVG detected: High=%s, Low[2]=%s, Gap=%s points", EnumToString(tfs[i].tf), DoubleToString(high0, _Digits), DoubleToString(low2, _Digits), DoubleToString(gap_H0_L2, 0))); CreateRec(fvgName, iTime(eaSymbol, tfs[i].tf, 0), low2, iTime(eaSymbol, tfs[i].tf, 0) + PeriodSeconds(tfs[i].tf) * FVG_Rec_Ext_Bars, high0, CLR_DOWN); } } if(DrawFVG) ChartRedraw(0); // Single redraw per tick Print("DetectFVGs completed"); } bool NewBar(ENUM_TIMEFRAMES tf) { int idx = TimeframeIndex(tf); if(idx < 0) return false; datetime cur = iTime(eaSymbol, tf, 0); if(cur != tfs[idx].lastBar) { tfs[idx].lastBar = cur; return true; } return false; } int TimeframeIndex(ENUM_TIMEFRAMES tf) { for(int i = 0; i < ArraySize(tfs); i++) { if(tfs[i].tf == tf) return i; } return -1; } int OnInit() { eaSymbol = _Symbol; if(!SymbolSelect(eaSymbol, true)) { Print("Error: Failed to select ", eaSymbol, " in Market Watch"); return(INIT_FAILED); } ArrayResize(tfs, 3); tfs[0].tf = PERIOD_M5; tfs[1].tf = PERIOD_M15; tfs[2].tf = PERIOD_H1; for(int i = 0; i < 3; i++) { tfs[i].lastBar = 0; } Print("FVG Detector initialized for ", eaSymbol, ". Timeframes: M5, M15, H1"); return(INIT_SUCCEEDED); } void OnDeinit(const int reason) { if(DrawFVG) ObjectsDeleteAll(0, FVG_Prefix); Print("FVG Detector stopped: ", reason); } void OnTick() { DetectFVGs(); }
安装:在 MetaEditor 中编译,然后将其附加到图表上。 为看涨公允价值缺口绘制绿色矩形,为看跌公允价值缺口绘制红色矩形。
使用示例:在 GOLD 的 M15 图表上检测缺口,以便进行直观分析。
FVG + MSS 智能交易系统的源代码
该 EA 会检测 FVG,等待价格向缺口回调,检查价格是否突破最近的关键高点或低点(Last High/Low),然后入场交易。 其中包括风险管理(每笔交易的风险为 2%)。
#property copyright "Eugene Mmene" #property link "EMcapital" #property version "2.27.2" #include <Trade\Trade.mqh> input double RiskPct = 2.0; // Base risk per trade % input double MaxLossUSD = 110.0; // Maximum loss per trade in USD input double RecTgt = 7000.0; // Equity recovery target input int ATR_Prd = 14; // ATR period input int Brk_Prd = 10; // Breakout period input int EMA_Prd = 20; // EMA period input string GS_Url = ""; // Google Sheets webhook URL input bool NewsFilt = true; // News filter input int NewsPause = 15; // Pause minutes input double MinBrkStr = 0.1; // Min breakout strength (x ATR) input int Vol_Prd = 1; // Volume period input bool Bypass = true; // Bypass volume, breakout, HTF trend filters for testing input bool useHTF = false; // Use D1 or H4 EMA trend filter input string NewsAPI_Url = "https://www.alphavantage.co/query?function=NEWS_SENTIMENT&apikey="; // Alpha Vantage API URL input string NewsAPI_Key = "pub_3f54bba977384ac19b6839a744444aba"; // Alpha Vantage API key input double DailyDDLimit = 2.5; // Daily drawdown limit (%) input double OverallDDLimit = 5.5; // Overall drawdown limit (%) input double TargetBalanceOrEquity = 6600.0; // Target balance or equity to pass challenge ($) input bool ResetProfitTarget = false; // Reset target to resume trading input int minPts = 100; // Minimum points for FVG gap to be valid input int FVG_Rec_Ext_Bars = 10; // Length of FVG rectangle in bars input bool DrawFVG = true; // Draw FVG rectangles on chart double CurRisk = RiskPct; double OrigRisk = RiskPct; double LastEqHigh = 0; double StartingBalance = 0; double DailyBalance = 0; datetime LastDay = 0; bool ProfitTargetReached = false; bool DailyDDPaused = false; CTrade trade; int h_ema_d1 = INVALID_HANDLE; int h_ema_h4 = INVALID_HANDLE; int winStreak = 0; int lossStreak = 0; string eaSymbol = _Symbol; struct TimeframeData { ENUM_TIMEFRAMES tf; int h_atr; int h_vol; int h_vol_ma; datetime lastSig; datetime lastBar; }; TimeframeData tfs[]; struct NewsEvt { datetime time; string evt; int impact; }; NewsEvt newsCal[]; int newsCnt = 0; struct TradeLog { ulong ticket; bool isWin; double profit; double brkStr; double vol; double risk; ENUM_TIMEFRAMES tf; }; TradeLog tradeHistory[]; int tradeCnt = 0; double dynBrkStr = MinBrkStr; #define FVG_Prefix "FVG_REC_" #define CLR_UP clrLime #define CLR_DOWN clrRed void CreateRec(string objName, datetime time1, double price1, datetime time2, double price2, color clr) { Print("CreateRec called: objName=", objName, ", time1=", TimeToString(time1), ", price1=", DoubleToString(price1, _Digits)); if(DrawFVG && ObjectFind(0, objName) < 0) { if(ObjectCreate(0, objName, OBJ_RECTANGLE, 0, time1, price1, time2, price2)) { ObjectSetInteger(0, objName, OBJPROP_TIME, 0, time1); ObjectSetDouble(0, objName, OBJPROP_PRICE, 0, price1); ObjectSetInteger(0, objName, OBJPROP_TIME, 1, time2); ObjectSetDouble(0, objName, OBJPROP_PRICE, 1, price2); ObjectSetInteger(0, objName, OBJPROP_COLOR, clr); ObjectSetInteger(0, objName, OBJPROP_FILL, true); ObjectSetInteger(0, objName, OBJPROP_BACK, false); Print("CreateRec: Rectangle created successfully: ", objName); } else { Print("CreateRec: Failed to create rectangle: ", objName, ", Error=", GetLastError()); } } else { Print("CreateRec: Skipped - DrawFVG=", DrawFVG, ", Object exists=", ObjectFind(0, objName) >= 0); } } void DetectFVGs() { Print("DetectFVGs started"); int maxObjects = 100; // Limit total objects to prevent overload int currentObjects = ObjectsTotal(0, 0, OBJ_RECTANGLE); if(currentObjects >= maxObjects) { Print("DetectFVGs: Object limit reached (", currentObjects, "/", maxObjects, "), skipping FVG creation"); return; } for(int i = 0; i < ArraySize(tfs); i++) { if(!NewBar(tfs[i].tf)) continue; double low0 = iLow(eaSymbol, tfs[i].tf, 0); double high2 = iHigh(eaSymbol, tfs[i].tf, 2); double gap_L0_H2 = NormalizeDouble((low0 - high2) / _Point, 0); double high0 = iHigh(eaSymbol, tfs[i].tf, 0); double low2 = iLow(eaSymbol, tfs[i].tf, 2); double gap_H0_L2 = NormalizeDouble((low2 - high0) / _Point, 0); if(gap_L0_H2 > minPts) { string fvgName = FVG_Prefix + EnumToString(tfs[i].tf) + "_" + TimeToString(iTime(eaSymbol, tfs[i].tf, 0), TIME_DATE|TIME_MINUTES); Print(StringFormat("%s Bullish FVG detected: Low=%s, High[2]=%s, Gap=%s points", EnumToString(tfs[i].tf), DoubleToString(low0, _Digits), DoubleToString(high2, _Digits), DoubleToString(gap_L0_H2, 0))); CreateRec(fvgName, iTime(eaSymbol, tfs[i].tf, 0), high2, iTime(eaSymbol, tfs[i].tf, 0) + PeriodSeconds(tfs[i].tf) * FVG_Rec_Ext_Bars, low0, CLR_UP); } if(gap_H0_L2 > minPts) { string fvgName = FVG_Prefix + EnumToString(tfs[i].tf) + "_" + TimeToString(iTime(eaSymbol, tfs[i].tf, 0), TIME_DATE|TIME_MINUTES); Print(StringFormat("%s Bearish FVG detected: High=%s, Low[2]=%s, Gap=%s points", EnumToString(tfs[i].tf), DoubleToString(high0, _Digits), DoubleToString(low2, _Digits), DoubleToString(gap_H0_L2, 0))); CreateRec(fvgName, iTime(eaSymbol, tfs[i].tf, 0), low2, iTime(eaSymbol, tfs[i].tf, 0) + PeriodSeconds(tfs[i].tf) * FVG_Rec_Ext_Bars, high0, CLR_DOWN); } } if(DrawFVG) ChartRedraw(0); // Single redraw per tick Print("DetectFVGs completed"); } int OnInit() { if(AccountInfoDouble(ACCOUNT_BALANCE) < 10.0) { Print("Low balance: ", DoubleToString(AccountInfoDouble(ACCOUNT_BALANCE), 2)); return(INIT_FAILED); } string sym = Symbol(); bool selected; if(!SymbolExist(sym, selected)) { Print("Error: Symbol ", sym, " not found in Market Watch. Available: ", _Symbol); eaSymbol = _Symbol; } else { eaSymbol = sym; Print("Symbol validated: ", eaSymbol, ", Selected in Market Watch: ", selected); } if(!SymbolSelect(eaSymbol, true)) { Print("Error: Failed to select ", eaSymbol, " in Market Watch"); return(INIT_FAILED); } Print("Please ensure ", NewsAPI_Url, " is added to allowed WebRequest URLs in MT5 settings"); StartingBalance = AccountInfoDouble(ACCOUNT_BALANCE); LastEqHigh = AccountInfoDouble(ACCOUNT_EQUITY); DailyBalance = StartingBalance; LastDay = TimeCurrent() / 86400 * 86400; ProfitTargetReached = ResetProfitTarget ? false : ProfitTargetReached; DailyDDPaused = false; ArrayResize(newsCal, 100); ArrayResize(tradeHistory, 100); ArrayResize(tfs, 3); tfs[0].tf = PERIOD_M5; tfs[1].tf = PERIOD_M15; tfs[2].tf = PERIOD_H1; for(int i = 0; i < 3; i++) { tfs[i].h_atr = iATR(eaSymbol, tfs[i].tf, ATR_Prd); tfs[i].h_vol = iVolumes(eaSymbol, tfs[i].tf, VOLUME_TICK); tfs[i].h_vol_ma = iMA(eaSymbol, tfs[i].tf, Vol_Prd, 0, MODE_SMA, PRICE_CLOSE); tfs[i].lastSig = 0; tfs[i].lastBar = 0; if(tfs[i].h_atr == INVALID_HANDLE || tfs[i].h_vol == INVALID_HANDLE || tfs[i].h_vol_ma == INVALID_HANDLE) { Print("Indicator init failed for ", EnumToString(tfs[i].tf)); return(INIT_FAILED); } } h_ema_d1 = iMA(eaSymbol, PERIOD_D1, EMA_Prd, 0, MODE_EMA, PRICE_CLOSE); h_ema_h4 = iMA(eaSymbol, PERIOD_H4, EMA_Prd, 0, MODE_EMA, PRICE_CLOSE); if(h_ema_d1 == INVALID_HANDLE || h_ema_h4 == INVALID_HANDLE) { Print("EMA init failed"); return(INIT_FAILED); } if(NewsFilt) FetchNewsCalendar(); Print("EA initialized. Timeframes: M5, M15, H1, News events: ", newsCnt, ", Bypass: ", Bypass, ", UseHTF: ", useHTF, ", Time时间: EAT (UTC+3), Server: ", TerminalInfoString(TERMINAL_NAME), ", Starting Balance: ", DoubleToString(StartingBalance, 2), ", Target Balance/Equity: ", DoubleToString(TargetBalanceOrEquity, 2)); return(INIT_SUCCEEDED); } void OnDeinit(const int reason) { if(h_ema_d1 != INVALID_HANDLE) IndicatorRelease(h_ema_d1); if(h_ema_h4 != INVALID_HANDLE) IndicatorRelease(h_ema_h4); for(int i = 0; i < ArraySize(tfs); i++) { if(tfs[i].h_atr != INVALID_HANDLE) IndicatorRelease(tfs[i].h_atr); if(tfs[i].h_vol != INVALID_HANDLE) IndicatorRelease(tfs[i].h_vol); if(tfs[i].h_vol_ma != INVALID_HANDLE) IndicatorRelease(tfs[i].h_vol_ma); } if(DrawFVG) ObjectsDeleteAll(0, FVG_Prefix); Print("EA stopped: ", reason); } void CloseAllPositions() { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(!PositionSelectByTicket(ticket) || PositionGetString(POSITION_SYMBOL) != eaSymbol) continue; long magic = PositionGetInteger(POSITION_MAGIC); if(magic == MagicNumber(PERIOD_M5) || magic == MagicNumber(PERIOD_M15) || magic == MagicNumber(PERIOD_H1)) { trade.PositionClose(ticket); Print("Closed position: Ticket=", ticket, ", Symbol=", eaSymbol, ", Magic=", magic); } } } void OnTick() { datetime currentDay = TimeCurrent() / 86400 * 86400; if(currentDay > LastDay) { DailyBalance = AccountInfoDouble(ACCOUNT_BALANCE); LastDay = currentDay; DailyDDPaused = false; Print("Daily balance reset: ", DoubleToString(DailyBalance, 2), " at ", TimeToString(currentDay, TIME_DATE)); } double equity = AccountInfoDouble(ACCOUNT_EQUITY); double balance = AccountInfoDouble(ACCOUNT_BALANCE); if(balance >= TargetBalanceOrEquity || equity >= TargetBalanceOrEquity) { CloseAllPositions(); ProfitTargetReached = true; Print("Trading paused: Target balance or equity reached. Balance=", DoubleToString(balance, 2), ", Equity=", DoubleToString(equity, 2), ", Target=", DoubleToString(TargetBalanceOrEquity, 2), ". All positions closed. Set ResetProfitTarget=true or restart EA to resume trading."); return; } double dailyDD = (DailyBalance - equity) / DailyBalance * 100; double overallDD = (StartingBalance - equity) / StartingBalance * 100; if(dailyDD >= DailyDDLimit) { CloseAllPositions(); DailyDDPaused = true; Print("Trading paused until next trading day: Daily DD=", StringFormat("%.2f", dailyDD), "% reached (Limit: ", DoubleToString(DailyDDLimit, 2), "%), Equity=", DoubleToString(equity, 2), ", Daily Balance=", DoubleToString(DailyBalance, 2), ". All positions closed."); return; } if(overallDD >= OverallDDLimit) { CloseAllPositions(); ProfitTargetReached = true; Print("Trading paused: Overall DD=", StringFormat("%.2f", overallDD), "% reached (Limit: ", DoubleToString(OverallDDLimit, 2), "%), Equity=", DoubleToString(equity, 2), ", Starting Balance=", DoubleToString(StartingBalance, 2), ". All positions closed. Set ResetProfitTarget=true or restart EA to resume trading."); return; } if(ProfitTargetReached) { Print("Trading paused: Target or overall drawdown previously reached. Balance=", DoubleToString(balance, 2), ", Equity=", DoubleToString(equity, 2), ", Target=", DoubleToString(TargetBalanceOrEquity, 2)); return; } if(DailyDDPaused) { Print("Trading paused: Daily drawdown limit previously reached. Waiting for next trading day. Equity=", DoubleToString(equity, 2), ", Daily Balance=", DoubleToString(DailyBalance, 2)); return; } static datetime lastNewsFetch = 0; if(NewsFilt && TimeCurrent() >= lastNewsFetch + 4 * 3600) { FetchNewsCalendar(); lastNewsFetch = TimeCurrent(); } for(int i = 0; i < ArraySize(tfs); i++) { if(!NewBar(tfs[i].tf)) continue; bool hasPosition = false; for(int j = PositionsTotal() - 1; j >= 0; j--) { ulong ticket = PositionGetTicket(j); if(PositionSelectByTicket(ticket) && PositionGetString(POSITION_SYMBOL) == eaSymbol && PositionGetInteger(POSITION_MAGIC) == MagicNumber(tfs[i].tf)) { hasPosition = true; break; } } if(hasPosition) { ManageTrades(tfs[i].tf); continue; } if(TimeCurrent() <= tfs[i].lastSig + PeriodSeconds(PERIOD_H1)) { Print(EnumToString(tfs[i].tf), " Trade skipped: Within 1-hour cooldown"); continue; } if(NewsFilt && IsNews()) { Print(EnumToString(tfs[i].tf), " Trade skipped: News pause active"); continue; } double eq = AccountInfoDouble(ACCOUNT_EQUITY); if(eq > LastEqHigh) LastEqHigh = eq; if(eq < LastEqHigh && lossStreak >= 2) CurRisk = MathMax(OrigRisk * 0.25, 0.1); else if(winStreak >= 3) CurRisk = MathMin(OrigRisk * 1.25, 5.0); else CurRisk = OrigRisk; if(eq >= RecTgt) { CurRisk = OrigRisk; winStreak = 0; lossStreak = 0; } bool bullHTF = !useHTF || (BullTrend(PERIOD_D1) || BullTrend(PERIOD_H4)); bool bearHTF = !useHTF || (BearTrend(PERIOD_D1) || BearTrend(PERIOD_H4)); bool buyBrk = BuyBrk(tfs[i].tf); bool sellBrk = SellBrk(tfs[i].tf); Print(EnumToString(tfs[i].tf), " Signal check: BullHTF=", bullHTF, ", BearHTF=", bearHTF, ", BuyBrk=", buyBrk, ", SellBrk=", sellBrk, ", Bid=", DoubleToString(SymbolInfoDouble(eaSymbol, SYMBOL_BID), _Digits), ", Ask=", DoubleToString(SymbolInfoDouble(eaSymbol, SYMBOL_ASK), _Digits)); double atr[1], vol[2], vol_ma[1]; if(CopyBuffer(tfs[i].h_atr, 0, 0, 1, atr) < 1 || CopyBuffer(tfs[i].h_vol, 0, 0, 2, vol) < 2 || CopyBuffer(tfs[i].h_vol_ma, 0, 1, 1, vol_ma) < 1) { Print(EnumToString(tfs[i].tf), " Trade skipped: Indicator copy failed"); continue; } double slPips = atr[0] * 2 / _Point; double lots = CalcLots(eq, CurRisk, slPips); double margReq = SymbolInfoDouble(eaSymbol, SYMBOL_MARGIN_INITIAL) * lots; double freeMarg = AccountInfoDouble(ACCOUNT_MARGIN_FREE); Print(EnumToString(tfs[i].tf), " Lot size: ", DoubleToString(lots, 2), ", Margin required: ", DoubleToString(margReq, 2), ", Free margin: ", DoubleToString(freeMarg, 2), ", SL Pips: ", DoubleToString(slPips, 2), ", Contract size: ", DoubleToString(SymbolInfoDouble(eaSymbol, SYMBOL_TRADE_CONTRACT_SIZE), 0)); if(freeMarg < margReq * 1.2) { Print(EnumToString(tfs[i].tf), " Trade skipped: Margin low (", DoubleToString(freeMarg, 2), " < ", DoubleToString(margReq * 1.2, 2), ")"); continue; } double brkStr = MathAbs(buyBrk ? SymbolInfoDouble(eaSymbol, SYMBOL_ASK) - iHigh(eaSymbol, tfs[i].tf, iHighest(eaSymbol, tfs[i].tf, MODE_HIGH, Brk_Prd, 1)) : iLow(eaSymbol, tfs[i].tf, iLowest(eaSymbol, tfs[i].tf, MODE_LOW, Brk_Prd, 1)) - SymbolInfoDouble(eaSymbol, SYMBOL_BID)) / atr[0]; if(!Bypass && brkStr < dynBrkStr) { Print(EnumToString(tfs[i].tf), " Trade skipped: Breakout strength too low (", DoubleToString(brkStr, 2), " < ", DoubleToString(dynBrkStr, 2), ")"); continue; } if(bullHTF && buyBrk) { double price = SymbolInfoDouble(eaSymbol, SYMBOL_ASK); double sl = price - slPips * _Point; double tp = price + slPips * 2 * _Point; Print(EnumToString(tfs[i].tf), " Attempting Buy: Price=", DoubleToString(price, _Digits), ", SL=", DoubleToString(sl, _Digits), ", TP=", DoubleToString(tp, _Digits), ", Lots=", DoubleToString(lots, 2)); trade.SetExpertMagicNumber(MagicNumber(tfs[i].tf)); if(trade.Buy(lots, eaSymbol, price, sl, tp)) { tfs[i].lastSig = TimeCurrent(); LogTrd(trade.ResultOrder(), eaSymbol, price, sl, tp, "Open", brkStr, vol[1], CurRisk, tfs[i].tf); Print(EnumToString(tfs[i].tf), " Buy opened: Ticket=", trade.ResultOrder()); } else { Print(EnumToString(tfs[i].tf), " Buy failed: Retcode=", trade.ResultRetcode(), ", Error=", GetLastError(), ", Comment=", trade.ResultComment()); } } else if(bearHTF && sellBrk) { double price = SymbolInfoDouble(eaSymbol, SYMBOL_BID); double sl = price + slPips * _Point; double tp = price - slPips * 2 * _Point; Print(EnumToString(tfs[i].tf), " Attempting Sell: Price=", DoubleToString(price, _Digits), ", SL=", DoubleToString(sl, _Digits), ", TP=", DoubleToString(tp, _Digits), ", Lots=", DoubleToString(lots, 2)); trade.SetExpertMagicNumber(MagicNumber(tfs[i].tf)); if(trade.Sell(lots, eaSymbol, price, sl, tp)) { tfs[i].lastSig = TimeCurrent(); LogTrd(trade.ResultOrder(), eaSymbol, price, sl, tp, "Open", brkStr, vol[1], CurRisk, tfs[i].tf); Print(EnumToString(tfs[i].tf), " Sell opened: Ticket=", trade.ResultOrder()); } else { Print(EnumToString(tfs[i].tf), " Sell failed: Retcode=", trade.ResultRetcode(), ", Error=", GetLastError(), ", Comment=", trade.ResultComment()); } } else { Print(EnumToString(tfs[i].tf), " Trade skipped: No valid signal"); } } // Run FVG detection after trade logic to ensure non-interference DetectFVGs(); } void ManageTrades(ENUM_TIMEFRAMES tf) { for(int i = PositionsTotal() - 1; i >= 0; i--) { ulong ticket = PositionGetTicket(i); if(!PositionSelectByTicket(ticket) || PositionGetString(POSITION_SYMBOL) != eaSymbol || PositionGetInteger(POSITION_MAGIC) != MagicNumber(tf)) continue; double openPrice, sl, tp, currPrice, lots, profit; if(!PositionGetDouble(POSITION_PRICE_OPEN, openPrice) || !PositionGetDouble(POSITION_SL, sl) || !PositionGetDouble(POSITION_TP, tp) || !PositionGetDouble(POSITION_VOLUME, lots) || !PositionGetDouble(POSITION_PROFIT, profit)) continue; currPrice = PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY ? SymbolInfoDouble(eaSymbol, SYMBOL_BID) : SymbolInfoDouble(eaSymbol, SYMBOL_ASK); int idx = TimeframeIndex(tf); if(idx < 0) continue; double atr[1]; if(CopyBuffer(tfs[idx].h_atr, 0, 0, 1, atr) < 1) continue; if((PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && currPrice >= openPrice + (openPrice - sl) * 3) || (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && currPrice <= openPrice - (sl - openPrice) * 3)) { if(lots > SymbolInfoDouble(eaSymbol, SYMBOL_VOLUME_MIN) * 2) { trade.PositionClosePartial(ticket, lots / 2); trade.PositionModify(ticket, openPrice, tp); Print(EnumToString(tf), " Partial close at 1:3 RR: Ticket=", ticket, ", Lots=", DoubleToString(lots / 2, 2)); } } double trail = atr[0] * 1.5 / _Point; if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY && currPrice > openPrice + trail * _Point && sl < currPrice - trail * _Point) { trade.PositionModify(ticket, currPrice - trail * _Point, tp); Print(EnumToString(tf), " Trailing stop updated: Ticket=", ticket, ", New SL=", DoubleToString(currPrice - trail * _Point, _Digits)); } else if(PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_SELL && currPrice < openPrice - trail * _Point && sl > currPrice + trail * _Point) { trade.PositionModify(ticket, currPrice + trail * _Point, tp); Print(EnumToString(tf), " Trailing stop updated: Ticket=", ticket, ", New SL=", DoubleToString(currPrice + trail * _Point, _Digits)); } if(profit != 0 && !PositionSelectByTicket(ticket)) { LogTrd(ticket, eaSymbol, openPrice, sl, tp, "Close", 0, 0, CurRisk, tf); Print(EnumToString(tf), " Position closed: Ticket=", ticket, ", Profit=", DoubleToString(profit, 2)); } } } void FetchNewsCalendar() { string url = NewsAPI_Url + NewsAPI_Key; string headers = ""; char post[], result[]; string result_headers; int timeout = 5000; int res = WebRequest("GET", url, headers, timeout, post, result, result_headers); if(res != 200) { Print("News API request failed: HTTP ", res, ", Error=", GetLastError()); newsCal[0].time = StringToTime("2025.07.15 14:30"); newsCal[0].evt = "CPI"; newsCal[0].impact = 90; newsCal[1].time = StringToTime("2025.07.23 20:00"); newsCal[1].evt = "FOMC"; newsCal[1].impact = 90; newsCnt = 2; Print("Using fallback news calendar with ", newsCnt, " events"); return; } string response = CharArrayToString(result); newsCnt = 0; ArrayResize(newsCal, 100); int pos = 0; while(pos >= 0 && newsCnt < 100) { pos = StringFind(response, "\"items\":", pos); if(pos < 0) break; pos = StringFind(response, "{", pos); if(pos < 0) break; int end = StringFind(response, "}", pos); if(end < 0) break; string item = StringSubstr(response, pos, end - pos + 1); string evtName = ExtractJsonField(item, "\"title\":"); string evtTime = ExtractJsonField(item, "\"time_published\":"); string relevance = ExtractJsonField(item, "\"relevance_score\":"); if(evtName != "" && evtTime != "") { string dt = StringSubstr(evtTime, 0, 4) + "." + StringSubstr(evtTime, 4, 2) + "." + StringSubstr(evtTime, 6, 2) + " " + StringSubstr(evtTime, 9, 2) + ":" + StringSubstr(evtTime, 11, 2); newsCal[newsCnt].time = StringToTime(dt); newsCal[newsCnt].evt = evtName; newsCal[newsCnt].impact = (relevance != "") ? (int)(StringToDouble(relevance) * 100) : 80; if(newsCal[newsCnt].impact > 80 && newsCal[newsCnt].time > TimeCurrent() - 7 * 86400) { newsCnt++; Print("News event loaded: ", evtName, " at ", TimeToString(newsCal[newsCnt-1].time), ", Impact=", newsCal[newsCnt-1].impact); } } pos = end + 1; } Print("Loaded ", newsCnt, " high-impact news events from API"); } string ExtractJsonField(string json, string field) { int pos = StringFind(json, field); if(pos < 0) return ""; pos += StringLen(field); if(StringFind(json, "\"", pos) == pos) pos++; int end = StringFind(json, "\"", pos); if(end < 0) return ""; return StringSubstr(json, pos, end - pos); } bool NewBar(ENUM_TIMEFRAMES tf) { int idx = TimeframeIndex(tf); if(idx < 0) return false; datetime cur = iTime(eaSymbol, tf, 0); if(cur != tfs[idx].lastBar) { tfs[idx].lastBar = cur; return true; } return false; } bool BullTrend(ENUM_TIMEFRAMES tf) { int handle = (tf == PERIOD_D1) ? h_ema_d1 : h_ema_h4; double ema[2]; if(CopyBuffer(handle, 0, 1, 2, ema) < 2) { Print("EMA copy failed for ", EnumToString(tf)); return false; } Print("EMA ", EnumToString(tf), ": ", DoubleToString(ema[1], _Digits), " vs ", DoubleToString(ema[0], _Digits)); return ema[1] > ema[0]; } bool BearTrend(ENUM_TIMEFRAMES tf) { int handle = (tf == PERIOD_D1) ? h_ema_d1 : h_ema_h4; double ema[2]; if(CopyBuffer(handle, 0, 1, 2, ema) < 2) { Print("EMA copy failed for ", EnumToString(tf)); return false; } Print("EMA ", EnumToString(tf), ": ", DoubleToString(ema[1], _Digits), " vs ", DoubleToString(ema[0], _Digits)); return ema[1] < ema[0]; } bool BuyBrk(ENUM_TIMEFRAMES tf) { double high = iHigh(eaSymbol, tf, iHighest(eaSymbol, tf, MODE_HIGH, Brk_Prd, 1)); double price = SymbolInfoDouble(eaSymbol, SYMBOL_ASK); Print(EnumToString(tf), " BuyBrk check: Price=", DoubleToString(price, _Digits), ", High=", DoubleToString(high, _Digits)); return price > high; } bool SellBrk(ENUM_TIMEFRAMES tf) { double low = iLow(eaSymbol, tf, iLowest(eaSymbol, tf, MODE_LOW, Brk_Prd, 1)); double price = SymbolInfoDouble(eaSymbol, SYMBOL_BID); Print(EnumToString(tf), " SellBrk check: Price=", DoubleToString(price, _Digits), ", Low=", DoubleToString(low, _Digits)); return price < low; } double CalcLots(double eq, double riskPct, double slPips) { double pipVal = SymbolInfoDouble(eaSymbol, SYMBOL_TRADE_TICK_VALUE); double riskAmt = MathMin(eq * (riskPct / 100), MaxLossUSD); double lots = riskAmt / (slPips * pipVal); double minLot = SymbolInfoDouble(eaSymbol, SYMBOL_VOLUME_MIN); double maxLot = SymbolInfoDouble(eaSymbol, SYMBOL_VOLUME_MAX); lots = NormalizeDouble(MathMax(minLot, MathMin(maxLot, lots)), 2); Print("CalcLots: Equity=", DoubleToString(eq, 2), ", Risk%=", DoubleToString(riskPct, 2), ", SL Pips=", DoubleToString(slPips, 2), ", PipVal=", DoubleToString(pipVal, 2), ", Lots=", DoubleToString(lots, 2), ", MinLot=", DoubleToString(minLot, 2), ", MaxLot=", DoubleToString(maxLot, 2)); return lots; } bool IsNews() { if(newsCnt == 0 && NewsFilt) { Print("No news events loaded, bypassing news filter"); return false; } datetime now = TimeCurrent(); Print("News check: Current time=", TimeToString(now, TIME_DATE|TIME_MINUTES)); for(int i = 0; i < newsCnt; i++) { if(now >= newsCal[i].time - NewsPause * 60 && now <= newsCal[i].time + NewsPause * 60 && newsCal[i].impact > 80) { Print("News event active: ", newsCal[i].evt, " at ", TimeToString(newsCal[i].time, TIME_DATE|TIME_MINUTES)); return true; } } Print("No active news events"); return false; } void LogTrd(ulong ticket, string sym, double price, double sl, double tp, string stat, double brkStr, double vol, double risk, ENUM_TIMEFRAMES tf) { string data = StringFormat("T=%I64u,S=%s,Tm=%s,P=%f,SL=%f,TP=%f,St=%s,BrkStr=%f,Vol=%f,Risk=%f,TF=%s", ticket, sym, TimeToString(TimeCurrent(), TIME_DATE|TIME_MINUTES), price, sl, tp, stat, brkStr, vol, risk, EnumToString(tf)); if(StringLen(GS_Url) > 0) Print("Webhook pending: ", data); Print("Trd: ", data); if(stat == "Close" && tradeCnt < ArraySize(tradeHistory)) { double profit; if(PositionSelectByTicket(ticket)) { PositionGetDouble(POSITION_PROFIT, profit); tradeHistory[tradeCnt].ticket = ticket; tradeHistory[tradeCnt].isWin = profit > 0; tradeHistory[tradeCnt].profit = profit; tradeHistory[tradeCnt].brkStr = brkStr; tradeHistory[tradeCnt].vol = vol; tradeHistory[tradeCnt].risk = risk; tradeHistory[tradeCnt].tf = tf; tradeCnt++; UpdateWinLossStreak(); AdjustBreakoutStrength(); } } } void UpdateWinLossStreak() { if(tradeCnt > 0) { if(tradeHistory[tradeCnt-1].isWin) { winStreak++; lossStreak = 0; } else { lossStreak++; winStreak = 0; } } } void AdjustBreakoutStrength() { if(tradeCnt < 10) return; int lossCnt = 0; double avgBrkStr = 0; for(int i = tradeCnt - 10; i < tradeCnt; i++) { if(!tradeHistory[i].isWin) lossCnt++; avgBrkStr += tradeHistory[i].brkStr; } avgBrkStr /= 10; if(lossCnt >= 5 && avgBrkStr < MinBrkStr * 1.5) dynBrkStr = MinBrkStr * 1.5; else if(lossCnt <= 2) dynBrkStr = MinBrkStr; Print("Breakout strength adjusted: dynBrkStr=", DoubleToString(dynBrkStr, 2)); } long MagicNumber(ENUM_TIMEFRAMES tf) { if(tf == PERIOD_M5) return 1005; if(tf == PERIOD_M15) return 1015; if(tf == PERIOD_H1) return 1060; return 0; } int TimeframeIndex(ENUM_TIMEFRAMES tf) { for(int i = 0; i < ArraySize(tfs); i++) { if(tfs[i].tf == tf) return i; } return -1; }
安装与回测:编译并附加到图表上。 在 GOLD 的 M15 时间周期上进行回测(2025 年),风险设为 2%。
策略测试
该策略在 GOLD 上效果最佳,因为其价格变动相对迅速、波动性较高,有利于散户进行日内交易。 我们将在 15 分钟(M15)时间周期上,以 2025 年 1 月 1 日至 2025 年 7 月 29 日期间的 GOLD 交易来测试该策略。 以下是我为该策略选定的参数。
策略测试器结果
在策略测试器上进行测试后,结果如下。
- 余额/净值曲线图:
- 回测结果:
摘要
我撰写本文,旨在介绍一款 MetaTrader 5 智能交易系统(EA),它结合公允价值缺口(FVG)检测与市场结构转变(MSS),用于识别 GOLD 上的高概率交易形态。 公允价值缺口是聪明钱概念中常用且极具价值的一部分,用于识别价格失衡和趋势转变。
我在 GOLD 上测试了该 EA,结果表明,它能够在 M15 和 H1 时间周期上高效、准确地检测公允价值缺口(FVG)。但检测公允价值缺口只是其中一个环节,因为如果没有发生市场结构转变,即使公允价值缺口有效,也不应执行交易。 这些市场结构转变可作为确认信号,有助于在波动剧烈的交易时段提高交易的准确性和质量。
要实施这一策略,请按照所示设置配置 EA 的输入参数,以获得理想的结果。 该 EA 旨在扫描 M15 或 H1 图表上的 FVG,并确保市场结构转变与更高时间周期的趋势(例如 H4/D1)保持一致。 有兴趣的用户应使用GOLD在模拟账户上对该EA进行回测。 我开发该 EA 的主要目标,是针对经过筛选的高概率交易形态进行优化,并纳入风险管理措施,例如将每笔交易的风险控制在 0.5%–2%,以及使用跟踪止损。
我还建议用户定期查看交易表现日志,根据自身目标或风险偏好来优化设置和输入参数。 免责声明:任何使用此 EA 的用户,在投入真实资金承担风险之前,都应先在模拟账户上进行测试和交易,以掌握这种旨在实现持续盈利的机构交易方法。
结论
本文的核心在于尽可能清楚地解释什么是公允价值缺口,它们出现在哪里、如何形成、为何形成,以及如何恰当地利用它们分析和理解市场,乃至执行交易。
大多数新手交易者,甚至一些中级交易者,都不知道如何应对公允价值缺口这一令人困惑的领域,甚至因此感到沮丧。他们无法真正理解其中的机制,也缺乏足够的洞察力,无法看清价格如何一次次回到这些缺口,以及如何利用这些缺口完成经典的交易操作,从而有可能获得实际利润。 即使不依据公允价值缺口执行交易,交易者也可以利用本文分享的内容,验证自己的交易、交易形态,乃至趋势和方向判断。他们还会饶有兴趣地发现,这些公允价值缺口发挥着至关重要的作用。
通过使用 MQL5 实现自动化交易,交易者可以减少情绪对决策的干扰,从而保持 FVG + Breaker/MSS 策略执行的一致性。
本文中提到的所有代码均附于下方。 下表介绍了本文附带的所有源代码文件。| 文件名 | 描述 |
|---|---|
| Fvg_detector.mq5 | 包含公允价值缺口检测代码的文件 |
| fvg-mss.mq5 | 包含整合了公允价值缺口检测与市场结构转变功能的完整智能交易系统(EA)代码的文件 |
本文由MetaQuotes Ltd译自英文
原文地址: https://www.mql5.com/en/articles/18669
注意: MetaQuotes Ltd.将保留所有关于这些材料的权利。全部或部分复制或者转载这些材料将被禁止。
本文由网站的一位用户撰写,反映了他们的个人观点。MetaQuotes Ltd 不对所提供信息的准确性负责,也不对因使用所述解决方案、策略或建议而产生的任何后果负责。
不错 👍。