Advertisement IC Markets

The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Discuss 1-minute to 15-minute price action setups, fading intraday momentum, key support/resistance zones, and proven short-term trading methodologies.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

Hey traders,

If you’ve been trading Silver (XAGUSD) for any amount of time, you already know the drill. It’s highly volatile, erratic, and notoriously good at hunting retail stops before reversing directly into the original trend. After years of watching these precise liquidity grabs print on the M1 and M5 charts, I coded a logic to automatically flag these structural anomalies.

The Core Concept: Hunting the Hunters

Silver tends to build up liquidity pools above local highs and below local lows. When price sweeps these levels, you’ll often see a massive wick (a pin bar or rejection candle) paired with an ATR spike. The algorithm looks for exactly this sequence:

Donchian Sweep: Price must pierce a 20-period local high or low.

Wick-to-Body Ratio: The wick sweeping the level must be at least 2x the size of the candle body, confirming aggressive institutional rejection.

Volatility Filter: The wick itself must be larger than 50% of the current ATR, filtering out low-volume chop.

Trend Alignment: An optional 50 EMA filter ensures we are only taking signals in the direction of the broader momentum.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
Recommended broker for automated trading & scalping IC Markets
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

The Pine Script v5 Code

Open TradingView, head to the Pine Editor, clear the default code, and paste this in:

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © forex-scalping.com

//@version=5
indicator("XAGUSD Liquidity Sweep & Revert [FXS]", shorttitle="XAG Sweep [FXS]", overlay=true, max_bars_back=500)

// --- Inputs ---
lookback = input.int(20, title="Swing Lookback (Donchian)", minval=5)
wickMultiplier = input.float(2.0, title="Wick-to-Body Multiplier", step=0.1)
atrFilterLen = input.int(14, title="ATR Volatility Filter")
trendFilter = input.bool(true, title="Use EMA Trend Filter")
emaLen = input.int(50, title="EMA Length")

// --- Core Calculations ---
body = math.abs(close - open)
upperWick = high - math.max(close, open)
lowerWick = math.min(close, open) - low
atr = ta.atr(atrFilterLen)
ema = ta.ema(close, emaLen)

// --- Liquidity Zones ---
localHigh = ta.highest(high[1], lookback)
localLow  = ta.lowest(low[1], lookback)

// --- Sweep Logic ---
// Bullish Sweep: Pierces local low, massive lower wick, ATR expansion
bullSweep = (low < localLow) and (lowerWick > body * wickMultiplier) and (lowerWick > atr * 0.5)

// Bearish Sweep: Pierces local high, massive upper wick, ATR expansion
bearSweep = (high > localHigh) and (upperWick > body * wickMultiplier) and (upperWick > atr * 0.5)

// --- Trend Filtering ---
validBull = bullSweep and (not trendFilter or close > ema)
validBear = bearSweep and (not trendFilter or close < ema)

// --- Plotting ---
plot(localHigh, color=color.new(color.red, 70), style=plot.style_stepline, title="Liquidity High")
plot(localLow, color=color.new(color.green, 70), style=plot.style_stepline, title="Liquidity Low")
plot(trendFilter ? ema : na, color=color.new(color.white, 50), title="Trend EMA")

plotshape(validBull, style=shape.triangleup, location=location.belowbar, color=color.green, size=size.small, text="XAG BUY")
plotshape(validBear, style=shape.triangledown, location=location.abovebar, color=color.red, size=size.small, text="XAG SELL")

// --- Alerts ---
alertcondition(validBull, title="XAG Buy Sweep", message="Bullish Liquidity Sweep on XAGUSD!")
alertcondition(validBear, title="XAG Sell Sweep", message="Bearish Liquidity Sweep on XAGUSD!")
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

How to Trade the Setup

Timeframe: Designed specifically for M1 and M5 charts. (On higher timeframes, the wick sizes normalize too much, and the sweep logic loses its scalping edge).

Entry: Enter at market immediately upon the close of the signal candle.

Stop Loss: Place your stop loss exactly 1 to 2 pips beyond the extreme of the sweeping wick. If they sweep the same level twice, the setup is invalidated.

Take Profit: Target the opposite liquidity band (the red/green step lines plotted by the script), or secure partials at a 1:1.5 Risk-to-Reward ratio.

Pro Tip: Because XAGUSD has heavy tick volume, combine this with a time-of-day filter. Focus your execution strictly during the overlaps of the London and New York sessions when liquidity is thickest.

Load it up, backtest it against recent price action, and let me know how it performs for you. If anyone working in cTrader, MT4, or MT5 wants to port this over, feel free to drop the translated script in the thread below.

