Community scripts › session indicator

session indicator

by Mangoat · v1 · updated 2 h ago Open source
session indicator by Mangoat on the live order book chart

What it does

Marks the Asia (Tokyo), London and New York sessions and the pre-market before each one, for as many days back as you choose. Each session gets a box with its name and its low-high range. You can also show only the high and low lines, a line at each session's opening time, the middle and opening price, and the London / New York overlap. An info box shows which session is running, how long until the next one, and each session's latest range.

How it works

It uses the candles of the chart you are on. For each day it finds the session's start and end time, takes the highest high and lowest low of the candles inside that window, and draws them. Standard times are the real exchange hours in each exchange's own time: Tokyo 09:00-15:30 (pre-market from 08:00), London 08:00-16:30 (pre-market from 05:00), New York 09:30-16:00 (pre-market from 04:00). Summer time is handled automatically, so the boxes stay on the right candles all year. Nothing is predicted or forecast: it only describes what already happened.

How to use it

Add it to the chart and use a timeframe of 1h or smaller (boxes are not drawn on 4h and above). Every setting is yours to change: days back, start/end/pre-market time for each session (typed in each exchange's own time, New York time, UTC or your own offset), colors, box and line transparency, line width and style, and a separate name tag that stays visible even when the boxes are fully transparent. The text in front of each setting, [std ...], shows the standard value, and the info box lists which settings differ from standard. The site keeps about 15 days of history, so "days back" above that shows nothing extra.

What's original

Everything can be shaped by the user: boxes, lines, opening-time lines and name tags can each be turned on or off with their own transparency and color. Times follow each exchange's own clock including summer time, or can be typed in New York time, UTC or a custom offset. The standard value of every setting is written next to it, and the info box shows exactly which settings you changed.

Limitations

Needs a chart of 1h or smaller. The site holds about 15 days of history, so you cannot see further back. Session times follow the standard exchange hours; public holidays and early closes are not taken into account. Ranges are made from the chart's own candles, so they can differ slightly from other data providers. It does not reset your own settings by itself: tick "STANDARD SETTINGS" to use the standard values without losing yours. Descriptive market data, not financial advice.

Source code

Open source under MPL-2.0. Copy it with credit: "Copy to my scripts" adds the credit for you.

// Swiftedge Sessions (Swiftedge Script)
// Descriptive market data, not financial advice.
// Marks the Asia (Tokyo), London and New York sessions and the pre-market before each of them, for as many days back as you choose.
// Standard times are the real exchange hours in each exchange's own time, with summer time handled automatically:
//   Tokyo 09:00-15:30 (pre-market 08:00-09:00) | London 08:00-16:30 (pre-market 05:00-08:00) | New York 09:30-16:00 (pre-market 04:00-09:30)
// Every time, colour, opacity and line is a setting. The "[std ...]" in front of each setting is the standard value.
script({ name: "Swiftedge Sessions", bars: 5000 });

const useDefaults = input.bool(false, "STANDARD SETTINGS: tick to use the built-in settings (the boxes below keep your numbers but are not used; untick to use them again)");
const reg = [];
const I = (v, d, name) => { reg.push({ v, d, name }); return useDefaults ? d : v; };

// ---------- General ----------
const daysBack = I(input.int(5, "[std 5] Days back (0 = today only). The site holds about 15 days", { min: 0, max: 60 }), 5, "Days back");
const timeMode = I(input.int(1, "[std 1] Times are typed in: 1 = each exchange's own time (summer time automatic), 2 = New York time (ET), 3 = UTC, 4 = my own offset", { min: 1, max: 4 }), 1, "Times are typed in");
const ownOffset = I(input.number(1, "[std 1] My own offset from UTC in hours (used only when times are typed in 4)", { step: 0.5 }), 1, "My own offset from UTC in hours");
const showMain = I(input.bool(true, "[std on] Show the sessions"), true, "Show the sessions");
const showPre = I(input.bool(true, "[std on] Show the pre-market before each session"), true, "Show the pre-market before each se");
const showLabels = I(input.bool(true, "[std on] Show the name and range in each box"), true, "Show the name and range in each bo");
const showTimesInLabel = I(input.bool(false, "[std off] Also write the times (New York time first, then UTC) in the box"), false, "Also write the times");
const extendHL = I(input.int(1, "[std 1] Session high and low lines: 0 = none, 1 = until the next session of the same kind, 2 = to the right edge", { min: 0, max: 2 }), 1, "Session high and low lines");
const showBoxes = I(input.bool(true, "[std on] Show the boxes (untick to see only lines)"), true, "Show the boxes");
const showHL = I(input.bool(true, "[std on] Show the high and low lines of each session"), true, "Show high/low lines");
const showStartLine = I(input.bool(false, "[std off] Show a vertical line at each session's opening time"), false, "Opening-time line");
const lineTransp = I(input.int(45, "[std 45] Line transparency, high/low and opening-time lines (0 = solid, 100 = invisible)", { min: 0, max: 100 }), 45, "Line transparency");
const showNames = I(input.bool(false, "[std off] Session name tag: own text on the chart, stays visible even when the boxes are invisible (turn the box text off to avoid doubles)"), false, "Session name tag");
const nameColor = I(input.color("#eceff4", "[std #eceff4] Name tag text colour"), "#eceff4", "Name tag colour");
const nameSize = I(input.int(12, "[std 12] Name tag text size", { min: 8, max: 30 }), 12, "Name tag size");
const nameWhere = I(input.int(1, "[std 1] Name tag position: 1 = at the high, 2 = at the low", { min: 1, max: 2 }), 1, "Name tag position");
const nameRange = I(input.bool(false, "[std off] Also write the range (low - high) in the name tag"), false, "Name tag range");
const namePre = I(input.bool(false, "[std off] Name tags on the pre-market too"), false, "Name tag pre-market");
const showMid = I(input.bool(false, "[std off] Show the middle of each session's range"), false, "Show the middle of each session's ");
const showOpen = I(input.bool(false, "[std off] Show each session's opening price"), false, "Show each session's opening price");
const showOverlap = I(input.bool(false, "[std off] Mark the London / New York overlap"), false, "Mark the London / New York overlap");
const liveToEnd = I(input.bool(false, "[std off] Draw the running session all the way to its planned end"), false, "Draw the running session all the w");
const showPanel = I(input.bool(true, "[std on] Show the session clock in the info box"), true, "Show the session clock in the info");
const alertsOn = I(input.bool(false, "[std off] Alerts when a session opens"), false, "Alerts when a session opens");

// ---------- Look ----------
const fillTransp = I(input.int(88, "[std 88] Box fill transparency, session (0 = solid, 100 = invisible)", { min: 0, max: 100 }), 88, "Box fill transparency");
const preTransp = I(input.int(94, "[std 94] Box fill transparency, pre-market (0 = solid, 100 = invisible)", { min: 0, max: 100 }), 94, "Box fill transparency");
const borderTransp = I(input.int(45, "[std 45] Box border transparency (0 = solid, 100 = invisible)", { min: 0, max: 100 }), 45, "Box border transparency");
const lineWidth = I(input.int(1, "[std 1] Width of the high / low lines", { min: 1, max: 5 }), 1, "Width of the high / low lines");
const lineStyleN = I(input.int(1, "[std 1] Style of the high / low lines: 1 = solid, 2 = dashed, 3 = dotted", { min: 1, max: 3 }), 1, "Style of the high / low lines");
const overlapColor = I(input.color("#ffd166", "[std #ffd166] Colour of the London / New York overlap"), "#ffd166", "Colour of the London / New York ov");
const overlapTransp = I(input.int(90, "[std 90] Overlap fill transparency", { min: 0, max: 100 }), 90, "Overlap fill transparency");

// ---------- Asia (Tokyo) ----------
const asiaOn = I(input.bool(true, "[std on] ASIA (Tokyo): show it"), true, "ASIA");
const asiaStart = I(input.text("09:00", "[std 09:00] ASIA session starts (HH:MM)"), "09:00", "ASIA session starts");
const asiaEnd = I(input.text("15:30", "[std 15:30] ASIA session ends (HH:MM)"), "15:30", "ASIA session ends");
const asiaPreStart = I(input.text("08:00", "[std 08:00] ASIA pre-market starts (HH:MM)"), "08:00", "ASIA pre-market starts");
const asiaCol = I(input.color("#b061e6", "[std #b061e6] ASIA colour"), "#b061e6", "ASIA colour");

// ---------- London ----------
const lonOn = I(input.bool(true, "[std on] LONDON: show it"), true, "LONDON");
const lonStart = I(input.text("08:00", "[std 08:00] LONDON session starts (HH:MM)"), "08:00", "LONDON session starts");
const lonEnd = I(input.text("16:30", "[std 16:30] LONDON session ends (HH:MM)"), "16:30", "LONDON session ends");
const lonPreStart = I(input.text("05:00", "[std 05:00] LONDON pre-market starts (HH:MM)"), "05:00", "LONDON pre-market starts");
const lonCol = I(input.color("#2dd4b4", "[std #2dd4b4] LONDON colour"), "#2dd4b4", "LONDON colour");

// ---------- New York ----------
const nyOn = I(input.bool(true, "[std on] NEW YORK: show it"), true, "NEW YORK");
const nyStart = I(input.text("09:30", "[std 09:30] NEW YORK session starts (HH:MM)"), "09:30", "NEW YORK session starts");
const nyEnd = I(input.text("16:00", "[std 16:00] NEW YORK session ends (HH:MM)"), "16:00", "NEW YORK session ends");
const nyPreStart = I(input.text("04:00", "[std 04:00] NEW YORK pre-market starts (HH:MM)"), "04:00", "NEW YORK pre-market starts");
const nyCol = I(input.color("#4c8dff", "[std #4c8dff] NEW YORK colour"), "#4c8dff", "NEW YORK colour");

// ---------- Time and summer-time helpers (no Date needed) ----------
const daysFromCivil = (y, m, d) => {
  y -= m <= 2 ? 1 : 0;
  const era = Math.floor(y / 400);
  const yoe = y - era * 400;
  const doy = Math.floor((153 * (m + (m > 2 ? -3 : 9)) + 2) / 5) + d - 1;
  const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;
  return era * 146097 + doe - 719468;
};
const civilFromDays = (z) => {
  z += 719468;
  const era = Math.floor(z / 146097);
  const doe = z - era * 146097;
  const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);
  const y = yoe + era * 400;
  const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));
  const mp = Math.floor((5 * doy + 2) / 153);
  const d = doy - Math.floor((153 * mp + 2) / 5) + 1;
  const m = mp + (mp < 10 ? 3 : -9);
  return { y: y + (m <= 2 ? 1 : 0), m, d };
};
const weekday = (days) => (((days + 4) % 7) + 7) % 7; // 0 = Sunday
const nthSunday = (y, m, nth) => {
  const first = daysFromCivil(y, m, 1);
  const firstSun = first + ((7 - weekday(first)) % 7);
  return firstSun + 7 * (nth - 1);
};
const lastSunday = (y, m) => {
  const lastDay = (m === 12 ? daysFromCivil(y + 1, 1, 1) : daysFromCivil(y, m + 1, 1)) - 1;
  return lastDay - weekday(lastDay);
};
const yearOf = (utcSec) => civilFromDays(Math.floor(utcSec / 86400)).y;
// New York: summer time from the 2nd Sunday of March 07:00 UTC to the 1st Sunday of November 06:00 UTC
const offNY = (utc) => {
  const y = yearOf(utc);
  const a = nthSunday(y, 3, 2) * 86400 + 7 * 3600;
  const b = nthSunday(y, 11, 1) * 86400 + 6 * 3600;
  return utc >= a && utc < b ? -4 : -5;
};
// London: summer time from the last Sunday of March 01:00 UTC to the last Sunday of October 01:00 UTC
const offLON = (utc) => {
  const y = yearOf(utc);
  const a = lastSunday(y, 3) * 86400 + 3600;
  const b = lastSunday(y, 10) * 86400 + 3600;
  return utc >= a && utc < b ? 1 : 0;
};
const offTokyo = () => 9;
const parseHM = (txt, fallback) => {
  const m = /^\s*(\d{1,2})\s*[:.]\s*(\d{1,2})\s*$/.exec(String(txt));
  if (!m) return fallback;
  const h = Math.min(23, +m[1]), mi = Math.min(59, +m[2]);
  return h * 60 + mi;
};
// which offset function a session uses
const offFor = (kind) => {
  if (timeMode === 1) return kind === "asia" ? offTokyo : kind === "lon" ? offLON : offNY;
  if (timeMode === 2) return offNY;
  if (timeMode === 3) return () => 0;
  return () => ownOffset;
};
// local calendar day (epoch days) + minutes -> UTC seconds
const localToUtc = (day, minutes, offFn) => {
  const local = day * 86400 + minutes * 60;
  let utc = local - offFn(local - 5 * 3600) * 3600;
  utc = local - offFn(utc) * 3600;
  return utc;
};

