i need a profitable strategy, winrate over 50%, based on break of structure and fvg
- User
i need a profitable strategy, winrate over 50%, based on break of structure and fvg
- Assistant
Certainly! Here’s a structured and practical trading strategy based on Break of Structure (BoS) and Fair Value Gaps (FVG) designed to target a win rate over 50%. This strategy is commonly used in price action and order flow trading and can be adapted to various markets (forex, crypto, stocks).
Strategy Overview:
- Concepts Used: Break of Structure (BoS) + Fair Value Gaps (FVG)
- Goal: Enter trades after a confirmed BoS and price retracement into an identified FVG to get favorable entries with good risk/reward.
- Win Rate Expectation: Around 50-60% with proper risk management and market conditions.
- Timeframes: Can work from 15-minute chart and above (e.g., 1H, 4H).
Key Concepts
1. Break of Structure (BoS)
- A Break of Structure signals a potential trend change or continuation.
- In an uptrend, BoS occurs when price breaks above a previous significant high (swing high).
- In a downtrend, BoS occurs when price breaks below a previous significant low (swing low).
2. Fair Value Gap (FVG)
- A Fair Value Gap is an unfilled “imbalance” in price action created when there is a sudden large move.
- Usually represented by 3 candles: the middle candle’s range (high to low) is not overlapped by the candles before and after.
- Price often retraces to these gaps to "fill" the inefficiency before continuing.
Step-by-Step Strategy
Step 1: Identify Market Structure and Wait for BoS
- Determine if the market is trending up or down on your chosen timeframe.
- Identify the last swing high and low.
- Wait for price to break a significant structure point:
- Bullish BoS: Price breaks above the last swing high.
- Bearish BoS: Price breaks below the last swing low.
Step 2: Locate Fair Value Gap (FVG)
- After BoS, look for a recent FVG on the chart:
- For bullish setup: Look for a downward Fair Value Gap created by the impulsive move upwards.
- For bearish setup: Look for an upward Fair Value Gap created by the impulsive down move.
- The FVG area acts as potential liquidity or correction zone where price is likely to pull back.
Step 3: Wait for Price to Retrace Back to the FVG Zone
- After the break, wait for price to come back and "fill" or approach the FVG zone.
- This gives a good entry price with reduced risk, rather than chasing the breakout.
Step 4: Entry Setup
- Confirm entry with a price action signal or confirmation candle at the FVG zone (e.g., pin bar, engulfing candle, or bullish/bearish rejection).
- Enter a buy if bullish; sell if bearish.
Step 5: Place Stop Loss
- Place your stop loss just beyond the opposite end of the FVG or beyond the latest swing low/high to protect against false breaks.
- This keeps your risk well-defined.
Step 6: Define Target & Manage Trade
- Target the next logical structure point, such as the next significant swing high (for longs) or swing low (for shorts).
- Aim for at least 1.5x-2x risk/reward ratio.
- Optionally trail stop or take partial profits if price action shows signs of reversal.
Example (Bullish Scenario)
- Price is in an uptrend; last swing high at 100.
- Price breaks above 100 - this is a Bullish BoS.
- Identify FVG gap below created between candles at ~102 to 104 during the impulsive upward move.
- Price retraces back to fill gap (~102-104 zone).
- Wait for bullish confirmation candle in FVG zone.
- Enter long at say 103.
- Stop loss below FVG at 101.5.
- Target next resistance at 107.
- Risk 1.5 units to make 4 units (good risk/reward).
Tips to Improve Win Rate
- Trade in the direction of higher timeframe trend.
- Avoid trading during low liquidity/high volatility news events.
- Use volume or momentum indicators for confirmation.
- Start with tight risk management: risk 1% or less per trade.
- Avoid taking trades against clearly visible strong opposing levels.
Summary Table
Step Action Detail 1 Identify Market Structure Find swing highs/lows and existing trend 2 Wait for Break of Structure Price breaks significant swing point 3 Identify Fair Value Gap Recent imbalance gap created during impulsive move 4 Wait for Price Retrace Price pulls back to FVG zone 5 Confirm Entry Use price action candle confirmation 6 Enter & Set Stop Loss Stop just beyond FVG or structure low/high 7 Set Target/Manage Trade Next structure level for target, good R:R
If you want, I can help you with charts or even code this strategy into an indicator or alert system for a specific platform like TradingView’s Pine Script. Would you like that?
- User
i want an expert advisor for mt5, mql5
- Assistant
Certainly! Below is a well-commented example of an MT5 Expert Advisor (EA) in MQL5 implementing a Break of Structure (BoS) + Fair Value Gap (FVG) based strategy as described. This is a simplified and educational template that you will need to optimize and test thoroughly before running on a live account.
Important Notes before using this EA:
- The EA is designed on a 1H timeframe but can be adjusted.
- It identifies BoS by detecting when price closes above a recent swing high (for longs) or below a recent swing low (for shorts).
- It identifies Fair Value Gaps as gaps between candles on previous bars.
- It waits for price to retrace into the FVG zone, then enters with a confirmation candle.
- Stop Loss and Take Profit are placed accordingly.
- The EA uses predefined parameters for lookback periods for swings, gap size, risk, etc.
- This is a starting point; further improvements and additional filters (e.g., trend confirmation, ATR-based SL/TP) are strongly recommended.
MQL5 Expert Advisor Code
//+------------------------------------------------------------------+ //| BoS_FVG_EA.mq5 | //| Break of Structure + Fair Value Gap Strategy (simplified) | //+------------------------------------------------------------------+ #property copyright "OpenAI" #property version "1.00" #property strict #include <Trade\Trade.mqh> input double Lots = 0.1; // Fixed lot size input int SwingLookback = 20; // bars to lookback for swing high/low input int FVGLookback = 10; // bars to look back for Fair Value Gaps input double SL_Pips = 50; // Stop loss in pips input double TP_Pips = 100; // Take profit in pips input double Gap_MinSize_Pips= 10; // Minimum FVG size in pips input int ConfirmationBars= 1; // Confirmation candle after retrace for entry input ENUM_TIMEFRAMES Timeframe= PERIOD_H1; // Chart timeframe to trade CTrade trade; // Structure to store swing points struct SwingPoint { int index; double price; }; //+------------------------------------------------------------------+ //| Find last swing high | //+------------------------------------------------------------------+ bool FindLastSwingHigh(int lookback, SwingPoint &swingHigh) { double highest= -1.0; int highest_index = -1; for(int i=1; i<=lookback; i++) { if(High[i]>highest) { highest = High[i]; highest_index = i; } } if(highest_index>0) { swingHigh.index = highest_index; swingHigh.price = highest; return true; } return false; } //+------------------------------------------------------------------+ //| Find last swing low | //+------------------------------------------------------------------+ bool FindLastSwingLow(int lookback, SwingPoint &swingLow) { double lowest= DBL_MAX; int lowest_index = -1; for(int i=1; i<=lookback; i++) { if(Low[i]<lowest) { lowest = Low[i]; lowest_index = i; } } if(lowest_index>0) { swingLow.index = lowest_index; swingLow.price = lowest; return true; } return false; } //+------------------------------------------------------------------+ //| Find Fair Value Gap | //| Returns true with gap detected between bars[gapIndex+1] and bars[gapIndex] | //+------------------------------------------------------------------+ bool FindFairValueGap(bool bullish, int lookback, double &gap_low, double &gap_high, int &gapIndex) { // Fair Value Gap criteria: // For bullish: gap between Low of bar[i] and High of bar[i+2], where Low[i] > High[i+2] // For bearish: gap between High of bar[i] and Low of bar[i+2], where High[i] < Low[i+2] for(int i=1; i<lookback-2; i++) { if(bullish) { if(Low[i] > High[i+2]) { double gapSizePips = (Low[i] - High[i+2]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = High[i+2]; gap_high= Low[i]; gapIndex=i; return true; } } } else // bearish { if(High[i] < Low[i+2]) { double gapSizePips = (Low[i+2] - High[i]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = High[i]; gap_high= Low[i+2]; gapIndex=i; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Check for Break of Structure | //+------------------------------------------------------------------+ bool CheckBreakOfStructure(bool bullish) { SwingPoint swingPoint; if(bullish) { // Check price closes above last swing high if(FindLastSwingHigh(SwingLookback, swingPoint)) { if(Close[1] > swingPoint.price) return true; } } else // bearish { if(FindLastSwingLow(SwingLookback, swingPoint)) { if(Close[1] < swingPoint.price) return true; } } return false; } //+------------------------------------------------------------------+ //| Check if price is in FVG zone | //+------------------------------------------------------------------+ bool IsPriceInFVG(double gap_low, double gap_high) { double priceNow = Close[1]; if(priceNow >= gap_low && priceNow <= gap_high) return true; return false; } //+------------------------------------------------------------------+ //| Place orders function | //+------------------------------------------------------------------+ bool PlaceOrder(bool buy) { MqlTradeRequest request; MqlTradeResult result; double price = 0.0; double sl = 0.0; double tp = 0.0; if(buy) { price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); sl = price - SL_Pips*_Point; tp = price + TP_Pips*_Point; } else { price = SymbolInfoDouble(_Symbol, SYMBOL_BID); sl = price + SL_Pips*_Point; tp = price - TP_Pips*_Point; } request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = Lots; request.type = buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; request.price = price; request.sl = sl; request.tp = tp; request.deviation = 5; request.magic = 123456; if(!OrderSend(request,result)) { Print("OrderSend failed: ", GetLastError()); return false; } else { Print((buy ? "BUY" : "SELL"), " order placed successfully. Ticket: ", result.order); return true; } } //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Print("BoS + FVG EA started."); EventSetMillisecondTimer(1000); // 1 second timer for ticks if needed return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { EventKillTimer(); } //+------------------------------------------------------------------+ //| Timer function (not used but could be extended) | //+------------------------------------------------------------------+ void OnTimer() { // Could be used for ticks if needed } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { static datetime lastTradeTime=0; static bool positionOpened = false; if(PositionSelect(_Symbol)) // Check if position already exists return; // Operate only on new bar static datetime lastBarTime=0; MqlRates rates[]; if(CopyRates(_Symbol, Timeframe, 0, SwingLookback+10, rates)<=0) return; datetime currentBarTime = rates[1].time; if(currentBarTime == lastBarTime) return; // Wait for new bar lastBarTime = currentBarTime; // 1. Check Bullish Setup if(CheckBreakOfStructure(true)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { // Confirmation candle - basic check: bullish candle close > open on current candle - ConfirmationBars bars ago if(Close[ConfirmationBars] > Open[ConfirmationBars]) { // Place buy order if(PlaceOrder(true)) { positionOpened = true; lastTradeTime=TimeCurrent(); } } } } } // 2. Check Bearish Setup if(!positionOpened && CheckBreakOfStructure(false)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(false, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { // Confirmation candle - bearish candle close < open if(Close[ConfirmationBars] < Open[ConfirmationBars]) { // Place sell order if(PlaceOrder(false)) { positionOpened = true; lastTradeTime=TimeCurrent(); } } } } } } //+------------------------------------------------------------------+
How to Use / Customize:
- Compile and attach to an H1 chart of your preferred symbol.
- Adjust inputs:
Lots,SwingLookback,FVGLookback,SL_Pips,TP_Pips. - Test extensively on demo account first! Adjust the logic and risk management based on performance.
- Add additional filters and improvements like ATR-based SL/TP, session filters, volume confirmation, etc for better results.
If you want, I can also assist you to add those advanced features or write a version for different timeframes or additional indicators. Let me know!
- User
does it display swing and fvg?
- Assistant
The provided EA code does not display Swing points or Fair Value Gap zones on the chart — it's focused purely on detecting these conditions internally and placing trades accordingly.
How to add visualization (display swing points and FVG zones) in MT5:
You can extend the EA to draw graphical objects on the chart that represent:
- Swing Points (e.g., arrows or labels at swing highs/lows)
- Fair Value Gaps (e.g., colored rectangles showing the gap zone)
Example snippet to visualize Swing Points and FVG zones:
Add these helper functions for drawing inside the EA, then call them after you identify swing/ FVG:
//+------------------------------------------------------------------+ //| Draw swing high arrow | //+------------------------------------------------------------------+ void DrawSwingHigh(int index, double price) { string name = "SwingHigh_" + IntegerToString(index); if(ObjectFind(0, name) < 0) // only draw if not exists { ObjectCreate(0, name, OBJ_ARROW, 0, Time[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233); // Up Arrow ObjectSetInteger(0, name, OBJPROP_COLOR, clrGreen); } } //+------------------------------------------------------------------+ //| Draw swing low arrow | //+------------------------------------------------------------------+ void DrawSwingLow(int index, double price) { string name = "SwingLow_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, Time[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234); // Down Arrow ObjectSetInteger(0, name, OBJPROP_COLOR, clrRed); } } //+------------------------------------------------------------------+ //| Draw Fair Value Gap rectangle | //+------------------------------------------------------------------+ void DrawFVGZone(int gapIndex, double gapLow, double gapHigh) { string name = "FVG_" + IntegerToString(gapIndex); if(ObjectFind(0, name) < 0) { datetime time1 = Time[gapIndex + 2]; datetime time2 = Time[gapIndex]; // Draw rectangle from bar time + small offset for width, use price low/high for vertical rectangle if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, gapHigh, time2, gapLow)) { Print("Failed to create FVG rectangle"); return; } ObjectSetInteger(0, name, OBJPROP_COLOR, clrYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); // Behind price ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); ObjectSetInteger(0, name, OBJPROP_TRANSPARENCY, 70); } }
Where to call these?
For example, in your
OnTick()or where you find swing highs/lows and FVG, after detecting them:// After you find a swing high SwingPoint swingHigh; if(FindLastSwingHigh(SwingLookback, swingHigh)) DrawSwingHigh(swingHigh.index, swingHigh.price); // After you find a swing low SwingPoint swingLow; if(FindLastSwingLow(SwingLookback, swingLow)) DrawSwingLow(swingLow.index, swingLow.price); // After you find an FVG double fvgLow, fvgHigh; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); if(FindFairValueGap(false, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh);
Summary:
- No UI visualization is included in the initial EA code.
- You need to add drawing code yourself (above snippets or similar).
- This improves debugging and understanding of the strategy visually.
If you want, I can prepare the full EA code with visualization included so you get buy/sell signals and see swing and FVG zones directly on the chart. Would you like me to do that?
- User
yes please
- Assistant
Certainly! Below is an enhanced version of the previous MT5 Expert Advisor that includes visualization of Swing Points (Highs/Lows) and Fair Value Gaps (FVG) on the chart, along with the existing Break of Structure + FVG-based trade logic.
Complete MT5 EA with Swing & FVG Visualization
//+------------------------------------------------------------------+ //| BoS_FVG_EA_with_Drawings.mq5 | //| Break of Structure + Fair Value Gap + Visuals | //+------------------------------------------------------------------+ #property copyright "OpenAI" #property version "1.01" #property strict #include <Trade\Trade.mqh> input double Lots = 0.1; // Fixed lot size input int SwingLookback = 20; // bars to lookback for swing high/low input int FVGLookback = 10; // bars to look back for Fair Value Gaps input double SL_Pips = 50; // Stop loss in pips input double TP_Pips = 100; // Take profit in pips input double Gap_MinSize_Pips= 10; // Minimum FVG size in pips input int ConfirmationBars= 1; // Confirmation candle after retrace for entry input ENUM_TIMEFRAMES Timeframe= PERIOD_H1; // Chart timeframe to trade input bool ShowVisuals = true; // Show swing and FVG visuals on chart CTrade trade; // Structure to store swing points struct SwingPoint { int index; double price; }; //+------------------------------------------------------------------+ //| Find last swing high | //+------------------------------------------------------------------+ bool FindLastSwingHigh(int lookback, SwingPoint &swingHigh) { double highest= -1.0; int highest_index = -1; for(int i=1; i<=lookback; i++) { if(High[i]>highest) { highest = High[i]; highest_index = i; } } if(highest_index>0) { swingHigh.index = highest_index; swingHigh.price = highest; return true; } return false; } //+------------------------------------------------------------------+ //| Find last swing low | //+------------------------------------------------------------------+ bool FindLastSwingLow(int lookback, SwingPoint &swingLow) { double lowest= DBL_MAX; int lowest_index = -1; for(int i=1; i<=lookback; i++) { if(Low[i]<lowest) { lowest = Low[i]; lowest_index = i; } } if(lowest_index>0) { swingLow.index = lowest_index; swingLow.price = lowest; return true; } return false; } //+------------------------------------------------------------------+ //| Find Fair Value Gap | //| Returns true with gap detected between bars[gapIndex+1] and bars[gapIndex] | //+------------------------------------------------------------------+ bool FindFairValueGap(bool bullish, int lookback, double &gap_low, double &gap_high, int &gapIndex) { // Fair Value Gap criteria: // For bullish: gap between Low of bar[i] and High of bar[i+2], where Low[i] > High[i+2] // For bearish: gap between High of bar[i] and Low of bar[i+2], where High[i] < Low[i+2] for(int i=1; i<lookback-2; i++) { if(bullish) { if(Low[i] > High[i+2]) { double gapSizePips = (Low[i] - High[i+2]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = High[i+2]; gap_high= Low[i]; gapIndex=i; return true; } } } else // bearish { if(High[i] < Low[i+2]) { double gapSizePips = (Low[i+2] - High[i]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = High[i]; gap_high= Low[i+2]; gapIndex=i; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Check for Break of Structure | //+------------------------------------------------------------------+ bool CheckBreakOfStructure(bool bullish) { SwingPoint swingPoint; if(bullish) { // Check price closes above last swing high if(FindLastSwingHigh(SwingLookback, swingPoint)) { if(Close[1] > swingPoint.price) return true; } } else // bearish { if(FindLastSwingLow(SwingLookback, swingPoint)) { if(Close[1] < swingPoint.price) return true; } } return false; } //+------------------------------------------------------------------+ //| Check if price is in FVG zone | //+------------------------------------------------------------------+ bool IsPriceInFVG(double gap_low, double gap_high) { double priceNow = Close[1]; if(priceNow >= gap_low && priceNow <= gap_high) return true; return false; } //+------------------------------------------------------------------+ //| Place orders function | //+------------------------------------------------------------------+ bool PlaceOrder(bool buy) { MqlTradeRequest request; MqlTradeResult result; double price = 0.0; double sl = 0.0; double tp = 0.0; if(buy) { price = SymbolInfoDouble(_Symbol, SYMBOL_ASK); sl = price - SL_Pips*_Point; tp = price + TP_Pips*_Point; } else { price = SymbolInfoDouble(_Symbol, SYMBOL_BID); sl = price + SL_Pips*_Point; tp = price - TP_Pips*_Point; } request.action = TRADE_ACTION_DEAL; request.symbol = _Symbol; request.volume = Lots; request.type = buy ? ORDER_TYPE_BUY : ORDER_TYPE_SELL; request.price = price; request.sl = sl; request.tp = tp; request.deviation = 10; request.magic = 123456; if(!OrderSend(request,result)) { Print("OrderSend failed: ", GetLastError()); return false; } else { Print((buy ? "BUY" : "SELL"), " order placed successfully. Ticket: ", result.order); return true; } } //+------------------------------------------------------------------+ //| Draw swing high arrow | //+------------------------------------------------------------------+ void DrawSwingHigh(int index, double price) { string name = "SwingHigh_" + IntegerToString(index); if(ObjectFind(0, name) < 0) // only draw if not exists { ObjectCreate(0, name, OBJ_ARROW, 0, Time[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233); // Up Arrow ObjectSetInteger(0, name, OBJPROP_COLOR, clrGreen); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw swing low arrow | //+------------------------------------------------------------------+ void DrawSwingLow(int index, double price) { string name = "SwingLow_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, Time[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234); // Down Arrow ObjectSetInteger(0, name, OBJPROP_COLOR, clrRed); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw Fair Value Gap rectangle | //+------------------------------------------------------------------+ void DrawFVGZone(int gapIndex, double gapLow, double gapHigh) { string name = "FVG_" + IntegerToString(gapIndex); if(ObjectFind(0, name) < 0) { datetime time1 = Time[gapIndex + 2]; datetime time2 = Time[gapIndex]; // Create rectangle from older bar to recent bar + small offset for width if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, gapHigh, time2, gapLow)) { Print("Failed to create FVG rectangle"); return; } ObjectSetInteger(0, name, OBJPROP_COLOR, clrYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); // behind price ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); ObjectSetInteger(0, name, OBJPROP_TRANSPARENCY, 70); } } //+------------------------------------------------------------------+ //| Expert initialization function | //+------------------------------------------------------------------+ int OnInit() { Print("BoS + FVG EA with visuals started."); EventSetMillisecondTimer(1000); // 1 second timer for ticks if needed return(INIT_SUCCEEDED); } //+------------------------------------------------------------------+ //| Expert deinitialization function | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { // Cleanup objects on deinit int total = ObjectsTotal(0,0); for(int i=total-1; i>=0; i--) { string name = ObjectName(0,i); if(StringFind(name,"SwingHigh_")==0 || StringFind(name,"SwingLow_")==0 || StringFind(name,"FVG_")==0) ObjectDelete(0,name); } EventKillTimer(); } //+------------------------------------------------------------------+ //| Timer function (not used but could be extended) | //+------------------------------------------------------------------+ void OnTimer() { // Could be used for ticks if needed } //+------------------------------------------------------------------+ //| Expert tick function | //+------------------------------------------------------------------+ void OnTick() { // Only trade on new bar static datetime lastBarTime=0; MqlRates rates[]; if(CopyRates(_Symbol, Timeframe, 0, SwingLookback+10, rates)<=0) return; datetime currentBarTime = rates[1].time; if(currentBarTime == lastBarTime) return; // wait for new bar/timeframe lastBarTime = currentBarTime; // Draw swings and FVG if enabled if(ShowVisuals) { SwingPoint swingHigh, swingLow; if(FindLastSwingHigh(SwingLookback, swingHigh)) DrawSwingHigh(swingHigh.index, swingHigh.price); if(FindLastSwingLow(SwingLookback, swingLow)) DrawSwingLow(swingLow.index, swingLow.price); double fvgLow, fvgHigh; int gapIndex; // Clear old FVG objects to avoid clutter (optional) // Alternatively keep and only draw new ones, but here we just draw any detected: if(FindFairValueGap(true, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); if(FindFairValueGap(false, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); } // Skip trading if any position exists on symbol if(PositionSelect(_Symbol)) return; // 1. Bullish setup if(CheckBreakOfStructure(true)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { // Confirmation candle - bullish if(Close[ConfirmationBars] > Open[ConfirmationBars]) { if(!trade.Buy(Lots,NULL,SymbolInfoDouble(_Symbol, SYMBOL_ASK),SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SL_Pips*_Point,SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TP_Pips*_Point,"BoS+FVG Buy")) Print("Buy order failed: ", GetLastError()); } } } } else if(CheckBreakOfStructure(false)) { // 2. Bearish setup double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(false, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { // Confirmation candle - bearish if(Close[ConfirmationBars] < Open[ConfirmationBars]) { if(!trade.Sell(Lots,NULL,SymbolInfoDouble(_Symbol, SYMBOL_BID),SymbolInfoDouble(_Symbol, SYMBOL_BID) + SL_Pips*_Point,SymbolInfoDouble(_Symbol, SYMBOL_BID) - TP_Pips*_Point,"BoS+FVG Sell")) Print("Sell order failed: ", GetLastError()); } } } } }
How This Works:
- Swing Points: Up arrows (green) mark swing highs, down arrows (red) mark swing lows from the past
SwingLookbackbars. - FVG Zones: Semi-transparent yellow rectangles mark zones identified as Fair Value Gaps within
FVGLookbackbars. - Trades: The EA waits for Break of Structure, confirms price is inside FVG, then enters with confirmation candle.
- Risk management done via fixed SL/TP in pips (adjustable).
- Visual objects auto-delete on EA removal.
- Trades only one position at a time per symbol.
How to Use:
- Compile and attach the EA to your chosen symbol chart (preferably H1 timeframe).
- Adjust inputs like
Lots,SwingLookback,FVGLookback,SL_Pips,TP_Pips,Gap_MinSize_Pipsas needed. ShowVisuals= true to enable drawings.- Backtest and demo test thoroughly before live.
- Watch the arrows and rectangles to understand how the EA decides entries.
If you want me to help with:
- Adding advanced filters (ATR SL/TP, session filter),
- Multi-timeframe confirmations,
- Alerts / notifications on signals,
Just ask!
Happy trading! 🚀
- Swing Points: Up arrows (green) mark swing highs, down arrows (red) mark swing lows from the past
- User
'Close' - undeclared identifier aaa.mq5 348 16 '[' - array required aaa.mq5 348 21 'Open' - undeclared identifier aaa.mq5 348 42
- Assistant
The errors
Close - undeclared identifierand'[' - array requiredindicate that the arraysClose[]andOpen[]are not defined or accessible in your EA code. In MQL5, unlike MQL4, the built-in price arrays likeClose[]andOpen[]are not automatically available—you need to retrieve them explicitly using functions such asCopyClose(),CopyOpen(), or by fetching full bars withCopyRates().
Fixing the errors
You have two main options:
Option 1: Use
CopyOpen()andCopyClose()to get the arraysDeclare global arrays for prices and fill them each bar, e.g.,
double CloseArray[]; double OpenArray[]; int barsToCopy = SwingLookback + 20; // safe margin // Fill arrays at start of OnTick or preferably OnCalculate bool CopyArrays() { if(CopyClose(_Symbol, Timeframe, 0, barsToCopy, CloseArray) <= 0) return false; if(CopyOpen(_Symbol, Timeframe, 0, barsToCopy, OpenArray) <= 0) return false; return true; }Then, replace all
Close[i]withCloseArray[i]andOpen[i]withOpenArray[i]in your code.
Option 2: Use
MqlRatesarraySince you already
CopyRates()intoMqlRates rates[], you can use:rates[i].close rates[i].open rates[i].high rates[i].low rates[i].timeYou would need to rewrite your code to use this
rates[]array instead ofClose[]andOpen[].
Minimal example fix for your EA (using Option 1)
At the top (global or in OnTick):
double CloseArray[]; double OpenArray[]; int barsToCopy = 100; ... void OnTick() { // Copy prices arrays if(!CopyClose(_Symbol, Timeframe, 0, barsToCopy, CloseArray)) { Print("Failed to copy Close prices"); return; } if(!CopyOpen(_Symbol, Timeframe, 0, barsToCopy, OpenArray)) { Print("Failed to copy Open prices"); return; } // Then use CloseArray[], OpenArray[] below instead of Close[], Open[] ... }Then update all lines such as:
if(Close[ConfirmationBars] > Open[ConfirmationBars])to
if(CloseArray[ConfirmationBars] > OpenArray[ConfirmationBars])
Note on indexes difference
Remember that when you
CopyClose()from index 0,CloseArray[0]corresponds to the most recent completed bar's close (bar with shift 0). Your original code usesClose[1]for previous bar, so you may want to adjust the indices accordingly. Be consistent.
Summary
- Declare and copy
CloseArray[]andOpenArray[]before using price arrays. - Replace all
Close[i]andOpen[i]references with these arrays. - Alternatively, refactor to use
rates[]arrays and their.closeand.openmembers.
If you want, I can provide a fixed version of your EA code using
CopyClose/CopyOpenproperly. Would you like me to do that? - Declare and copy
- User
ya
- Assistant
Got it! I'll provide a corrected version of the EA where we properly load
CloseandOpenprice arrays usingCopyClose()andCopyOpen()functions and replace allClose[]andOpen[]references withCloseArray[]andOpenArray[]respectively.
Corrected EA snippet with price arrays
//+------------------------------------------------------------------+ //| BoS_FVG_EA_with_Drawings.mq5 | //| Break of Structure + Fair Value Gap + Visuals | //+------------------------------------------------------------------+ #property copyright "OpenAI" #property version "1.02" #property strict #include <Trade\Trade.mqh> input double Lots = 0.1; // Fixed lot size input int SwingLookback = 20; // bars to lookback for swing high/low input int FVGLookback = 10; // bars to look back for Fair Value Gaps input double SL_Pips = 50; // Stop loss in pips input double TP_Pips = 100; // Take profit in pips input double Gap_MinSize_Pips= 10; // Minimum FVG size in pips input int ConfirmationBars= 1; // Confirmation candle after retrace for entry input ENUM_TIMEFRAMES Timeframe= PERIOD_H1; // Chart timeframe to trade input bool ShowVisuals = true; // Show swing and FVG visuals on chart CTrade trade; // Declare price arrays double CloseArray[]; double OpenArray[]; double HighArray[]; double LowArray[]; datetime TimeArray[]; // Structure to store swing points struct SwingPoint { int index; double price; }; //+------------------------------------------------------------------+ //| Copy price arrays function | //+------------------------------------------------------------------+ bool CopyPriceArrays(int barsNeeded) { if(CopyClose(_Symbol, Timeframe, 0, barsNeeded, CloseArray) <= 0) { Print("Failed to copy Close array"); return false; } if(CopyOpen(_Symbol, Timeframe, 0, barsNeeded, OpenArray) <= 0) { Print("Failed to copy Open array"); return false; } if(CopyHigh(_Symbol, Timeframe, 0, barsNeeded, HighArray) <= 0) { Print("Failed to copy High array"); return false; } if(CopyLow(_Symbol, Timeframe, 0, barsNeeded, LowArray) <= 0) { Print("Failed to copy Low array"); return false; } if(CopyTime(_Symbol, Timeframe, 0, barsNeeded, TimeArray) <= 0) { Print("Failed to copy Time array"); return false; } return true; } //+------------------------------------------------------------------+ //| Find last swing high | //+------------------------------------------------------------------+ bool FindLastSwingHigh(int lookback, SwingPoint &swingHigh) { double highest= -1.0; int highest_index = -1; for(int i=1; i<=lookback; i++) { if(HighArray[i] > highest) { highest = HighArray[i]; highest_index = i; } } if(highest_index > 0) { swingHigh.index = highest_index; swingHigh.price = highest; return true; } return false; } //+------------------------------------------------------------------+ //| Find last swing low | //+------------------------------------------------------------------+ bool FindLastSwingLow(int lookback, SwingPoint &swingLow) { double lowest= DBL_MAX; int lowest_index = -1; for(int i=1; i<=lookback; i++) { if(LowArray[i] < lowest) { lowest = LowArray[i]; lowest_index = i; } } if(lowest_index > 0) { swingLow.index = lowest_index; swingLow.price = lowest; return true; } return false; } //+------------------------------------------------------------------+ //| Find Fair Value Gap | //+------------------------------------------------------------------+ bool FindFairValueGap(bool bullish, int lookback, double &gap_low, double &gap_high, int &gapIndex) { for(int i=1; i<lookback-2; i++) { if(bullish) { if(LowArray[i] > HighArray[i+2]) { double gapSizePips = (LowArray[i] - HighArray[i+2]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = HighArray[i+2]; gap_high= LowArray[i]; gapIndex = i; return true; } } } else // bearish { if(HighArray[i] < LowArray[i+2]) { double gapSizePips = (LowArray[i+2] - HighArray[i]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = HighArray[i]; gap_high= LowArray[i+2]; gapIndex = i; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Check for Break of Structure | //+------------------------------------------------------------------+ bool CheckBreakOfStructure(bool bullish) { SwingPoint swingPoint; if(bullish) { if(FindLastSwingHigh(SwingLookback, swingPoint)) { if(CloseArray[1] > swingPoint.price) return true; } } else { if(FindLastSwingLow(SwingLookback, swingPoint)) { if(CloseArray[1] < swingPoint.price) return true; } } return false; } //+------------------------------------------------------------------+ //| Check if price is in FVG zone | //+------------------------------------------------------------------+ bool IsPriceInFVG(double gap_low, double gap_high) { double priceNow = CloseArray[1]; if(priceNow >= gap_low && priceNow <= gap_high) return true; return false; } //+------------------------------------------------------------------+ //| Draw swing high arrow | //+------------------------------------------------------------------+ void DrawSwingHigh(int index, double price) { string name = "SwingHigh_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, TimeArray[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233); ObjectSetInteger(0, name, OBJPROP_COLOR, clrGreen); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw swing low arrow | //+------------------------------------------------------------------+ void DrawSwingLow(int index, double price) { string name = "SwingLow_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, TimeArray[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234); ObjectSetInteger(0, name, OBJPROP_COLOR, clrRed); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw Fair Value Gap rectangle | //+------------------------------------------------------------------+ void DrawFVGZone(int gapIndex, double gapLow, double gapHigh) { string name = "FVG_" + IntegerToString(gapIndex); if(ObjectFind(0, name) < 0) { datetime time1 = TimeArray[gapIndex + 2]; datetime time2 = TimeArray[gapIndex]; if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, gapHigh, time2, gapLow)) { Print("Failed to create FVG rectangle"); return; } ObjectSetInteger(0, name, OBJPROP_COLOR, clrYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); ObjectSetInteger(0, name, OBJPROP_TRANSPARENCY, 70); } } //+------------------------------------------------------------------+ //| Expert deinit | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { int total = ObjectsTotal(0,0); for(int i=total-1; i>=0; i--) { string name = ObjectName(0,i); if(StringFind(name,"SwingHigh_")==0 || StringFind(name,"SwingLow_")==0 || StringFind(name,"FVG_")==0) ObjectDelete(0,name); } } //+------------------------------------------------------------------+ //| Expert tick | //+------------------------------------------------------------------+ void OnTick() { // Calculate how many bars needed for arrays int barsNeeded = SwingLookback + FVGLookback + 10; // Copy price arrays if(!CopyPriceArrays(barsNeeded)) return; // Operate only on new bar static datetime lastBarTime = 0; if(TimeArray[1] == lastBarTime) return; // no new bar yet lastBarTime = TimeArray[1]; // Draw visuals if(ShowVisuals) { SwingPoint swingHigh, swingLow; if(FindLastSwingHigh(SwingLookback, swingHigh)) DrawSwingHigh(swingHigh.index, swingHigh.price); if(FindLastSwingLow(SwingLookback, swingLow)) DrawSwingLow(swingLow.index, swingLow.price); double fvgLow, fvgHigh; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); if(FindFairValueGap(false, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); } // Don't trade if position exists if(PositionSelect(_Symbol)) return; // Bullish setup if(CheckBreakOfStructure(true)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { if(CloseArray[ConfirmationBars] > OpenArray[ConfirmationBars]) { if(!trade.Buy(Lots, NULL, SymbolInfoDouble(_Symbol, SYMBOL_ASK), SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SL_Pips*_Point, SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TP_Pips*_Point, "BoS+FVG Buy")) Print("Buy order failed: ", GetLastError()); } } } } else if(CheckBreakOfStructure(false)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(false, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { if(CloseArray[ConfirmationBars] < OpenArray[ConfirmationBars]) { if(!trade.Sell(Lots, NULL, SymbolInfoDouble(_Symbol, SYMBOL_BID), SymbolInfoDouble(_Symbol, SYMBOL_BID) + SL_Pips*_Point, SymbolInfoDouble(_Symbol, SYMBOL_BID) - TP_Pips*_Point, "BoS+FVG Sell")) Print("Sell order failed: ", GetLastError()); } } } } } //+------------------------------------------------------------------+
What Changed?
- Before accessing price arrays, we explicitly copy
Close,Open,High,Low, andTimearrays from MT5 history usingCopyClose(),CopyOpen()etc. - All price array references (
Close[i],Open[i],High[i],Low[i],Time[i]) replaced withCloseArray[i],OpenArray[i],HighArray[i],LowArray[i],TimeArray[i]. - Added error handling when copying prices.
- Use
TimeArray[]for drawing chart objects timestamps. - Adjusted bar indexing consistently (0 = current forming bar, 1 = last closed bar, etc).
- The EA draws swings and FVGs, and places orders according to your strategy.
Compile this EA in MetaEditor and attach to the desired chart (eg. H1).
Make sure you enable AutoTrading before testing.
If you want me to add further polish or features such as alerts, multi-symbol handling, or trailing stops, just let me know!
- Before accessing price arrays, we explicitly copy
- User
'OBJPROP_TRANSPARENCY' - undeclared identifier aaa.mq5 246 33 'ObjectSetInteger' - no one of the overloads can be applied to the function call aaa.mq5 246 7
- Assistant
The error about
OBJPROP_TRANSPARENCYandObjectSetIntegernot accepting it arises because in MQL5, the transparency of objects is set differently than in MQL4.
Explanation:
- In MQL4, you use
OBJPROP_BACKandOBJPROP_TRANSPARENCYwithObjectSetInteger(). - In MQL5, the transparency is set using color with alpha channel (RGBA), not a separate property.
How to fix transparency in MQL5 rectangle:
- Instead of setting transparency via
OBJPROP_TRANSPARENCY, you create acolorvariable with alpha and assign it toOBJPROP_COLOR.
Example for creating semi-transparent yellow color:
// Create semi-transparent yellow color with 70% opacity // Alpha range 0-255, where 0 = fully opaque and 255 = fully transparent in MQL5 // But in MQL5 alpha=0 means fully transparent, alpha=255 fully opaque (opposite from some libs) // To get ~70% transparent, use alpha = 255 * 0.7 = ~179 (meaning mostly transparent) // MQL5 uses ARGB format for color: // Use function ColorToARGB() or define a helper function to build color with alpha int alpha = (int)(255 * 0.7); // approx 70% transparency color transparentYellow = (color)((alpha << 24) | (clrYellow & 0x00FFFFFF)); // Set object color: ObjectSetInteger(0, name, OBJPROP_COLOR, transparentYellow);
So in your FVG drawing function, replace this:
ObjectSetInteger(0, name, OBJPROP_COLOR, clrYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); // behind price ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); ObjectSetInteger(0, name, OBJPROP_TRANSPARENCY, 70); // <-- INVALID in MQL5
With this:
int alpha = (int)(255 * 0.7); // 70% transparency color transparentYellow = (color)((alpha << 24) | (clrYellow & 0x00FFFFFF)); ObjectSetInteger(0, name, OBJPROP_COLOR, transparentYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true);
Full modified DrawFVGZone function snippet:
void DrawFVGZone(int gapIndex, double gapLow, double gapHigh) { string name = "FVG_" + IntegerToString(gapIndex); if(ObjectFind(0, name) < 0) { datetime time1 = TimeArray[gapIndex + 2]; datetime time2 = TimeArray[gapIndex]; if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, gapHigh, time2, gapLow)) { Print("Failed to create FVG rectangle"); return; } int alpha = (int)(255 * 0.7); // 70% transparency color transparentYellow = (color)((alpha << 24) | (clrYellow & 0x00FFFFFF)); ObjectSetInteger(0, name, OBJPROP_COLOR, transparentYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); } }
Additional Notes
- Alpha channel in MQL5 color: highest byte represents transparency.
OBJPROP_FILLcontrols whether the rectangle is filled.- You don't need to set transparency separately; it’s encoded in the color.
If you want me to update your full EA code with this fix included, just say so!
- In MQL4, you use
- User
ya
- Assistant
Certainly! Here is the updated full EA code with transparency properly set for the FVG rectangles using alpha in the color, as well as all your previous requested features (price array copying, swing and FVG visualization, BoS + FVG entries):
//+------------------------------------------------------------------+ //| BoS_FVG_EA_with_Drawings.mq5 | //| Break of Structure + Fair Value Gap + Visuals | //+------------------------------------------------------------------+ #property copyright "OpenAI" #property version "1.03" #property strict #include <Trade\Trade.mqh> input double Lots = 0.1; // Fixed lot size input int SwingLookback = 20; // bars to lookback for swing high/low input int FVGLookback = 10; // bars to look back for Fair Value Gaps input double SL_Pips = 50; // Stop loss in pips input double TP_Pips = 100; // Take profit in pips input double Gap_MinSize_Pips= 10; // Minimum FVG size in pips input int ConfirmationBars= 1; // Confirmation candle after retrace for entry input ENUM_TIMEFRAMES Timeframe= PERIOD_H1; // Chart timeframe to trade input bool ShowVisuals = true; // Show swing and FVG visuals on chart CTrade trade; // Declare price arrays double CloseArray[]; double OpenArray[]; double HighArray[]; double LowArray[]; datetime TimeArray[]; // Structure to store swing points struct SwingPoint { int index; double price; }; //+------------------------------------------------------------------+ //| Copy price arrays function | //+------------------------------------------------------------------+ bool CopyPriceArrays(int barsNeeded) { if(CopyClose(_Symbol, Timeframe, 0, barsNeeded, CloseArray) <= 0) { Print("Failed to copy Close array"); return false; } if(CopyOpen(_Symbol, Timeframe, 0, barsNeeded, OpenArray) <= 0) { Print("Failed to copy Open array"); return false; } if(CopyHigh(_Symbol, Timeframe, 0, barsNeeded, HighArray) <= 0) { Print("Failed to copy High array"); return false; } if(CopyLow(_Symbol, Timeframe, 0, barsNeeded, LowArray) <= 0) { Print("Failed to copy Low array"); return false; } if(CopyTime(_Symbol, Timeframe, 0, barsNeeded, TimeArray) <= 0) { Print("Failed to copy Time array"); return false; } return true; } //+------------------------------------------------------------------+ //| Find last swing high | //+------------------------------------------------------------------+ bool FindLastSwingHigh(int lookback, SwingPoint &swingHigh) { double highest= -1.0; int highest_index = -1; for(int i=1; i<=lookback; i++) { if(HighArray[i] > highest) { highest = HighArray[i]; highest_index = i; } } if(highest_index > 0) { swingHigh.index = highest_index; swingHigh.price = highest; return true; } return false; } //+------------------------------------------------------------------+ //| Find last swing low | //+------------------------------------------------------------------+ bool FindLastSwingLow(int lookback, SwingPoint &swingLow) { double lowest= DBL_MAX; int lowest_index = -1; for(int i=1; i<=lookback; i++) { if(LowArray[i] < lowest) { lowest = LowArray[i]; lowest_index = i; } } if(lowest_index > 0) { swingLow.index = lowest_index; swingLow.price = lowest; return true; } return false; } //+------------------------------------------------------------------+ //| Find Fair Value Gap | //+------------------------------------------------------------------+ bool FindFairValueGap(bool bullish, int lookback, double &gap_low, double &gap_high, int &gapIndex) { for(int i=1; i<lookback-2; i++) { if(bullish) { if(LowArray[i] > HighArray[i+2]) { double gapSizePips = (LowArray[i] - HighArray[i+2]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = HighArray[i+2]; gap_high= LowArray[i]; gapIndex = i; return true; } } } else // bearish { if(HighArray[i] < LowArray[i+2]) { double gapSizePips = (LowArray[i+2] - HighArray[i]) / _Point; if(gapSizePips >= Gap_MinSize_Pips) { gap_low = HighArray[i]; gap_high= LowArray[i+2]; gapIndex = i; return true; } } } } return false; } //+------------------------------------------------------------------+ //| Check for Break of Structure | //+------------------------------------------------------------------+ bool CheckBreakOfStructure(bool bullish) { SwingPoint swingPoint; if(bullish) { if(FindLastSwingHigh(SwingLookback, swingPoint)) { if(CloseArray[1] > swingPoint.price) return true; } } else { if(FindLastSwingLow(SwingLookback, swingPoint)) { if(CloseArray[1] < swingPoint.price) return true; } } return false; } //+------------------------------------------------------------------+ //| Check if price is in FVG zone | //+------------------------------------------------------------------+ bool IsPriceInFVG(double gap_low, double gap_high) { double priceNow = CloseArray[1]; if(priceNow >= gap_low && priceNow <= gap_high) return true; return false; } //+------------------------------------------------------------------+ //| Draw swing high arrow | //+------------------------------------------------------------------+ void DrawSwingHigh(int index, double price) { string name = "SwingHigh_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, TimeArray[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 233); ObjectSetInteger(0, name, OBJPROP_COLOR, clrGreen); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw swing low arrow | //+------------------------------------------------------------------+ void DrawSwingLow(int index, double price) { string name = "SwingLow_" + IntegerToString(index); if(ObjectFind(0, name) < 0) { ObjectCreate(0, name, OBJ_ARROW, 0, TimeArray[index], price); ObjectSetInteger(0, name, OBJPROP_ARROWCODE, 234); ObjectSetInteger(0, name, OBJPROP_COLOR, clrRed); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_BACK, false); } } //+------------------------------------------------------------------+ //| Draw Fair Value Gap rectangle with transparency | //+------------------------------------------------------------------+ void DrawFVGZone(int gapIndex, double gapLow, double gapHigh) { string name = "FVG_" + IntegerToString(gapIndex); if(ObjectFind(0, name) < 0) { datetime time1 = TimeArray[gapIndex + 2]; datetime time2 = TimeArray[gapIndex]; if(!ObjectCreate(0, name, OBJ_RECTANGLE, 0, time1, gapHigh, time2, gapLow)) { Print("Failed to create FVG rectangle"); return; } int alpha = (int)(255 * 0.7); // 70% transparency color transparentYellow = (color)((alpha << 24) | (clrYellow & 0x00FFFFFF)); ObjectSetInteger(0, name, OBJPROP_COLOR, transparentYellow); ObjectSetInteger(0, name, OBJPROP_BACK, true); ObjectSetInteger(0, name, OBJPROP_STYLE, STYLE_SOLID); ObjectSetInteger(0, name, OBJPROP_WIDTH, 2); ObjectSetInteger(0, name, OBJPROP_FILL, true); } } //+------------------------------------------------------------------+ //| Expert deinit | //+------------------------------------------------------------------+ void OnDeinit(const int reason) { int total = ObjectsTotal(0,0); for(int i=total-1; i>=0; i--) { string name = ObjectName(0,i); if(StringFind(name,"SwingHigh_")==0 || StringFind(name,"SwingLow_")==0 || StringFind(name,"FVG_")==0) ObjectDelete(0,name); } } //+------------------------------------------------------------------+ //| Expert tick | //+------------------------------------------------------------------+ void OnTick() { // Calculate how many bars needed for arrays int barsNeeded = SwingLookback + FVGLookback + 10; // Copy price arrays if(!CopyPriceArrays(barsNeeded)) return; // Operate only on new bar static datetime lastBarTime = 0; if(TimeArray[1] == lastBarTime) return; // no new bar yet lastBarTime = TimeArray[1]; // Draw visuals if(ShowVisuals) { SwingPoint swingHigh, swingLow; if(FindLastSwingHigh(SwingLookback, swingHigh)) DrawSwingHigh(swingHigh.index, swingHigh.price); if(FindLastSwingLow(SwingLookback, swingLow)) DrawSwingLow(swingLow.index, swingLow.price); double fvgLow, fvgHigh; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); if(FindFairValueGap(false, FVGLookback, fvgLow, fvgHigh, gapIndex)) DrawFVGZone(gapIndex, fvgLow, fvgHigh); } // Don't trade if position exists if(PositionSelect(_Symbol)) return; // Bullish setup if(CheckBreakOfStructure(true)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(true, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { if(CloseArray[ConfirmationBars] > OpenArray[ConfirmationBars]) { if(!trade.Buy(Lots, NULL, SymbolInfoDouble(_Symbol, SYMBOL_ASK), SymbolInfoDouble(_Symbol, SYMBOL_ASK) - SL_Pips*_Point, SymbolInfoDouble(_Symbol, SYMBOL_ASK) + TP_Pips*_Point, "BoS+FVG Buy")) Print("Buy order failed: ", GetLastError()); } } } } else if(CheckBreakOfStructure(false)) { double fvg_low, fvg_high; int gapIndex; if(FindFairValueGap(false, FVGLookback, fvg_low, fvg_high, gapIndex)) { if(IsPriceInFVG(fvg_low, fvg_high)) { if(CloseArray[ConfirmationBars] < OpenArray[ConfirmationBars]) { if(!trade.Sell(Lots, NULL, SymbolInfoDouble(_Symbol, SYMBOL_BID), SymbolInfoDouble(_Symbol, SYMBOL_BID) + SL_Pips*_Point, SymbolInfoDouble(_Symbol, SYMBOL_BID) - TP_Pips*_Point, "BoS+FVG Sell")) Print("Sell order failed: ", GetLastError()); } } } } } //+------------------------------------------------------------------+
Just compile and run this in MT5 — it draws swings and FVG rectangles with alpha transparency, and trades break of structure + fair value gap entries with confirmation.
Let me know if you want help adding alerts, multi-symbol support, or anything else!