KPS Session-Range Mapping

SamD1995 · study · 190 行 · 点赞 4 · TradingView 原页

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

Pine Script

//@version=6
// ═══════════════════════════════════════════════════════════════
//  © SamD1995
//  KPS Academy — Session-Range Mapping
//  Session high/low boxes, optional 50% equilibrium line,
//  session name + range labels, fully customisable times & style.
// ═══════════════════════════════════════════════════════════════
indicator("KPS Session-Range Mapping", overlay = true, max_boxes_count = 500, max_lines_count = 500, max_labels_count = 500)
 
// ───────────── General ─────────────
G_GEN = "General"
tzMode    = input.string("Region (auto DST)", "Timezone mode", options = ["Region (auto DST)", "Manual (UTC offset)"], group = G_GEN, tooltip = "Region: session times follow that region's clock and adjust for daylight saving automatically.\n\nManual: session times use a fixed UTC offset and never shift. You must update the offset yourself when clocks change.")
isManual  = tzMode == "Manual (UTC offset)"
tzInput   = input.string("Europe/London", "Region", options = ["Exchange", "UTC", "Europe/London", "Europe/Berlin", "America/New_York", "Asia/Dubai", "Asia/Tokyo", "Asia/Singapore", "Australia/Sydney"], group = G_GEN, active = not isManual, tooltip = "Used when Timezone mode is Region. Europe/London adjusts for BST/GMT automatically.")
utcHours  = input.int(0, "Manual UTC offset", minval = -12, maxval = 14, inline = "utc", group = G_GEN, active = isManual, tooltip = "Used when Timezone mode is Manual. Hours and minutes, e.g. +4 : 00 for Dubai, +5 : 30 for India, -5 : 00 for New York winter.")
utcMins   = input.string("00", ":", options = ["00", "30", "45"], inline = "utc", group = G_GEN, active = isManual)
keepInput = input.int(20, "Sessions to show (each)", minval = 1, maxval = 60, group = G_GEN, tooltip = "How many past sessions of each type stay on the chart.")
 