// ---------- Bars ----------
const ok = (v) => typeof v === "number" && Number.isFinite(v);
const n = close.length;
const sec = (t) => (t > 1e12 ? t / 1000 : t);
const T = time.map(sec);
const lastT = T[n - 1];
const barSecs = n > 2 ? Math.max(1, T[n - 1] - T[n - 2]) : 300;
const fmtP = (x) => fmt(x, market.decimals);
const pad2 = (v) => String(v).padStart(2, "0");
const op = (transp) => Math.max(0, Math.min(1, (100 - transp) / 100));
const lineStyle = lineStyleN === 2 ? "dashed" : lineStyleN === 3 ? "dotted" : "solid";

// first bar index with time >= t
const lowerBound = (t) => {
  let lo = 0, hi = n;
  while (lo < hi) { const mid = (lo + hi) >> 1; if (T[mid] < t) lo = mid + 1; else hi = mid; }
  return lo;
};

// ---------- Build the windows ----------
const defs = [
  { key: "asia", name: "Asia", on: asiaOn, start: asiaStart, end: asiaEnd, pre: asiaPreStart, col: asiaCol, startDef: 9 * 60, endDef: 15 * 60 + 30, preDef: 8 * 60 },
  { key: "lon", name: "London", on: lonOn, start: lonStart, end: lonEnd, pre: lonPreStart, col: lonCol, startDef: 8 * 60, endDef: 16 * 60 + 30, preDef: 5 * 60 },
  { key: "ny", name: "New York", on: nyOn, start: nyStart, end: nyEnd, pre: nyPreStart, col: nyCol, startDef: 9 * 60 + 30, endDef: 16 * 60, preDef: 4 * 60 }
];
const todayUtcDay = Math.floor(lastT / 86400);
const firstDay = todayUtcDay - daysBack - 1;
const lastDay = todayUtcDay + 1;
const cutoff = (todayUtcDay - daysBack) * 86400;
const windows = [];
defs.forEach((df) => {
  if (!df.on) return;
  const offFn = offFor(df.key);
  const sMin = parseHM(df.start, df.startDef), eMin = parseHM(df.end, df.endDef), pMin = parseHM(df.pre, df.preDef);
  for (let d = firstDay; d <= lastDay; d++) {
    const s = localToUtc(d, sMin, offFn);
    const e = localToUtc(d + (eMin <= sMin ? 1 : 0), eMin, offFn);
    const p = localToUtc(d + (pMin >= sMin ? -1 : 0), pMin, offFn);
    if (e >= cutoff && s <= lastT + 86400) windows.push({ df, pre: false, s, e });
    if (showPre && s > p && s >= cutoff && p <= lastT + 86400) windows.push({ df, pre: true, s: p, e: s });
  }
});

