MonoIntel Settlements: Previous Day and Week Settlement

monobosh · study · 204 行 · 点赞 8 · TradingView 原页

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

Pine Script

//@version=6
indicator("MonoIntel Settlements: Previous Day and Week Settlement", shorttitle="MI Settlements", overlay=true,
     max_lines_count=500, max_labels_count=500)
 
// Built for CME futures on charts from 1 minute to 4 hours. All times are New York.
// Settlement = the 16:00 New York close on every market.
// PDS is the settlement of the session that just ended. From the Sunday open to Monday's close it is Friday's.
// PWS is the last settlement of the previous trading week (Friday's), drawn once at the Sunday 18:00 open.
// On early-close days the settlement is the last traded price of that session.
// Prices are read from 30-minute or 1-minute data underneath the chart, so the 16:00 close is exact
// on any intraday timeframe, including ones whose bars don't split at 16:00.
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 1 — INPUTS
// ══════════════════════════════════════════════════════════════════════════════
 
// ── Previous Day Settlement ──────────────────────────────────────────────────
i_showPDS        = input.bool(true,      "Show PDS",              group="Previous Day Settlement",
     tooltip="Draws the previous day's 16:00 settlement.")
i_pdsColor       = input.color(#FF8C00,  "Color",                 group="Previous Day Settlement",
     tooltip="Colour of the PDS line and label.")
i_pdsWidth       = input.int(2,          "Line Width",            group="Previous Day Settlement",
     minval=1, maxval=4, tooltip="Thickness of the PDS line.")
i_pdsStyle       = input.string("Solid", "Line Style",            group="Previous Day Settlement",
     options=["Solid", "Dashed", "Dotted"], tooltip="Style of the PDS line.")
i_pdsDays        = input.int(1,          "History (days)",        group="Previous Day Settlement",
     minval=1, maxval=20, tooltip="How many PDS lines stay on the chart. 1 shows only the latest.")
i_pdsOutstanding = input.bool(false,     "Show outstanding only", group="Previous Day Settlement",
     tooltip="When on, a PDS line is removed once price trades through it.")
 
// ── Previous Week Settlement ─────────────────────────────────────────────────
i_showPWS        = input.bool(true,       "Show PWS",              group="Previous Week Settlement",
     tooltip="Draws the previous week's Friday 16:00 settlement.")
i_pwsColor       = input.color(#FF8C00,   "Color",                 group="Previous Week Settlement",
     tooltip="Colour of the PWS line and label.")
i_pwsWidth       = input.int(2,           "Line Width",            group="Previous Week Settlement",
     minval=1, maxval=4, tooltip="Thickness of the PWS line.")
i_pwsStyle       = input.string("Dashed", "Line Style",            group="Previous Week Settlement",
     options=["Solid", "Dashed", "Dotted"], tooltip="Style of the PWS line.")
i_pwsDays        = input.int(1,           "History (weeks)",       group="Previous Week Settlement",
     minval=1, maxval=20, tooltip="How many PWS lines stay on the chart. 1 shows only the latest.")
i_pwsOutstanding = input.bool(false,      "Show outstanding only", group="Previous Week Settlement",
     tooltip="When on, a PWS line is removed once price trades through it.")
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 2 — CONSTANTS + HELPERS
// ══════════════════════════════════════════════════════════════════════════════
 
string TZ         = "America/New_York"
int    SETTLE_MIN = 16 * 60          // 16:00, minutes after midnight
int    DAY_MS     = 86400000
int    SHIFT_MS   = 6 * 3600000      // moves the 18:00 open onto the next calendar day
 
f_lineStyle(s) =>
    switch s
        "Dashed" => line.style_dashed
        "Dotted" => line.style_dotted
        =>          line.style_solid
 
// True for a bar that opens before 16:00, so it closes at or before the settlement.
f_beforeSettle(int t) =>
    hour(t, TZ) * 60 + minute(t, TZ) < SETTLE_MIN
 
// Trading day number: a session opening at 18:00 belongs to the next calendar day.
f_tradingDay(int t) =>
    int x = t + SHIFT_MS
    int(timestamp("UTC", year(x, TZ), month(x, TZ), dayofmonth(x, TZ)) / DAY_MS)
 
// Trading week number, Monday based. Day 0 (1 Jan 1970) was a Thursday.
f_tradingWeek(int day) =>
    math.floor((day + 3) / 7)
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 3 — DATA UNDER THE CHART
// ══════════════════════════════════════════════════════════════════════════════
// Charts whose bars split cleanly at 16:00 (timeframes that divide one hour) read
// their own bars. Anything else reads 30m bars (above 30m) or 1m bars (below).
 
int    tfSec   = timeframe.in_seconds()
bool   aligned = tfSec < 60 or 3600 % tfSec == 0
bool   active  = timeframe.isintraday and tfSec <= 4 * 3600   // 4 hour charts and below
string dataTF  = aligned or not active ? timeframe.period : tfSec > 1800 ? "30" : "1"
 
