Strategy · Pine Script v5 · On the chart

FVG Strategy

by muammeryldrm42

Calculates three-bar Fair Value Gaps (FVG) and filters them using Average True Range.

View on GitHub

GitHub stars7on the repository
Pine versionv5runs as is
Lines of code105
Settings8inputs
LicenceMIT
Last update3 months ago8 Jul 2026

Add It to Your TradingView Chart

  1. 1Copy the scriptPress Copy script above, or the copy button on the code below.
  2. 2Open the Pine EditorOpen a TradingView chart and choose Pine Editor at the bottom of the screen.
  3. 3Paste over the templateCreate a new strategy, select all of the template text and paste. Press Save and give it a name.
  4. 4Add it to the chartPress Add to chart. The trades and results appear in the Strategy Tester tab; adjust the settings with the gear icon.

Source Code

105 lines of Pine Script v5 from public/code/smc__fvg.pine, published under MIT. Keep the author's credit and licence lines when you reuse it.

smc__fvg.pine
//@version=5
// =====================================================
// FVG (Fair Value Gap) Strategy - Strategy Lab
// =====================================================
// Detects gaps formed across 3 candles, enters on mitigation.
// Bullish FVG: candle[2].high < candle[0].low
// Bearish FVG: candle[2].low  > candle[0].high
// =====================================================

strategy("FVG Strategy", overlay=true, initial_capital=1000,
         default_qty_type=strategy.percent_of_equity, default_qty_value=10,
         commission_type=strategy.commission.percent, commission_value=0.05)

// ============ INPUTS ============
minGapAtr     = input.float(0.3, "Min Gap (ATR multiple)", minval=0.0, step=0.1)
useTrendFilter= input.bool(true, "Use EMA Trend Filter")
emaPeriod     = input.int(200, "EMA Period", minval=20)
atrPeriod     = input.int(14, "ATR Period")
slAtrMult     = input.float(0.5, "SL ATR Multiplier", minval=0.1, step=0.1)
tp1RR         = input.float(2.0, "TP1 Risk:Reward")
tp2RR         = input.float(3.0, "TP2 Risk:Reward")
tp3RR         = input.float(5.0, "TP3 Risk:Reward")

// ============ INDICATORS ============
emaTrend = ta.ema(close, emaPeriod)
atrVal   = ta.atr(atrPeriod)
trendUp  = close > emaTrend
trendDn  = close < emaTrend

// ============ FVG DETECTION ============
// candle[2] = 2 candles ago, candle[0] = now
bullFVG = high[2] < low[0] and (low[0] - high[2]) >= atrVal * minGapAtr
bearFVG = low[2]  > high[0] and (low[2] - high[0]) >= atrVal * minGapAtr

// Draw box
var box[] bullBoxes = array.new<box>()
var box[] bearBoxes = array.new<box>()

if bullFVG
    b = box.new(bar_index - 2, low[0], bar_index + 20, high[2],
                bgcolor=color.new(color.green, 80), border_color=color.green)
    array.push(bullBoxes, b)

if bearFVG
    b = box.new(bar_index - 2, low[2], bar_index + 20, high[0],
                bgcolor=color.new(color.red, 80), border_color=color.red)
    array.push(bearBoxes, b)

// ============ STATE TRACKING ============
var float lastBullMid    = na
var float lastBullBottom = na
var float lastBullTop    = na
var float lastBearMid    = na
var float lastBearBottom = na
var float lastBearTop    = na
var bool  bullActive     = false
var bool  bearActive     = false

if bullFVG
    lastBullBottom := high[2]
    lastBullTop    := low[0]
    lastBullMid    := (high[2] + low[0]) / 2
    bullActive     := true

if bearFVG
    lastBearBottom := high[0]
    lastBearTop    := low[2]
    lastBearMid    := (low[2] + high[0]) / 2
    bearActive     := true

// ============ ENTRY LOGIC ============
longCond  = bullActive and low <= lastBullMid and high > lastBullBottom
           and (not useTrendFilter or trendUp)
shortCond = bearActive and high >= lastBearMid and low < lastBearTop
           and (not useTrendFilter or trendDn)

// ============ RISK / TARGETS ============
if longCond and strategy.position_size == 0
    sl   = lastBullBottom - slAtrMult * atrVal
    risk = lastBullMid - sl
    tp1  = lastBullMid + risk * tp1RR
    tp2  = lastBullMid + risk * tp2RR
    tp3  = lastBullMid + risk * tp3RR
    strategy.entry("FVG Long", strategy.long, limit=lastBullMid)
    strategy.exit("Exit Long", "FVG Long", stop=sl, limit=tp2)
    bullActive := false