// range of every window from the bars inside it
windows.forEach((w) => {
  const i0 = lowerBound(w.s);
  let hi = -Infinity, lo = Infinity, cnt = 0, first = -1, last = -1;
  for (let i = i0; i < n && T[i] < w.e; i++) {
    if (high[i] > hi) hi = high[i];
    if (low[i] < lo) lo = low[i];
    if (first < 0) first = i;
    last = i;
    cnt++;
  }
  w.cnt = cnt; w.hi = hi; w.lo = lo; w.first = first; w.last = last;
  w.live = w.s <= lastT && lastT < w.e;
  w.open = first >= 0 ? open[first] : NaN;
  w.close = last >= 0 ? close[last] : NaN;
});
const real = windows.filter((w) => w.cnt > 0 && w.s <= lastT);

// ---------- Draw ----------
const tooCoarse = barSecs >= 4 * 3600;
const etLabel = (utc) => {
  const loc = utc + offNY(utc) * 3600;
  const mins = Math.floor((((loc % 86400) + 86400) % 86400) / 60);
  const h = Math.floor(mins / 60), mi = mins % 60;
  return `${((h + 11) % 12) + 1}:${pad2(mi)} ${h < 12 ? "AM" : "PM"} ET`;
};
const utcLabel = (utc) => {
  const mins = Math.floor((((utc % 86400) + 86400) % 86400) / 60);
  return `${pad2(Math.floor(mins / 60))}:${pad2(mins % 60)} UTC`;
};
let allHi = -Infinity, allLo = Infinity;
for (let i = 0; i < n; i++) { if (high[i] > allHi) allHi = high[i]; if (low[i] < allLo) allLo = low[i]; }
const drawn = { sessions: 0, pre: 0 };
if (!tooCoarse) {
  real.forEach((w) => {
    const df = w.df;
    if (w.pre ? !showPre : !showMain) return;
    const endX = w.live && !liveToEnd ? lastT : w.e;
    const range = w.hi - w.lo;
    let text = "";
    if (showLabels) {
      text = `${df.name}${w.pre ? " pre-market" : ""}  ${fmtP(w.lo)} - ${fmtP(w.hi)}  (${fmtP(range)})`;
      if (showTimesInLabel) text += `  ${etLabel(w.s)} (${utcLabel(w.s)})`;
    }
    if (showBoxes) draw.box(w.s, w.hi, endX, w.lo, {
      fill: color.new(df.col, op(w.pre ? preTransp : fillTransp)),
      borderColor: color.new(df.col, op(borderTransp)),
      text,
      textAlign: "left"
    });
    if (w.pre) drawn.pre++; else drawn.sessions++;
    if (showNames && (!w.pre || namePre)) {
      const tag = `${df.name}${w.pre ? " pre-market" : ""}${nameRange ? "  " + fmtP(w.lo) + " - " + fmtP(w.hi) : ""}`;
      canvas.text(w.s, nameWhere === 2 ? w.lo : w.hi, tag, { size: nameSize, color: nameColor });
    }
    if (showStartLine) draw.line(w.s, allLo, w.s, allHi, { color: color.new(df.col, op(lineTransp)), width: lineWidth, style: lineStyle });
    if (w.pre) return;
    // high / low lines carried to the right
    if (showHL && extendHL > 0) {
      const same = real.filter((x) => x.df === df && !x.pre && x.s > w.s).sort((a, b) => a.s - b.s)[0];
      const xe = extendHL === 2 || !same ? lastT + 20 * barSecs : same.s;
      const lc = color.new(df.col, op(lineTransp));
      const x0 = showBoxes ? endX : w.s;
      draw.line(x0, w.hi, xe, w.hi, { color: lc, width: lineWidth, style: lineStyle });
      draw.line(x0, w.lo, xe, w.lo, { color: lc, width: lineWidth, style: lineStyle });
    }
    if (showMid) draw.line(w.s, (w.hi + w.lo) / 2, endX, (w.hi + w.lo) / 2, { color: color.new(df.col, 0.6), width: 1, style: "dotted" });
    if (showOpen && ok(w.open)) draw.line(w.s, w.open, endX, w.open, { color: color.new(df.col, 0.8), width: 1, style: "dashed" });
  });
  // overlap of London and New York
  if (showOverlap && showMain) {
    real.filter((w) => w.df.key === "lon" && !w.pre).forEach((a) => {
      real.filter((w) => w.df.key === "ny" && !w.pre).forEach((b) => {
        const s = Math.max(a.s, b.s), e = Math.min(a.e, b.e);
        if (e <= s || s > lastT) return;
        const i0 = lowerBound(s);
        let hi = -Infinity, lo = Infinity;
        for (let i = i0; i < n && T[i] < e; i++) { if (high[i] > hi) hi = high[i]; if (low[i] < lo) lo = low[i]; }
        if (hi > -Infinity) draw.box(s, hi, Math.min(e, lastT), lo, { fill: color.new(overlapColor, op(overlapTransp)), borderColor: color.new(overlapColor, 0.3), text: showLabels ? "London / New York overlap" : "", textAlign: "left" });
      });
    });
  }
}