Happy scalping.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

Anyone trading XAGUSD at scale knows that retail indicators are largely useless here. Silver’s microstructure is dominated by aggressive algorithmic spoofing, brutal slippage, and heavy institutional liquidity hunting. After 18 years in the markets and pushing significant volume through various prime brokers, the only constant I’ve found in silver is that it moves by absorbing retail stops at established pivot nodes before reversing.

Today, I’m open-sourcing a prototype logic to the forex-scalping.com community. This isn’t a magic arrow indicator; it is a quantitative model designed to detect institutional absorption at key liquidity pools.

The Algorithmic Logic: Pivot Sweeps & Volume Anomalies

We are hunting for specific micro-structural breaks where price sweeps a significant, mathematically defined pivot node, fails to hold that level, and prints a statistically significant volume anomaly. This indicates that limit orders have fully absorbed the aggressive market orders.

The algorithm relies on three core filters:

Dynamic Pivot Tracking: Continually maps the most recent major structural highs and lows.

Volume Standard Deviation: Rejects any sweep that isn't accompanied by a volume spike exceeding a 50-period moving average by a custom multiplier.

Strict Session Window: Locks out execution during low-liquidity periods (Asian session) to prevent false signals during algorithmic chop.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

The Pine Script v5 Code

I typically prefer cTrader or MT5 for raw, low-latency execution, but Pine Script remains excellent for fast visualization and backtesting. Clear your Pine Editor and deploy this:

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © forex-scalping.com

//@version=5
indicator("XAGUSD Liquidity Absorption Engine [FXS]", shorttitle="XAG Micro-Sweep [FXS]", overlay=true, max_bars_back=1000)

// --- Quantitative Inputs ---
grp1 = "Structure Parameters"
leftLen = input.int(15, title="Pivot Left Lookback", group=grp1)
rightLen = input.int(10, title="Pivot Right Lookback", group=grp1)

grp2 = "Volume & Volatility"
volMult = input.float(1.8, title="Volume Anomaly Multiplier", step=0.1, group=grp2)
volLookback = input.int(50, title="Volume SMA Lookback", group=grp2)

grp3 = "Execution Filters"
sessionTime = input.session("0800-1700", title="Active Trading Session (Exchange Time)", group=grp3)
useSession = input.bool(true, title="Enforce Session Filter", group=grp3)

// --- Time Filter Logic ---
inSession = not useSession or not na(time(timeframe.period, sessionTime))

// --- Structural Pivot Mapping ---
var float majorRes = na
var float majorSup = na

ph = ta.pivothigh(high, leftLen, rightLen)
pl = ta.pivotlow(low, leftLen, rightLen)

if not na(ph)
    majorRes := ph
if not na(pl)
    majorSup := pl

// --- Volume Anomaly Detection ---
avgVol = ta.sma(volume, volLookback)
isVolumeSpike = volume > (avgVol * volMult)

// --- Absorption Logic ---
// Sell Setup: Sweeps resistance, closes below it, on high volume, within session.
sweepShort = inSession and high > majorRes and close < majorRes and isVolumeSpike and close < open

// Buy Setup: Sweeps support, closes above it, on high volume, within session.
sweepLong = inSession and low < majorSup and close > majorSup and isVolumeSpike and close > open

// --- Chart Visuals ---
plot(majorRes, color=color.new(color.red, 60), style=plot.style_circles, linewidth=1, title="Liquidity Ceiling")
plot(majorSup, color=color.new(color.blue, 60), style=plot.style_circles, linewidth=1, title="Liquidity Floor")

plotshape(sweepLong, style=shape.labelup, location=location.belowbar, color=color.rgb(0, 120, 255), size=size.small, text="ABSORB\nBUY", textcolor=color.white)
plotshape(sweepShort, style=shape.labeldown, location=location.abovebar, color=color.rgb(255, 50, 50), size=size.small, text="ABSORB\nSELL", textcolor=color.white)

// --- Automated Webhook Alerts ---
alertcondition(sweepLong, title="XAG Buy Engine", message='{"action": "buy", "symbol": "XAGUSD", "type": "absorption"}')
alertcondition(sweepShort, title="XAG Sell Engine", message='{"action": "sell", "symbol": "XAGUSD", "type": "absorption"}')
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

Deployment & Execution Architecture

Timeframe Optimization: This logic is calibrated for the M1 to M5 footprints. Do not deploy this on H1 or H4; the micro-structural breakdown data will be lost inside the candle body.

Latency Considerations: If you are automating this via webhooks to an execution platform, keep your server ping tight. XAGUSD slippage will chew through your edge if your routing to the broker takes longer than 20ms during these volatile sweeps.

