Session Levels: PM, PD, Asia, POC, VWAP

ORBMap · study · 282 行 · 点赞 18 · TradingView 原页

本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。

Pine Script

// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © ORBMap
 
//@version=6
indicator("Session Levels: PM, PD, Asia, POC, VWAP", shorttitle = "Session Levels", overlay = true, max_labels_count = 50)
 
// ─────────────────────────────── Inputs ───────────────────────────────
grpS     = "Sessions (HHMM-HHMM, exchange-agnostic)"
tz       = input.string("America/New_York", "Timezone", group = grpS)
rthSess  = input.string("0930-1600", "Regular session (RTH)", group = grpS)
pmSess   = input.string("0400-0930", "Pre-market session", group = grpS)
asiaSess = input.string("2000-0000", "Asia session", group = grpS, tooltip = "Overnight windows are supported, e.g. 2000-0000 or 1800-0300.")
pdMode   = input.string("RTH", "Previous day basis", options = ["RTH", "Full trading day"], group = grpS,
     tooltip = "RTH = prior regular-session high/low.\nFull trading day = prior exchange day including overnight (CME futures: 6pm–5pm ET).")
 
grpL     = "Levels"
showPD   = input.bool(true, "Previous day high / low", group = grpL, inline = "pd")
colPDH   = input.color(#F23645, "", group = grpL, inline = "pd")
colPDL   = input.color(#4CAF50, "", group = grpL, inline = "pd")
showPM   = input.bool(true, "Pre-market high / low", group = grpL, inline = "pm")
colPMH   = input.color(#7B1FA2, "", group = grpL, inline = "pm")
colPML   = input.color(#00C853, "", group = grpL, inline = "pm")
showAsia = input.bool(true, "Asia high / low", group = grpL, inline = "as")
colAH    = input.color(#FF9800, "", group = grpL, inline = "as")
colAL    = input.color(#26A69A, "", group = grpL, inline = "as")
showVW   = input.bool(true, "VWAP", group = grpL, inline = "vw")
colVW    = input.color(#00BCD4, "", group = grpL, inline = "vw")
 
grpP     = "Point of Control / VWAP"
showPOC  = input.bool(true, "Developing POC", group = grpP, inline = "poc")
colPOC   = input.color(#2962FF, "", group = grpP, inline = "poc")
showPPOC = input.bool(false, "Previous POC", group = grpP, inline = "ppoc")
colPPOC  = input.color(color.new(#2962FF, 50), "", group = grpP, inline = "ppoc")
anchor   = input.string("Trading day", "POC / VWAP reset", options = ["Trading day", "RTH open"], group = grpP,
     tooltip = "Trading day = resets at the exchange day start (CME futures: 6pm ET; stocks: first pre-market bar).\nRTH open = resets at the regular session open.")
useLtf   = input.bool(true, "Build POC from 1-minute data", group = grpP,
     tooltip = "Distributes volume using 1-minute bars inside each chart bar, so the POC matches the volume profile far more closely on 5m/15m/30m charts. Falls back to chart bars where 1-minute history isn't available.")
rowTicks = input.int(0, "Row size in ticks (0 = auto)", minval = 0, group = grpP,
     tooltip = "0 = auto: previous profile's range ÷ 200, rounded to the tick. Set 1 for tick-level POC (most precise, heavier).")
 
grpB     = "Bias panel"
showTbl  = input.bool(true, "Show bias panel", group = grpB)
tblPosIn = input.string("Top right", "Position", options = ["Top right", "Bottom right", "Top left", "Bottom left"], group = grpB)
slopeLen = input.int(10, "VWAP slope lookback (bars)", minval = 2, group = grpB)
 
grpD     = "Display"
lineW    = input.int(1, "Line width", minval = 1, maxval = 4, group = grpD)
showLbl  = input.bool(true, "Price labels on the right", group = grpD)
lblOff   = input.int(5, "Label offset (bars)", minval = 0, maxval = 50, group = grpD)
 
// ─────────────────────────────── Helpers ───────────────────────────────
// Minutes since midnight from "HHMM" at a given offset of "HHMM-HHMM".
parseMin(string s, int offset) =>
    int(str.tonumber(str.substring(s, offset, offset + 2))) * 60 + int(str.tonumber(str.substring(s, offset + 2, offset + 4)))
 
// True when the bar OPENS inside the window [start, end), in the chosen timezone.
// Handles overnight windows (end <= start).
inWin(string s) =>
    int st  = parseMin(s, 0)
    int en  = parseMin(s, 5)
    int tod = hour(time, tz) * 60 + minute(time, tz)
    st < en ? tod >= st and tod < en : tod >= st or tod < en
 
// -1 below range, 0 inside, +1 above
locOf(float hi, float lo) =>
    na(hi) or na(lo) ? 0 : close > hi ? 1 : close < lo ? -1 : 0
 
newDay = timeframe.change("D")
 
// ─────────────────────────── Previous day H/L ──────────────────────────
var float dayH = na
var float dayL = na
var float rthH = na
var float rthL = na
var float pdH  = na
var float pdL  = na
 
inRTH    = inWin(rthSess)
rthStart = inRTH and (not inRTH[1] or newDay)
// RTH finalizes on the first bar after it ends, or (RTH-only charts) when a new RTH starts right after the old one.
rthEnd   = (inRTH[1] and not inRTH) or (rthStart and inRTH[1])
 
if pdMode == "RTH" and rthEnd and not na(rthH)
    pdH := rthH
    pdL := rthL
 
if rthStart
    rthH := high
    rthL := low
else if inRTH
    rthH := math.max(rthH, high)
    rthL := math.min(rthL, low)
 
if newDay
    if pdMode == "Full trading day" and not na(dayH)
        pdH := dayH
        pdL := dayL
    dayH := high
    dayL := low
else
    dayH := math.max(nz(dayH, high), high)
    dayL := math.min(nz(dayL, low), low)
 
// ─────────────────────────── Point of Control ──────────────────────────
// Volume profile built incrementally from the reset point. Each (1-minute or chart) bar's
// volume is spread evenly over the price rows it traded through. POC = row with the most volume.
resetProf = anchor == "RTH open" ? rthStart : newDay
 
ltfStr = timeframe.in_seconds() <= 60 ? timeframe.period : "1"
[ltfH, ltfL, ltfV] = request.security_lower_tf(syminfo.tickerid, ltfStr, [high, low, volume], ignore_invalid_timeframe = true)
 
var map<int, float> vp = map.new<int, float>()
var float bucket  = na
var int   pocKey  = na
var float pocVol  = 0.0
var float poc     = na
var float prevPoc = na
var float profH   = na
var float profL   = na
 
if resetProf
    float r = profH - profL
    bucket  := rowTicks > 0 ? rowTicks * syminfo.mintick :
         na(r) or r <= 0 ? syminfo.mintick * 4 : math.max(syminfo.mintick, math.round_to_mintick(r / 200))
    prevPoc := poc
    vp.clear()
    pocKey  := na
    pocVol  := 0.0
    poc     := na
    profH   := high
    profL   := low
else
    profH := math.max(nz(profH, high), high)
    profL := math.min(nz(profL, low), low)
 
if na(bucket)
    bucket := rowTicks > 0 ? rowTicks * syminfo.mintick : syminfo.mintick * 4
 
int nSub = 0
if useLtf and not na(ltfV)
    nSub := ltfV.size()
int loops = nSub > 0 ? nSub : 1
 
for j = 0 to loops - 1
    float bh = high
    float bl = low
    float bv = volume
    if nSub > 0
        bh := ltfH.get(j)
        bl := ltfL.get(j)
        bv := ltfV.get(j)
    if nz(bv) > 0 and not na(bh) and not na(bl)
        int kLo = math.floor(bl / bucket + 1e-9)
        int kHi = math.floor(bh / bucket + 1e-9)
        int n   = math.max(1, math.min(kHi - kLo + 1, 500))
        float share = bv / n
        for i = 0 to n - 1
            int k = kLo + i
            float nv = nz(vp.get(k)) + share
            vp.put(k, nv)
            if nv > pocVol
                pocVol := nv
                pocKey := k
 
if not na(pocKey)
    // 1-tick rows report the exact price; wider rows report the row midpoint
    poc := bucket <= syminfo.mintick ? math.round_to_mintick(pocKey * bucket) : math.round_to_mintick((pocKey + 0.5) * bucket)
 
// ─────────────────────────── Pre-market H/L ────────────────────────────
var float pmH = na
var float pmL = na
inPM    = inWin(pmSess)
pmStart = inPM and (not inPM[1] or newDay)
if pmStart
    pmH := high
    pmL := low
else if inPM
    pmH := math.max(pmH, high)
    pmL := math.min(pmL, low)
 
// ───────────────────────────── Asia H/L ────────────────────────────────
var float asH = na
var float asL = na
inAsia    = inWin(asiaSess)
asiaStart = inAsia and not inAsia[1]
if asiaStart
    asH := high
    asL := low
else if inAsia
    asH := math.max(asH, high)
    asL := math.min(asL, low)
 
// ─────────────────────────────── VWAP ──────────────────────────────────
vw = ta.vwap(hlc3, resetProf)
 
// ─────────────────────────────── Plots ─────────────────────────────────
// One-bar gap at each reset so old and new levels are never joined by a slanted line.
pdGap = pdH != pdH[1]
plot(showPD   and not pdGap     ? pdH     : na, "Previous Day High", colPDH,  lineW, plot.style_linebr)
plot(showPD   and not pdGap     ? pdL     : na, "Previous Day Low",  colPDL,  lineW, plot.style_linebr)
plot(showPM   and not pmStart   ? pmH     : na, "Pre Market High",   colPMH,  lineW, plot.style_linebr)
plot(showPM   and not pmStart   ? pmL     : na, "Pre Market Low",    colPML,  lineW, plot.style_linebr)
plot(showAsia and not asiaStart ? asH     : na, "Asia High",         colAH,   lineW, plot.style_linebr)
plot(showAsia and not asiaStart ? asL     : na, "Asia Low",          colAL,   lineW, plot.style_linebr)
plot(showPOC  and not resetProf ? poc     : na, "POC",               colPOC,  lineW, plot.style_linebr)
plot(showPPOC and not resetProf ? prevPoc : na, "Previous POC",      colPPOC, lineW, plot.style_linebr)
plot(showVW   and not resetProf ? vw      : na, "VWAP",              colVW,   lineW + 1, plot.style_linebr)
 
// ─────────────────────────────── Bias ──────────────────────────────────
barsIn   = ta.barssince(resetProf)
slopeDir = nz(barsIn) >= slopeLen ? (vw > vw[slopeLen] ? 1 : vw < vw[slopeLen] ? -1 : 0) : 0
vwSide   = na(vw)  ? 0 : close > vw  ? 1 : close < vw  ? -1 : 0
pocSide  = na(poc) ? 0 : close > poc ? 1 : close < poc ? -1 : 0
pdLoc    = locOf(pdH, pdL)
pmLoc    = inPM   ? 0 : locOf(pmH, pmL)
asLoc    = inAsia ? 0 : locOf(asH, asL)
score    = vwSide + slopeDir + pocSide + pdLoc + pmLoc
 
bull  = color.new(#26A69A, 0)
bear  = color.new(#F23645, 0)
neut  = color.new(#9E9E9E, 0)
colOf(int d) => d > 0 ? bull : d < 0 ? bear : neut
sideTxt(int d) => d > 0 ? "Above" : d < 0 ? "Below" : "At"
rangeTxt(int d, string hiName, string loName) => d > 0 ? "Above " + hiName : d < 0 ? "Below " + loName : "Inside"
 
tblPos = tblPosIn == "Top right" ? position.top_right : tblPosIn == "Bottom right" ? position.bottom_right : tblPosIn == "Top left" ? position.top_left : position.bottom_left
// Table is only created when enabled, so turning it off leaves nothing on the chart (not even an empty frame).
var table tbl = showTbl ? table.new(tblPos, 2, 6, bgcolor = color.new(color.black, 85), border_width = 1, frame_color = color.new(color.gray, 70), frame_width = 1) : na
 
if showTbl and barstate.islast
    string biasTxt = score >= 3 ? "Bullish" : score <= -3 ? "Bearish" : "Mixed / balance"
    int    biasDir = score >= 3 ? 1 : score <= -3 ? -1 : 0
    string vwTxt   = sideTxt(vwSide) + (slopeDir > 0 ? ", rising" : slopeDir < 0 ? ", falling" : ", flat")
    table.cell(tbl, 0, 0, "Bias", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 0, biasTxt + " (" + str.tostring(score) + "/5)", text_color = colOf(biasDir), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 1, "VWAP", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 1, vwTxt, text_color = colOf(vwSide), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 2, "POC", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 2, sideTxt(pocSide), text_color = colOf(pocSide), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 3, "Prior day", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 3, rangeTxt(pdLoc, "PDH", "PDL"), text_color = colOf(pdLoc), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 4, "Pre-market", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 4, inPM ? "Forming" : rangeTxt(pmLoc, "PMH", "PML"), text_color = colOf(pmLoc), text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 0, 5, "Asia", text_color = color.white, text_size = size.small, text_halign = text.align_left)
    table.cell(tbl, 1, 5, inAsia ? "Forming" : rangeTxt(asLoc, "Asia H", "Asia L"), text_color = colOf(asLoc), text_size = size.small, text_halign = text.align_left)
 
// ─────────────────────────────── Labels ────────────────────────────────
var array<label> lbls = array.new<label>()
 
addLbl(bool show, float y, string name, color c) =>
    if show and not na(y)
        lbls.push(label.new(bar_index + lblOff, y, name + " (" + str.tostring(y, format.mintick) + ")",
             style = label.style_label_left, color = color.new(color.black, 100), textcolor = c, size = size.small))
 
if barstate.islast
    while lbls.size() > 0
        lbls.pop().delete()
    if showLbl
        addLbl(showAsia, asH,     "Asia High",         colAH)
        addLbl(showPM,   pmH,     "Pre Market High",   colPMH)
        addLbl(showPD,   pdH,     "Previous Day High", colPDH)
        addLbl(showVW,   vw,      "VWAP",              colVW)
        addLbl(showAsia, asL,     "Asia Low",          colAL)
        addLbl(showPD,   pdL,     "Previous Day Low",  colPDL)
        addLbl(showPOC,  poc,     "POC",               colPOC)
        addLbl(showPPOC, prevPoc, "Prev POC",          colPPOC)
        addLbl(showPM,   pmL,     "Pre Market Low",    colPML)
    if not timeframe.isintraday or timeframe.in_seconds() > 1800
        lbls.push(label.new(bar_index, high, "Session Levels: use a 30m or lower chart for exact session levels",
             style = label.style_label_down, color = color.gray, textcolor = color.white, size = size.small))
 
// ─────────────────────────────── Alerts ────────────────────────────────
alertcondition(ta.cross(close, pdH), "Cross PDH",       "{{ticker}} crossed Previous Day High")
alertcondition(ta.cross(close, pdL), "Cross PDL",       "{{ticker}} crossed Previous Day Low")
alertcondition(ta.cross(close, pmH), "Cross PMH",       "{{ticker}} crossed Pre Market High")
alertcondition(ta.cross(close, pmL), "Cross PML",       "{{ticker}} crossed Pre Market Low")
alertcondition(ta.cross(close, asH), "Cross Asia High", "{{ticker}} crossed Asia High")
alertcondition(ta.cross(close, asL), "Cross Asia Low",  "{{ticker}} crossed Asia Low")
alertcondition(ta.cross(close, poc), "Cross POC",       "{{ticker}} crossed developing POC")
alertcondition(ta.cross(close, vw),  "Cross VWAP",      "{{ticker}} crossed VWAP")
alertcondition(ta.change(math.sign(score - 2.5)) != 0 and score >= 3,  "Bias turned bullish", "{{ticker}} session bias turned bullish")
alertcondition(ta.change(math.sign(score + 2.5)) != 0 and score <= -3, "Bias turned bearish", "{{ticker}} session bias turned bearish")

← 返回列表