Files

58 lines
2.2 KiB
Plaintext

// Licensed under the Apache License, Version 2.0
// © mihakralj
//@version=6
indicator("Volume Weighted Average Price (VWAP)", "VWAP", overlay=true)
//@function Calculates session-based VWAP (Volume Weighted Average Price)
//@param src Source price series (typically hlc3)
//@param vol Volume series
//@param reset_condition Condition to reset VWAP calculation
//@returns VWAP value representing cumulative volume-weighted average price from session start
//@optimized for performance and dirty data
vwap(series float src, series float vol, series bool reset_condition) =>
var float sum_pv = 0.0, var float sum_vol = 0.0
float current_price = nz(src), float current_vol = nz(vol, 0.0)
if reset_condition
sum_pv := current_vol > 0.0 ? current_price * current_vol : 0.0
sum_vol := current_vol > 0.0 ? current_vol : 0.0
else
if current_vol > 0.0
sum_pv += current_price * current_vol
sum_vol += current_vol
sum_vol > 0.0 ? sum_pv / sum_vol : src
// ---------- Main loop ----------
// Inputs
i_source = input.source(hlc3, "Source")
i_session_type = input.string("1D", "Session Reset", options=["1m", "2m", "3m", "5m", "10m", "15m", "30m", "45m", "1H", "2H", "3H", "4H", "1D", "1W", "1M", "3M", "6M", "12M", "Never"])
// Calculate reset condition
reset_condition = switch i_session_type
"1m" => ta.change(time("1")) != 0
"2m" => ta.change(time("2")) != 0
"3m" => ta.change(time("3")) != 0
"5m" => ta.change(time("5")) != 0
"10m" => ta.change(time("10")) != 0
"15m" => ta.change(time("15")) != 0
"30m" => ta.change(time("30")) != 0
"45m" => ta.change(time("45")) != 0
"1H" => ta.change(time("60")) != 0
"2H" => ta.change(time("120")) != 0
"3H" => ta.change(time("180")) != 0
"4H" => ta.change(time("240")) != 0
"1D" => ta.change(time("1D")) != 0
"1W" => ta.change(time("1W")) != 0
"1M" => ta.change(time("1M")) != 0
"3M" => ta.change(time("3M")) != 0
"6M" => ta.change(time("6M")) != 0
"12M" => ta.change(time("12M")) != 0
"Never" => bar_index == 0
=> false
// Calculation
vwap_value = vwap(i_source, volume, reset_condition)
// Plot
plot(vwap_value, "VWAP", color=color.yellow, linewidth=2)