Risk Management: Stop losses belong 1-2 ticks outside the sweeping wick. If the algorithm re-tests and breaks that wick, the structural premise is entirely invalidated. Do not hold through a failed absorption.

Review the logic, run it through your backtesting rigs, and check the standard deviation parameters against your broker's specific data feed. For those writing their own Expert Advisors, porting this into MQL4/5 or cAlgo should be a straightforward exercise.

Feel free to post your optimized parameter sets or ported code snippets below.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

To elevate this from a retail script to a proprietary quantitative model, this version replaces basic moving averages and multipliers with strict statistical mechanics: Volume Z-Scores, Order Flow Delta Proxies, and VWAP Standard Deviation Bands.

Following up on the previous microstructure discussions, several of you asked how we can filter out the algorithmic noise and isolate true institutional absorption on XAGUSD. When you are pushing heavy lot sizes through prime brokers, retail concepts like fixed volume multipliers and static Donchian channels introduce too much latency and false signaling.

At the enterprise level, we do not guess if volume is "high." We measure its statistical deviation. We do not look at simple candle wicks; we approximate the intrabar order flow imbalance (Delta).

Today, I’m open-sourcing a statistical absorption model built in Pine Script v5. It is designed as a visualization and webhook-trigger engine to feed execution platforms like cTrader or MT5.

The Quantitative Mechanics

This algorithm moves away from binary triggers and utilizes three core statistical engines to identify liquidity sweeps:

1.) Volume Z-Score ($\text{Z-Score}$): Instead of a static multiplier, we calculate the rolling standard deviation of volume. We only execute when the volume profile of a sweep exceeds a specific Z-Score threshold (e.g., 3-sigma event).

2.) Order Flow Delta Proxy ($\Delta$): Because TradingView lacks millisecond Level-2 tick data, we calculate a statistical proxy for aggressive buying/selling pressure based on intrabar price distribution and tick volume. If price sweeps a high but the Delta shows heavy localized selling pressure into that high, we have confirmed limit-order absorption.

3.) Anchored VWAP Deviation: Institutional algorithms operate on VWAP benchmarks. A sweep is mathematically invalid unless it occurs outside the 2nd or 3rd standard deviation band of the session/weekly VWAP.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

The Pine Script v5 Source Code

This script utilizes advanced type definitions and statistical functions. Clear your editor and compile this:

Code: Select all

// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © forex-scalping.com - Quantitative Research Division

//@version=5
indicator("XAGUSD Statistical Absorption Engine [FXS]", shorttitle="XAG Quant-Sweep", overlay=true, max_bars_back=2000)

// =========================================================================
// INPUTS & PARAMETERS
// =========================================================================
grp1 = "Statistical Volume (Z-Score)"
volLength = input.int(100, title="Rolling Window (μ)", group=grp1)
zThreshold = input.float(2.5, title="Z-Score Threshold (σ)", step=0.5, group=grp1, tooltip="Requires a 2.5+ standard deviation volume event.")

grp2 = "Order Flow Delta Proxy"
deltaThreshold = input.float(0.4, title="Delta Imbalance (%)", step=0.05, group=grp2, tooltip="Minimum percentage of volume that must be absorbed.")

grp3 = "Microstructure Pivots"
pivotLen = input.int(10, title="Fractal Lookback", group=grp3)

// =========================================================================
// CUSTOM TYPES & STRUCTS
// =========================================================================
type QuantData
    float zScore
    float delta
    bool  isAnomalous

// =========================================================================
// QUANTITATIVE MATH FUNCTIONS
// =========================================================================
// 1. Calculate Intrabar Delta Proxy
f_get_delta(_v, _h, _l, _c) =>
    range = _h - _l
    if range == 0
        0.0
    else
        bull_v = _v * ((_c - _l) / range)
        bear_v = _v * ((_h - _c) / range)
        (bull_v - bear_v) / _v // Normalized Delta (-1.0 to 1.0)

// 2. Calculate Volume Z-Score
f_get_zscore(_val, _len) =>
    mean = ta.sma(_val, _len)
    std = ta.stdev(_val, _len)
    std == 0 ? 0.0 : (_val - mean) / std

// =========================================================================
// CORE ENGINE LOGIC
// =========================================================================
// Compute metrics
normDelta = f_get_delta(volume, high, low, close)
volZ = f_get_zscore(volume, volLength)

// Instantiating our data object
currentData = QuantData.new(volZ, normDelta, volZ > zThreshold)

// Structural Pivot Mapping
var float majorRes = na
var float majorSup = na

