FVG Maxing - Fair Value Gaps, Equilibrium, and Candle Patterns
What this script does
This open-source indicator highlights 3-candle fair value gaps (FVGs) on the active chart timeframe, draws their midpoint ("equilibrium") line, tracks when each gap is mitigated, and optionally marks simple candle patterns (engulfing and doji) for confluence. It is intended as an educational tool to study how price interacts with imbalances.
3-candle bullish and bearish FVG zones drawn as forward-extending boxes.
Equilibrium line at 50% of each gap.
Different styling for mitigated vs unmitigated gaps.
Compact statistics panel showing how many gaps are currently active and filled.
Optional overlays for bullish/bearish engulfing patterns and doji candles.
1. FVG logic (3-candle gaps)
The script focuses on a strict 3-candle definition of a fair value gap:
Three consecutive candles with the same body direction.
The wick of candle 3 is separated from the wick of candle 1 (no overlap).
A bullish gap is created when price moves up fast enough to leave a gap between candle 1 and 3. A bearish gap is the mirror case to the downside.
In Pine, the core detection looks like this:
// Three candles with the same body direction
bull_seq = close > open and close > open and close > open
bear_seq = close < open and close < open and close < open
// Wick gap between candle 1 and candle 3
bull_gap = bull_seq and low > high
bear_gap = bear_seq and high < low
// Final FVG flags
is_bull_fvg = bull_gap
is_bear_fvg = bear_gap
For each detected FVG:
Bullish FVG range: from high up to low (gap below current price).
Bearish FVG range: from low down to high (gap above current price).
Each zone is stored in a custom FVGData structure so it can be updated when price later trades back inside it.
2. Equilibrium line (0.5 of the gap)
Every FVG box gets an optional equilibrium line plotted at the midpoint between its top and bottom:
eq_level = (top + bottom) / 2.0
right_index = extend_boxes ? bar_index + extend_length_bars : bar_index
bx = box.new(bar_index - 2, top, right_index, bottom)
eq_ln = line.new(bar_index - 2, eq_level, right_index, eq_level)
line.set_style(eq_ln, line.style_dashed)
line.set_color(eq_ln, eq_color)
You can use this line as a neutral “fair value” reference inside the zone, or as a simple way to think in terms of premium/discount within each gap.
3. Mitigation rules and styling
Each FVG stays active until price trades back into the gap:
Bullish FVG is considered mitigated when the low touches or moves below the top of the gap.
Bearish FVG is considered mitigated when the high touches or moves above the bottom of the gap.
When that happens, the script:
Marks the internal FVGData entry as mitigated.
Softens the box fill and border colors.
Optionally updates the label text from "BULL EQ / BEAR EQ" to "BULL FILLED / BEAR FILLED".
Can hide mitigated zones almost completely if you only want to see unfilled imbalances.
This allows you to distinguish between current areas of interest and zones that have already been traded through.
4. Candle pattern overlays (engulfing and doji)
For additional confluence, the script can mark simple candle patterns on top of the FVG view:
Bullish engulfing — current candle body fully wraps the previous bearish body and is larger in size.
Bearish engulfing — current candle body fully wraps the previous bullish body and is larger in size.
Doji — candles where the real body is small relative to the full range (high–low).
The detection is based on basic body and range geometry:
curr_body = math.abs(close - open)
prev_body = math.abs(close - open )
curr_range = high - low
body_ratio = curr_range > 0 ? curr_body / curr_range : 1.0
bull_engulfing = close > open and close < open and open <= close and close >= open and curr_body > prev_body
bear_engulfing = close < open and close > open and open >= close and close <= open and curr_body > prev_body
is_doji = curr_range > 0 and body_ratio <= doji_body_ratio
On the chart, they appear as:
Small triangle markers below bullish engulfing candles.
Small triangle markers above bearish engulfing candles.
Small circles above doji candles.
All three overlays are optional and can be turned on or off and recolored in the CANDLE PATTERNS group of inputs.
5. Inputs overview
The script organizes settings into clear groups:
DISPLAY SETTINGS : Show bullish/bearish FVGs, show/hide mitigated zones, box extension length, box border width, and maximum number of boxes.
EQUILIBRIUM : Toggle equilibrium lines, color, and line width.
LABELS : Enable labels, choose whether to label unmitigated and/or mitigated zones, and select label size.
BULLISH COLORS / BEARISH COLORS : Separate fill and border colors for bullish and bearish gaps.
MITIGATED STYLE : Opacity used when a gap is marked as mitigated.
STATISTICS : Toggle the on-chart FVG statistics panel.
CANDLE PATTERNS : Show engulfing patterns, show dojis, colors, and the body-to-range threshold that defines a doji.
6. Statistics panel
An optional table in the corner of the chart summarizes the current state of all tracked gaps:
Total number of FVGs still being tracked.
Number of bullish vs bearish FVGs.
Number of unfilled vs mitigated FVGs.
Simple fill rate: percentage of tracked FVGs that have been marked as mitigated.
This can help you study how a particular market tends to treat gaps over time.
7. How you might use it (examples)
These are usage ideas only, not recommendations:
Study how often your symbol mitigates gaps and where inside the zone price tends to react.
Use higher-timeframe context and then refine entries near the equilibrium line on your trading timeframe.
Combine FVG zones with basic candle patterns (engulfing/doji) as an extra visual anchor, if that fits your process.
Hope you enjoy, give your feedback in the comments!
- officialjackofalltrades
Indicies
RiskCraft - Advanced Risk Management SystemRiskCraft – Risk Intelligence Dashboard
Trade like you actually respect risk
"I know the setup looks good… but how much am I actually risking right now?"
RiskCraft is an open-source Pine Script v6 indicator that keeps risk transparent directly on the chart. It is not a signal generator; it is a risk desk that calculates size, frames volatility, and reminds you when your behaviour drifts away from the plan.
Core utilities
Calculates professional-style position sizing in real time.
Reads volatility and market regime before position size is confirmed.
Adjusts risk based on the trader’s emotional state and confidence inputs.
Maps session risk across Asian, London, and New York hours.
Draws exactly one stop line and one target line in the preferred direction.
Provides rotating education tips plus contextual warnings when risk escalates.
It is intentionally conservative and keeps you in the game long enough for any separate entry logic to matter.
---
Chart layout checklist
Use a clean chart on a liquid symbol (e.g., AMEX:SPY or major FX pairs).
Main RiskCraft dashboard placed on the right edge.
Session Risk box on the left with UTC time visible.
Floating risk badge above price.
Stop/target guide lines enabled.
Education panel visible in the bottom-right corner.
---
1. On-chart components
Right-side dashboard : account risk %, position size/value, stop, target, risk/reward, regime, trend strength, emotional state, behavioural score, correlation, and preferred trade direction.
Session Risk box : highlights active session (Asian, London, NY), current UTC time, and risk label (High/Med/Low) per session.
Floating risk badge : keeps actual account risk percent visible with colour-coded wording from Ultra Cautious to Very Aggressive.
Stop/target lines : exactly one dashed stop and one dashed target aligned with the preferred bias.
Education panel : rotates core principles and AI-style warnings tied to volatility, risk %, and behaviour flags.
---
2. Volatility engine – ATR with context 📈
atr = ta.atr(atrLength)
atrPercent = (atr / close) * 100
atrSMA = ta.sma(atr, atrLength)
volatilityRatio = atr / atrSMA
isHighVol = volatilityRatio > volThreshold
ATR vs ATR SMA shows how wild price is relative to recent history.
Volatility ratio above the threshold flips isHighVol , which immediately trims risk.
An ATR percentile rank over the last 100 bars indicates calm versus chaotic regimes.
Daily ATR sampling via request.security() gives higher time-frame context for intraday sessions.
When volatility spikes the script dials position size down automatically instead of cheering for maximum exposure.
---
3. Market regime radar – Danger or Drift 🌊
ema20 = ta.ema(close, 20)
ema50 = ta.ema(close, 50)
ema200 = ta.ema(close, 200)
trendScore = (close > ema20 ? 1 : -1) +
(ema20 > ema50 ? 1 : -1) +
(ema50 > ema200 ? 1 : -1)
= ta.dmi(14, 14)
Regimes covered:
Danger : high volatility with weak trend.
Volatile : volatility elevated but structure still directional.
Choppy : low ADX and noisy action.
Trending : directional flows without extreme volatility.
Mixed : anything between.
Each regime maps to a 1–10 risk score and a multiplier that feeds the final position size. Danger and Choppy clamp size; Trending restores normal risk.
---
4. Behaviour engine – trader inputs matter 🧠
You provide:
Emotional state : Confident, Neutral, FOMO, Revenge, Fearful.
Confidence : slider from 1 to 10.
Toggle for behavioural adjustment on/off.
Behind the scenes:
Each state triggers an emotional multiplier .
Confidence produces a confidence multiplier .
Combined they form behavioralFactor and a 0–100 Behavioural Score .
High-risk emotions or low conviction clamp the final risk. Calm inputs allow normal size. The dashboard prints both fields to keep accountability on-screen.
---
5. Correlation guardrail – avoid stacking identical risk 📊
Optional correlation mode compares the active symbol to a reference (default AMEX:SPY ):
corrClose = request.security(correlationSymbol, timeframe.period, close)
priceReturn = ta.change(close) / close
corrReturn = ta.change(corrClose) / corrClose
correlation = calcCorrelation()
Absolute correlation above the threshold applies a correlation multiplier (< 1) to reduce size.
Dashboard row shows the live correlation and reference ticker.
When disabled, the row simply echoes the current symbol, keeping the table readable.
---
6. Position sizing engine – heart of the script 💰
baseRiskAmount = accountSize * (baseRiskPercent / 100)
adjustedRisk = baseRiskAmount * behavioralFactor *
regimeAdjustment * volAdjustment *
correlationAdjustment
finalRiskAmount = math.min(adjustedRisk,
accountSize * (maxRiskCap / 100))
stopDistance = atr * atrStopMultiplier
takeProfit = atr * atrTargetMultiplier
positionSize = stopDistance > 0 ? finalRiskAmount / stopDistance : 0
positionValue = positionSize * close
Outputs shown on the dashboard:
Position size in units and value in currency.
Actual risk % back on account after adjustments.
Risk/Reward derived from ATR-based stop and target.
---
7. Intelligent trade direction – bias without signals 🎯
Direction score ingredients:
EMA stack alignment.
Price versus EMA20.
RSI momentum relative to 50.
MACD line vs signal.
Directional Movement (DI+/DI–).
The resulting Trade Direction row prints LONG, SHORT, or NEUTRAL. No orders are generated—this is guidance so you only risk capital when the structure supports it.
---
8. Stop/target guide lines – two lines only ✂️
if showStopLines
if preferLong
// long stop below, target above
else if preferShort
// short stop above, target below
Lines refresh each bar to keep clutter low.
When the direction score is neutral, no lines appear.
Use them as visual anchors, not auto-orders.
---
9. Session Risk map – global volatility clock 🌍
Tracks Asian, London, and New York windows via UTC.
Computes average ATR per session versus global ATR SMA.
Labels each session High/Med/Low and colours the cells accordingly.
Top row shows the active session plus current UTC time so you always know the regime you are trading.
One glance tells you whether you are trading quiet drift or the part of the day that hunts stops.
---
10. Floating risk badge – honesty above price 🪪
Text ranges from Ultra Cautious through Very Aggressive.
Colour matches the risk palette inputs (High/Med/Low).
Updates on the last bar only, keeping historical clutter off the chart.
Account risk becomes impossible to ignore while you stare at price.
---
11. Education engine & warnings 📚
Rotates evergreen principles (risk 1–2%, journal trades, respect plan).
Triggers contextual warnings when volatility and risk % conflict.
Flags when emotional state = FOMO or Revenge.
Highlights sub-standard risk/reward setups.
When multiple danger flags stack, an AI-style warning overrides the tip text so you can course-correct before capital is exposed.
---
12. Alerts – hard guard rails 🚨
Excessive Risk Alert : actual risk % crosses custom threshold.
High Volatility Alert : ATR behaviour signals danger regime.
Emotional State Warning : FOMO or Revenge selected.
Poor Risk/Reward Alert : risk/reward drops below your standard.
All alerts reinforce discipline; none suggest entries or exits.
---
13. Multi-market behaviour 🕒
Intraday (1m–1h): session box and badge react quickly; ideal for scalpers needing constant risk context.
Higher time frames (1D–1W): dashboard shifts slowly, supporting swing planning.
Asset classes confirmed in validation: crypto majors, large-cap equities, indices, major FX pairs, and liquid commodities.
Risk logic is price-based, so it adapts across markets without bespoke tuning.
15. Key inputs & recommended defaults
Account Size : 10,000 (modify to match actual account; min 100).
Base Risk % : 1.0 with a Maximum Risk Cap of 2.5%.
ATR Period : 14, Stop Multiplier 2.0, Target Multiplier 3.0.
High Vol Threshold : 1.5 for ATR ratio.
Behavioural Adjustment : enabled by default; disable for fixed risk.
Correlation Check : optional; default symbol AMEX:SPY , threshold 0.7.
Display toggles : main dashboard, risk badge, session map, education panel, and stop lines can be individually disabled to reduce clutter.
16. Usage notes & limits
Indicator mode only; no automated entries or exits.
Trade history panel intentionally disabled (requires strategy context).
Correlation analysis depends on additional data requests and may lag slightly on illiquid symbols.
Session timing uses UTC; adjust expectations if you trade localized instruments.
HTF ATR sampling uses daily data, so bar replay on lower charts may show brief data gaps while HTF loads.
What does everyone think RISK really means?
Custom Index CompositeCustom Index Composite calculates an unweighted composite index by averaging the daily returns of multiple stock tickers. Instead of using price-level weighting, it focuses solely on percentage change, allowing you to compare diverse market themes side by side on a common basis.
Why Use a Custom Index Composite?
Unlike traditional indices that often lean on market capitalization or price-level data, a custom composite based solely on returns strips out the bias inherent to high-priced stocks. This provides several benefits:
Objective Cross-Comparison:
When stocks or market themes trade at very different price levels, it can be difficult to assess performance objectively. Using percentage returns, the composite creates an even playing field, enabling a clear comparison between different assets or themes.
Tailored Benchmarking:
By selecting and combining specific tickers, you can create benchmarks that better represent the segments or strategies you’re interested in. This is particularly useful when standard indices do not capture the nuances of your investment approach.
Performance Normalization:
Converting raw price data into daily percentage returns minimizes distortions that arise from price differences. This normalization helps in understanding true performance trends across the chosen tickers, making the composite index a more reliable gauge of relative market movement.
Custom Analysis Framework:
The indicator offers flexibility to adjust the lookback period (defaulting to about 3 months) so you can fine-tune the sensitivity of the index to recent market behavior. This enables you to either smooth out volatility or capture a more immediate trend, depending on your analytical needs.
Key Features:
Configurable Appearance:
You can easily configure the line color, line width, index name, and index name color via the options panel.
Ticker Configuration:
By default, you can enter up to 15 different tickers into the composite index. Technically, the indicator supports up to 40 tickers (these additional inputs are commented out by default to maintain performance), and you may enable them individually if required.
Calculated Bars Length:
The indicator uses a “Calculated bars length” setting, which is set by default to 63 days (approximately 3 months). This value can be adjusted, and it is recommended to use the greatest common denominator for consistent analysis.
How To Configure Your Chart:
Add the Indicator:
Place the Custom Index Composite on your chart.
Disable Main Symbol Visibility:
Hide the primary symbol’s plot and set its scale to “None” to prevent interference with the composite display.
Pin to Right Scale:
Set the scale of the first composite indicator to “Pinned to right scale.” This helps maintain consistency across different composite indicators.
Add Multiple Composites:
You can add additional composite indicators and set their scales to “Pinned to right scale” (or alternatively to “A”) for convenient comparison.
Limitations:
If a ticker symbol is set once in the options, it cannot be cleared to an empty value later. As a result, the symbol will continue to appear in the indicator’s title on the chart. The only way to remove an unwanted symbol is to completely reset the settings and re-enter your desired tickers.
Confluence CandlesThis indicator looks for confluence among three indicators (RSI, Stochastic, and MACD), a strategy popularized by Markus Heitkoetter in his book, “The PowerX Strategy: How to Trade Stocks and Options in Only 15 Minutes a Day”, and expands it to look for agreement on up to four symbols.
Each indicator is configurable in the settings, as well as the ability to choose which of the indicators are used.
Default Logic
Green Candles
RSI > 50
Stochastic > 50
MACD Histogram > 0
Red Candles
RSI < 50
Stochastic < 50
MACD Histogram < 0
When multiple symbols are selected, the above needs to be true for all selected symbols.
Example Use Cases
- Setting the indicator to the Nasdaq 100 (QQQ or NQ1!) while trading a stock that is part of that index such as AAPL or TSLA
- Setting the indicator to multiple indexes that tend to move together in order to trade one of them since they tend to make stronger moves when moving together (ex. SPY & QQQ, or ES1! & NQ1!)
- Setting the indicator to Bitcoin while trading a smaller crypto pair that moves as a sympathy play.
Tip
If you have trouble finding the full name for a specific instrument from an exchange such as BTCUSD from Coinbase, you can bring up TradingView’s “Symbol Search” pop-up modal, enter your search term, use the down arrow key on your keyboard to move the focus to the symbol you want, and you will see the full name in the search field such as “COINBASE:BTCUSD”.