// ---------- Info box ----------
const fmtDur = (secs) => {
  const m = Math.max(0, Math.round(secs / 60));
  return m >= 60 ? `${Math.floor(m / 60)}h ${pad2(m % 60)}m` : `${m}m`;
};
const rows = [];
if (tooCoarse) rows.push(["Note", "Sessions need a chart of 1h or smaller", "warn"]);
else if (showPanel) {
  const nowW = windows.filter((w) => !w.pre && w.s <= lastT && lastT < w.e);
  const nowP = windows.filter((w) => w.pre && w.s <= lastT && lastT < w.e);
  nowW.forEach((w) => rows.push([`Now: ${w.df.name}`, `closes in ${fmtDur(w.e - lastT)}`, "accent"]));
  nowP.forEach((w) => rows.push([`Now: ${w.df.name} pre-market`, `session opens in ${fmtDur(w.e - lastT)}`, "muted"]));
  if (!nowW.length && !nowP.length) rows.push(["Now", "between sessions", "muted"]);
  const next = windows.filter((w) => !w.pre && w.s > lastT).sort((a, b) => a.s - b.s)[0];
  if (next) rows.push(["Next", `${next.df.name} in ${fmtDur(next.s - lastT)}`, "muted"]);
  const lastBy = {};
  real.filter((w) => !w.pre).forEach((w) => { if (!lastBy[w.df.key] || w.s > lastBy[w.df.key].s) lastBy[w.df.key] = w; });
  defs.forEach((df) => { const w = lastBy[df.key]; if (w) rows.push([`${df.name} range`, `${fmtP(w.lo)} - ${fmtP(w.hi)}${w.live ? " (live)" : ""}`, "muted"]); });
  rows.push(["Boxes", `${drawn.sessions} sessions, ${drawn.pre} pre-market`, "muted"]);
}
const norm = (x) => {
  const t = String(x).trim().toLowerCase();
  const m = /^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/.exec(t);
  return m ? "#" + [m[1], m[2], m[3]].map((q) => (+q).toString(16).padStart(2, "0")).join("") : t;
};
const changed = reg.filter((r) => norm(r.v) !== norm(r.d));
rows.push(["Settings", changed.length ? `${changed.length} differ from standard` : "all standard", changed.length ? "warn" : "muted"]);
changed.slice(0, 12).forEach((r) => rows.push(["  " + r.name, `${r.v}  (standard ${r.d})`, "muted"]));
if (useDefaults) rows.push(["STANDARD SETTINGS", "ON: your values are ignored", "warn"]);
rows.push(["Info", "Descriptive data, not advice", "muted"]);
plot.info(rows, { title: "Swiftedge Sessions" });

// ---------- Alerts ----------
if (alertsOn && !tooCoarse) {
  defs.forEach((df) => {
    const flag = new Array(n).fill(false);
    real.filter((w) => w.df === df && !w.pre).forEach((w) => { if (w.first >= 0) flag[w.first] = true; });
    alert(flag, `${df.name} session opened on ${market.symbol}`);
  });
}

Comments · 0