if shortCond and strategy.position_size == 0
    sl   = lastBearTop + slAtrMult * atrVal
    risk = sl - lastBearMid
    tp1  = lastBearMid - risk * tp1RR
    tp2  = lastBearMid - risk * tp2RR
    tp3  = lastBearMid - risk * tp3RR
    strategy.entry("FVG Short", strategy.short, limit=lastBearMid)
    strategy.exit("Exit Short", "FVG Short", stop=sl, limit=tp2)
    bearActive := false

// ============ PLOTS ============
plot(emaTrend, "EMA Trend", color=color.yellow, linewidth=2)
plotshape(longCond,  "Long Setup",  shape.triangleup,   location.belowbar, color.green, size=size.small)
plotshape(shortCond, "Short Setup", shape.triangledown, location.abovebar, color.red,   size=size.small)

// ============ ALERTS ============
alertcondition(longCond,  "FVG Long Entry",  "FVG Bullish mitigation - LONG entry")
alertcondition(shortCond, "FVG Short Entry", "FVG Bearish mitigation - SHORT entry")

Overview

When price mitigates the FVG midpoint, the strategy enters a position in the direction of the gap, provided an optional EMA trend filter is satisfied. Exits are defined by an ATR-buffered stop loss positioned outside the FVG zone and a fixed risk-to-reward limit target. FVG zones are highlighted directly on the main price chart.

Details

Published by

muammeryldrm42 on GitHub

Type

Strategy, Pine Script v5

Draws

On the price chart

Category

SMC / ICT / price action, Support & resistance, Trend

Markets

Any symbol

Timeframes

Any timeframe

Risk Notes

No repainting, lookahead or stacked entries were found in its code or README. That says nothing about how well it works: test it first.

Topics

cryptofuturessodexsosovaluestrategyvaluechain

Settings

The inputs you can change from the gear icon on the chart. Defaults are the author's.

SettingTypeDefaultVariable
Min Gap (ATR multiple)float0.3minGapAtr
Use EMA Trend FilterbooltrueuseTrendFilter
EMA Periodint200emaPeriod
ATR Periodint14atrPeriod
SL ATR Multiplierfloat0.5slAtrMult
TP1 Risk:Rewardfloat2.0tp1RR
TP2 Risk:Rewardfloat3.0tp2RR
TP3 Risk:Rewardfloat5.0tp3RR
Third-party code. ForexR did not write, test or endorse this script, and the summary above was generated automatically from its code and README. Indicators describe the past, and a strategy's backtest can look better than live trading, especially when a script repaints. Check it in the Strategy Tester and on a demo account before you rely on it.

Similar Pine Scripts

FilledValueGap A006

by ruckard
13 stars

This strategy enters trades in the opposite direction of filled value gaps, operating under the assumption that price action will resume the primary trend after filling a recent gap. It plots directly on the main price chart and supports MA-based trend filters

Strategy v5 SMC / ICT / price actionTrend
Updated 1 year ago · None stated GitHub repository of FilledValueGap A006

XXX

by MeridianAlgo
9 stars

This multi-timeframe scalping strategy plots moving averages alongside Smart Money Concepts elements on the price chart. It calculates trend signals using configurable moving average types like ALMA, Hull MA, or TEMA across alternate timeframes. It also plots

Strategy v5 TrendMoving averages Repaints
Updated 4 months ago · MIT GitHub repository of XXX

NQ 9:45-10:15 ICT Strategy

by eddiebelaval
7 stars

This ICT-based strategy trades during the 9:45 AM to 10:15 AM New York session window. It calculates a daily bias using a 20-period daily EMA and tracks previous day highs and lows to identify liquidity sweeps. The script refines order block entry levels and m

Strategy v6 SMC / ICT / price actionSessions & time Repaints
Updated 3 months ago · None stated GitHub repository of NQ 9:45-10:15 ICT Strategy
6 stars

This strategy detects key support and resistance zones based on candle wick rejections and liquidity sweeps. It filters trade setups using an exponential moving average and optional higher-timeframe trend confluence, while also permitting high-confidence count

Strategy v5 Support & resistanceSMC / ICT / price action
Updated 7 months ago · None stated GitHub repository of Wick Rejection S/R Strategy v3
5 stars

RG Structure is a pivot-constrained break-and-retest strategy that calculates dynamic trendlines, market structure changes, and regime states on the price chart. It identifies support and resistance lines through pivot points and evaluates break-and-retest sig

Strategy v6 TrendSupport & resistance
Updated 7 weeks ago · None stated GitHub repository of RG Structure Visual Edition

This trend-following strategy executes a classic Donchian channel breakout system designed to cross-validate backtest results against external framework benchmarks. It triggers a long entry when the closing price breaks above the highest high of the prior entr

Strategy v6 BreakoutTrend
Updated today · AGPL-3.0 GitHub repository of Forven S01509 - Simple Donchian 20/10 Breakout

More strategys

Trade Your Charts With a Regulated Broker

Compare brokers that connect to TradingView, with spreads, minimum deposits and leverage side by side.

Compare brokers