[subTime, subHigh, subLow, subClose] = request.security_lower_tf(syminfo.tickerid, dataTF,
     [time, high, low, close], ignore_invalid_timeframe=true)
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 4 — STATE
// ══════════════════════════════════════════════════════════════════════════════
 
var int   prevTime      = na
var int   prevDay       = na
var bool  prevBefore    = false
var float prevClose     = na
var int   prevChartTime = na
 
// The most recent settlement, held for the weekly level.
var float lastSettle     = na
var int   lastSettleTime = na
 
var line[]  pds_lines  = array.new<line>(0)
var label[] pds_labels = array.new<label>(0)
var float[] pds_levels = array.new<float>(0)
 
var line[]  pws_lines  = array.new<line>(0)
var label[] pws_labels = array.new<label>(0)
var float[] pws_levels = array.new<float>(0)
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 5 — DRAWING HELPERS
// ══════════════════════════════════════════════════════════════════════════════
 
// Prune the oldest entry when over the limit, then add a new line and label.
f_spawn(array<line> lns, array<label> lbs, array<float> lvls, int limit,
     int x1, float lvl, string txt, color col, string sty, int wid) =>
    if array.size(lns) >= limit
        line.delete(array.shift(lns))
        label.delete(array.shift(lbs))
        array.shift(lvls)
    ln = line.new(x1=x1, y1=lvl, x2=time, y2=lvl, xloc=xloc.bar_time,
         color=col, style=f_lineStyle(sty), width=wid)
    lb = label.new(x=time, y=lvl, text=txt, xloc=xloc.bar_time,
         style=label.style_none, textcolor=col, size=size.small)
    array.push(lns, ln)
    array.push(lbs, lb)
    array.push(lvls, lvl)
 
// Remove any level that the given price range traded through.
// Reverse iteration keeps the indexes valid while removing.
// skipNewest leaves the most recent level alone (used until the session after it opens).
f_mitigate(array<line> lns, array<label> lbs, array<float> lvls, float h, float l, bool skipNewest = false) =>
    int i = array.size(lns) - (skipNewest ? 2 : 1)
    while i >= 0
        float lvl = array.get(lvls, i)
        if h >= lvl and l <= lvl
            line.delete(array.get(lns, i))
            label.delete(array.get(lbs, i))
            array.remove(lns,  i)
            array.remove(lbs,  i)
            array.remove(lvls, i)
        i := i - 1
 
f_extend(array<line> lns, array<label> lbs) =>
    for [i, ln] in lns
        line.set_x2(ln, time)
        label.set_x(array.get(lbs, i), time)
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 6 — WALK THE DATA, BAR BY BAR
// ══════════════════════════════════════════════════════════════════════════════
// A session settles on the first bar after its last pre-16:00 bar: either the
// 16:00 bar, or the next open after an early close. The settlement is the close
// of that last pre-16:00 bar, so it is only drawn once that bar is final.
 
var int pdsSpawnDay = na
 
if active
    for [k, t] in subTime
        float h      = array.get(subHigh,  k)
        float l      = array.get(subLow,   k)
        bool  before = f_beforeSettle(t)
        int   day    = f_tradingDay(t)
        bool  first  = na(prevTime)
 
        // Session settled: draw PDS.
        if not first and prevBefore and (not before or day != prevDay)
            lastSettle     := prevClose
            lastSettleTime := prevChartTime
            if i_showPDS
                f_spawn(pds_lines, pds_labels, pds_levels, i_pdsDays,
                     lastSettleTime, lastSettle, "PDS", i_pdsColor, i_pdsStyle, i_pdsWidth)
                pdsSpawnDay := prevDay   // the session that settled; early closes spawn at the next open
 
        // New trading week (the Sunday 18:00 open): draw PWS once.
        if not first and f_tradingWeek(day) != f_tradingWeek(prevDay) and not na(lastSettle)
            if i_showPWS
                f_spawn(pws_lines, pws_labels, pws_levels, i_pwsDays,
                     lastSettleTime, lastSettle, "PWS", i_pwsColor, i_pwsStyle, i_pwsWidth)
 
        // Only price after a level formed can mitigate it.
        // The 16:00 to 17:00 hour trades around the settlement it just made, so a new
        // PDS only starts counting from the next session's 18:00 open.
        if i_pdsOutstanding
            f_mitigate(pds_lines, pds_labels, pds_levels, h, l, day == pdsSpawnDay)
        if i_pwsOutstanding
            f_mitigate(pws_lines, pws_labels, pws_levels, h, l)
 
        prevTime      := t
        prevDay       := day
        prevBefore    := before
        prevClose     := array.get(subClose, k)
        prevChartTime := time
 
    f_extend(pds_lines, pds_labels)
    f_extend(pws_lines, pws_labels)
 
// ══════════════════════════════════════════════════════════════════════════════
// SECTION 7 — NOTICE ABOVE THE 4 HOUR CHART
// ══════════════════════════════════════════════════════════════════════════════
 
var table notice = table.new(position.bottom_right, 1, 1)
if barstate.islast and not active
    table.cell(notice, 0, 0, "MonoIntel Settlements works on 4 hour charts and below.",
         text_color=chart.fg_color, text_size=size.small)

← 返回列表