Pine Script Anchored VWAP (AVWAP)

Master this powerful technical analysis tool in TradingView's Pine Script that calculates the Volume-Weighted Average Price from a specific, user-defined anchor point, revealing significant support, resistance, and market conviction.

Last Updated on: Expertise: Advanced

What is Anchored VWAP (AVWAP)?

Anchored Volume-Weighted Average Price (AVWAP) is a powerful technical indicator that calculates the Volume-Weighted Average Price (VWAP) starting from a specific, user-defined "anchor" point on the chart. Unlike the standard VWAP (which typically resets at the start of each trading session), the AVWAP accumulates volume and price data from its anchor point indefinitely, providing a continuous average of the price at which the majority of volume has been traded *since that specific event or price level*.

The core philosophy behind AVWAP is that major market movements, significant news events, earnings releases, or important swing highs/lows can serve as "anchors" for new phases of market activity. By tracking the average price paid (weighted by volume) since such an event, traders can infer whether market participants who entered around that anchor point are currently in profit or loss, and identify areas of strong support or resistance.

AVWAP is primarily used by professional and institutional traders to:

In Pine Script, implementing Anchored VWAP requires a custom calculation of cumulative price-volume and cumulative volume from a user-specified starting bar or time, making it a highly customizable tool for advanced pine script strategies.

Components and Calculation

The calculation of Anchored VWAP is based on the cumulative sum of `(Typical Price * Volume)` divided by the cumulative sum of `Volume`, starting from the designated anchor point. The formula is as follows:


`Typical Price (TP) = (High + Low + Close) / 3`
`Cumulative TP * Volume = sum(TP * volume)` from anchor bar to current bar
`Cumulative Volume = sum(volume)` from anchor bar to current bar
`AVWAP = Cumulative TP * Volume / Cumulative Volume`

Crucially, the accumulation of `TP * volume` and `volume` only begins *after* the specified anchor point and continues indefinitely until the indicator is reset or the chart changes.

Basic Anchored VWAP Implementation in Pine Script

Since Pine Script does not have a direct built-in `ta.anchoredVwap()` function that dynamically anchors to arbitrary points like a manual drawing tool, we'll implement a custom version. This version will allow you to specify the anchor either by its bar index (e.g., bar of a swing high/low) or by a specific date/time. Using a date/time input is often more practical for anchoring to specific historical events.

//@version=5
indicator("My Anchored VWAP (AVWAP)", overlay=true, max_bars_back=5000) // overlay=true to plot on price chart.
// max_bars_back is important for calculations over long periods.

// --- User Inputs for Anchor Point ---
anchorType = input.string("Time", title="Anchor Type", options=["Time", "Bar Index"])
anchorTime = input.time(timestamp("01 Jan 2024 09:15 +0530"), title="Anchor Date/Time (HH:MM IST)", tooltip="Set a specific date and time for the AVWAP to start from. Format: 'DD Mon YYYY HH:MM +HHMM'")
anchorBarOffset = input.int(200, title="Anchor Bars Back (from current bar)", minval=1, tooltip="Number of bars back from the current bar to set the anchor. Used if 'Anchor Type' is 'Bar Index'.")
resetOnSession = input.bool(false, title="Reset AVWAP on New Session?", tooltip="If true, AVWAP will reset calculation at the start of each new daily session, behaving like a traditional daily VWAP. If false, it continues from its anchor point.")

// --- Plotting Options ---
avwapColor = input.color(color.new(color.blue, 0), title="AVWAP Line Color")
avwapWidth = input.int(2, title="AVWAP Line Width", minval=1, maxval=4)

// --- Calculate Anchor Bar Index ---
var int anchorIdx = na // This will store the bar index of our anchor point

// Find the anchor bar index based on the chosen anchor type
if anchorType == "Time"
    // For 'Time' anchor, find the first bar whose `time` is greater than or equal to `anchorTime`
    // We only need to set this once when the script loads or when anchorTime changes.
    // Use `varip` to initialize once per script instance.
    varip bool anchorFound = false
    if not anchorFound
        for i = 0 to bar_index
            if time[i] >= anchorTime
                anchorIdx := bar_index[i]
                anchorFound := true
                break
else // Anchor Type == "Bar Index"
    anchorIdx := bar_index - anchorBarOffset

// Ensure anchorIdx is not NA and is within valid range
if na(anchorIdx) or anchorIdx < 0
    anchorIdx := 0 // Default to first bar if anchor not found or invalid

// --- Calculate AVWAP ---
var float cumulative_tp_volume = 0.0
var float cumulative_volume = 0.0
var float avwap_value = na

// Reset logic based on input
var bool isNewSession = false
if resetOnSession
    isNewSession := ta.change(time("D"))
    if isNewSession
        cumulative_tp_volume := 0.0
        cumulative_volume := 0.0

// Calculate typical price for the current bar
float tp = (high + low + close) / 3.0