// ───────────── Sessions ─────────────
G_S1 = "Session 1"
s1On     = input.bool(true, "", inline = "s1a", group = G_S1)
s1Name   = input.string("Asian", "", inline = "s1a", group = G_S1)
s1Time   = input.session("0000-0800", "", inline = "s1a", group = G_S1)
s1Fill   = input.color(color.new(#2962FF, 88), "Background", inline = "s1b", group = G_S1)
s1Border = input.color(color.new(#2962FF, 30), "Border", inline = "s1b", group = G_S1)
 
G_S2 = "Session 2"
s2On     = input.bool(true, "", inline = "s2a", group = G_S2)
s2Name   = input.string("London", "", inline = "s2a", group = G_S2)
s2Time   = input.session("0800-1600", "", inline = "s2a", group = G_S2)
s2Fill   = input.color(color.new(#FF9800, 88), "Background", inline = "s2b", group = G_S2)
s2Border = input.color(color.new(#FF9800, 30), "Border", inline = "s2b", group = G_S2)
 
G_S3 = "Session 3"
s3On     = input.bool(true, "", inline = "s3a", group = G_S3)
s3Name   = input.string("New York", "", inline = "s3a", group = G_S3)
s3Time   = input.session("1300-2100", "", inline = "s3a", group = G_S3)
s3Fill   = input.color(color.new(#089981, 88), "Background", inline = "s3b", group = G_S3)
s3Border = input.color(color.new(#089981, 30), "Border", inline = "s3b", group = G_S3)
 
G_S4 = "Session 4 (custom)"
s4On     = input.bool(false, "", inline = "s4a", group = G_S4)
s4Name   = input.string("Custom", "", inline = "s4a", group = G_S4)
s4Time   = input.session("1330-1530", "", inline = "s4a", group = G_S4)
s4Fill   = input.color(color.new(#9C27B0, 88), "Background", inline = "s4b", group = G_S4)
s4Border = input.color(color.new(#9C27B0, 30), "Border", inline = "s4b", group = G_S4)
 
// ───────────── Box style ─────────────
G_BOX = "Box Style"
showFill     = input.bool(true, "Show background", group = G_BOX)
showBorder   = input.bool(true, "Show border", group = G_BOX)
borderStyleI = input.string("Solid", "Border style", options = ["Solid", "Dashed", "Dotted"], group = G_BOX)
borderWidth  = input.int(1, "Border width", minval = 1, maxval = 4, group = G_BOX)
 
// ───────────── Equilibrium ─────────────
G_EQ = "Equilibrium (50%)"
showEq    = input.bool(false, "Show equilibrium line", group = G_EQ)
eqUseSess = input.bool(true, "Use session border colour", group = G_EQ, active = showEq)
eqColor   = input.color(color.gray, "Custom colour", group = G_EQ, active = showEq and not eqUseSess)
eqStyleI  = input.string("Dashed", "Line style", options = ["Solid", "Dashed", "Dotted"], group = G_EQ, active = showEq)
eqWidth   = input.int(1, "Line width", minval = 1, maxval = 4, group = G_EQ, active = showEq)
 
// ───────────── Labels ─────────────
G_LBL = "Labels"
showName    = input.bool(true, "Show session name", group = G_LBL)
showRange   = input.bool(true, "Show range", group = G_LBL)
rangeUnit   = input.string("Pips", "Range units", options = ["Pips", "Points", "Price"], group = G_LBL, active = showRange)
pipOverride = input.float(0.0, "Pip size override (0 = auto)", minval = 0, step = 0.0001, group = G_LBL, active = showRange, tooltip = "Auto: forex = 0.0001 (JPY pairs 0.01), gold = 0.1, silver = 0.01. 1 point = 1/10 pip. Indices, crypto and other markets show the range in price unless you enter a pip size here.")
lblUseSess  = input.bool(true, "Use session colour for text", group = G_LBL)
lblColor    = input.color(color.white, "Custom text colour", group = G_LBL, active = not lblUseSess)
lblSizeI    = input.string("Small", "Label size", options = ["Tiny", "Small", "Normal"], group = G_LBL)
 
// ───────────── Helpers ─────────────
lineStyle(string s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        => line.style_solid
 
labelSize(string s) =>
    switch s
        "Tiny"   => size.tiny
        "Normal" => size.normal
        => size.small
 
borderStyle = lineStyle(borderStyleI)
eqStyle     = lineStyle(eqStyleI)
lblSize     = labelSize(lblSizeI)
manualTz    = "GMT" + (utcHours < 0 ? "-" : "+") + str.format("{0,number,00}", math.abs(utcHours)) + utcMins
tz          = isManual ? manualTz : tzInput == "Exchange" ? syminfo.timezone : tzInput
isMetal     = syminfo.type != "stock"
isGold      = isMetal and (syminfo.basecurrency == "XAU" or str.contains(syminfo.ticker, "XAU") or str.contains(syminfo.ticker, "GOLD"))
isSilver    = isMetal and (syminfo.basecurrency == "XAG" or str.contains(syminfo.ticker, "XAG") or str.contains(syminfo.ticker, "SILVER"))
isFX        = syminfo.type == "forex" and not isGold and not isSilver
// Fixed pip sizes so ranges read the same on every broker:
// forex 0.0001 (JPY pairs 0.01), gold 0.1, silver 0.01. 1 point = 1/10 pip.
// Other markets (indices, crypto, stocks) have no pip, so their range is shown in price.
autoPip     = isGold ? 0.1 : isSilver ? 0.01 : isFX ? (syminfo.currency == "JPY" ? 0.01 : 0.0001) : na
pipSize     = pipOverride > 0 ? pipOverride : autoPip
clearCol    = color.new(color.white, 100)
 
formatRange(float r) =>
    switch rangeUnit
        "Pips"   => "R: " + (na(pipSize) ? str.tostring(r, format.mintick) : str.tostring(r / pipSize, "#.#"))
        "Points" => "R: " + (na(pipSize) ? str.tostring(r, format.mintick) : str.tostring(r / (pipSize / 10), "#"))
        => "R: " + str.tostring(r, format.mintick)
 
// ───────────── Types ─────────────
type Drawing
    box   bx
    line  eq
    label nm
    label rng
 
type Session
    string         name
    color          fill
    color          border
    bool           active = false
    float          hi
    float          lo
    int            startTime
    Drawing        cur
    array<Drawing> history
 
newSession(string name, color fillCol, color borderCol) =>
    Session.new(name = name, fill = fillCol, border = borderCol, active = false, history = array.new<Drawing>())
 
// ───────────── Core logic ─────────────
updateSession(Session s, bool enabled, string times) =>
    inSess = enabled and timeframe.isintraday and not na(time(timeframe.period, times, tz))
    if inSess
        if not s.active
            // A new session has opened
            s.active   := true
            s.hi       := high
            s.lo       := low
            s.startTime := time
            txtCol = lblUseSess ? color.new(s.border, 0) : lblColor
            nd = Drawing.new()
            // Drawn in time coordinates: left = open of first bar, right = CLOSE of last bar,
            // so a 00:00-08:00 session ends exactly at 08:00 on any timeframe.
            nd.bx := box.new(time, high, time_close, low, xloc = xloc.bar_time, border_color = showBorder ? s.border : clearCol, border_width = borderWidth, border_style = borderStyle, bgcolor = showFill ? s.fill : clearCol)
            if showEq
                nd.eq := line.new(time, hl2, time_close, hl2, xloc = xloc.bar_time, color = eqUseSess ? color.new(s.border, 0) : eqColor, style = eqStyle, width = eqWidth)
            if showName
                nd.nm := label.new(time, high, s.name, xloc = xloc.bar_time, color = clearCol, textcolor = txtCol, style = label.style_label_down, size = lblSize)
            if showRange
                nd.rng := label.new(time, low, "", xloc = xloc.bar_time, color = clearCol, textcolor = txtCol, style = label.style_label_up, size = lblSize)
            s.cur := nd
            s.history.push(nd)
            // Remove the oldest session once over the limit
            if s.history.size() > keepInput
                old = s.history.shift()
                box.delete(old.bx)
                line.delete(old.eq)
                label.delete(old.nm)
                label.delete(old.rng)
        else
            // Session still running: extend high/low
            s.hi := math.max(s.hi, high)
            s.lo := math.min(s.lo, low)
        // Refresh the drawings for the live session
        d    = s.cur
        mid  = math.avg(s.hi, s.lo)
        midX = int((s.startTime + time_close) / 2)
        box.set_top(d.bx, s.hi)
        box.set_bottom(d.bx, s.lo)
        box.set_right(d.bx, time_close)
        if showEq
            line.set_xy1(d.eq, s.startTime, mid)
            line.set_xy2(d.eq, time_close, mid)
        if showName
            label.set_xy(d.nm, midX, s.hi)
        if showRange
            label.set_xy(d.rng, midX, s.lo)
            label.set_text(d.rng, formatRange(s.hi - s.lo))
    else
        s.active := false
    s
 
var Session sess1 = newSession(s1Name, s1Fill, s1Border)
var Session sess2 = newSession(s2Name, s2Fill, s2Border)
var Session sess3 = newSession(s3Name, s3Fill, s3Border)
var Session sess4 = newSession(s4Name, s4Fill, s4Border)
 
updateSession(sess1, s1On, s1Time)
updateSession(sess2, s2On, s2Time)
updateSession(sess3, s3On, s3Time)
updateSession(sess4, s4On, s4Time)

← 返回列表