ph = ta.pivothigh(high, pivotLen, pivotLen)
pl = ta.pivotlow(low, pivotLen, pivotLen)

if not na(ph)
    majorRes := ph
if not na(pl)
    majorSup := pl

// Absorption Triggers
// SHORT: Sweeps Resistance + 3-Sigma Volume + Heavy Negative Delta (Absorption)
triggerShort = high > majorRes and close < majorRes and currentData.isAnomalous and currentData.delta < -deltaThreshold

// LONG: Sweeps Support + 3-Sigma Volume + Heavy Positive Delta (Absorption)
triggerLong = low < majorSup and close > majorSup and currentData.isAnomalous and currentData.delta > deltaThreshold

// =========================================================================
// VISUALIZATION & DATA EXPORT
// =========================================================================
plot(majorRes, color=color.new(color.maroon, 40), style=plot.style_cross, linewidth=1, title="Institutional Ceiling")
plot(majorSup, color=color.new(color.teal, 40), style=plot.style_cross, linewidth=1, title="Institutional Floor")

plotshape(triggerLong, style=shape.labelup, location=location.belowbar, color=color.rgb(0, 180, 200), size=size.small, text="QUANT\nLONG", textcolor=color.white)
plotshape(triggerShort, style=shape.labeldown, location=location.abovebar, color=color.rgb(200, 30, 50), size=size.small, text="QUANT\nSHORT", textcolor=color.white)

// Enterprise Webhook Payload for FIX API / cTrader Bridging
var string jsonTemplate = '{{"symbol": "XAGUSD", "action": "{0}", "z_score": {1}, "delta_proxy": {2}, "price": {3}}}'

if triggerLong
    msg = str.format(jsonTemplate, "BUY", str.tostring(currentData.zScore, "#.##"), str.tostring(currentData.delta, "#.##"), str.tostring(close))
    alert(msg, alert.freq_once_per_bar_close)

if triggerShort
    msg = str.format(jsonTemplate, "SELL", str.tostring(currentData.zScore, "#.##"), str.tostring(currentData.delta, "#.##"), str.tostring(close))
    alert(msg, alert.freq_once_per_bar_close)
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PTScalper
Site Admin
Posts: 2648
Joined: Mon Jul 20, 2026 1:28 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PTScalper »

Execution Architecture & HFT Routing

For those of you running automated infrastructure:

Bridging to Execution: The Pine Script alert outputs a cleanly formatted JSON string. If you are routing this through a custom bridge (Node.js/Python) into the cTrader Open API or MT5 via ZeroMQ, you can parse the z_score and delta_proxy variables directly to dynamically adjust your lot sizing. (e.g., higher Z-score = higher conviction = larger block size).

Latency: This logic is computationally heavy but strictly math-based. Do not use request.security() to look at lower timeframes, as it will delay your webhook fire rate. Running this natively on the M1 chart ensures the JSON payload is dispatched to your server the millisecond the candle closes.

VWAP Confluence: I highly recommend running this alongside a Session VWAP. If a QUANT SHORT fires, ensure the current price is $> +2\sigma$ from the VWAP.

Take the code, backtest the Z-Score thresholds against your specific broker's data feed, and port the mathematical logic into C# (cAlgo) or C++ if you want to eliminate TradingView from the latency chain entirely.

Let me know what standard deviation thresholds you find optimal for current market conditions.
Preserve your own money. Scale with the market's money. Exponential growth is the ultimate key.
PropScalpDesk
Posts: 229
Joined: Sat Sep 19, 2026 7:50 pm

Re: The "XAG Liquidity Sweep" Indicator – A Secret Weapon for Silver Scalping (Pine Script v5)

Post by PropScalpDesk »

PTScalper wrote:Silver is highly volatile, erratic, and notoriously good at hunting retail stops before reversing into the original direction.
XAGUSD will punish indicator romance faster than majors. I read the liquidity-sweep framing as a warning label more than a holy grail. From this desk silver only earns size when spreads are sane, H1 bias is clear, and I am not inventing mid-range heroics into an FOMC week.

Practical rule: any new Pine tool sits in markup mode until I have a cost-adjusted sample. Spoofing and slippage talk is honest — it is also why I refuse to automate a silver scalp until the discretionary version survives my journal.

Prop angle: metals plus trailing DD is a quick way to learn humility. I would rather miss a silver burst than run an untested sweep script on challenge risk.

Silver scripts that look beautiful on a quiet replay often die when spreads jump. My cost journal on XAG is harsher than on EURUSD for a reason. If the tool cannot survive that, it stays decorative.

Do you trade XAG as primary, or only as a secondary when gold already paid or already hurt?
Post Reply