// Accumulate data only from the anchor bar onwards
if bar_index >= anchorIdx
    cumulative_tp_volume := cumulative_tp_volume + (tp * volume)
    cumulative_volume := cumulative_volume + volume

    // Avoid division by zero
    if cumulative_volume > 0
        avwap_value := cumulative_tp_volume / cumulative_volume
    else
        avwap_value := tp // If no volume yet (e.g., very first bar after anchor), use typical price
else
    // Before the anchor point, AVWAP is not plotted or is NA
    avwap_value := na
    cumulative_tp_volume := 0.0 // Reset sums before anchor for correct restart
    cumulative_volume := 0.0


// --- Plotting AVWAP ---
plot(avwap_value, title="AVWAP", color=avwapColor, linewidth=avwapWidth)

// Optional: Highlight the anchor point visually
anchorPlotColor = color.new(color.white, 20)
plotshape(bar_index == anchorIdx ? high : na, title="Anchor Point", location=location.belowbar, color=anchorPlotColor, style=shape.triangleup, size=size.small, text="Anchor")

// --- Simple Strategy Example (Conceptual) ---
// This strategy demonstrates how you might react to AVWAP levels.
// It is highly simplified and for educational purposes only.
// Real trading strategies require more complex confirmation.

strategy("AVWAP Strategy", overlay=true, initial_capital=10000, default_qty_type=strategy.percent_of_equity, default_qty_value=10)

// Ensure AVWAP value is valid before using in strategy
if not na(avwap_value) and bar_index > anchorIdx // Only trade after the anchor is established

    // Strategy 1: Price crossing AVWAP (Mean Reversion/Trend Confirmation)
    // Long Entry: Price crosses above AVWAP
    longCondition = ta.crossover(close, avwap_value)

    // Short Entry: Price crosses below AVWAP
    shortCondition = ta.crossunder(close, avwap_value)

    if (longCondition)
        strategy.entry("Long AVWAP Cross", strategy.long)

    if (shortCondition)
        strategy.entry("Short AVWAP Cross", strategy.short)

    // Exit on opposite cross
    strategy.close("Long AVWAP Cross", when=shortCondition)
    strategy.close("Short AVWAP Cross", when=longCondition)


    // Strategy 2: Price bouncing off AVWAP (Support/Resistance)
    // This requires more sophisticated logic to detect a "bounce" vs. a "cross".
    // For simplicity, let's look for closes near AVWAP in the direction of the bounce.
    
    // Check if price closes above AVWAP after being below it and is near AVWAP
    closeAboveAVWAP = close > avwap_value and close[1] <= avwap_value[1]
    isNearAVWAP = math.abs(close - avwap_value) / close * 100 < 0.1 // Within 0.1% of AVWAP
    
    // Long Bounce: price goes below AVWAP and closes back above it, confirming support
    longBounceCondition = low < avwap_value and close > avwap_value and closeAboveAVWAP

    // Short Bounce: price goes above AVWAP and closes back below it, confirming resistance
    shortBounceCondition = high > avwap_value and close < avwap_value and not closeAboveAVWAP


    // For a more robust strategy, you might need additional filters like trend, momentum, etc.
    // Example: Only take long bounces if overall trend is up (e.g., price > 200 EMA)
    // currentTrendIsUp = close > ta.ema(close, 200)

    // if (longBounceCondition and currentTrendIsUp)
    //     strategy.entry("Long AVWAP Bounce", strategy.long)

    // if (shortBounceCondition and not currentTrendIsUp)
    //     strategy.entry("Short AVWAP Bounce", strategy.short)

    // Basic exit with fixed profit/loss or opposite signal
    // For AVWAP bounces, often target swing highs/lows or R:R.
    // profitTargetPct = input.float(2.0, title="Profit Target (%)", minval=0.1)
    // stopLossPct = input.float(1.0, title="Stop Loss (%)", minval=0.1)

    // strategy.exit("Long AVWAP Bounce Exit", from_entry="Long AVWAP Bounce", profit=close * (1 + profitTargetPct / 100), stop=close * (1 - stopLossPct / 100))
    // strategy.exit("Short AVWAP Bounce Exit", from_entry="Short AVWAP Bounce", profit=close * (1 - profitTargetPct / 100), stop=close * (1 + stopLossPct / 100))

Optimizing Anchored VWAP (AVWAP) Performance

To get the most from Anchored VWAP in Pine Script:

Smart Money Compass: AVWAP acts as a compass for institutional and "smart money" participation. If price is above their average entry (AVWAP), they're profitable; if below, they're under pressure. This provides a unique lens into market conviction.

Common Anchored VWAP (AVWAP) Pitfalls

Conclusion

Anchored VWAP (AVWAP) is an exceptionally powerful and insightful technical analysis tool available in Pine Script for TradingView. By calculating the Volume-Weighted Average Price from a precise, user-defined anchor point, it provides a unique and continuous perspective on market conviction, revealing dynamic support and resistance levels that reflect the collective average entry price of market participants since a significant event. While demanding careful selection of the anchor point and diligent confirmation from price action, volume, and other technical tools, mastering AVWAP can significantly enhance your pine script strategies. By integrating this indicator into your trading plan, you can gain a deeper understanding of market dynamics, identify high-probability trading zones, and make more informed decisions based on where the true "smart money" has transacted.