本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
//@version=6
indicator("VWAP y bandas medidas", shorttitle = "VWAP medido", overlay = true)
// Session VWAP of the regular session with bands at 1, 2 and 3 standard deviations, computed from the bars of THIS
// chart, and how often our measured sessions reached each band by 10:30, 12:00, 14:00 and the close, against the same
// distance measured from the session's open.
//
// The line: each bar adds its typical price (high + low + close) / 3 weighted by its volume, from the first bar of the
// regular session: VWAP = sum(price x volume) / sum(volume). Bands: VWAP +/- k standard deviations of those prices
// around the VWAP, weighted by volume. It is computed from the chart's bars, so it approximates a VWAP built trade by
// trade; on a 1-minute chart it follows the same arithmetic as our table.
//
// The table (from 2022, the market's regular session 09:30-16:00 New York): share of sessions in which a bar reached
// VWAP +/- k standard deviations (either side: the statistic is about distance, never a side) before each time, with
// its n and 95% interval, next to the share that reached the same distance measured from the open. When the paired
// interval of the difference holds zero, the band was reached as often as any point that far from the open: "igual al
// azar". Each bar is compared with the band known at the end of the bar before it; the first 30 minutes only build the
// bands and are not counted. The table says how often a distance was reached; it does not say that price returns to
// the VWAP or stops at a band, and it is not a signal.
// --- BEGIN GENERATED CONSTANTS
// Written by scripts/build_tradingview_constants.py. Do not edit by hand.
// 8 markets, sessions through 2026-10-16. Rates, intervals, counts and session hours only.
string DATA_THROUGH = "2026-10-16"
f_parent(string r) =>
switch r
"MES" => "ES"
"MNQ" => "NQ"
"M2K" => "RTY"
"MYM" => "YM"
"MGC" => "GC"
"SIL" => "SI"
"MHG" => "HG"
"MCL" => "CL"
"QM" => "CL"
"MNG" => "NG"
"QG" => "NG"
"MBT" => "BTC"
"MET" => "ETH"
"M6E" => "6E"
"M6A" => "6A"
"M6B" => "6B"
"E7" => "6E"
"J7" => "6J"
"XC" => "ZC"
"XK" => "ZS"
"XW" => "ZW"
"10Y" => "ZN"
"MTN" => "ZN"
"MWN" => "ZB"
=> r
f_lvSess(string r) =>
switch r
"NKD" => "0900-1515"
=> "0930-1600"
f_lvTz(string r) =>
switch r
"NKD" => "Asia/Tokyo"
=> "America/New_York"
f_ownSess(string r) =>
switch r
"6A" => "0820-1500"
"6B" => "0820-1500"
"6C" => "0820-1500"
"6E" => "0820-1500"
"6J" => "0820-1500"
"6M" => "0820-1500"
"6N" => "0820-1500"
"6S" => "0820-1500"
"CL" => "0900-1430"
"GC" => "0820-1330"
"HG" => "0810-1300"
"NG" => "0900-1430"
"NKD" => "0900-1515"
"PA" => "0830-1300"
"PL" => "0820-1305"
"SI" => "0820-1330"
"ZB" => "0820-1500"
"ZC" => "0930-1420"
"ZF" => "0820-1500"
"ZN" => "0820-1500"
"ZS" => "0930-1420"
"ZT" => "0820-1500"
"ZW" => "0930-1420"
=> "0930-1600"
f_ownTz(string r) =>
switch r
"NKD" => "Asia/Tokyo"
=> "America/New_York"
f_vw(string r) =>
switch r
"6E" => "VW1|6E|2026-10-16|N|2022-01-03|2026-10-16|1215|1215,99.8,99.4,100,99.8,-0.3,0.3,1;1215,100,99.7,100,100,0,0,1;1215,100,99.7,100,100,0,0,1;1215,100,99.7,100,100,0,0,1;1215,1000,1215,1000|1215,87.2,85.2,88.9,96,-10.6,-7,0;1215,97.5,96.4,98.3,99.4,-2.8,-0.9,0;1215,98.6,97.7,99.2,99.8,-2,-0.5,0;1215,98.9,98.2,99.4,99.9,-1.6,-0.4,0;1202,1002,1214,1000|1215,49.1,46.2,51.9,78.3,-32.2,-26.2,0;1215,64.4,61.5,67.2,90.4,-29,-23,0;1215,69.9,67.1,72.5,93.3,-26.1,-20.6,0;1215,72.3,69.7,74.9,93.9,-24.2,-18.9,0;879,1009,1141,1002"
"CL" => "VW1|CL|2026-10-16|N|2022-01-03|2026-10-16|1197|1197,99.7,99.3,99.9,99.7,-0.4,0.4,1;1197,100,99.7,100,100,0,0,1;1197,100,99.7,100,100,0,0,1;1197,100,99.7,100,100,0,0,1;1197,1000,1197,1000|1197,81.8,79.4,84,94.2,-15,-9.8,0;1197,97.7,96.6,98.4,99.6,-2.9,-1,0;1197,98.7,97.9,99.3,99.8,-1.8,-0.4,0;1197,99,98.3,99.4,99.8,-1.4,-0.2,0;1185,1004,1195,1000|1197,36.4,33.7,39.3,72.3,-39,-32.8,0;1197,62.8,59.9,65.6,88.6,-28.9,-22.8,0;1197,68.6,65.7,71.3,92.6,-26.9,-21.2,0;1197,70.2,67.3,72.9,93.9,-26.6,-20.8,0;840,1027,1124,1003"
"ES" => "VW1|ES|2026-10-16|N|2022-01-03|2026-10-16|1193|1193,99.8,99.4,100,100,-0.4,0.1,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,1000,1193,1000|1193,87.3,85.2,89,95.3,-10.2,-5.9,0;1193,96.7,95.5,97.6,99.3,-3.7,-1.5,0;1193,98.7,97.9,99.2,99.7,-1.6,-0.2,0;1193,99.6,99,99.8,100,-0.8,-0.1,0;1188,1002,1193,1000|1193,40,37.1,43,73.5,-36.8,-30.2,0;1193,54.9,51.8,57.9,85.2,-33.5,-27,0;1193,60.1,57.1,63.1,89.5,-32.5,-26.3,0;1193,64.7,61.8,67.5,92.5,-30.6,-24.9,0;772,1014,1103,1001"
"GC" => "VW1|GC|2026-10-16|N|2022-01-03|2026-10-16|1196|1196,99.5,98.9,99.8,99.7,-0.7,0.2,1;1196,99.9,99.5,100,100,-0.2,0.1,1;1196,100,99.7,100,100,0,0,1;1196,100,99.7,100,100,0,0,1;1196,1000,1196,1000|1196,80.4,77.9,82.6,93.4,-15.5,-10.6,0;1196,94.6,93.2,95.8,98.7,-5.4,-2.8,0;1196,97.2,96.2,98,99.4,-3.1,-1.2,0;1196,98.1,97.1,98.7,99.6,-2.4,-0.7,0;1173,1003,1191,1000|1196,36.5,33.7,39.3,69.9,-36.6,-30.3,0;1196,54.2,51.3,57.1,84.5,-33.4,-27.3,0;1196,58.6,55.7,61.4,88.1,-32.5,-26.6,0;1196,62.5,59.6,65.3,90.1,-30.6,-24.8,0;747,1019,1078,1003"
"NQ" => "VW1|NQ|2026-10-16|N|2022-01-03|2026-10-16|1193|1193,99.8,99.4,100,99.8,-0.3,0.3,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,1000,1193,1000|1193,82.2,80,84.3,93.2,-13.3,-8.7,0;1193,93.9,92.4,95.1,98.6,-6.1,-3.3,0;1193,96.1,94.8,97,99.3,-4.4,-2.1,0;1193,97.4,96.3,98.2,99.5,-3.1,-1.1,0;1162,1003,1187,1000|1193,30.6,28,33.3,70.4,-43.3,-36.4,0;1193,42.8,40,45.8,83.2,-43.7,-37,0;1193,47.4,44.4,50.3,87.6,-43.4,-37.1,0;1193,52.6,49.5,55.6,90.5,-41,-34.9,0;627,1018,1080,1001"
"RTY" => "VW1|RTY|2026-10-16|N|2022-01-03|2026-10-16|1193|1193,99.3,98.7,99.7,99.8,-1,0,0;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,1000,1193,1000|1193,78.5,75.8,80.9,92.6,-16.8,-11.5,0;1193,90.7,88.7,92.4,98.2,-9.3,-5.6,0;1193,94.7,93.2,95.9,98.8,-5.6,-2.7,0;1193,96.3,95.1,97.3,99.2,-4.1,-1.6,0;1149,1003,1183,1000|1193,26.4,23.9,29.1,66.2,-43.3,-36.4,0;1193,35.9,33.1,38.8,78.6,-46.1,-39.4,0;1193,40,37.2,42.9,82.6,-45.8,-39.5,0;1193,44.3,41.5,47.2,86.3,-44.9,-38.9,0;529,1019,1029,1002"
"YM" => "VW1|YM|2026-10-16|N|2022-01-03|2026-10-16|1193|1193,99.3,98.7,99.7,100,-1.1,-0.2,0;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,100,99.7,100,100,0,0,1;1193,1000,1193,1000|1193,79,76.4,81.3,91.8,-15.3,-10.3,0;1193,92.8,91.2,94.1,98.2,-6.9,-3.8,0;1193,96.3,95,97.3,99,-3.9,-1.5,0;1193,98.2,97.2,98.8,99.3,-2,-0.3,0;1171,1004,1185,1000|1193,28.6,26,31.3,65,-39.6,-33.3,0;1193,44.5,41.5,47.5,79.7,-38.4,-32,0;1193,50.6,47.6,53.7,85.5,-38,-31.7,0;1193,56.2,53.3,59.1,88.8,-35.5,-29.5,0;671,1028,1059,1004"
"ZN" => "VW1|ZN|2026-10-16|N|2022-01-03|2026-10-16|1196|1196,99.8,99.4,100,100,-0.4,0.1,1;1196,100,99.7,100,100,0,0,1;1196,100,99.7,100,100,0,0,1;1196,100,99.7,100,100,0,0,1;1196,1000,1196,1000|1196,84.2,82,86.2,95.5,-13.5,-9.1,0;1196,96.5,95.3,97.4,99.8,-4.4,-2.3,0;1196,98.2,97.2,98.8,99.8,-2.4,-0.9,0;1196,98.7,97.9,99.2,99.9,-1.8,-0.5,0;1181,1002,1195,1000|1196,45.7,42.7,48.6,74.6,-32.2,-25.6,0;1196,61.4,58.4,64.2,89,-30.7,-24.7,0;1196,67.7,64.9,70.4,92.6,-27.8,-21.9,0;1196,71.3,68.6,73.9,94,-25.4,-19.9,0;853,1010,1124,1001"
=> ""
// --- END GENERATED CONSTANTS
// --- BEGIN SHARED CORE
// One session state machine, fed bar by bar. The same code runs (a) inside a fixed-timeframe request, where the chart
// keeps enough sessions for the 20-session average range and the row size, and (b) on the chart bars (or on their
// intrabars when the chart timeframe does not line up with the session), for what happens inside today's session.
type Sess
int startMin = 570
int endMin = 960
string tz = "America/New_York"
int ibMin = 60
int orMin = 15
int rowTicks = 0
bool active = false
int count = 0
int finished = 0
int dayKey = 0
int startTime = 0
int elapsed = 0
int lastDow = 0
int lastMonth = 0
float o = na
float h = na
float l = na
float c = na
float orH = na
float orL = na
bool orDone = false
float ibH = na
float ibL = na
bool ibDone = false
bool brkOrUp = false
bool brkOrDn = false
bool brkIbUp = false
bool brkIbDn = false
bool gapFilled = false
float step = na
float nextStep = na
array<float> perH
array<float> perL
float pO = na
float pH = na
float pL = na
float pC = na
float pVAH = na
float pVAL = na
float pPOC = na
float pStep = na
int pDayKey = 0
int pDow = 0
int pStart = 0
array<float> pPerH
array<float> pPerL
array<float> ranges
array<float> trs
float atr = na
float wO = na
float wH = na
float wL = na
float pwH = na
float pwL = na
bool wPartial = true
float mO = na
float mH = na
float mL = na
float pmH = na
float pmL = na
bool mPartial = true
f_newSess(int startMin, int endMin, string tz, int ibMin, int orMin, int rowTicks) =>
Sess.new(startMin = startMin, endMin = endMin, tz = tz, ibMin = ibMin, orMin = orMin, rowTicks = rowTicks, perH = array.new<float>(), perL = array.new<float>(), pPerH = array.new<float>(), pPerL = array.new<float>(), ranges = array.new<float>(), trs = array.new<float>())
// "HHMM-HHMM" -> minutes of the day
f_sessStart(string s) =>
int(str.tonumber(str.substring(s, 0, 2)) * 60 + str.tonumber(str.substring(s, 2, 4)))
f_sessEnd(string s) =>
int(str.tonumber(str.substring(s, 5, 7)) * 60 + str.tonumber(str.substring(s, 7, 9)))
// Row size of the profile: a round number of ticks that gives about 45 rows for a typical session
// (the median range of up to 60 sessions before the one being read). rowTicks > 0 overrides it.
f_autoStep(array<float> ranges, int rowTicks, float fallbackRange) =>
float typical = fallbackRange
int n = ranges.size()
if n > 0
array<float> srt = ranges.copy()
srt.sort(order.ascending)
typical := srt.get(int(math.floor(n / 2)))
int k = int(math.max(1, math.ceil(nz(typical, syminfo.mintick * 45) / 45 / syminfo.mintick)))
int ticks = k
array<int> nice = array.from(1, 2, 4, 5, 8, 10, 20, 25, 40, 50, 100, 200, 250, 500, 1000)
bool found = false
for v in nice
if not found and v >= k
ticks := v
found := true
if rowTicks > 0
ticks := rowTicks
ticks * syminfo.mintick
f_row(float price, float step) =>
int(math.floor(price / step + 1e-9))
// Point of control and 70% value area from the highs and lows of the 30-minute periods of one session.
// POC = the row with the most periods; ties go to the row closest to the middle of the range, then the higher one.
// Value area = grown from the POC one row at a time toward the side with more periods (ties up) until 70%.
// A row is named by its lower price, like the profile page of the portal.
f_profile(array<float> perH, array<float> perL, float step) =>
float poc = na
float vah = na
float val = na
int bot = na
int top = na
int np = perH.size()
if np > 0 and not na(step) and step > 0
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
int rl = f_row(pl, step)
int rh = f_row(ph, step)
bot := na(bot) ? rl : math.min(bot, rl)
top := na(top) ? rh : math.max(top, rh)
if not na(bot) and top - bot < 5000
int nrows = top - bot + 1
array<int> counts = array.new<int>(nrows, 0)
for i = 0 to np - 1
float ph = perH.get(i)
float pl = perL.get(i)
if not na(ph) and not na(pl)
int rl = f_row(pl, step) - bot
int rh = f_row(ph, step) - bot
for r = rl to rh
counts.set(r, counts.get(r) + 1)
int mx = counts.max()
float mid = (nrows - 1) / 2.0
int pr = -1
float best = na
for r = 0 to nrows - 1
if counts.get(r) == mx
float d = math.abs(r - mid)
if pr < 0 or d <= best
pr := r
best := d
int total = counts.sum()
int loR = pr
int hiR = pr
float acc = counts.get(pr)
while acc < 0.70 * total and (loR > 0 or hiR < nrows - 1)
int up = hiR < nrows - 1 ? counts.get(hiR + 1) : -1
int dn = loR > 0 ? counts.get(loR - 1) : -1
if up >= dn
hiR += 1
acc += up
else
loR -= 1
acc += dn
poc := math.round_to_mintick((bot + pr) * step)
vah := math.round_to_mintick((bot + hiR) * step)
val := math.round_to_mintick((bot + loR) * step)
[poc, vah, val]
// Closes the running session: its levels become the "prior session" ones.
method finish(Sess s) =>
if s.active
s.active := false
s.finished := s.finished + 1
float rng = s.h - s.l
[poc, vah, val] = f_profile(s.perH, s.perL, s.step)
float tr = na(s.pC) ? rng : math.max(rng, math.max(math.abs(s.h - s.pC), math.abs(s.l - s.pC)))
s.trs.push(tr)
if s.trs.size() > 20
s.trs.shift()
s.ranges.push(rng)
if s.ranges.size() > 60
s.ranges.shift()
s.atr := s.trs.size() >= 5 ? s.trs.avg() : na
s.nextStep := f_autoStep(s.ranges, s.rowTicks, rng)
s.pO := s.o
s.pH := s.h
s.pL := s.l
s.pC := s.c
s.pPOC := poc
s.pVAH := vah
s.pVAL := val
s.pStep := s.step
s.pDayKey := s.dayKey
s.pDow := s.lastDow
s.pStart := s.startTime
s.pPerH := s.perH.copy()
s.pPerL := s.perL.copy()
s.wH := na(s.wH) ? s.h : math.max(s.wH, s.h)
s.wL := na(s.wL) ? s.l : math.min(s.wL, s.l)
s.mH := na(s.mH) ? s.h : math.max(s.mH, s.h)
s.mL := na(s.mL) ? s.l : math.min(s.mL, s.l)
s.finished
// Opens a new session at the bar that starts at time t (off = minutes after the nominal session open).
method begin(Sess s, int t, int off, int key, int dow, float o) =>
bool first = s.lastDow == 0
bool newWeek = first or dow <= s.lastDow or t - s.startTime > 6 * 86400000
if newWeek
s.pwH := s.wPartial ? na : s.wH
s.pwL := s.wPartial ? na : s.wL
s.wPartial := first and dow != dayofweek.monday
s.wH := na
s.wL := na
s.wO := o
int mon = month(t, s.tz)
if mon != s.lastMonth
s.pmH := s.mPartial ? na : s.mH
s.pmL := s.mPartial ? na : s.mL
s.mPartial := first
s.mH := na
s.mL := na
s.mO := o
s.lastDow := dow
s.lastMonth := mon
s.dayKey := key
s.startTime := t - off * 60000
s.active := true
s.count := s.count + 1
s.o := o
s.h := na
s.l := na
s.c := na
s.orH := na
s.orL := na
s.orDone := false
s.ibH := na
s.ibL := na
s.ibDone := false
s.brkOrUp := false
s.brkOrDn := false
s.brkIbUp := false
s.brkIbDn := false
s.gapFilled := false
s.elapsed := 0
s.step := f_autoStep(s.ranges, s.rowTicks, na)
s.perH := array.new<float>()
s.perL := array.new<float>()
s.count
// One bar (or intrabar) that starts at time t and lasts dur minutes; done = the bar is complete.
method feed(Sess s, int t, int dur, bool done, float o, float h, float l, float c) =>
int mins = hour(t, s.tz) * 60 + minute(t, s.tz)
int dow = dayofweek(t, s.tz)
bool inWin = mins >= s.startMin and mins < s.endMin and dow != dayofweek.saturday and dow != dayofweek.sunday and not na(h) and not na(l)
int key = year(t, s.tz) * 10000 + month(t, s.tz) * 100 + dayofmonth(t, s.tz)
if s.active and (not inWin or key != s.dayKey)
s.finish()
if inWin
int off = mins - s.startMin
if key != s.dayKey
s.begin(t, off, key, dow, o)
s.h := na(s.h) ? h : math.max(s.h, h)
s.l := na(s.l) ? l : math.min(s.l, l)
s.c := c
s.elapsed := off + dur
// opening range: bars that start inside the window build it; the first bar after it fixes it
if off < s.orMin
s.orH := na(s.orH) ? h : math.max(s.orH, h)
s.orL := na(s.orL) ? l : math.min(s.orL, l)
else
s.orDone := true
if h > s.orH
s.brkOrUp := true
if l < s.orL
s.brkOrDn := true
if off < s.ibMin
s.ibH := na(s.ibH) ? h : math.max(s.ibH, h)
s.ibL := na(s.ibL) ? l : math.min(s.ibL, l)
else
s.ibDone := true
if h > s.ibH
s.brkIbUp := true
if l < s.ibL
s.brkIbDn := true
// gap against the previous session's last price: filled when price trades back at it
if not na(s.pC) and not s.gapFilled
if (s.o > s.pC and l <= s.pC) or (s.o < s.pC and h >= s.pC)
s.gapFilled := true
// highs and lows of the 30-minute periods (A = first 30 minutes)
int k = int(math.floor(off / 30))
while s.perH.size() <= k
s.perH.push(na)
s.perL.push(na)
float ph = s.perH.get(k)
float pl = s.perL.get(k)
s.perH.set(k, na(ph) ? h : math.max(ph, h))
s.perL.set(k, na(pl) ? l : math.min(pl, l))
// the bar that ends the window closes the session (once that bar is complete)
if done and s.elapsed >= s.endMin - s.startMin
s.finish()
s.count
// The deep-history context: prior-session levels, 20-session average true range of the regular session, row size,
// week and month references. Evaluated on a fixed timeframe so that a 1-minute chart has the same history as a
// 60-minute one. Everything it returns is final when the session it describes has ended.
f_ctx(int startMin, int endMin, string tz, int rowTicks, int dur) =>
var Sess s = f_newSess(startMin, endMin, tz, 60, 15, rowTicks)
s.feed(time, dur, barstate.isconfirmed, open, high, low, close)
[s.finished, s.pDayKey, s.pDow, s.lastMonth, s.pStart, s.pO, s.pH, s.pL, s.pC, s.pVAH, s.pVAL, s.pPOC, s.atr, s.trs.size(), s.pStep, s.nextStep, s.wO, s.wH, s.wL, s.pwH, s.pwL, s.wPartial, s.mO, s.mH, s.mL, s.pmH, s.pmL, s.mPartial]
// Timeframe of the deep-history context and of the intrabars: the coarsest of 15 / 5 / 1 minutes the session lines up with.
f_gridTf(int a, int b, int cap) =>
a % 15 == 0 and b % 15 == 0 and cap >= 15 ? 15 : a % 5 == 0 and b % 5 == 0 and cap >= 5 ? 5 : 1
// --- END SHARED CORE
// ------------------------------------------------------------------------------------------------------------ inputs
string G0 = "General"
string lang = input.string("es", "Idioma / Language / Idioma", options = ["es", "en", "pt"], group = G0)
string marketIn = input.string("Auto", "Mercado de las estadísticas / Market", options = ["Auto", "ES", "NQ", "RTY", "YM", "GC", "CL", "ZN", "6E"], group = G0, tooltip = "Auto: se toma del símbolo del gráfico (los micros usan las estadísticas de su contrato grande). Otros mercados: se dibuja la línea sin tabla. / Auto: taken from the chart symbol.")
bool showB1 = input.bool(true, "Banda de 1 desviación", group = G0)
bool showB2 = input.bool(true, "Banda de 2 desviaciones", group = G0)
bool showB3 = input.bool(true, "Banda de 3 desviaciones", group = G0)
bool showTable = input.bool(true, "Tabla", group = G0)
string tablePos = input.string("top_right", "Posición de la tabla", options = ["top_right", "top_left", "bottom_right", "bottom_left", "middle_right"], group = G0)
string G5 = "Colores / Colours"
color cVw = input.color(#f59e0b, "VWAP", group = G5)
color cB1 = input.color(color.new(#a78bfa, 20), "1 desviación", group = G5)
color cB2 = input.color(color.new(#58a6ff, 25), "2 desviaciones", group = G5)
color cB3 = input.color(color.new(#8b98a8, 25), "3 desviaciones", group = G5)
color cText = input.color(#c9d1d9, "Texto de la tabla", group = G5)
color cTableBg = input.color(color.new(#0d1117, 15), "Fondo de la tabla", group = G5)
f_t(string es, string en, string pt) =>
lang == "es" ? es : lang == "en" ? en : pt
// ------------------------------------------------------------------------------------------------------------- setup
int WARMUP = 30
string root = marketIn == "Auto" ? f_parent(syminfo.root) : marketIn
string lvSpec = f_lvSess(root)
string lvTz = f_lvTz(root)
int lvStart = f_sessStart(lvSpec)
int lvEnd = f_sessEnd(lvSpec)
int mult = timeframe.multiplier
// the bars must start on the session open and on 10:00: a chart of 1 to 30 minutes, aligned
bool okTf = timeframe.isminutes and mult <= 30 and lvStart % mult == 0 and WARMUP % mult == 0
var array<int> CHECK = array.from(60, 150, 270, 390)
int mins = hour(time, lvTz) * 60 + minute(time, lvTz)
int dow = dayofweek(time, lvTz)
bool inS = okTf and mins >= lvStart and mins < lvEnd and dow != dayofweek.saturday and dow != dayofweek.sunday
int dayKey = year(time, lvTz) * 10000 + month(time, lvTz) * 100 + dayofmonth(time, lvTz)
int off = mins - lvStart
// ------------------------------------------------------------------------------------------------ VWAP, bar by bar
var int curKey = na
var float sv = 0.0
var float sx = 0.0
var float sxx = 0.0
var float ref = na
var float prevVw = na
var float prevSd = na
var float sOpen = na
// minute of the session at which each band (1, 2, 3) and each control distance was first reached today; -1 = not yet
var array<int> touch = array.new<int>(3, -1)
var array<int> touchCtl = array.new<int>(3, -1)
// a comparison against na is never true: the first session is caught explicitly
bool newS = inS and (na(curKey) or dayKey != curKey)
if newS
curKey := dayKey
sv := 0.0
sx := 0.0
sxx := 0.0
ref := na
prevVw := na
prevSd := na
sOpen := open
touch.fill(-1)
touchCtl.fill(-1)
float vw = na
float sd = na
if inS
// the bands this bar is compared with: the ones known at the end of the bar before it
float bVw = prevVw
float bSd = prevSd
float tp = (high + low + close) / 3
if not na(volume) and volume > 0
// prices re-centred on the session's first typical price keep the variance precise
if na(ref)
ref := tp
float x = tp - ref
sv += volume
sx += volume * x
sxx += volume * x * x
if sv > 0
float m = sx / sv
vw := ref + m
sd := math.sqrt(math.max(sxx / sv - m * m, 0.0))
if off >= WARMUP and not na(bVw) and not na(bSd)
for k = 0 to 2
float dist = (k + 1) * bSd
if touch.get(k) < 0 and (high >= bVw + dist or low <= bVw - dist)
touch.set(k, off)
if touchCtl.get(k) < 0 and (high >= sOpen + dist or low <= sOpen - dist)
touchCtl.set(k, off)
prevVw := vw
prevSd := sd
plot(vw, "VWAP", color = cVw, linewidth = 2, style = plot.style_linebr)
plot(showB1 and not na(vw) ? vw + sd : na, "VWAP + 1 desviación", color = cB1, style = plot.style_linebr)
plot(showB1 and not na(vw) ? vw - sd : na, "VWAP - 1 desviación", color = cB1, style = plot.style_linebr)
plot(showB2 and not na(vw) ? vw + 2 * sd : na, "VWAP + 2 desviaciones", color = cB2, style = plot.style_linebr)
plot(showB2 and not na(vw) ? vw - 2 * sd : na, "VWAP - 2 desviaciones", color = cB2, style = plot.style_linebr)
plot(showB3 and not na(vw) ? vw + 3 * sd : na, "VWAP + 3 desviaciones", color = cB3, style = plot.style_linebr)
plot(showB3 and not na(vw) ? vw - 3 * sd : na, "VWAP - 3 desviaciones", color = cB3, style = plot.style_linebr)
// ------------------------------------------------------------------------------------------------------- statistics
// VW1|root|data through|window|from|to|sessions|band 1|band 2|band 3; a band = four checkpoints (10:30, 12:00, 14:00,
// close) and the first touch, ";"-separated; a checkpoint = n,pct,low,high,control pct,difference low,difference
// high,same (1 = igual al azar); the first touch = n,HHMM,control n,control HHMM
var array<string> fs = str.split(f_vw(root), "|")
var bool statsOn = fs.size() >= 10 and fs.get(0) == "VW1"
f_part(array<string> f, int i, int j) =>
array<string> out = array.new<string>()
if i < f.size()
array<string> cells = str.split(f.get(i), ";")
if j < cells.size()
out := str.split(cells.get(j), ",")
out
f_num(array<string> a, int i) =>
float v = na
if i < a.size()
v := str.tonumber(a.get(i))
v
f_str(array<string> a, int i) =>
string v = ""
if i < a.size()
v := a.get(i)
v
f_2(int v) =>
v < 10 ? "0" + str.tostring(v) : str.tostring(v)
f_clock(int m) =>
f_2(int(math.floor(m / 60))) + ":" + f_2(m % 60)
f_dec(float v, string fmt) =>
string s = na(v) ? "—" : str.tostring(v, fmt)
lang == "en" ? s : str.replace_all(s, ".", ",")
f_pct(float v) =>
na(v) ? "—" : f_dec(v, "0.0") + (lang == "en" ? "%" : " %")
f_same(string s) =>
s == "1" ? f_t("igual al azar", "same as chance", "igual ao acaso") : s == "0" ? f_t("distinto", "different", "diferente") : "—"
// today: reached at HH:MM, or not (yet)
f_today(int m, bool over) =>
m >= 0 ? f_clock(lvStart + m) : over ? f_t("no", "no", "não") : f_t("aún no", "not yet", "ainda não")
// ------------------------------------------------------------------------------------------------------------- table
f_pos(string p) =>
p == "top_left" ? position.top_left : p == "bottom_right" ? position.bottom_right : p == "bottom_left" ? position.bottom_left : p == "middle_right" ? position.middle_right : position.top_right
f_cell(table t, int col, int row, string txt, color tc, string al) =>
table.cell(t, col, row, txt, text_color = tc, text_size = size.small, text_halign = al)
true
string FOOT = f_t("Solo distancia y frecuencia: no dice que el precio vuelva al VWAP ni que se detenga en una banda, ni hacia dónde irá. No es una señal.", "Distance and frequency only: it does not say that price returns to the VWAP or stops at a band, nor which way it goes. Not a signal.", "Só distância e frequência: não diz que o preço volta ao VWAP nem que para numa banda, nem para onde vai. Não é um sinal.")
var table info = na
if barstate.islast and showTable
// a fresh table on every update: merged cells are defined once per table
if not na(info)
table.delete(info)
info := table.new(f_pos(tablePos), 6, 15, bgcolor = cTableBg, border_width = 0)
color dim = color.new(cText, 35)
if not okTf
f_cell(info, 0, 0, f_t("Usa un gráfico de 1, 2, 3, 5, 10, 15 o 30 minutos que empiece en la apertura (", "Use a 1, 2, 3, 5, 10, 15 or 30-minute chart that starts on the open (", "Use um gráfico de 1, 2, 3, 5, 10, 15 ou 30 minutos que comece na abertura (") + f_clock(lvStart) + ").", cText, text.align_left)
else
bool over = not inS or off >= lvEnd - lvStart
string head = f_t("VWAP y bandas · ", "VWAP and bands · ", "VWAP e bandas · ") + root + " · " + f_clock(lvStart) + "–" + f_clock(lvEnd) + " " + lvTz + (statsOn ? f_t(" · desde 2022: ", " · since 2022: ", " · desde 2022: ") + f_str(fs, 4) + f_t(" a ", " to ", " a ") + f_str(fs, 5) + ", n = " + f_str(fs, 6) + f_t(" sesiones", " sessions", " sessões") : f_t(" · sin tabla para este mercado", " · no table for this market", " · sem tabela para este mercado"))
f_cell(info, 0, 0, head, cText, text.align_left)
table.merge_cells(info, 0, 0, 5, 0)
f_cell(info, 0, 1, f_t("alcanzó (cualquier lado)", "reached (either side)", "atingiu (qualquer lado)"), dim, text.align_left)
f_cell(info, 1, 1, f_t("hoy", "today", "hoje"), dim, text.align_right)
f_cell(info, 2, 1, f_t("antes de 10:30", "before 10:30", "antes de 10:30"), dim, text.align_right)
f_cell(info, 3, 1, f_t("antes de 12:00", "before 12:00", "antes de 12:00"), dim, text.align_right)
f_cell(info, 4, 1, f_t("antes de 14:00", "before 14:00", "antes de 14:00"), dim, text.align_right)
f_cell(info, 5, 1, f_t("al cierre", "by the close", "até o fechamento"), dim, text.align_right)
for k = 0 to 2
int r0 = 2 + 3 * k
string kk = str.tostring(k + 1)
f_cell(info, 0, r0, "VWAP ± " + kk + f_t(" desv.", " st. dev.", " desv."), cText, text.align_left)
f_cell(info, 0, r0 + 1, f_t(" misma distancia desde la apertura", " same distance from the open", " mesma distância desde a abertura"), dim, text.align_left)
f_cell(info, 0, r0 + 2, f_t(" veredicto", " verdict", " veredito"), dim, text.align_left)
f_cell(info, 1, r0, f_today(touch.get(k), over), cText, text.align_right)
f_cell(info, 1, r0 + 1, f_today(touchCtl.get(k), over), dim, text.align_right)
f_cell(info, 1, r0 + 2, "", dim, text.align_right)
for j = 0 to 3
array<string> c = statsOn ? f_part(fs, 7 + k, j) : array.new<string>()
string pc = statsOn ? f_pct(f_num(c, 1)) + " [" + f_dec(f_num(c, 2), "0.0") + "–" + f_dec(f_num(c, 3), "0.0") + "]" : "—"
f_cell(info, 2 + j, r0, pc, cText, text.align_right)
f_cell(info, 2 + j, r0 + 1, statsOn ? f_pct(f_num(c, 4)) : "—", dim, text.align_right)
f_cell(info, 2 + j, r0 + 2, statsOn ? f_same(f_str(c, 7)) : "—", cText, text.align_right)
string how = f_t("Calculado con las velas del gráfico (precio típico por volumen); con velas de 1 minuto es la misma cuenta que la tabla. Se cuenta desde las 10:00; cada vela contra la banda de la vela anterior. Igual al azar: el intervalo pareado de la diferencia contiene cero. Datos al ", "Computed from the chart's bars (typical price by volume); on 1-minute bars it is the same arithmetic as the table. Counted from 10:00; each bar against the band of the bar before. Same as chance: the paired interval of the difference holds zero. Data through ", "Calculado com as velas do gráfico (preço típico por volume); com velas de 1 minuto é a mesma conta da tabela. Conta-se a partir das 10:00; cada vela contra a banda da vela anterior. Igual ao acaso: o intervalo pareado da diferença contém zero. Dados até ") + DATA_THROUGH + "."
f_cell(info, 0, 11, how, dim, text.align_left)
table.merge_cells(info, 0, 11, 5, 11)
f_cell(info, 0, 12, FOOT, dim, text.align_left)
table.merge_cells(info, 0, 12, 5, 12)
// ------------------------------------------------------------------------------------------------------------ alerts
// The first time today (from 10:00) a bar reaches each band, on either side. A distance reached, not a call.
bool a1 = inS and touch.get(0) >= 0
bool a2 = inS and touch.get(1) >= 0
bool a3 = inS and touch.get(2) >= 0
alertcondition(a1 and not a1[1], "VWAP band 1 reached", "Banda VWAP ± 1 desviación alcanzada hoy (primera vez) / VWAP ± 1 st. dev. band reached today (first time)")
alertcondition(a2 and not a2[1], "VWAP band 2 reached", "Banda VWAP ± 2 desviaciones alcanzada hoy (primera vez) / VWAP ± 2 st. dev. band reached today (first time)")
alertcondition(a3 and not a3[1], "VWAP band 3 reached", "Banda VWAP ± 3 desviaciones alcanzada hoy (primera vez) / VWAP ± 3 st. dev. band reached today (first time)")