本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © OGDubsky
//@version=6
indicator("News Candle Range", overlay = true, max_lines_count = 100, max_labels_count = 120)
// ————— Conceptual Information
// A scheduled news release (CPI, NFP, FOMC, ...) prints its first reaction in the "news candle": the candle of length W
// (default 15m) that opens at the release time T. This script measures how far past news candles swung away from their own
// open, and projects that typical swing around the next release's anchor.
//
// Event types: up to 15 (Event 1 to Event 15 in the settings; 12 preset with the monthly high-impact US releases and the
// FOMC decision, 3 spare), each with a name, a release time and a list of dates. They share the time zone and W. Each type
// is measured and projected from its own past events only, so a CPI projection never uses FOMC candles.
//
// One past event at time T, news candle [T, T + W), measured from its own open:
// up = max(high - open, 0) / open * 100 down = max(open - low, 0) / open * 100 (percent of open)
// wick = the leg against the news candle's direction (candleDirection(), its own close against its open):
// bullish (close > open): down, bearish (close < open): up, doji (close = open): the smaller leg
// expansion = the other leg, in the candle's direction
// A candle that ran one way (a bullish one that never traded below its open) has a wick of 0. The clamp at 0 is only a
// guard: high >= open >= low. Percent, not points, so events from a different price level stay comparable. The candle's
// OHLC is all it takes, the time order of the extremes doesn't matter.
//
// Projection of event k: the statistic (median, mean or maximum) of the wicks, and separately of the expansions, of its
// sample: all valid events of the same type before k, the most recent MAX_SAMPLE (50) at most, so the listed dates set the
// sample size. Walk-forward: event k never enters its own lines. Candles with barely any wick would pull the wick statistic
// onto the anchor, so with Drop small wicks on, wicks of 0 (one-way candles) are left out of it, and so are positive
// wicks below exp(mean - m * standard deviation) of their logs (wickCutoffOf(), m from the settings). Log scale because
// wicks are >= 0 and right-skewed: on a linear scale mean - m * sd almost always lies below 0 and removes nothing, their
// logs are roughly symmetric. With no wick left (all 0) the wick is 0 and the dashed lines sit at the anchor. The
// expansions always use all sample events. The lines sit at anchor * (1 +/- pct / 100). The anchor follows the projection
// phase: before T the close of the chart bar that ends at or before T (live, the preliminary close, from T - W), from T on
// the news candle's open, the open of the first chart bar inside [T, T + W), frozen. Dashed lines are the wick, solid
// lines the expansion, each drawn above AND below the anchor because the direction is unknown in advance. "Projections to
// draw" is a total across all types: the most recent drawable events, newest first.
//
// Data: Pine can't read a news calendar, so the event dates are pasted into the settings. The past events are months back,
// further than a 1m chart reaches, so all measuring runs in ONE request on the W timeframe with a long history
// (calc_bars_count). The measurement depends only on the event time, so the request measures the sorted, unique union of
// all types' event times once, and each type keeps the indices of its own events in that union. Two types released at the
// same moment (PPI and Retail Sales at 8:30 on the same day) share the measurement but keep their own samples and lines.
// The request is the same from every chart timeframe, so the levels don't change when switching between a 15m and a 1m
// chart. It returns its measurements on its last bar and around every event time; the chart keeps the latest ones it got,
// so the lines also show in Bar Replay, where the request's last bar may not be the replay point.
//
// Volatility scaling (optional): a news candle's swing grows with the market's expected volatility. vol of an event = the
// volatility index's (VIX) previous daily close as of the bar that ends at T, the same expression on both sides
// (previousVolClose(): close[1] with lookahead on). The previous close is known before the release, so the event day's
// own close never leaks in; before the index's session opens it can be one day older, mostly on both sides alike (see
// previousVolClose() for the one exception). With scaling on, each sample event i contributes r = leg_i / vol_i (wick and
// expansion separately, the small-wick cut on r), and the projected pct = statistic(r) * vol of the projected event, so
// the lines widen when the index is high. Events without vol are left out of the scaled statistics; without a vol for the
// projected event or in its sample, the plain lines are drawn. The table's vol check predicts every past release of the focus type from its earlier ones, plain and scaled on
// the same events, and compares the errors. It runs with scaling off too: that's when it tells whether to switch it on.
// ————— Constants
const string TIMEZONE_NY = "America/New_York"
const string TIMEZONE_LONDON = "Europe/London"
const string TIMEZONE_BERLIN = "Europe/Berlin"
const string TIMEZONE_TOKYO = "Asia/Tokyo"
const string TIMEZONE_UTC = "UTC"
const int MS_PER_MINUTE = 60000
const int SECONDS_PER_MINUTE = 60
const int MS_PER_DAY = 24 * 60 * MS_PER_MINUTE
// Longest closed-market stretch between the chart's last bar and now (a long weekend). Within it timenow sets "today" for
// the table, so next week's event shows on a weekend. Beyond it (Bar Replay, stale data) the last bar's time sets it
const int MAX_CLOSED_MARKET_MS = 4 * MS_PER_DAY
const int MAX_EVENT_HOUR = 23
const int MAX_EVENT_MINUTE = 59
// Defaults of the event types (Event 1 to Event 15 in the settings): the monthly high-impact US releases and the FOMC
// decision, then spare slots. Times are HH:MM, 24h, in the time zone under All events. Dates are YYYY-MM-DD,
// comma-separated: the past releases and the upcoming one
const bool EVENT_1_ENABLED = true
const string EVENT_1_NAME = "CPI"
const string EVENT_1_TIME = "08:30"
const string EVENT_1_DATES = "2024-10-10, 2024-11-13, 2024-12-11, 2025-01-15, 2025-02-12, 2025-03-12, 2025-04-10, 2025-05-13, 2025-06-11, 2025-07-15, 2025-08-12, 2025-09-11, 2025-10-24, 2025-12-18, 2026-01-13, 2026-02-13, 2026-03-11, 2026-04-10, 2026-05-12, 2026-06-10, 2026-07-14, 2026-08-12, 2026-09-11, 2026-10-14, 2026-11-10, 2026-12-10"
const bool EVENT_2_ENABLED = true
const string EVENT_2_NAME = "NFP"
const string EVENT_2_TIME = "08:30"
const string EVENT_2_DATES = "2024-10-04, 2024-11-01, 2024-12-06, 2025-01-10, 2025-02-07, 2025-03-07, 2025-04-04, 2025-05-02, 2025-06-06, 2025-07-03, 2025-08-01, 2025-09-05, 2025-11-20, 2025-12-16, 2026-01-09, 2026-02-11, 2026-03-06, 2026-04-03, 2026-05-08, 2026-06-05, 2026-07-02, 2026-08-07, 2026-09-04, 2026-10-02, 2026-11-06, 2026-12-04"
const bool EVENT_3_ENABLED = true
const string EVENT_3_NAME = "FOMC"
const string EVENT_3_TIME = "14:00"
const string EVENT_3_DATES = "2023-11-01, 2023-12-13, 2024-01-31, 2024-03-20, 2024-05-01, 2024-06-12, 2024-07-31, 2024-09-18, 2024-11-07, 2024-12-18, 2025-01-29, 2025-03-19, 2025-05-07, 2025-06-18, 2025-07-30, 2025-09-17, 2025-10-29, 2025-12-10, 2026-01-28, 2026-03-18, 2026-04-29, 2026-06-17, 2026-07-29, 2026-09-16, 2026-10-28, 2026-12-09"
const bool EVENT_4_ENABLED = true
const string EVENT_4_NAME = "PPI"
const string EVENT_4_TIME = "08:30"
const string EVENT_4_DATES = "2024-10-11, 2024-11-14, 2024-12-12, 2025-01-14, 2025-02-13, 2025-03-13, 2025-04-11, 2025-05-15, 2025-06-12, 2025-07-16, 2025-08-14, 2025-09-10, 2025-11-25, 2026-01-14, 2026-01-30, 2026-02-27, 2026-03-18, 2026-04-14, 2026-05-13, 2026-06-11, 2026-07-15, 2026-08-13, 2026-09-10, 2026-10-15, 2026-11-13, 2026-12-15"
const bool EVENT_5_ENABLED = true
const string EVENT_5_NAME = "Retail Sales"
const string EVENT_5_TIME = "08:30"
const string EVENT_5_DATES = "2024-10-17, 2024-11-15, 2024-12-17, 2025-01-16, 2025-02-14, 2025-03-17, 2025-04-16, 2025-05-15, 2025-06-17, 2025-07-17, 2025-08-15, 2025-09-16, 2025-11-25, 2025-12-16, 2026-01-14, 2026-02-10, 2026-03-06, 2026-04-01, 2026-04-21, 2026-05-14, 2026-06-17, 2026-07-16, 2026-08-14, 2026-09-16, 2026-10-15, 2026-11-17"
const bool EVENT_6_ENABLED = true
const string EVENT_6_NAME = "Core PCE"
const string EVENT_6_TIME = "08:30"
const string EVENT_6_DATES = "2024-05-31, 2024-06-28, 2024-07-26, 2024-08-30, 2024-09-27, 2024-10-31, 2024-12-20, 2025-01-31, 2025-02-28, 2025-03-28, 2025-05-30, 2025-06-27, 2025-07-31, 2025-08-29, 2025-09-26, 2026-02-20, 2026-03-13, 2026-04-09, 2026-04-30, 2026-05-28, 2026-06-25, 2026-07-30, 2026-08-26, 2026-09-30, 2026-10-29, 2026-11-25"
const bool EVENT_7_ENABLED = true
const string EVENT_7_NAME = "ISM Manufacturing"
const string EVENT_7_TIME = "10:00"
const string EVENT_7_DATES = "2024-11-01, 2024-12-02, 2025-01-03, 2025-02-03, 2025-03-03, 2025-04-01, 2025-05-01, 2025-06-02, 2025-07-01, 2025-08-01, 2025-09-02, 2025-10-01, 2025-11-03, 2025-12-01, 2026-01-05, 2026-02-02, 2026-03-02, 2026-04-01, 2026-05-01, 2026-06-01, 2026-07-01, 2026-08-03, 2026-09-01, 2026-10-01, 2026-11-02, 2026-12-01"
const bool EVENT_8_ENABLED = true
const string EVENT_8_NAME = "ISM Services"
const string EVENT_8_TIME = "10:00"
const string EVENT_8_DATES = "2024-11-05, 2024-12-04, 2025-01-07, 2025-02-05, 2025-03-05, 2025-04-03, 2025-05-05, 2025-06-04, 2025-07-03, 2025-08-05, 2025-09-04, 2025-10-03, 2025-11-05, 2025-12-03, 2026-01-07, 2026-02-04, 2026-03-04, 2026-04-06, 2026-05-05, 2026-06-03, 2026-07-06, 2026-08-05, 2026-09-03, 2026-10-05, 2026-11-04, 2026-12-03"
const bool EVENT_9_ENABLED = true
const string EVENT_9_NAME = "JOLTS"
const string EVENT_9_TIME = "10:00"
const string EVENT_9_DATES = "2024-10-01, 2024-10-29, 2024-12-03, 2025-01-07, 2025-02-04, 2025-03-11, 2025-04-01, 2025-04-29, 2025-06-03, 2025-07-01, 2025-07-29, 2025-09-03, 2025-09-30, 2025-12-09, 2026-01-07, 2026-02-05, 2026-03-13, 2026-03-31, 2026-05-05, 2026-06-02, 2026-06-30, 2026-08-04, 2026-09-01, 2026-09-29, 2026-11-03, 2026-12-01"
const bool EVENT_10_ENABLED = true
const string EVENT_10_NAME = "ADP"
const string EVENT_10_TIME = "08:15"
const string EVENT_10_DATES = "2024-10-30, 2024-12-04, 2025-01-08, 2025-02-05, 2025-03-05, 2025-04-02, 2025-04-30, 2025-06-04, 2025-07-02, 2025-07-30, 2025-09-04, 2025-10-01, 2025-11-05, 2025-12-03, 2026-01-07, 2026-02-04, 2026-03-04, 2026-04-01, 2026-05-06, 2026-06-03, 2026-07-01, 2026-08-05, 2026-09-02, 2026-09-30, 2026-11-04, 2026-12-02"
const bool EVENT_11_ENABLED = true
const string EVENT_11_NAME = "Flash PMI"
const string EVENT_11_TIME = "09:45"
const string EVENT_11_DATES = "2024-10-24, 2024-11-22, 2024-12-16, 2025-01-24, 2025-02-21, 2025-03-24, 2025-04-23, 2025-05-22, 2025-06-23, 2025-07-24, 2025-08-21, 2025-09-23, 2025-10-24, 2025-11-21, 2025-12-16, 2026-01-23, 2026-02-20, 2026-03-24, 2026-04-23, 2026-05-21, 2026-06-23, 2026-07-24, 2026-08-21, 2026-09-23, 2026-10-23, 2026-11-23"
const bool EVENT_12_ENABLED = true
const string EVENT_12_NAME = "Consumer Confidence"
const string EVENT_12_TIME = "10:00"
const string EVENT_12_DATES = "2024-10-29, 2024-11-26, 2024-12-23, 2025-01-28, 2025-02-25, 2025-03-25, 2025-04-29, 2025-05-27, 2025-06-24, 2025-07-29, 2025-08-26, 2025-09-30, 2025-10-28, 2025-11-25, 2025-12-23, 2026-01-27, 2026-02-24, 2026-03-31, 2026-04-28, 2026-05-26, 2026-06-30, 2026-07-28, 2026-08-25, 2026-09-29, 2026-10-27, 2026-11-24"
// Spare slots: no name (shows as Event n) and off. The time is a placeholder, so ticking one doesn't stop the script
// before a time is set
const bool EVENT_13_ENABLED = false
const string EVENT_13_NAME = ""
const string EVENT_13_TIME = "08:30"
const string EVENT_13_DATES = ""
const bool EVENT_14_ENABLED = false
const string EVENT_14_NAME = ""
const string EVENT_14_TIME = "08:30"
const string EVENT_14_DATES = ""
const bool EVENT_15_ENABLED = false
const string EVENT_15_NAME = ""
const string EVENT_15_TIME = "08:30"
const string EVENT_15_DATES = ""
// Prefix of a slot's default name, such as "Event 3"
const string TEXT_EVENT = "Event "
// Separates hour and minute in an event time
const string TIME_SEPARATOR = ":"
// Separates slot and event time in a projection key
const string KEY_SEPARATOR = "@"
// Bars of the news-candle timeframe in the measuring request. Large on purpose: past events are months back. The
// request's first bar shows in the table ("Data since"), so the real reach can be checked on the chart
const int NEWS_CONTEXT_BARS = 100000
// Besides on its last bar, the measuring request returns its payload on 2 bars per event time T: the bar this many news
// candles W before T (any bar that opens in [T - 2W, T - W)) and the T bar, after T is measured. With lookahead off a
// historical chart bar sees a news-timeframe bar's value only from the chart bar where that bar closes on: the T - 2W
// payload arrives 1 chart bar before T - W, the T payload (with T measured) 1 before T + W. latestMeasured keeps each until
// the next one, so the T - 2W payload covers the lines from T - W on, also where the chart history has no earlier event. A
// T - W payload would add nothing: no event is measured between T - 2W and T - W
const int PAYLOAD_WINDOW_CANDLES = 2
// Status of one event in the measurement. Plain int codes, not an enum: the payload of request.security() only holds
// fundamental types
const int STATUS_PENDING = 0
const int STATUS_OK = 1
const int STATUS_NO_DATA = 2
const int STATUS_MISALIGNED = 3
// Direction of a news candle, returned by candleDirection()
const int CANDLE_BULLISH = 1
const int CANDLE_BEARISH = -1
const int CANDLE_DOJI = 0
// Volatility index for the optional scaling: default symbol, the timeframe of its previous close, and how many daily bars
// its requests load. 5000 daily bars (about 20 years) reach back past the oldest listed events
const string VOL_SYMBOL = "TVC:VIX"
const string VOL_TIMEFRAME = "1D"
const int VOL_DAILY_BARS = 5000
const string VOL_FORMAT = "0.00"
// The vol column of the sample rows
const string VOL_SHORT_FORMAT = "0.0"
const string TEXT_MISSING = "–"
// Vol check: a past event is only scored with at least MIN_CHECK_SAMPLE earlier events (with vol) to predict it from, and
// the result only shows with at least MIN_CHECK_EVENTS scored events
const int MIN_CHECK_SAMPLE = 5
const int MIN_CHECK_EVENTS = 8
// Small-wick cut: below this many positive wicks the standard deviation means little, so only the wicks of 0 are cut.
// The default k of 2 on the log scale only removes wicks far smaller than the typical one (about 10x)
const int MIN_CUT_SAMPLE = 3
const float DEFAULT_WICK_CUT_SIGMA = 2.0
const float WICK_CUT_SIGMA_STEP = 0.25
// Per projection: wick up and down, expansion up and down, anchor = 5 lines, and their 5 labels plus the anchor's knob = 6
// labels. 20 projections = 100 lines and 120 labels, which must equal max_lines_count and max_labels_count in indicator()
// (literals there: indicator() comes before the constants). The limit is a total across all event types
const int MAX_PROJECTIONS = 20
const int DEFAULT_PROJECTIONS = 5
// Sample of a projection: every valid earlier event of its type, newest first, at most this many. Keeps the statistic on
// recent behavior when a date list grows long, and the table fits a sample row per event
const int MAX_SAMPLE = 50
const int MAX_EXTENSION_MINUTES = 480
const int MIN_LINE_WIDTH = 1
const int MAX_LINE_WIDTH = 4
const int DEFAULT_LINE_WIDTH = 1
// Summary rows: header, event, next date missing, candle, lines note, projection, wick, wicks used, expansion, anchor,
// volatility, vol check expansion, vol check wick, bullish / bearish, skipped, data since, sample header = 17 (one spare).
// The "Data" note replaces the rows from projection on. The sample rows follow. Without a focus event only header, no
// upcoming event and next date missing show
const int TABLE_SUMMARY_ROWS = 18
const int TABLE_ROWS = TABLE_SUMMARY_ROWS + MAX_SAMPLE
const string DIGITS = "0123456789"
const string DATE_FORMAT = "yyyy-MM-dd"
const string DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm"
// Words in the level labels, "$NAME $candle $type ±$percent $price": wick for the dashed lines, expansion for the solid
// lines
const string LABEL_WICK = "wick"
const string LABEL_EXPANSION = "expansion"
// The anchor line's label says open, also before the release while the line is the preview at the previous close
const string LABEL_ANCHOR = "open"
const string SIGN_PLUS = "+"
const string SIGN_MINUS = "−"
const string SIGN_PLUS_MINUS = "±"
// Percentages always show 2 decimals. A value that formats to PCT_ZERO gets no sign, so there is no "−0.00%"
const string PCT_FORMAT = "0.00"
const string PCT_ZERO = "0.00"
// For a positive cutoff that would read 0.00%
const string PCT_FINE_FORMAT = "0.000"
const string ARROW_UP = "▲"
const string ARROW_DOWN = "▼"
const string SYMBOL_DOJI = "–"
// Marks a sample wick left out by the small-wick cut
const string MARK_CUT = "×"
const string TEXT_NONE = "none"
const string GROUP_LINES = "Lines"
const string GROUP_TABLE = "Table"
const string GROUP_ALL_EVENTS = "All events"
const string GROUP_STATS = "Statistics"
const string GROUP_EVENT_1 = "Event 1"
const string GROUP_EVENT_2 = "Event 2"
const string GROUP_EVENT_3 = "Event 3"
const string GROUP_EVENT_4 = "Event 4"
const string GROUP_EVENT_5 = "Event 5"
const string GROUP_EVENT_6 = "Event 6"
const string GROUP_EVENT_7 = "Event 7"
const string GROUP_EVENT_8 = "Event 8"
const string GROUP_EVENT_9 = "Event 9"
const string GROUP_EVENT_10 = "Event 10"
const string GROUP_EVENT_11 = "Event 11"
const string GROUP_EVENT_12 = "Event 12"
const string GROUP_EVENT_13 = "Event 13"
const string GROUP_EVENT_14 = "Event 14"
const string GROUP_EVENT_15 = "Event 15"
// Tooltips shared by the 15 event groups. TOOLTIP_DATES spells out MAX_SAMPLE (50): a const string can't format an int
const string TOOLTIP_EVENT = "Checkbox: measure and project this event. Name: shown in the labels, the table and the logs (empty: the group's title, such as Event 3). Time: the release time as HH:MM, 24h (8:30 works too), in the time zone under All events. The news candle is the candle that opens at this time. Daylight saving time is handled by the time zone."
const string TOOLTIP_DATES = "Release dates of this event as YYYY-MM-DD, separated by commas (new lines, semicolons and spaces work too, a trailing comma is ignored). List the past releases (they are measured) AND the upcoming one (it gets the lines). Add each new release date to the end as soon as it is announced; old dates can stay. The sample behind each projection is every earlier date that could be measured, the most recent 50 at most, so more past dates make a bigger sample. Order doesn't matter, duplicates are ignored. Example: 2026-09-11, 2026-10-15, 2026-11-13. An invalid entry stops the script with an error naming the event and the entry."
// Deeper orange than color.orange, so the dashed lines and their labels stay readable on light chart backgrounds
const color COLOR_WICK = color.new(#F57C00, 0)
const color COLOR_EXPANSION = color.new(color.blue, 0)
const color COLOR_ANCHOR = color.new(color.gray, 20)
const color COLOR_LABEL_BG = color.new(color.gray, 100)
// Text to the right of the line end, vertically centered on its price, without a visible background
const string LABEL_STYLE = label.style_label_left
const string LABEL_SIZE = size.small
// Knob at the start of the anchor line: a text glyph centered on the point, on a transparent background. A glyph rather than
// label.style_circle, whose minimum size is far too big for a hint. "•" is an even smaller alternative
const string KNOB_GLYPH = "●"
const string KNOB_STYLE = label.style_label_center
const string KNOB_SIZE = size.tiny
const color COLOR_TABLE_BG = color.new(color.gray, 85)
const color COLOR_TABLE_TEXT = color.gray
const string TABLE_TEXT_SIZE = size.small
// ————— Enums
// @enum Time zone of the event times.
enum EventTimeZone
newYork = "America/New_York"
london = "Europe/London"
berlin = "Europe/Berlin"
tokyo = "Asia/Tokyo"
utc = "UTC"
// @enum Statistic of the sample that sets the lines.
enum Statistic
median = "Median"
mean = "Mean"
maximum = "Maximum"
// @enum Table corner choices.
enum TablePosition
topRight = "Top right"
topLeft = "Top left"
bottomRight = "Bottom right"
bottomLeft = "Bottom left"
// ————— Inputs
int projectionsInput = input.int(DEFAULT_PROJECTIONS, "Projections to draw", minval = 1, maxval = MAX_PROJECTIONS, tooltip = "Total across all event types: the most recent events that get lines, newest first (the upcoming ones included once the chart reaches 1 news candle before them). Each projection takes 5 lines and up to 6 labels, so 20 at most. Past events only show while the chart history reaches them.", group = GROUP_LINES, display = display.none)
int extensionMinutesInput = input.int(0, "Extend after the news candle (minutes)", minval = 0, maxval = MAX_EXTENSION_MINUTES, tooltip = "The wick and expansion lines start 1 news candle before the event, the anchor line at the event time. All end when the news candle ends, plus this many minutes.", group = GROUP_LINES, display = display.none)
color wickColorInput = input.color(COLOR_WICK, "Wick (dashed)", inline = "wick", group = GROUP_LINES, display = display.none)
int wickWidthInput = input.int(DEFAULT_LINE_WIDTH, "", minval = MIN_LINE_WIDTH, maxval = MAX_LINE_WIDTH, tooltip = "Color and width of the two dashed lines: the typical wick, the leg against the news candle's direction (how far a bullish news candle dipped below its open, or a bearish one rose above it), drawn above and below the anchor.", inline = "wick", group = GROUP_LINES, display = display.none)
color expansionColorInput = input.color(COLOR_EXPANSION, "Expansion (solid)", inline = "expansion", group = GROUP_LINES, display = display.none)
int expansionWidthInput = input.int(DEFAULT_LINE_WIDTH, "", minval = MIN_LINE_WIDTH, maxval = MAX_LINE_WIDTH, tooltip = "Color and width of the two solid lines: the typical expansion, the leg in the news candle's direction (how far a bullish news candle rose above its open, or a bearish one fell below it), drawn above and below the anchor.", inline = "expansion", group = GROUP_LINES, display = display.none)
bool showAnchorInput = input.bool(true, "Show anchor line (dotted)", inline = "anchor", group = GROUP_LINES, display = display.none)
color anchorColorInput = input.color(COLOR_ANCHOR, "", tooltip = "The center of the projection: the close of the candle before the news candle until the event time, the news candle's open from then on. The line runs from the event time to the end of the other lines, also before the event time.", inline = "anchor", group = GROUP_LINES, display = display.none)
bool showLabelsInput = input.bool(true, "Show labels", tooltip = "Text at the right end of each line, with the event's name, the news candle length and the level, such as CPI 15m wick +0.21% 21345.25 (dashed lines) or CPI 15m expansion −0.45% 21250.50 (solid lines).", group = GROUP_LINES, display = display.none)
bool showTableInput = input.bool(false, "Show table", group = GROUP_TABLE, display = display.none)
bool showSampleRowsInput = input.bool(true, "Show sample events", tooltip = "One row per event behind the table's projection, newest first: date, news candle direction (▲ bullish, ▼ bearish, – doji), wick, expansion and the volatility index's previous close (vol). × marks a wick left out by Drop small wicks.", group = GROUP_TABLE, display = display.none)
TablePosition tablePositionInput = input.enum(TablePosition.topRight, "Position", group = GROUP_TABLE, display = display.none)
EventTimeZone timeZoneInput = input.enum(EventTimeZone.newYork, "Time zone", tooltip = "Time zone of all event times (America/New_York for US releases such as CPI at 8:30 and FOMC at 14:00). Daylight saving time is handled by the time zone.", group = GROUP_ALL_EVENTS, display = display.none)
int newsMinutesInput = input.int(15, "News candle length (minutes)", options = [5, 15, 30, 60], tooltip = "Length of the news candle, the same for all events. Every event time must fall on this candle grid: 10:00 and 14:00 fit all four lengths, 8:30 fits 5, 15 and 30, and 8:15 (ADP) and 9:45 (Flash PMI) fit only 5 and 15. Events off the grid show as misaligned and get no lines. Lines show on intraday charts whose timeframe divides this length.", group = GROUP_ALL_EVENTS, display = display.none)
Statistic statisticInput = input.enum(Statistic.median, "Statistic", tooltip = "How the sample is summarized, separately for the wick and the expansion. Median: the typical event. Mean: pulled up by outliers. Maximum: the largest swing in the sample.", group = GROUP_STATS, display = display.none)
bool cutSmallWicksInput = input.bool(true, "Drop small wicks below mean −", inline = "wickCut", group = GROUP_STATS, display = display.none)
float wickCutSigmaInput = input.float(DEFAULT_WICK_CUT_SIGMA, "× std dev (log)", minval = 0.0, step = WICK_CUT_SIGMA_STEP, tooltip = "Wicks of 0 (the candle ran one way) are always left out of the wick statistic. Of the rest, those more than k standard deviations below the mean on a log scale are left out too, so candles with barely any wick don't pull the dashed lines onto the anchor. k is the number set here. At 2 that is only wicks far smaller than the typical one (about 10×). Worked out per projected event from its own sample, and only with at least 3 positive wicks. The solid lines always use all sample events.", inline = "wickCut", group = GROUP_STATS, display = display.none)
bool volScaleInput = input.bool(false, "Scale by volatility index", inline = "vol", group = GROUP_STATS, display = display.none)
string volSymbolInput = input.symbol(VOL_SYMBOL, "", tooltip = "On: each past news candle's legs are measured per point of the volatility index's previous daily close, and projected with the index's previous close before the projected release, so the lines widen when the index is high. Use TVC:VIX for ES and SPX, CBOE:VXN for NQ. Off: plain percentages. The table's Vol check rows show whether scaling would have been closer on past releases.", inline = "vol", group = GROUP_STATS, display = display.none)
bool event1EnabledInput = input.bool(EVENT_1_ENABLED, "", inline = "event1", group = GROUP_EVENT_1, display = display.none)
string event1NameInput = input.string(EVENT_1_NAME, "", inline = "event1", group = GROUP_EVENT_1, display = display.none)
string event1TimeInput = input.string(EVENT_1_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event1", group = GROUP_EVENT_1, display = display.none)
string event1DatesInput = input.text_area(EVENT_1_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_1, display = display.none)
bool event2EnabledInput = input.bool(EVENT_2_ENABLED, "", inline = "event2", group = GROUP_EVENT_2, display = display.none)
string event2NameInput = input.string(EVENT_2_NAME, "", inline = "event2", group = GROUP_EVENT_2, display = display.none)
string event2TimeInput = input.string(EVENT_2_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event2", group = GROUP_EVENT_2, display = display.none)
string event2DatesInput = input.text_area(EVENT_2_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_2, display = display.none)
bool event3EnabledInput = input.bool(EVENT_3_ENABLED, "", inline = "event3", group = GROUP_EVENT_3, display = display.none)
string event3NameInput = input.string(EVENT_3_NAME, "", inline = "event3", group = GROUP_EVENT_3, display = display.none)
string event3TimeInput = input.string(EVENT_3_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event3", group = GROUP_EVENT_3, display = display.none)
string event3DatesInput = input.text_area(EVENT_3_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_3, display = display.none)
bool event4EnabledInput = input.bool(EVENT_4_ENABLED, "", inline = "event4", group = GROUP_EVENT_4, display = display.none)
string event4NameInput = input.string(EVENT_4_NAME, "", inline = "event4", group = GROUP_EVENT_4, display = display.none)
string event4TimeInput = input.string(EVENT_4_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event4", group = GROUP_EVENT_4, display = display.none)
string event4DatesInput = input.text_area(EVENT_4_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_4, display = display.none)
bool event5EnabledInput = input.bool(EVENT_5_ENABLED, "", inline = "event5", group = GROUP_EVENT_5, display = display.none)
string event5NameInput = input.string(EVENT_5_NAME, "", inline = "event5", group = GROUP_EVENT_5, display = display.none)
string event5TimeInput = input.string(EVENT_5_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event5", group = GROUP_EVENT_5, display = display.none)
string event5DatesInput = input.text_area(EVENT_5_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_5, display = display.none)
bool event6EnabledInput = input.bool(EVENT_6_ENABLED, "", inline = "event6", group = GROUP_EVENT_6, display = display.none)
string event6NameInput = input.string(EVENT_6_NAME, "", inline = "event6", group = GROUP_EVENT_6, display = display.none)
string event6TimeInput = input.string(EVENT_6_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event6", group = GROUP_EVENT_6, display = display.none)
string event6DatesInput = input.text_area(EVENT_6_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_6, display = display.none)
bool event7EnabledInput = input.bool(EVENT_7_ENABLED, "", inline = "event7", group = GROUP_EVENT_7, display = display.none)
string event7NameInput = input.string(EVENT_7_NAME, "", inline = "event7", group = GROUP_EVENT_7, display = display.none)
string event7TimeInput = input.string(EVENT_7_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event7", group = GROUP_EVENT_7, display = display.none)
string event7DatesInput = input.text_area(EVENT_7_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_7, display = display.none)
bool event8EnabledInput = input.bool(EVENT_8_ENABLED, "", inline = "event8", group = GROUP_EVENT_8, display = display.none)
string event8NameInput = input.string(EVENT_8_NAME, "", inline = "event8", group = GROUP_EVENT_8, display = display.none)
string event8TimeInput = input.string(EVENT_8_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event8", group = GROUP_EVENT_8, display = display.none)
string event8DatesInput = input.text_area(EVENT_8_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_8, display = display.none)
bool event9EnabledInput = input.bool(EVENT_9_ENABLED, "", inline = "event9", group = GROUP_EVENT_9, display = display.none)
string event9NameInput = input.string(EVENT_9_NAME, "", inline = "event9", group = GROUP_EVENT_9, display = display.none)
string event9TimeInput = input.string(EVENT_9_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event9", group = GROUP_EVENT_9, display = display.none)
string event9DatesInput = input.text_area(EVENT_9_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_9, display = display.none)
bool event10EnabledInput = input.bool(EVENT_10_ENABLED, "", inline = "event10", group = GROUP_EVENT_10, display = display.none)
string event10NameInput = input.string(EVENT_10_NAME, "", inline = "event10", group = GROUP_EVENT_10, display = display.none)
string event10TimeInput = input.string(EVENT_10_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event10", group = GROUP_EVENT_10, display = display.none)
string event10DatesInput = input.text_area(EVENT_10_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_10, display = display.none)
bool event11EnabledInput = input.bool(EVENT_11_ENABLED, "", inline = "event11", group = GROUP_EVENT_11, display = display.none)
string event11NameInput = input.string(EVENT_11_NAME, "", inline = "event11", group = GROUP_EVENT_11, display = display.none)
string event11TimeInput = input.string(EVENT_11_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event11", group = GROUP_EVENT_11, display = display.none)
string event11DatesInput = input.text_area(EVENT_11_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_11, display = display.none)
bool event12EnabledInput = input.bool(EVENT_12_ENABLED, "", inline = "event12", group = GROUP_EVENT_12, display = display.none)
string event12NameInput = input.string(EVENT_12_NAME, "", inline = "event12", group = GROUP_EVENT_12, display = display.none)
string event12TimeInput = input.string(EVENT_12_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event12", group = GROUP_EVENT_12, display = display.none)
string event12DatesInput = input.text_area(EVENT_12_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_12, display = display.none)
bool event13EnabledInput = input.bool(EVENT_13_ENABLED, "", inline = "event13", group = GROUP_EVENT_13, display = display.none)
string event13NameInput = input.string(EVENT_13_NAME, "", inline = "event13", group = GROUP_EVENT_13, display = display.none)
string event13TimeInput = input.string(EVENT_13_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event13", group = GROUP_EVENT_13, display = display.none)
string event13DatesInput = input.text_area(EVENT_13_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_13, display = display.none)
bool event14EnabledInput = input.bool(EVENT_14_ENABLED, "", inline = "event14", group = GROUP_EVENT_14, display = display.none)
string event14NameInput = input.string(EVENT_14_NAME, "", inline = "event14", group = GROUP_EVENT_14, display = display.none)
string event14TimeInput = input.string(EVENT_14_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event14", group = GROUP_EVENT_14, display = display.none)
string event14DatesInput = input.text_area(EVENT_14_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_14, display = display.none)
bool event15EnabledInput = input.bool(EVENT_15_ENABLED, "", inline = "event15", group = GROUP_EVENT_15, display = display.none)
string event15NameInput = input.string(EVENT_15_NAME, "", inline = "event15", group = GROUP_EVENT_15, display = display.none)
string event15TimeInput = input.string(EVENT_15_TIME, "at", tooltip = TOOLTIP_EVENT, inline = "event15", group = GROUP_EVENT_15, display = display.none)
string event15DatesInput = input.text_area(EVENT_15_DATES, "Dates", tooltip = TOOLTIP_DATES, group = GROUP_EVENT_15, display = display.none)
// ————— Type Definitions
// @type An enabled event type (one Event n group of the settings) and its events.
// @field slot (int) Slot number, 1 to 15.
// @field name (string) Name in the labels, the table and the logs.
// @field times (array<int>) Event times in ms, ascending, unique.
// @field indices (array<int>) Parallel to times: the index of each event in the union of all event times (eventTimes), so
// ascending too. Only filled on the chart (indexIn()).
type EventType
int slot
string name
array<int> times
array<int> indices
// @type Measurements of all event times on the news-candle timeframe, indexed like the union of all event types' times.
// Holds only arrays of fundamental types and ints, so request.security() can return it.
// @field statuses (array<int>) STATUS_* code per event time.
// @field opens (array<float>) Open of the news candle, na unless measured.
// @field highs (array<float>) High of the news candle, na unless measured.
// @field lows (array<float>) Low of the news candle, na unless measured.
// @field closes (array<float>) Close of the news candle, na unless measured.
// @field vols (array<float>) vol of the event: the volatility index's previous daily close on the bar that ends at the event
// time (previousVolClose()). na unless measured; na or <= 0 is unusable (usableVol()).
// @field contextStart (int) Open time of the first bar of the news-candle request.
type EventData
array<int> statuses
array<float> opens
array<float> highs
array<float> lows
array<float> closes
array<float> vols
int contextStart = na
// @type Walk-forward statistics behind one projected event. With scaling the statistics are of r = leg / vol, and the
// percentages below are already multiplied by the projected event's vol.
// @field wickPct (float) Statistic of the wicks that survived the small-wick cut in percent, 0 when none survived (all
// were 0), na when the sample is empty.
// @field expansionPct (float) Statistic of all expansions of the sample in percent, na when the sample is empty.
// @field sample (array<int>) Union indices of the sample events (all of the projected event's type), newest first.
// @field wickCut (array<bool>) Parallel to sample: true when the event's wick was left out of wickPct (a wick of 0, or
// one below wickCutoff).
// @field wickCutoff (float) Positive wicks below it were left out, in percent (with scaling: the cutoff on r times the
// projected event's vol). na when the cut is off or fewer than MIN_CUT_SAMPLE wicks are positive.
// @field noWick (int) Sample events with a wick of 0 (the candle ran one way); left out of wickPct while the cut is on.
// @field scaled (bool) True when the volatility scaling was applied, false for plain statistics (also on fallback).
// @field wicksUsed (int) Sample events whose wick is in wickPct.
// @field bullish (int) Sample events whose news candle closed above its open.
// @field bearish (int) Sample events whose news candle closed below its open.
// @field doji (int) Sample events whose news candle closed at its open.
// @field noData (int) Earlier events of the same type skipped: no news candle in the data.
// @field misaligned (int) Earlier events of the same type skipped: a candle straddles the event time.
type SampleStats
float wickPct = na
float expansionPct = na
array<int> sample
array<bool> wickCut
float wickCutoff = na
int noWick = 0
bool scaled = false
int wicksUsed = 0
int bullish = 0
int bearish = 0
int doji = 0
int noData = 0
int misaligned = 0
// @type Walk-forward comparison of plain and scaled projections on the past events of one type (volCheckOf()).
// @field withVol (int) Earlier measured events of the type with a usable vol. 0 means no vol data.
// @field scored (int) Events scored: with a usable vol and at least MIN_CHECK_SAMPLE earlier events with vol.
// @field expansionErrPlain (float) Median absolute error of the plain expansion prediction in percent, na when none scored.
// @field expansionErrScaled (float) Same for the scaled expansion prediction.
// @field expansionCloser (int) Scored events where the scaled expansion prediction was strictly closer.
// @field wickErrPlain (float) Median absolute error of the plain wick prediction in percent, na when none scored.
// @field wickErrScaled (float) Same for the scaled wick prediction.
// @field wickCloser (int) Scored events where the scaled wick prediction was strictly closer.
type VolCheck
int withVol = 0
int scored = 0
float expansionErrPlain = na
float expansionErrScaled = na
int expansionCloser = 0
float wickErrPlain = na
float wickErrScaled = na
int wickCloser = 0
// @type Drawings of one projected event, kept while it is among the most recent drawn events.
// @field wickUpLine (line) Anchor plus the wick.
// @field wickDownLine (line) Anchor minus the wick.
// @field expansionUpLine (line) Anchor plus the expansion.
// @field expansionDownLine (line) Anchor minus the expansion.
// @field anchorLine (line) The anchor, na when switched off.
// @field wickUpLabel (label) Label of wickUpLine, na when labels are off.
// @field wickDownLabel (label) Label of wickDownLine.
// @field expansionUpLabel (label) Label of expansionUpLine.
// @field expansionDownLabel (label) Label of expansionDownLine.
// @field anchorLabel (label) Label of anchorLine.
// @field anchorKnob (label) Dot at the start of anchorLine (the event time) while the release is ahead, na otherwise.
type Projection
line wickUpLine
line wickDownLine
line expansionUpLine
line expansionDownLine
line anchorLine
label wickUpLabel
label wickDownLabel
label expansionUpLabel
label expansionDownLabel
label anchorLabel
label anchorKnob
// ————— Function Declarations
// @function Maps the time zone input to its IANA name.
// @param option (EventTimeZone) Selected time zone.
// @returns (string) Time zone name, such as "America/New_York".
timeZoneOf(EventTimeZone option) =>
switch option
EventTimeZone.london => TIMEZONE_LONDON
EventTimeZone.berlin => TIMEZONE_BERLIN
EventTimeZone.tokyo => TIMEZONE_TOKYO
EventTimeZone.utc => TIMEZONE_UTC
=> TIMEZONE_NY
// @function Maps the position input to a table position.
// @param option (TablePosition) Selected corner.
// @returns (string) A position.* constant.
tablePositionOf(TablePosition option) =>
switch option
TablePosition.topLeft => position.top_left
TablePosition.bottomRight => position.bottom_right
TablePosition.bottomLeft => position.bottom_left
=> position.top_right
// @function Name of the selected statistic.
// @returns (string) "Median", "Mean" or "Maximum".
statisticName() =>
switch statisticInput
Statistic.mean => "Mean"
Statistic.maximum => "Maximum"
=> "Median"
// @function Checks that a string is not empty and only holds the digits 0 to 9.
// @param value (string) Text to check.
// @returns (bool) True for digits only.
isDigits(string value) =>
int length = str.length(value)
bool result = length > 0
if result
for i = 0 to length - 1
if not str.contains(DIGITS, str.substring(value, i, i + 1))
result := false
break
result
// @function Parses the time of an event type, or stops the script with an error that names the slot.
// @param timeText (string) Time input, "HH:MM" or "H:MM", 24h.
// @param slotText (string) The slot for the error, such as "Event 3 (FOMC)".
// @returns ([int, int]) Hour (0 to 23) and minute (0 to 59).
eventClockOf(string timeText, string slotText) =>
array<string> parts = str.split(str.trim(timeText), TIME_SEPARATOR)
bool valid = parts.size() == 2
if valid
valid := str.length(parts.get(0)) <= 2 and str.length(parts.get(1)) == 2 and isDigits(parts.get(0)) and isDigits(parts.get(1))
int eventHour = na
int eventMinute = na
if valid
eventHour := int(str.tonumber(parts.get(0)))
eventMinute := int(str.tonumber(parts.get(1)))
valid := eventHour <= MAX_EVENT_HOUR and eventMinute <= MAX_EVENT_MINUTE
if not valid
runtime.error(slotText + ": time \"" + timeText + "\" is not HH:MM (24h, for example 08:30).")
[eventHour, eventMinute]
// @function Converts one YYYY-MM-DD token into the event time on that date, or stops the script with an error that names the
// slot and the token. A date that doesn't exist (2026-02-30) is rejected: timestamp() would roll it into the next month.
// @param token (string) Date token, trimmed.
// @param tz (string) Time zone of the event time.
// @param eventHour (int) Hour of the event time, 0 to 23.
// @param eventMinute (int) Minute of the event time, 0 to 59.
// @param slotText (string) The slot for the error, such as "Event 3 (FOMC)".
// @returns (int) UNIX time in ms of the event on that date.
eventTimeOf(string token, string tz, int eventHour, int eventMinute, string slotText) =>
array<string> parts = str.split(token, "-")
bool valid = parts.size() == 3
if valid
valid := str.length(parts.get(0)) == 4 and str.length(parts.get(1)) <= 2 and str.length(parts.get(2)) <= 2 and isDigits(parts.get(0)) and isDigits(parts.get(1)) and isDigits(parts.get(2))
int result = na
if valid
int yearPart = int(str.tonumber(parts.get(0)))
int monthPart = int(str.tonumber(parts.get(1)))
int dayPart = int(str.tonumber(parts.get(2)))
int dayStart = timestamp(tz, yearPart, monthPart, dayPart, 0, 0)
valid := year(dayStart, tz) == yearPart and month(dayStart, tz) == monthPart and dayofmonth(dayStart, tz) == dayPart
result := timestamp(tz, yearPart, monthPart, dayPart, eventHour, eventMinute)
if not valid
runtime.error(slotText + ": date \"" + token + "\" is not YYYY-MM-DD (for example 2026-11-13).")
result
// @function Sorts times and drops the duplicates.
// @param values (array<int>) Times in ms, sorted in place.
// @returns (array<int>) A new array of the times, ascending, unique.
uniqueAscending(array<int> values) =>
values.sort(order.ascending)
array<int> result = array.new<int>()
for t in values
if result.size() == 0 or t != result.last()
result.push(t)
result
// @function Parses the dates input of an event type into its event times. Empty tokens (a trailing comma or space) are
// skipped.
// @param datesText (string) Dates input: YYYY-MM-DD tokens separated by new lines, commas, semicolons or spaces.
// @param tz (string) Time zone of the event time.
// @param eventHour (int) Hour of the event time, 0 to 23.
// @param eventMinute (int) Minute of the event time, 0 to 59.
// @param slotText (string) The slot for errors, such as "Event 3 (FOMC)".
// @returns (array<int>) Event times in ms, ascending, unique. Empty when no dates are listed.
parseEventTimes(string datesText, string tz, int eventHour, int eventMinute, string slotText) =>
// New lines, commas and semicolons become spaces. str.trim() removes a leftover carriage return or tab at a token's end
string normalized = str.replace_all(str.replace_all(str.replace_all(datesText, "\n", " "), ",", " "), ";", " ")
array<int> times = array.new<int>()
for token in str.split(normalized, " ")
string trimmed = str.trim(token)
if str.length(trimmed) > 0
times.push(eventTimeOf(trimmed, tz, eventHour, eventMinute, slotText))
uniqueAscending(times)
// @function Builds an enabled event type from its inputs. Only called for enabled slots, so a typo in a disabled one can't
// stop the script. An invalid time or date stops it with an error that names the slot. No dates is not an error, the type
// just has no events.
// @param slot (int) Slot number, 1 to 15.
// @param nameText (string) Name input, empty for "Event n".
// @param timeText (string) Time input, "HH:MM" or "H:MM", 24h.
// @param datesText (string) Dates input, may be empty.
// @param tz (string) Time zone of the event time.
// @returns (EventType) The event type. Its indices stay empty until indexIn().
eventTypeOf(int slot, string nameText, string timeText, string datesText, string tz) =>
string slotName = TEXT_EVENT + str.tostring(slot)
string trimmedName = str.trim(nameText)
string slotText = trimmedName == "" ? slotName : slotName + " (" + trimmedName + ")"
[eventHour, eventMinute] = eventClockOf(timeText, slotText)
array<int> times = parseEventTimes(datesText, tz, eventHour, eventMinute, slotText)
EventType.new(slot, trimmedName == "" ? slotName : trimmedName, times, array.new<int>())
// @function Builds the enabled event types from the inputs, lowest slot first. Runs on the chart and inside the measuring
// request (measureEvents()), so both parse the same inputs the same way.
// @returns (array<EventType>) Enabled event types. Empty when none is enabled.
setUpEventTypes() =>
string tz = timeZoneOf(timeZoneInput)
array<EventType> result = array.new<EventType>()
if event1EnabledInput
result.push(eventTypeOf(1, event1NameInput, event1TimeInput, event1DatesInput, tz))
if event2EnabledInput
result.push(eventTypeOf(2, event2NameInput, event2TimeInput, event2DatesInput, tz))
if event3EnabledInput
result.push(eventTypeOf(3, event3NameInput, event3TimeInput, event3DatesInput, tz))
if event4EnabledInput
result.push(eventTypeOf(4, event4NameInput, event4TimeInput, event4DatesInput, tz))
if event5EnabledInput
result.push(eventTypeOf(5, event5NameInput, event5TimeInput, event5DatesInput, tz))
if event6EnabledInput
result.push(eventTypeOf(6, event6NameInput, event6TimeInput, event6DatesInput, tz))
if event7EnabledInput
result.push(eventTypeOf(7, event7NameInput, event7TimeInput, event7DatesInput, tz))
if event8EnabledInput
result.push(eventTypeOf(8, event8NameInput, event8TimeInput, event8DatesInput, tz))
if event9EnabledInput
result.push(eventTypeOf(9, event9NameInput, event9TimeInput, event9DatesInput, tz))
if event10EnabledInput
result.push(eventTypeOf(10, event10NameInput, event10TimeInput, event10DatesInput, tz))
if event11EnabledInput
result.push(eventTypeOf(11, event11NameInput, event11TimeInput, event11DatesInput, tz))
if event12EnabledInput
result.push(eventTypeOf(12, event12NameInput, event12TimeInput, event12DatesInput, tz))
if event13EnabledInput
result.push(eventTypeOf(13, event13NameInput, event13TimeInput, event13DatesInput, tz))
if event14EnabledInput
result.push(eventTypeOf(14, event14NameInput, event14TimeInput, event14DatesInput, tz))
if event15EnabledInput
result.push(eventTypeOf(15, event15NameInput, event15TimeInput, event15DatesInput, tz))
result
// @function Union of the event times of all event types. The measurement depends only on the event time, so the request
// measures each time once. Called on the chart and inside measureEvents(), both times on setUpEventTypes(), so both get the
// same array and the indices into it match the payload.
// @param typeList (array<EventType>) Enabled event types.
// @returns (array<int>) Event times in ms, ascending, unique.
unionTimesOf(array<EventType> typeList) =>
array<int> merged = array.new<int>()
for eventType in typeList
merged.concat(eventType.times)
uniqueAscending(merged)
// @function Fills the indices of an event type: the index of each of its events in the union. Chart side only, the request
// needs the union alone. Clears the indices first, so running it again can't fill them twice.
// @param this (EventType) The event type.
// @param unionTimes (array<int>) Union of all event times, ascending (unionTimesOf()).
// @returns (EventType) The event type.
method indexIn(EventType this, array<int> unionTimes) =>
this.indices.clear()
for t in this.times
this.indices.push(unionTimes.binary_search(t))
this
// @function vol: the volatility index's previous daily close, as of the current bar. The ONE definition, called inside the
// measuring request (past events) and on the chart (projected events), so both sides mean the same thing. close[1] with
// lookahead on is the repo's non-repainting form: the previous day's close is final when the day starts, so it never
// holds the current day's close, on history and realtime alike. Before the index's daily bar opens (an 8:30 release when
// that bar starts later) the latest daily bar is the day before's, so the value is one day older, on both sides alike.
// Exception: the payload takes vol on the news-timeframe bar that opens at T - W, the chart on its last bar before T. If the
// index's daily bar opens in between (a 60m news candle, a 10:00 event and an index opening at 9:30), the projected
// event's vol is one day newer than its sample's. Not possible with the default 15m news candle.
// Requested whether scaling is on or off: the table's vol check needs it either way. Call at the top level only.
// @returns (float) The previous close, na for an invalid symbol or before the index's data starts.
previousVolClose() =>
request.security(volSymbolInput, VOL_TIMEFRAME, close[1], lookahead = barmerge.lookahead_on, ignore_invalid_symbol = true, calc_bars_count = VOL_DAILY_BARS)
// @function Checks that a vol can scale: a positive number.
// @param vol (float) A vol, may be na.
// @returns (bool) False for na or <= 0.
usableVol(float vol) =>
not na(vol) and vol > 0.0
// @function Short name of a symbol for the table: the part after the exchange prefix. syminfo.ticker only describes the
// chart's own symbol.
// @param symbol (string) Symbol such as "TVC:VIX".
// @returns (string) Name such as "VIX".
shortSymbolOf(string symbol) =>
array<string> parts = str.split(symbol, ":")
parts.size() > 0 ? parts.last() : symbol
// @function Measures every event time of the union on the news-candle timeframe. Only called as the expression of one
// request.security() on that timeframe, which runs it on every bar of it. The [1] reference sits at the top level of the
// function, so it runs on every bar too. Per event time the status becomes:
// no data no bar opens at T (holiday, closed market, before the first bar of this request)
// misaligned a bar straddles T (the event time isn't on the news-candle grid, such as 8:30 with 60m)
// ok a bar opens at T: the news candle's open, high, low and close, and vol are stored
// vol comes from a nested request (previousVolClose()) at the top level, so it runs on every bar; the stored value is the one
// on the bar that ends at T, before the news candle.
// Doesn't reference timeframe.*: it would be evaluated in the requested context, not on the chart.
// @returns (EventData) The measurements, indexed like the union, on the request's last bar (live use) and on 2 bars per
// event time T (history and Bar Replay): the bar PAYLOAD_WINDOW_CANDLES news candles before T and the T bar. na on all
// other bars. Each returned payload is assumed to be a copy of the 6 arrays, one entry per union time each. On every bar
// that would be up to NEWS_CONTEXT_BARS copies. Here it is at most 2 copies per union time, fewer where nearby events
// share a bar (each bar returns at most once): with 12 types of 26 dates, about 312 times x 2 copies x 6 arrays x 312
// entries = about 1.2M array elements.
measureEvents() =>
// The same union as on the chart: same inputs, same functions, so the indices match
var array<int> requestTimes = unionTimesOf(setUpEventTypes())
var int requestCount = requestTimes.size()
var EventData data = EventData.new(array.new<int>(requestCount, STATUS_PENDING), array.new<float>(requestCount, na), array.new<float>(requestCount, na), array.new<float>(requestCount, na), array.new<float>(requestCount, na), array.new<float>(requestCount, na), time)
var int nextIndex = 0
float volClose = previousVolClose()
float previousVol = volClose[1]
// Events before this bar that no bar opened at
while nextIndex < requestCount and requestTimes.get(nextIndex) < time
data.statuses.set(nextIndex, STATUS_NO_DATA)
nextIndex += 1
// Payload bar of the next event time T: it opens in [T - 2W, T - W) or at T. Checked before the event bar steps past T
// below. A bar that straddles a misaligned T isn't one: that event gets no lines
int newsLengthMs = newsMinutesInput * MS_PER_MINUTE
int gapToNext = nextIndex < requestCount ? requestTimes.get(nextIndex) - time : na
bool payloadBar = not na(gapToNext) and (gapToNext == 0 or (gapToNext > newsLengthMs and gapToNext <= PAYLOAD_WINDOW_CANDLES * newsLengthMs))
if nextIndex < requestCount
int eventTime = requestTimes.get(nextIndex)
if eventTime == time
// The legs are percent of the open, so it must be positive
if na(open) or open <= 0.0
data.statuses.set(nextIndex, STATUS_NO_DATA)
else
data.statuses.set(nextIndex, STATUS_OK)
data.opens.set(nextIndex, open)
data.highs.set(nextIndex, high)
data.lows.set(nextIndex, low)
data.closes.set(nextIndex, close)
data.vols.set(nextIndex, previousVol)
nextIndex += 1
else if eventTime < time_close
data.statuses.set(nextIndex, STATUS_MISALIGNED)
nextIndex += 1
// After this bar's measurement, so the payload of the event bar holds the event itself
EventData result = na
if barstate.islast or payloadBar
result := data
result
// @function Direction of a candle. This is the rule that picks the wick (legsOf()): the wick is the leg against the
// candle's direction. Swap the expression here to change the rule everywhere.
// @param openPrice (float) Open of the candle.
// @param closePrice (float) Close of the candle.
// @returns (int) CANDLE_BULLISH (1) for close > open, CANDLE_BEARISH (-1) for close < open, CANDLE_DOJI (0) for
// close = open.
candleDirection(float openPrice, float closePrice) =>
closePrice > openPrice ? CANDLE_BULLISH : closePrice < openPrice ? CANDLE_BEARISH : CANDLE_DOJI
// @function Direction of a measured event's news candle.
// @param data (EventData) Measurements.
// @param index (int) Union index of a measured event (status ok).
// @returns (int) CANDLE_BULLISH, CANDLE_BEARISH or CANDLE_DOJI.
directionOf(EventData data, int index) =>
candleDirection(data.opens.get(index), data.closes.get(index))
// @function Wick and expansion of a measured event, in percent of the news candle's open. The one place the legs are
// defined: projections, sample rows, logs and the vol check all use it. The news candle's direction picks the wick:
// bullish => the down leg (the dip below the open), bearish => the up leg (the rise above the open), doji => the smaller
// leg. On a doji whose legs are equal the down leg is the wick; both numbers are the same then, only the side differs.
// @param data (EventData) Measurements.
// @param index (int) Union index of a measured event (status ok).
// @returns ([float, float, bool]) Wick and expansion in percent, both >= 0, and true when the wick is the up leg.
legsOf(EventData data, int index) =>
float openPrice = data.opens.get(index)
float upPct = math.max(data.highs.get(index) - openPrice, 0.0) / openPrice * 100.0
float downPct = math.max(openPrice - data.lows.get(index), 0.0) / openPrice * 100.0
int direction = directionOf(data, index)
bool wickUp = direction == CANDLE_BEARISH or (direction == CANDLE_DOJI and upPct < downPct)
[wickUp ? upPct : downPct, wickUp ? downPct : upPct, wickUp]
// @function Summarizes a sample with the selected statistic.
// @param values (array<float>) Values, not empty.
// @returns (float) Median, mean or maximum.
statisticOf(array<float> values) =>
switch statisticInput
Statistic.mean => values.avg()
Statistic.maximum => values.max()
=> values.median()
// @function Small-wick cut, the cutoff on a log scale: exp(mL - k * sL) with mL and sL the mean and the sample standard
// deviation of the logs of the positive wicks (k from the settings). Wicks are >= 0 and right-skewed; on a linear scale
// mean - k * sd almost always lies below 0 and removes nothing, on the log scale they are roughly symmetric, so the cutoff
// marks real low-end outliers. Wicks of 0 have no log: isCutWick() drops them separately. Swap the rule here (a fixed
// minimum, a percentile) to change it everywhere.
// @param wicks (array<float>) Wicks of one walk-forward sample, all >= 0: in percent, or as r = wick / vol when scaled.
// @returns (float) The cutoff in the same units, never above the largest wick. na when the cut is off or fewer than
// MIN_CUT_SAMPLE wicks are positive.
wickCutoffOf(array<float> wicks) =>
float cutoff = na
if cutSmallWicksInput
array<float> logWicks = array.new<float>()
for wick in wicks
if wick > 0.0
logWicks.push(math.log(wick))
if logWicks.size() >= MIN_CUT_SAMPLE
// Sample standard deviation (biased = false divides by n - 1): the wicks are a sample of the event's history
cutoff := math.exp(logWicks.avg() - wickCutSigmaInput * logWicks.stdev(false))
// For k >= 0 the largest wick is >= the cutoff anyway. min() keeps it when all wicks are equal and avg() or
// exp(log()) rounds up by a hair, which would otherwise drop every wick. The wick itself, not exp(log(max)),
// which could round the same way
cutoff := math.min(cutoff, wicks.max())
cutoff
// @function Whether the small-wick cut leaves a wick out of the wick statistic: with the cut on, a wick of 0 (the
// candle ran one way) always, and any wick below the cutoff. With the cut off, none. The one rule for the projections,
// the × marks and the vol check.
// @param wick (float) A wick, >= 0, in the sample's units.
// @param cutoff (float) wickCutoffOf() of its sample, may be na.
// @returns (bool) True when the wick is left out.
isCutWick(float wick, float cutoff) =>
cutSmallWicksInput and (wick <= 0.0 or (not na(cutoff) and wick < cutoff))
// @function Wicks that survive the small-wick cut (isCutWick()).
// @param wicks (array<float>) Wicks of one sample, in percent or as r = wick / vol.
// @param cutoff (float) wickCutoffOf() of the same wicks, may be na.
// @returns (array<float>) The kept wicks, in their order. Empty when all were 0.
keptWicksOf(array<float> wicks, float cutoff) =>
array<float> kept = array.new<float>()
for wick in wicks
if not isCutWick(wick, cutoff)
kept.push(wick)
kept
// @function Wick statistic of a sample after the small-wick cut. Shared by the projections and the vol check, so both
// cut the same way.
// @param wicks (array<float>) Wicks of one sample, not empty, in percent or as r = wick / vol.
// @param cutoff (float) wickCutoffOf() of the same wicks, may be na.
// @returns (float) The statistic of the kept wicks in the same units, 0 when none is kept (all were 0): the dashed lines
// then sit at the anchor.
wickStatisticOf(array<float> wicks, float cutoff) =>
array<float> kept = keptWicksOf(wicks, cutoff)
kept.size() > 0 ? statisticOf(kept) : 0.0
// @function Walk-forward sample of an event, plain or scaled, without fallback (sampleStats() decides).
// @param data (EventData) Measurements, indexed like the union.
// @param eventType (EventType) Type of the projected event, indexed (indexIn()).
// @param ordinal (int) Place of the projected event among the type's own events (times and indices).
// @param scaleVol (float) Usable vol of the projected event to scale with, na for plain.
// @returns (SampleStats) The statistics in percent. wickPct and expansionPct are na when the sample is empty.
collectSample(EventData data, EventType eventType, int ordinal, float scaleVol) =>
bool scaling = not na(scaleVol)
SampleStats stats = SampleStats.new(sample = array.new<int>(), wickCut = array.new<bool>(), scaled = scaling)
// Legs in percent (plain) or r = leg / vol of the sample event (scaled)
array<float> wicks = array.new<float>()
array<float> expansions = array.new<float>()
int earlier = ordinal - 1
while earlier >= 0
int j = eventType.indices.get(earlier)
int eventStatus = data.statuses.get(j)
if eventStatus == STATUS_OK
float sampleVol = data.vols.get(j)
// With scaling, an event without a usable vol is left out of the sample
if stats.sample.size() < MAX_SAMPLE and (not scaling or usableVol(sampleVol))
[wickPct, expansionPct, wickUp] = legsOf(data, j)
float divisor = scaling ? sampleVol : 1.0
wicks.push(wickPct / divisor)
expansions.push(expansionPct / divisor)
stats.sample.push(j)
int direction = directionOf(data, j)
if direction == CANDLE_BULLISH
stats.bullish += 1
else if direction == CANDLE_BEARISH
stats.bearish += 1
else
stats.doji += 1
else if eventStatus == STATUS_NO_DATA
stats.noData += 1
else if eventStatus == STATUS_MISALIGNED
stats.misaligned += 1
earlier -= 1
if wicks.size() > 0
// The cut works in the sample's own units (percent or r), then everything goes back to percent: with scaling,
// times the projected event's vol
float cutoff = wickCutoffOf(wicks)
for wick in wicks
bool cut = isCutWick(wick, cutoff)
stats.wickCut.push(cut)
if not cut
stats.wicksUsed += 1
if wick <= 0.0
stats.noWick += 1
float factor = scaling ? scaleVol : 1.0
stats.wickCutoff := cutoff * factor
stats.wickPct := wickStatisticOf(wicks, cutoff) * factor
stats.expansionPct := statisticOf(expansions) * factor
stats
// @function Walk-forward sample of an event: all valid events of the same type before it, newest first, the most recent
// MAX_SAMPLE at most, and its statistics. Steps back through the type's own events only, so other types never enter the
// sample. The wick statistic leaves out the wicks below wickCutoffOf() of the sample's wicks, the expansion statistic
// uses the whole sample. Counts every earlier event of the type that was skipped, also beyond the MAX_SAMPLE used ones.
// With a usable scaleVol the projection is scaled: the statistics of r = leg / vol over the sample events that have a
// vol, times scaleVol. It falls back to plain when scaleVol is unusable or no sample event has a vol: plain lines, never
// none. The one place both the lines and the table get their statistics from.
// @param data (EventData) Measurements, indexed like the union.
// @param eventType (EventType) Type of the projected event, indexed (indexIn()).
// @param ordinal (int) Place of the projected event among the type's own events (times and indices).
// @param scaleVol (float) vol of the projected event to scale with, na for plain.
// @returns (SampleStats) The statistics in percent; scaled tells whether scaling was applied. wickPct and expansionPct are na
// when the sample is empty.
sampleStats(EventData data, EventType eventType, int ordinal, float scaleVol) =>
SampleStats stats = collectSample(data, eventType, ordinal, usableVol(scaleVol) ? scaleVol : na)
if stats.scaled and stats.sample.size() == 0
SampleStats plain = collectSample(data, eventType, ordinal, na)
if plain.sample.size() > 0
stats := plain
stats
// @function Vol check: walk-forward test of plain against scaled projections on the past events of one type. Every
// measured event j before the given one with a usable vol is predicted from its own sample S_j (the earlier measured
// events of the type with a usable vol, newest first, at most MAX_SAMPLE): plain as the statistic of the legs, scaled as
// the statistic of r = leg / vol times vol_j, each with its small-wick cut. Both use exactly S_j, so the comparison is like
// for like; j is scored when S_j has at least MIN_CHECK_SAMPLE events. Error: |prediction - actual leg| in percent.
// @param data (EventData) Measurements.
// @param eventType (EventType) Type of the table's event, indexed (indexIn()).
// @param ordinal (int) Place of the table's event among the type's events: only the events before it are scored.
// @returns (VolCheck) The comparison.
volCheckOf(EventData data, EventType eventType, int ordinal) =>
VolCheck result = VolCheck.new()
array<float> expansionPlainErrors = array.new<float>()
array<float> expansionScaledErrors = array.new<float>()
array<float> wickPlainErrors = array.new<float>()
array<float> wickScaledErrors = array.new<float>()
// while, not for: at ordinal 0 a for loop up to ordinal - 1 would count down to -1
int scoredOrdinal = 0
while scoredOrdinal < ordinal
int j = eventType.indices.get(scoredOrdinal)
float scoredVol = data.vols.get(j)
if data.statuses.get(j) == STATUS_OK and usableVol(scoredVol)
result.withVol += 1
// S_j in one walk, plain and scaled side by side
array<float> plainWicks = array.new<float>()
array<float> plainExpansions = array.new<float>()
array<float> scaledWicks = array.new<float>()
array<float> scaledExpansions = array.new<float>()
int earlier = scoredOrdinal - 1
while earlier >= 0 and plainWicks.size() < MAX_SAMPLE
int i = eventType.indices.get(earlier)
float sampleVol = data.vols.get(i)
if data.statuses.get(i) == STATUS_OK and usableVol(sampleVol)
[sampleWick, sampleExpansion, sampleWickUp] = legsOf(data, i)
plainWicks.push(sampleWick)
plainExpansions.push(sampleExpansion)
scaledWicks.push(sampleWick / sampleVol)
scaledExpansions.push(sampleExpansion / sampleVol)
earlier -= 1
if plainWicks.size() >= MIN_CHECK_SAMPLE
[actualWick, actualExpansion, actualWickUp] = legsOf(data, j)
float expansionPlainError = math.abs(statisticOf(plainExpansions) - actualExpansion)
float expansionScaledError = math.abs(statisticOf(scaledExpansions) * scoredVol - actualExpansion)
float wickPlainError = math.abs(wickStatisticOf(plainWicks, wickCutoffOf(plainWicks)) - actualWick)
float wickScaledError = math.abs(wickStatisticOf(scaledWicks, wickCutoffOf(scaledWicks)) * scoredVol - actualWick)
expansionPlainErrors.push(expansionPlainError)
expansionScaledErrors.push(expansionScaledError)
wickPlainErrors.push(wickPlainError)
wickScaledErrors.push(wickScaledError)
if expansionScaledError < expansionPlainError
result.expansionCloser += 1
if wickScaledError < wickPlainError
result.wickCloser += 1
scoredOrdinal += 1
result.scored := expansionPlainErrors.size()
if result.scored > 0
result.expansionErrPlain := expansionPlainErrors.median()
result.expansionErrScaled := expansionScaledErrors.median()
result.wickErrPlain := wickPlainErrors.median()
result.wickErrScaled := wickScaledErrors.median()
result
// @function Name of an event status, for the logs.
// @param eventStatus (int) STATUS_* code.
// @returns (string) "ok", "no data", "misaligned" or "pending".
statusText(int eventStatus) =>
switch eventStatus
STATUS_OK => "ok"
STATUS_NO_DATA => "no data"
STATUS_MISALIGNED => "misaligned"
=> "pending"
// @function Name of a candle direction, for the logs.
// @param direction (int) CANDLE_BULLISH, CANDLE_BEARISH or CANDLE_DOJI.
// @returns (string) "bullish", "bearish" or "doji".
directionName(int direction) =>
switch direction
CANDLE_BULLISH => "bullish"
CANDLE_BEARISH => "bearish"
=> "doji"
// @function Symbol of a candle direction, for the table.
// @param direction (int) CANDLE_BULLISH, CANDLE_BEARISH or CANDLE_DOJI.
// @returns (string) "▲", "▼" or "–".
directionSymbol(int direction) =>
switch direction
CANDLE_BULLISH => ARROW_UP
CANDLE_BEARISH => ARROW_DOWN
=> SYMBOL_DOJI
// @function Formats a time as a date in the event time zone.
// @param t (int) UNIX time in ms, may be na.
// @param tz (string) Time zone.
// @returns (string) Date such as "2026-11-13", or "none".
dateText(int t, string tz) =>
na(t) ? TEXT_NONE : str.format_time(t, DATE_FORMAT, tz)
// @function Puts a sign in front of a formatted distance, unless the distance formats to zero: no "−0.00%".
// @param signText (string) SIGN_PLUS, SIGN_MINUS or SIGN_PLUS_MINUS.
// @param digits (string) The distance, >= 0, formatted.
// @param zeroDigits (string) Zero in the same format, such as "0.00".
// @param pad (bool) True to put a space where the sign would be, so monospace columns stay aligned.
// @returns (string) Text such as "+0.21", " 0.00" (padded) or "0.00".
withSign(string signText, string digits, string zeroDigits, bool pad) =>
digits == zeroDigits ? (pad ? " " : "") + digits : signText + digits
// @function Formats a percentage with 2 decimals and a sign, no sign when it formats to 0.00.
// @param signText (string) SIGN_PLUS, SIGN_MINUS or SIGN_PLUS_MINUS.
// @param pct (float) Distance in percent, >= 0.
// @param pad (bool) True to put a space where the sign would be (table columns), false for labels and logs.
// @returns (string) Text such as "+0.21%", " 0.00%" (padded) or "0.00%".
pctText(string signText, float pct, bool pad) =>
withSign(signText, str.tostring(pct, PCT_FORMAT), PCT_ZERO, pad) + "%"
// @function Name of the news candle length, as in the table and the labels.
// @returns (string) Such as "15m".
newsCandleName() =>
str.tostring(newsMinutesInput) + "m"
// @function Builds the text of a level label: "$NAME $candle $type ±$percent $price".
// @param eventName (string) Name of the event type.
// @param labelWord (string) LABEL_WICK or LABEL_EXPANSION.
// @param upper (bool) True for the line above the anchor.
// @param pct (float) Distance in percent.
// @param price (float) Level.
// @returns (string) Text such as "CPI 15m wick +0.21% 21345.25" or "CPI 15m expansion −0.45% 21250.50".
levelText(string eventName, string labelWord, bool upper, float pct, float price) =>
eventName + " " + newsCandleName() + " " + labelWord + " " + pctText(upper ? SIGN_PLUS : SIGN_MINUS, pct, false) + " " + str.tostring(price, format.mintick)
// @function Builds the text of the anchor label.
// @param eventName (string) Name of the event type.
// @param price (float) Anchor price.
// @returns (string) Text such as "CPI 15m open 21300.00".
anchorLabelText(string eventName, float price) =>
eventName + " " + newsCandleName() + " " + LABEL_ANCHOR + " " + str.tostring(price, format.mintick)
// @function Creates a horizontal line, or moves an existing one.
// @param existing (line) The line, na to create it.
// @param left (int) Start time.
// @param right (int) End time.
// @param price (float) Level.
// @param lineColor (color) Color, only used on creation.
// @param lineStyle (string) A line.style_* constant, only used on creation.
// @param lineWidth (int) Width, only used on creation.
// @returns (line) The line.
placeLine(line existing, int left, int right, float price, color lineColor, string lineStyle, int lineWidth) =>
line result = existing
if na(result)
result := line.new(left, price, right, price, xloc.bar_time, extend.none, lineColor, lineStyle, lineWidth)
else
result.set_xy1(left, price)
result.set_xy2(right, price)
result
// @function Creates a label at the right end of a line, or moves an existing one.
// @param existing (label) The label, na to create it.
// @param x (int) Time of the line end.
// @param price (float) Level.
// @param labelText (string) Text.
// @param textColor (color) Text color, only used on creation.
// @returns (label) The label.
placeLabel(label existing, int x, float price, string labelText, color textColor) =>
label result = existing
if na(result)
result := label.new(x, price, labelText, xloc.bar_time, yloc.price, COLOR_LABEL_BG, LABEL_STYLE, textColor, LABEL_SIZE, text.align_left)
else
result.set_xy(x, price)
result.set_text(labelText)
result
// @function Creates the knob at the start of the anchor line, or moves an existing one.
// @param existing (label) The knob, na to create it.
// @param x (int) Time of the line start (the event time).
// @param price (float) Anchor price.
// @returns (label) The knob.
placeKnob(label existing, int x, float price) =>
label result = existing
if na(result)
result := label.new(x, price, KNOB_GLYPH, xloc.bar_time, yloc.price, COLOR_LABEL_BG, KNOB_STYLE, anchorColorInput, KNOB_SIZE)
else
result.set_xy(x, price)
result
// @function Draws the lines and labels of a projection on first use, and moves them afterwards (the anchor is live until
// the event time). The wick and expansion lines run from 1 news candle before the event to the end of the news candle
// plus the extension. The anchor line always starts at the event time, also before it (xloc.bar_time reaches into the
// future), and ends with the others; while the release is ahead, a knob marks that start.
// @param this (Projection) The projection.
// @param eventName (string) Name of the event type, for the labels.
// @param eventTime (int) Event time.
// @param anchor (float) Anchor price.
// @param stats (SampleStats) Statistics of the event, not empty.
// @param releaseAhead (bool) True while the chart's last bar opens before the event time.
// @returns (Projection) The projection.
method place(Projection this, string eventName, int eventTime, float anchor, SampleStats stats, bool releaseAhead) =>
int newsLengthMs = newsMinutesInput * MS_PER_MINUTE
int left = eventTime - newsLengthMs
int right = eventTime + newsLengthMs + extensionMinutesInput * MS_PER_MINUTE
float wickUp = anchor * (1.0 + stats.wickPct / 100.0)
float wickDown = anchor * (1.0 - stats.wickPct / 100.0)
float expansionUp = anchor * (1.0 + stats.expansionPct / 100.0)
float expansionDown = anchor * (1.0 - stats.expansionPct / 100.0)
this.wickUpLine := placeLine(this.wickUpLine, left, right, wickUp, wickColorInput, line.style_dashed, wickWidthInput)
this.wickDownLine := placeLine(this.wickDownLine, left, right, wickDown, wickColorInput, line.style_dashed, wickWidthInput)
this.expansionUpLine := placeLine(this.expansionUpLine, left, right, expansionUp, expansionColorInput, line.style_solid, expansionWidthInput)
this.expansionDownLine := placeLine(this.expansionDownLine, left, right, expansionDown, expansionColorInput, line.style_solid, expansionWidthInput)
if showLabelsInput
this.wickUpLabel := placeLabel(this.wickUpLabel, right, wickUp, levelText(eventName, LABEL_WICK, true, stats.wickPct, wickUp), wickColorInput)
this.wickDownLabel := placeLabel(this.wickDownLabel, right, wickDown, levelText(eventName, LABEL_WICK, false, stats.wickPct, wickDown), wickColorInput)
this.expansionUpLabel := placeLabel(this.expansionUpLabel, right, expansionUp, levelText(eventName, LABEL_EXPANSION, true, stats.expansionPct, expansionUp), expansionColorInput)
this.expansionDownLabel := placeLabel(this.expansionDownLabel, right, expansionDown, levelText(eventName, LABEL_EXPANSION, false, stats.expansionPct, expansionDown), expansionColorInput)
if showAnchorInput
// From the event time, on creation and on every move (placeLine() sets both ends)
this.anchorLine := placeLine(this.anchorLine, eventTime, right, anchor, anchorColorInput, line.style_dotted, DEFAULT_LINE_WIDTH)
if showLabelsInput
this.anchorLabel := placeLabel(this.anchorLabel, right, anchor, anchorLabelText(eventName, anchor), anchorColorInput)
// Knob at the line's start while the release is ahead, where no bar marks the start yet; it follows the live anchor.
// Once the news candle opens the line starts at a real bar, so the knob goes. To keep it for good, pass true for
// releaseAhead at the call site (one line)
if showAnchorInput and releaseAhead
this.anchorKnob := placeKnob(this.anchorKnob, eventTime, anchor)
else if not na(this.anchorKnob)
this.anchorKnob.delete()
this.anchorKnob := na
this
// @function Deletes all drawings of a projection.
// @param this (Projection) The projection.
method removeAll(Projection this) =>
this.wickUpLine.delete()
this.wickDownLine.delete()
this.expansionUpLine.delete()
this.expansionDownLine.delete()
this.anchorLine.delete()
this.wickUpLabel.delete()
this.wickDownLabel.delete()
this.expansionUpLabel.delete()
this.expansionDownLabel.delete()
this.anchorLabel.delete()
this.anchorKnob.delete()
// @function Key of a projection in the projections map. Two event types can share an event time (PPI and Retail Sales at
// 8:30 on the same day), so the key holds the slot as well as the event. The event is its union index, a small int, not
// its time in ms: the union is a var that never changes within a run, so the index is stable.
// @param slot (int) Slot number of the event type.
// @param unionIndex (int) Index of the event time in the union (eventTimes).
// @returns (string) Key such as "4@27".
projectionKey(int slot, int unionIndex) =>
str.tostring(slot) + KEY_SEPARATOR + str.tostring(unionIndex)
// @function Formats a projected leg for the table. A distance that formats to zero gets no ± sign.
// @param pct (float) Distance in percent, may be na.
// @param anchor (float) Anchor price, na to show the percentage only.
// @returns (string) Text such as "±0.21% / ±45.25 pts", or "n/a".
legText(float pct, float anchor) =>
string pointsText = na(anchor) ? "" : " / " + withSign(SIGN_PLUS_MINUS, str.tostring(anchor * pct / 100.0, format.mintick), str.tostring(0.0, format.mintick), false) + " pts"
na(pct) ? "n/a" : pctText(SIGN_PLUS_MINUS, pct, false) + pointsText
// @function Formats the small-wick cut of a sample for the table.
// @param stats (SampleStats) Statistics of the table's event.
// @returns (string) Text such as "8 of 10 (2 without wick, cut below 0.01%)", "9 of 10 (cut below 0.01%)",
// "8 of 10 (2 without wick, too few for a cut)", "0 of 10 (none had a wick)" or "10 of 10, no cut".
wicksUsedText(SampleStats stats) =>
string counts = str.tostring(stats.wicksUsed) + " of " + str.tostring(stats.sample.size())
string result = counts + ", no cut"
if cutSmallWicksInput and stats.sample.size() > 0
if stats.wicksUsed == 0
result := counts + " (none had a wick)"
else
string cutoffDigits = str.tostring(stats.wickCutoff, PCT_FORMAT)
// A positive cutoff that rounds to 0.00 gets a third decimal, so it doesn't read as "below 0.00%"
if cutoffDigits == PCT_ZERO
cutoffDigits := str.tostring(stats.wickCutoff, PCT_FINE_FORMAT)
string zeros = stats.noWick > 0 ? str.tostring(stats.noWick) + " without wick, " : ""
string rule = na(stats.wickCutoff) ? "too few for a cut" : "cut below " + cutoffDigits + "%"
result := counts + " (" + zeros + rule + ")"
result
// @function Formats the volatility row of the table.
// @param vol (float) vol of the table's event, else the current one (preview), may be na.
// @param stats (SampleStats) Statistics of the table's event.
// @returns (string) Text such as "VIX 18.42 (previous close), scaling on" or "n/a: no data for VIX, plain lines".
volRowText(float vol, SampleStats stats) =>
string volName = shortSymbolOf(volSymbolInput)
string state = not volScaleInput ? "scaling off" : stats.scaled ? "scaling on" : "scaling on, no vol in the sample: plain lines"
usableVol(vol) ? volName + " " + str.tostring(vol, VOL_FORMAT) + " (previous close), " + state : "n/a: no data for " + volName + ", plain lines"
// @function Formats one vol check row of the table.
// @param check (VolCheck) The comparison (volCheckOf()).
// @param forExpansion (bool) True for the expansion, false for the wick.
// @returns (string) Text such as "scaled error −14%, closer in 12 of 19", "too few events (5)" or "n/a (no vol data)".
volCheckText(VolCheck check, bool forExpansion) =>
float errPlain = forExpansion ? check.expansionErrPlain : check.wickErrPlain
float errScaled = forExpansion ? check.expansionErrScaled : check.wickErrScaled
int closer = forExpansion ? check.expansionCloser : check.wickCloser
string result = "n/a (no vol data)"
if check.withVol > 0
if check.scored < MIN_CHECK_EVENTS
result := "too few events (" + str.tostring(check.scored) + ")"
else if errPlain > 0.0
float errorChange = (errScaled / errPlain - 1.0) * 100.0
result := "scaled error " + withSign(errorChange < 0.0 ? SIGN_MINUS : SIGN_PLUS, str.tostring(math.abs(errorChange), "0"), "0", false) + "%, closer in " + str.tostring(closer) + " of " + str.tostring(check.scored)
else
result := "n/a (plain error is 0)"
result
// @function Pads a text with leading spaces to a width, for right-aligned monospace columns.
// @param value (string) Text.
// @param width (int) Width in characters.
// @returns (string) The text, unchanged when it is already as wide.
padLeft(string value, int width) =>
str.repeat(" ", math.max(width - str.length(value), 0)) + value
// @function Builds the value cells of the table's sample rows, in fixed-width columns that line up in a monospace font
// under the header "candle wick expansion vol": direction symbol, two spaces, wick, cut mark (× or a space), one space,
// expansion, two spaces, vol (– when missing). Each leg is signed by the side it is on (+ above, − below the news
// candle's open), and each column is padded to its widest value, so every row ends on the vol's last digit.
// @param data (EventData) Measurements.
// @param stats (SampleStats) Statistics of the table's event.
// @returns (array<string>) One value per sample event, newest first, parallel to stats.sample.
sampleRowsOf(EventData data, SampleStats stats) =>
array<string> symbols = array.new<string>()
array<string> wickTexts = array.new<string>()
array<string> expansionTexts = array.new<string>()
array<string> volTexts = array.new<string>()
int wickColumn = 0
int expansionColumn = 0
int volColumn = 0
for index in stats.sample
[wickPct, expansionPct, wickUp] = legsOf(data, index)
string wickText = pctText(wickUp ? SIGN_PLUS : SIGN_MINUS, wickPct, true)
string expansionText = pctText(wickUp ? SIGN_MINUS : SIGN_PLUS, expansionPct, true)
float sampleVol = data.vols.get(index)
string volCell = usableVol(sampleVol) ? str.tostring(sampleVol, VOL_SHORT_FORMAT) : TEXT_MISSING
symbols.push(directionSymbol(directionOf(data, index)))
wickTexts.push(wickText)
expansionTexts.push(expansionText)
volTexts.push(volCell)
wickColumn := math.max(wickColumn, str.length(wickText))
expansionColumn := math.max(expansionColumn, str.length(expansionText))
volColumn := math.max(volColumn, str.length(volCell))
array<string> rows = array.new<string>()
for [i, symbolText] in symbols
string cutMark = stats.wickCut.get(i) ? MARK_CUT : " "
rows.push(symbolText + " " + padLeft(wickTexts.get(i), wickColumn) + cutMark + " " + padLeft(expansionTexts.get(i), expansionColumn) + " " + padLeft(volTexts.get(i), volColumn))
rows
// @function Formats the anchor of the table's event with its state.
// @param anchor (float) Anchor price, may be na.
// @param eventTime (int) Event time.
// @param lastTime (int) Open time of the chart's last bar.
// @param linesShown (bool) False when the chart timeframe hides the lines.
// @returns (string) Price and state: preview (current close), live (previous close), or the news candle's open.
anchorText(float anchor, int eventTime, int lastTime, bool linesShown) =>
string state = lastTime < eventTime - newsMinutesInput * MS_PER_MINUTE ? "preview, current close" : lastTime < eventTime ? "live, previous close" : "news candle open"
not linesShown ? "n/a on this timeframe" : na(anchor) ? "n/a (chart history doesn't reach the event)" : str.tostring(anchor, format.mintick) + " (" + state + ")"
// @function Writes one table row with a tooltip on both cells.
// @param t (table) The table.
// @param row (int) Row index.
// @param labelText (string) Left cell text.
// @param value (string) Right cell text.
// @param tip (string) Tooltip text.
// @param fontFamily (string) A font.family_* constant.
setRowTip(table t, int row, string labelText, string value, string tip, string fontFamily = font.family_default) =>
t.cell(0, row, labelText, text_color = COLOR_TABLE_TEXT, text_halign = text.align_left, text_size = TABLE_TEXT_SIZE, bgcolor = COLOR_TABLE_BG, tooltip = tip, text_font_family = fontFamily)
t.cell(1, row, value, text_color = COLOR_TABLE_TEXT, text_halign = text.align_right, text_size = TABLE_TEXT_SIZE, bgcolor = COLOR_TABLE_BG, tooltip = tip, text_font_family = fontFamily)
// @function Writes one table row.
// @param t (table) The table.
// @param row (int) Row index.
// @param labelText (string) Left cell text.
// @param value (string) Right cell text.
setRow(table t, int row, string labelText, string value) =>
setRowTip(t, row, labelText, value, "")
// ————— Global Variable Initialization
var string eventTimeZone = timeZoneOf(timeZoneInput)
// Enabled event types, lowest slot first
var array<EventType> eventTypes = setUpEventTypes()
// Sorted, unique union of all event types' times. measureEvents() builds the same array inside the request
var array<int> eventTimes = unionTimesOf(eventTypes)
var int eventCount = eventTimes.size()
var int newsMs = newsMinutesInput * MS_PER_MINUTE
var string newsTimeframe = str.tostring(newsMinutesInput)
var string newsName = newsCandleName()
// Anchor per event time of the union: close of the last chart bar that ended at or before the event time
var array<float> anchors = array.new<float>(eventCount, na)
// vol per event time of the union, parallel to anchors and set with them: live until the event time, frozen from then on,
// so a past event's lines keep that day's value, not today's
var array<float> volAnchors = array.new<float>(eventCount, na)
// First event time of the union that the chart hasn't reached yet
var int nextEvent = 0
// Drawn projections, keyed by projectionKey(): slot and union index of the event
var map<string, Projection> projections = map.new<string, Projection>()
var table infoTable = table.new(tablePositionOf(tablePositionInput), 2, TABLE_ROWS, border_width = 1)
// Deliberate tick-level state: a var flag set on a realtime tick would be rolled back and log again on every tick
varip bool summaryLogged = false
// Each type's indices into the union, once. Chart side only: the request needs the union alone
if barstate.isfirst
for eventType in eventTypes
eventType.indexIn(eventTimes)
// Lines only on intraday charts whose bars tile the news candle, so a chart bar ends exactly at the event time
var int chartSeconds = timeframe.in_seconds(timeframe.period)
var int newsSeconds = newsMinutesInput * SECONDS_PER_MINUTE
bool linesEnabled = (timeframe.isseconds or timeframe.isminutes) and chartSeconds <= newsSeconds and newsSeconds % chartSeconds == 0
// ————— Calculations / Main Logic
// Live form (lookahead off, no offset), chosen deliberately. The payload exists only on the request's last bar and on the
// bars around each event time (measureEvents()). The last bar maps to the chart's last bar (the developing news-timeframe
// bar on realtime, the last one on a closed market). On history, lookahead off hands an event-window payload to the chart
// only on the chart bar where its news-timeframe bar closes, and the payload only holds events up to that bar, so no
// future data reaches a historical chart bar. That also makes the hand-off independent of where the request's last bar
// is, which in Bar Replay may not be the replay point. calc_bars_count gives the request its own long history, independent of
// the chart's.
EventData measured = request.security(syminfo.tickerid, newsTimeframe, measureEvents(), calc_bars_count = NEWS_CONTEXT_BARS)
// The latest usable payload. The request returns na between the event windows, so the last one is kept. Any payload holds
// the statuses of all event times before its bar, and a projection's sample only needs earlier events, so an older payload
// serves every event at or after its bar. The payload holds one entry per union time and both sides parse the same inputs,
// so a size mismatch means no usable data
var EventData latestMeasured = na
if not na(measured) and measured.statuses.size() == eventCount
latestMeasured := measured
// vol on the chart: the same expression as in measureEvents() (previousVolClose()), whether scaling is on or off, because
// the table's vol check and Volatility row need it too
float volNow = previousVolClose()
// Anchor, projection phase: the close of the chart bar that ends at or before the next event time. On the realtime bar it
// follows the preliminary close tick by tick. Its vol follows the same rule and stays frozen from the event time on.
// From the event time T: the news candle's open, the open of the first chart bar inside [T, T + W), set once when the
// chart reaches it (on the realtime bar the open is the same on every tick) and frozen afterwards. Without a chart bar
// inside the news candle (a data gap) the last preview value stays
while nextEvent < eventCount and eventTimes.get(nextEvent) <= time
if time < eventTimes.get(nextEvent) + newsMs
anchors.set(nextEvent, open)
nextEvent += 1
if nextEvent < eventCount and time_close <= eventTimes.get(nextEvent)
anchors.set(nextEvent, close)
volAnchors.set(nextEvent, volNow)
// ————— Visuals
if barstate.islast
int lastTime = time
// Reference time for "today": timenow while the last bar is at most MAX_CLOSED_MARKET_MS old (weekend or holiday: the
// real day counts), else the last bar's time (Bar Replay or stale data: the replay date counts). Whether timenow is the
// real or the replay time in Bar Replay isn't documented; this works either way
int nowTime = timenow >= lastTime and timenow - lastTime <= MAX_CLOSED_MARKET_MS ? timenow : lastTime
// Today: the calendar day of nowTime in the event time zone. timestamp() rolls day + 1 over a month or year end
int dayStart = timestamp(eventTimeZone, year(nowTime, eventTimeZone), month(nowTime, eventTimeZone), dayofmonth(nowTime, eventTimeZone), 0, 0)
int dayEnd = timestamp(eventTimeZone, year(nowTime, eventTimeZone), month(nowTime, eventTimeZone), dayofmonth(nowTime, eventTimeZone) + 1, 0, 0)
// Table event: today's first event whose news candle hasn't ended, or today's last one once all of today's have ended.
// Without an event today, the next event whose news candle hasn't ended. None when no listed date is that late. Of
// several types at the chosen time, the lowest slot
int todayIndex = na
bool todayPending = false
int upcomingIndex = na
for [i, t] in eventTimes
bool candleEnded = t + newsMs <= lastTime
if t >= dayStart and t < dayEnd and not todayPending
todayIndex := i
todayPending := not candleEnded
if na(upcomingIndex) and not candleEnded
upcomingIndex := i
int focusIndex = na(todayIndex) ? upcomingIndex : todayIndex
EventType focusType = na
int focusOrdinal = na
if not na(focusIndex)
for candidate in eventTypes
int candidateOrdinal = candidate.indices.binary_search(focusIndex)
if candidateOrdinal >= 0
focusType := candidate
focusOrdinal := candidateOrdinal
break
bool dataReady = not na(latestMeasured)
// The most recent events across all types that the chart has reached (1 news candle before the event) with a known
// anchor and a sample, newest first, projectionsInput in total. Types that share an event time: lowest slot first.
// Without data the existing drawings stay as they are
if linesEnabled and dataReady
array<string> wanted = array.new<string>()
int k = eventCount - 1
while k >= 0 and wanted.size() < projectionsInput
int eventTime = eventTimes.get(k)
float anchor = anchors.get(k)
if lastTime >= eventTime - newsMs and not na(anchor)
for drawType in eventTypes
int drawOrdinal = drawType.indices.binary_search(k)
// The budget is checked per type too: two types at the same time must not overshoot it
if drawOrdinal >= 0 and wanted.size() < projectionsInput
SampleStats stats = sampleStats(latestMeasured, drawType, drawOrdinal, volScaleInput ? volAnchors.get(k) : na)
if stats.sample.size() > 0
string drawKey = projectionKey(drawType.slot, k)
wanted.push(drawKey)
Projection projection = projections.get(drawKey)
if na(projection)
projection := Projection.new()
projections.put(drawKey, projection)
projection.place(drawType.name, eventTime, anchor, stats, lastTime < eventTime)
k -= 1
for key in projections.keys()
if not wanted.includes(key)
projections.get(key).removeAll()
projections.remove(key)
if showTableInput
infoTable.clear(0, 0, 1, TABLE_ROWS - 1)
int row = 0
// No focus type without events (the default: all date lists empty) or without an upcoming one
string focusName = ""
if not na(focusType)
focusName := focusType.name
setRow(infoTable, row, "News Candle Range", focusName)
row += 1
if eventCount == 0
setRowTip(infoTable, row, "Event dates", "none: enable an event and paste its dates", "Settings > Event 1 to Event 15: tick an event and paste its past release dates and the upcoming one, as YYYY-MM-DD.")
row += 1
else
int focusTime = na
if na(focusIndex)
setRowTip(infoTable, row, "No upcoming event", "add the next release dates", "No enabled event has a date after today, so there are no stats to show and no lines to draw. Add the next release date to each event's list in the settings.")
else
focusTime := eventTimes.get(focusIndex)
setRow(infoTable, row, "Event", str.format_time(focusTime, DATE_TIME_FORMAT, eventTimeZone) + " " + eventTimeZone)
row += 1
// Types with dates whose last listed event has passed: they get no lines until the next date is added
array<string> missingNext = array.new<string>()
for checkType in eventTypes
if checkType.times.size() > 0 and checkType.times.last() + newsMs <= lastTime
missingNext.push(checkType.name)
if missingNext.size() > 0
setRowTip(infoTable, row, "Next date missing", missingNext.join(", "), "These events have no upcoming date, so they get no lines. Add the next release date to the end of their list in the settings.")
row += 1
// The detail rows describe the focus event; without one only the rows above show
if not na(focusIndex)
setRow(infoTable, row, "News candle", newsName)
row += 1
if not linesEnabled
setRowTip(infoTable, row, "Lines hidden", "chart timeframe must divide " + newsName, "Lines show on intraday charts whose timeframe divides the news candle (for 15m: 1m, 3m, 5m, 15m and seconds charts), so a chart bar ends exactly at the event time.")
row += 1
if not dataReady
setRowTip(infoTable, row, "Data", "no measurements yet", "The " + newsName + " request hasn't returned anything usable up to this bar (it sends its measurements around each event and on its last bar). Check the Pine Logs and the README (Limits).")
row += 1
else
// vol of the table's event: its live or frozen value, else the current one (preview)
float focusVol = usableVol(volAnchors.get(focusIndex)) ? volAnchors.get(focusIndex) : volNow
SampleStats focusStats = sampleStats(latestMeasured, focusType, focusOrdinal, volScaleInput ? focusVol : na)
float focusAnchor = linesEnabled ? anchors.get(focusIndex) : na
int used = focusStats.sample.size()
string sampleText = (used >= MAX_SAMPLE ? "the last " : "") + str.tostring(used) + (used == 1 ? " event" : " events")
string scaledText = focusStats.scaled ? ", scaled by " + shortSymbolOf(volSymbolInput) : ""
setRowTip(infoTable, row, "Projection", statisticName() + " of " + sampleText + scaledText, "The sample behind this event's lines: every listed earlier release of this event that could be measured, at most the most recent " + str.tostring(MAX_SAMPLE) + ". Add more past dates for a bigger sample. The statistic is set under Statistics in the settings. Scaled: each release's legs are taken per point of the volatility index and set to its value before this event (Volatility below); releases without a volatility value are left out then.")
row += 1
setRowTip(infoTable, row, "Wick (dashed)", legText(focusStats.wickPct, focusAnchor), "Typical wick: the leg against the news candle's direction (how far a bullish news candle dipped below its open, or a bearish one rose above it), drawn both above and below the anchor because the direction isn't known in advance. Points at the anchor below.")
row += 1
setRowTip(infoTable, row, "Wicks used", wicksUsedText(focusStats), "Sample events whose wick sets the dashed lines. With Drop small wicks on, wicks of 0 (the candle ran one way) are left out, and of the rest those more than " + str.tostring(wickCutSigmaInput) + " standard deviations below this sample's mean on a log scale (× in the sample rows), so candles with barely any wick don't pull the dashed lines onto the anchor. The log cut needs at least " + str.tostring(MIN_CUT_SAMPLE) + " positive wicks. If none had a wick, the dashed lines sit at the anchor. The solid lines always use all sample events. Scaled: the cut works on the wicks per point of the volatility index, and the cutoff shows in percent at the value before this event.")
row += 1
setRowTip(infoTable, row, "Expansion (solid)", legText(focusStats.expansionPct, focusAnchor), "Typical expansion: the leg in the news candle's direction (how far a bullish news candle rose above its open, or a bearish one fell below it), from all sample events, drawn both above and below the anchor.")
row += 1
setRowTip(infoTable, row, "Anchor", anchorText(focusAnchor, focusTime, lastTime, linesEnabled), "The center of the projection. Preview: the current close, before the lines appear. Live, previous close: the close of the candle before the news candle, still forming, the lines follow it. News candle open: from the event time on, the open of the news candle, fixed.")
row += 1
setRowTip(infoTable, row, "Volatility", volRowText(focusVol, focusStats), "vol: the volatility index's previous daily close (Scale by volatility index in the settings), as of the candle before the news candle: live until the event time, frozen from then on, the current value before. Never the event day's own close. Scaled lines are the sample's legs per point of vol, times this value. Plain lines when the index has no data or no sample release has a vol.")
row += 1
// Computed with scaling off too: it is what tells whether switching scaling on would have helped
VolCheck focusCheck = volCheckOf(latestMeasured, focusType, focusOrdinal)
string checkTip = "Walk-forward test on this event's past releases: each one is predicted only from the releases before it (those with a volatility value, at most " + str.tostring(MAX_SAMPLE) + ", at least " + str.tostring(MIN_CHECK_SAMPLE) + "), once plain and once scaled by the volatility index, both from the same releases, and compared with what actually happened. Scaled error: the median error of the scaled prediction against the plain one; negative means scaling was closer. Closer in: releases where scaling was closer. With about 20 releases, a few percent either way is noise. Shown whether scaling is on or off, so you can decide."
setRowTip(infoTable, row, "Vol check (expansion)", volCheckText(focusCheck, true), checkTip)
row += 1
setRowTip(infoTable, row, "Vol check (wick)", volCheckText(focusCheck, false), checkTip + " The wick test is biased for both methods: the dashed lines leave small wicks out, the actual wicks include them. The expansion row is the fairer test.")
row += 1
string dojiText = focusStats.doji > 0 ? " / " + str.tostring(focusStats.doji) + " doji" : ""
setRowTip(infoTable, row, "Bullish / bearish", str.tostring(focusStats.bullish) + " / " + str.tostring(focusStats.bearish) + dojiText, "Sample candles that closed above / below their open (doji: close at the open). For bullish ones the wick is the dip below the open, for bearish ones the rise above it, for a doji the smaller of the two legs.")
row += 1
setRowTip(infoTable, row, "Skipped no data / misaligned", str.tostring(focusStats.noData) + " / " + str.tostring(focusStats.misaligned), "Earlier listed events of this type that can't be measured. No data: no " + newsName + " candle opens at the event time (holiday, market closed, or before the data reach). Misaligned: the event time isn't on the " + newsName + " grid.")
row += 1
setRowTip(infoTable, row, "Data since", dateText(latestMeasured.contextStart, eventTimeZone), "How far back the " + newsName + " news-candle data reaches on your plan. Listed events before this date are 'no data'.")
row += 1
if showSampleRowsInput and used > 0
setRowTip(infoTable, row, "Sample, newest first", "candle wick expansion vol", "Candle: ▲ bullish (closed above its open), ▼ bearish (closed below), – doji (closed at the open). Wick and expansion in percent of the news candle's open, signed by their side: + above, − below the open. × marks a wick left out of the dashed lines by Drop small wicks: a wick of 0, or one far below the sample's typical wick (scaled: judged per point of vol). Vol: the volatility index's previous daily close before the release, – when missing.", font.family_monospace)
row += 1
array<string> sampleRows = sampleRowsOf(latestMeasured, focusStats)
for [i, rowText] in sampleRows
setRowTip(infoTable, row, dateText(eventTimes.get(focusStats.sample.get(i)), eventTimeZone), rowText, "", font.family_monospace)
row += 1
// Per-event summary in the Pine Logs pane, once per script run, as soon as a payload has arrived (latestMeasured)
if not summaryLogged and dataReady
summaryLogged := true
log.info("News Candle Range: " + str.tostring(eventTypes.size()) + " event types, " + str.tostring(eventCount) + " event times, " + newsName + " data since " + dateText(latestMeasured.contextStart, eventTimeZone))
for logType in eventTypes
log.info(logType.name + ": " + str.tostring(logType.times.size()) + " events")
for [ordinal, loggedTime] in logType.times
int index = logType.indices.get(ordinal)
int eventStatus = latestMeasured.statuses.get(index)
string entry = logType.name + " " + str.format_time(loggedTime, DATE_TIME_FORMAT, eventTimeZone) + ": " + statusText(eventStatus)
if eventStatus == STATUS_OK
[wickPct, expansionPct, wickUp] = legsOf(latestMeasured, index)
bool forming = loggedTime + newsMs > lastTime
entry += ", " + directionName(directionOf(latestMeasured, index)) + ", open " + str.tostring(latestMeasured.opens.get(index), format.mintick) + ", high " + str.tostring(latestMeasured.highs.get(index), format.mintick) + ", low " + str.tostring(latestMeasured.lows.get(index), format.mintick) + ", close " + str.tostring(latestMeasured.closes.get(index), format.mintick) + ", wick " + pctText(wickUp ? SIGN_PLUS : SIGN_MINUS, wickPct, false) + ", expansion " + pctText(wickUp ? SIGN_MINUS : SIGN_PLUS, expansionPct, false) + ", vol " + (usableVol(latestMeasured.vols.get(index)) ? str.tostring(latestMeasured.vols.get(index), VOL_FORMAT) : "n/a") + (forming ? ", candle still forming" : "")
log.info(entry)