tradingview-gex-flashalpha 0.0.0-stage → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +323 -0
- package/LICENSE +21 -0
- package/README.md +1103 -2
- package/dist/tradingview-gex-flashalpha.cjs +3722 -0
- package/dist/tradingview-gex-flashalpha.css +2 -0
- package/dist/tradingview-gex-flashalpha.js +3696 -0
- package/dist/tradingview-gex-flashalpha.min.js +52 -0
- package/dist/tradingview-gex-flashalpha.mjs +3701 -0
- package/embed.js +116 -0
- package/package.json +97 -4
- package/types/index.d.ts +460 -0
|
@@ -0,0 +1,3701 @@
|
|
|
1
|
+
/*! tradingview-gex-flashalpha v1.2.0 | MIT | https://github.com/FlashAlpha-lab/tradingview-gex-flashalpha */
|
|
2
|
+
|
|
3
|
+
// src/constants.js
|
|
4
|
+
var ET = "America/New_York";
|
|
5
|
+
var RESOLUTIONS = ["1m", "5m", "15m", "1h", "1d", "1w"];
|
|
6
|
+
var LINE_STYLES = { solid: 0, dotted: 1, dashed: 2 };
|
|
7
|
+
var RES_LABELS = { "1m": "1 minute", "5m": "5 minutes", "15m": "15 minutes", "1h": "1 hour", "1d": "1 day", "1w": "1 week" };
|
|
8
|
+
var INTRADAY = ["1m", "5m", "15m", "1h"];
|
|
9
|
+
var RES_SECONDS = { "1m": 60, "5m": 300, "15m": 900, "1h": 3600, "1d": 86400, "1w": 604800 };
|
|
10
|
+
var RANGES = [["1D", 1], ["5D", 5], ["1M", 31], ["6M", 183], ["1Y", 366]];
|
|
11
|
+
var DEFAULT_DAYS = { "1m": 1, "5m": 5, "15m": 5, "1h": 31, "1d": 183, "1w": 366 };
|
|
12
|
+
var MAX_DAYS = { "1m": 5, "5m": 31, "15m": 62, "1h": 366, "1d": 3660, "1w": 3660 };
|
|
13
|
+
var PLANS = ["free", "basic", "growth", "alpha", "enterprise"];
|
|
14
|
+
var PLAN_NAMES = { free: "Free", basic: "Basic", growth: "Growth", alpha: "Alpha", enterprise: "Enterprise" };
|
|
15
|
+
var UPGRADE_URL = "https://flashalpha.com/pricing";
|
|
16
|
+
var SIGNUP_URL = "https://flashalpha.com/pricing";
|
|
17
|
+
var KEY_ERRORS = ["api_key_required", "invalid_api_key", "invalid_embed_key"];
|
|
18
|
+
var STORAGE_KEY = "tradingview-gex-flashalpha:layers";
|
|
19
|
+
var PLAN_PITCH = {
|
|
20
|
+
basic: "See where dealers hedge: call wall, put wall, gamma flip, max pain.",
|
|
21
|
+
growth: "Strike heatmap, GEX profile and 0DTE.",
|
|
22
|
+
alpha: "Levels from live open interest, updated through the session.",
|
|
23
|
+
enterprise: "Everything, for your team and your site."
|
|
24
|
+
};
|
|
25
|
+
var NOTE = "GEX levels are model estimates from open interest, not observed dealer positions. Not financial advice.";
|
|
26
|
+
var ERRORS = {
|
|
27
|
+
api_key_required: "Add your FlashAlpha key to show this chart.",
|
|
28
|
+
invalid_api_key: "This FlashAlpha key is not valid.",
|
|
29
|
+
too_many_requests: "Too many requests. Retrying in a minute.",
|
|
30
|
+
too_many_key_lookups: "Too many requests. Retrying in a minute.",
|
|
31
|
+
auth_unavailable: "Chart data is unavailable right now. Retrying.",
|
|
32
|
+
questdb_unavailable: "Chart data is unavailable right now. Retrying.",
|
|
33
|
+
network: "Could not reach the chart server.",
|
|
34
|
+
timeout: "The chart server did not answer."
|
|
35
|
+
};
|
|
36
|
+
var GATE = {
|
|
37
|
+
title: (symbol) => symbol ? `Sign up free to see the ${symbol} chart` : "Sign up free to see this chart",
|
|
38
|
+
text: "A free FlashAlpha account loads price and volume here. From the Basic plan the chart adds the levels dealers hedge around: call wall, put wall, gamma flip and max pain.",
|
|
39
|
+
cta: "Sign up free"
|
|
40
|
+
};
|
|
41
|
+
var COLORS = {
|
|
42
|
+
line: "#4f8cff",
|
|
43
|
+
up: "#26a69a",
|
|
44
|
+
down: "#ef5350",
|
|
45
|
+
spotUp: "#5f8f8a",
|
|
46
|
+
spotDown: "#9a6463",
|
|
47
|
+
flip: "#fbbf24",
|
|
48
|
+
unverified: "#6b7080",
|
|
49
|
+
maxpain: "#a78bfa",
|
|
50
|
+
volUp: "rgba(38,166,154,0.35)",
|
|
51
|
+
volDown: "rgba(239,83,80,0.35)"
|
|
52
|
+
};
|
|
53
|
+
var THEMES = {
|
|
54
|
+
dark: {
|
|
55
|
+
bg: "#0f1115",
|
|
56
|
+
text: "#d6d9e0",
|
|
57
|
+
muted: "#8a909c",
|
|
58
|
+
line: "#262a33",
|
|
59
|
+
grid: "#1b1e25",
|
|
60
|
+
shadow: "rgba(0,0,0,0.4)",
|
|
61
|
+
shade: "rgba(15,17,21,0.6)",
|
|
62
|
+
scheme: "dark"
|
|
63
|
+
},
|
|
64
|
+
light: {
|
|
65
|
+
bg: "#ffffff",
|
|
66
|
+
text: "#1f2430",
|
|
67
|
+
muted: "#5b6270",
|
|
68
|
+
line: "#d9dde4",
|
|
69
|
+
grid: "#eef0f3",
|
|
70
|
+
shadow: "rgba(20,24,32,0.15)",
|
|
71
|
+
shade: "rgba(255,255,255,0.6)",
|
|
72
|
+
scheme: "light"
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
var NARROW = 560;
|
|
76
|
+
var TINY = 480;
|
|
77
|
+
|
|
78
|
+
// src/env.js
|
|
79
|
+
var global = typeof window !== "undefined" ? window : globalThis;
|
|
80
|
+
|
|
81
|
+
// src/css.js
|
|
82
|
+
var css = true ? '.fac{background:var(--fac-bg,#0f1115);width:100%;height:100%;min-height:240px;color:var(--fac-text,#d6d9e0);flex-direction:column;font:12px/1.4 system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;display:flex;position:relative}.fac a.fac-lock,.fac-grp a.fac-lock{color:var(--fac-muted,#8a909c);white-space:nowrap;border-radius:4px;align-items:center;gap:6px;padding:4px 6px;text-decoration:none;display:flex}.fac a.fac-lock:hover,.fac-grp a.fac-lock:hover{background:var(--fac-line,#262a33);color:var(--fac-text,#d6d9e0)}.fac-lock .plan,.fac-upsell .plan{background:var(--fac-accent,#4f8cff);color:#fff;border-radius:3px;padding:1px 5px;font-size:10px}.fac-more{border-top:1px solid var(--fac-line,#262a33);flex-direction:column;gap:6px;margin-top:4px;padding:6px 6px 2px;display:none}.fac-more:not(:empty){display:flex}.fac-more select{max-width:none}.fac-upsell{z-index:5;border:1px solid var(--fac-line,#262a33);background:var(--fac-bg,#0f1115);color:var(--fac-text,#d6d9e0);box-shadow:0 2px 10px var(--fac-shadow,#0006);border-radius:6px;align-items:center;gap:8px;padding:4px 6px 4px 10px;display:flex;position:absolute;top:6px;right:64px}.fac-upsell[hidden]{display:none}.fac-upsell a{background:var(--fac-accent,#4f8cff);color:#fff;border-radius:4px;padding:3px 10px;font-weight:600;text-decoration:none}.fac-narrow .fac-upsell{top:auto;bottom:34px;left:8px;right:auto}.fac-bar{border-bottom:1px solid var(--fac-line,#262a33);flex-wrap:wrap;align-items:center;gap:8px;padding:6px 8px;display:flex}.fac-timebar{border-top:1px solid var(--fac-line,#262a33);flex-wrap:wrap;align-items:center;gap:4px 8px;padding:3px 8px;display:flex}.fac-timebar .fac-group{border:0;padding:0}.fac-spacer{flex:1}.fac-clock{color:var(--fac-muted,#8a909c);font-variant-numeric:tabular-nums;white-space:nowrap}.fac-narrow .fac-clock{display:none}.fac-group{border:1px solid var(--fac-line,#262a33);border-radius:6px;gap:2px;padding:2px;display:flex}.fac-group button,.fac-menu>button{color:var(--fac-muted,#8a909c);cursor:pointer;font:inherit;background:0 0;border:0;border-radius:4px;padding:3px 8px}.fac-group button:hover,.fac-menu>button:hover{color:var(--fac-text,#d6d9e0)}.fac select option,.fac-grp select option{background:var(--fac-bg,#0f1115);color:var(--fac-text,#d6d9e0)}.fac-group button.on{background:var(--fac-accent,#4f8cff);color:#fff}.fac select,.fac-grp select{color:inherit;border:1px solid var(--fac-line,#262a33);font:inherit;background:0 0;border-radius:6px;max-width:170px;padding:3px 4px}.fac-menu{border:1px solid var(--fac-line,#262a33);border-radius:6px;position:relative}.fac-menu>button{color:var(--fac-text,#d6d9e0)}.fac-panel{z-index:10;background:var(--fac-bg,#0f1115);border:1px solid var(--fac-line,#262a33);border-radius:6px;min-width:190px;padding:6px;display:none;position:absolute;top:calc(100% + 4px);left:0;box-shadow:0 6px 24px #0006}.fac-menu.open .fac-panel{display:block}.fac-panel label{cursor:pointer;white-space:nowrap;border-radius:4px;align-items:center;gap:8px;padding:4px 6px;display:flex}.fac-panel label:hover{background:var(--fac-line,#262a33)}.fac-status{color:var(--fac-muted,#8a909c)}.fac-body{flex:1;min-height:0;position:relative}.fac-canvas{position:absolute;top:0;bottom:0;left:0;right:0}.fac-legend{top:6px;left:calc(10px + var(--fac-axis-left,0px));right:calc(var(--fac-plot-right,0px) + 6px);z-index:3;pointer-events:none;font-variant-numeric:tabular-nums;position:absolute}.fac-legend b{margin-right:6px;font-size:14px}.fac-legend .k{color:var(--fac-muted,#8a909c);margin-left:6px}.fac-legend .up{color:#26a69a}.fac-legend .dn{color:#ef5350}.fac-legend .sub{color:var(--fac-muted,#8a909c);margin-top:2px}.fac-empty{z-index:4;text-align:center;color:var(--fac-muted,#8a909c);background:var(--fac-bg,#0f1115);justify-content:center;align-items:center;padding:16px;display:none;position:absolute;top:0;bottom:0;left:0;right:0}.fac-empty.fac-gate{padding:0;overflow:hidden}.fac-gate-bg{filter:blur(6px);opacity:.35;pointer-events:none;width:100%;height:100%;position:absolute;top:0;bottom:0;left:0;right:0}.fac-gate-box{background:var(--fac-shade,#0f111599);-webkit-backdrop-filter:blur(2px);backdrop-filter:blur(2px);flex-direction:column;justify-content:center;align-items:center;padding:16px;display:flex;position:absolute;top:0;bottom:0;left:0;right:0;overflow:auto}.fac-gate-box>svg{width:40px;height:40px;color:var(--fac-muted,#8a909c);flex:none;margin-bottom:12px}.fac-gate-ttl{color:var(--fac-text,#d6d9e0);margin:0 0 4px;font-size:16px;font-weight:600;line-height:1.4}.fac-gate-txt{max-width:384px;color:var(--fac-muted,#8a909c);margin:0 0 16px;font-size:13px;line-height:1.5}.fac-gate-cta{color:#fff;background:var(--fac-accent,#4f8cff);border-radius:8px;align-items:center;gap:8px;padding:10px 20px;font-size:13px;font-weight:600;text-decoration:none;display:inline-flex;box-shadow:0 8px 20px -6px #4f8cff73}.fac-gate-cta:hover{filter:brightness(1.1)}.fac-gate-cta svg{width:16px;height:16px}.fac-narrow .fac-gate-ttl{font-size:14px}.fac-narrow .fac-gate-txt{margin-bottom:12px;font-size:12px}.fac-narrow .fac-gate-box>svg{width:32px;height:32px;margin-bottom:8px}.fac-narrow .fac-status{display:none}.fac-narrow .fac-group button,.fac-narrow .fac-menu>button{min-width:32px;min-height:32px;padding:3px 7px}.fac-credit{justify-content:space-between;align-items:center;gap:8px;padding:2px 10px 4px;font-size:10px;display:flex}.fac-credit a{color:var(--fac-muted,#8a909c);text-decoration:none}.fac-credit a:hover{text-decoration:underline}.fac-body>.fac-brand{left:calc(10px + var(--fac-axis-left,0px));z-index:3;color:var(--fac-text,#d6d9e0);opacity:.55;align-items:center;gap:5px;font:600 12px/1 system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;text-decoration:none;display:flex;position:absolute;bottom:34px}.fac-body>.fac-brand:hover{opacity:1}.fac-body>.fac-brand img{height:16px}.fac-narrow .fac-body>.fac-brand span{display:none}.fac select,.fac select option,.fac select optgroup,.fac-grp select,.fac-grp select option,.fac-grp select optgroup{background-color:var(--fac-bg,#0f1115);color:var(--fac-text,#d6d9e0)}.fac-panel .fac-field{color:var(--fac-muted,#8a909c);cursor:default;white-space:normal;flex-direction:column;align-items:stretch;gap:3px;padding:2px 6px;font-size:11px;display:flex}.fac-panel .fac-field:hover{background:0 0}.fac-field select{width:100%;max-width:none;color:var(--fac-text,#d6d9e0)}.fac-panel{min-width:230px}.fac-credit .fac-brand{color:var(--fac-text,#d6d9e0);opacity:.8;align-items:center;gap:5px;font:600 12px/1 system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;display:flex}.fac-credit .fac-brand:hover{opacity:1;text-decoration:none}.fac-brand img{width:auto;height:16px}.fac-note{text-align:center;min-width:0;color:var(--fac-muted,#8a909c);text-overflow:ellipsis;white-space:nowrap;flex:1;overflow:hidden}.fac-narrow .fac-note{white-space:normal;text-overflow:clip;line-height:1.3}.fac-empty.fac-loading{pointer-events:none;background:0 0}.fac-busy{z-index:5;border:1px solid var(--fac-line,#262a33);background:var(--fac-bg,#0f1115);color:var(--fac-muted,#8a909c);pointer-events:none;opacity:0;border-radius:10px;padding:2px 10px;font-size:12px;transition:opacity .15s;position:absolute;top:8px;left:50%;transform:translate(-50%)}.fac-busy.on{opacity:1;transition-delay:.2s}.fac-upsell .pitch{color:var(--fac-muted,#8a909c);max-width:260px}.fac-narrow .fac-upsell .pitch{display:none}.fac-panel{overflow-y:auto}.fac-dd-btn{align-items:center;gap:5px;display:inline-flex}.fac-dd-btn svg{width:16px;height:16px;color:var(--fac-muted,#8a909c)}.fac-dd-btn b{font-weight:700}.fac-menu.open>button,.fac-dd-btn:hover{background:var(--fac-line,#262a33)}.fac-menu.open .fac-sym-panel{flex-direction:column;display:flex}.fac-sym-panel{width:250px;min-width:0;overflow:hidden}.fac-dd .fac-panel:not(.fac-sym-panel){min-width:150px}.fac-search{box-sizing:border-box;width:100%;color:inherit;border:1px solid var(--fac-line,#262a33);font:inherit;background:0 0;border-radius:4px;outline:none;margin-bottom:4px;padding:5px 8px}.fac-search:focus{border-color:var(--fac-accent,#4f8cff)}.fac-list{flex:1;min-height:0;max-height:280px;overflow-y:auto}.fac-opt{cursor:pointer;white-space:nowrap;border-radius:4px;justify-content:space-between;gap:14px;padding:5px 8px;display:flex}.fac-opt:hover,.fac-opt.active{background:var(--fac-line,#262a33)}.fac-opt.on{color:var(--fac-accent,#4f8cff);font-weight:600}.fac-hint{text-overflow:ellipsis;min-width:0;color:var(--fac-muted,#8a909c);font-weight:400;overflow:hidden}.fac-none{color:var(--fac-muted,#8a909c);padding:6px 8px}.fac-right{align-items:center;gap:2px;display:flex}.fac-right .fac-menu{border:0}.fac-icon{width:30px;height:28px;color:var(--fac-muted,#8a909c);cursor:pointer;background:0 0;border:0;border-radius:4px;justify-content:center;align-items:center;padding:0;display:inline-flex}.fac-menu>button.fac-icon{color:var(--fac-muted,#8a909c);padding:0}.fac-icon:hover,.fac-menu.open>button.fac-icon{background:var(--fac-line,#262a33);color:var(--fac-text,#d6d9e0)}.fac-icon[hidden],.fac-account[hidden]{display:none}.fac-ttl{padding:2px 6px 6px;font-weight:600}.fac-sec{color:var(--fac-muted,#8a909c);letter-spacing:.06em;text-transform:uppercase;padding:8px 6px 2px;font-size:10px;font-weight:600}.fac-ttl+.fac-sec{padding-top:0}.fac-type .fac-dd-btn svg{color:currentColor;width:18px;height:18px}.fac-type-opt{align-items:center;gap:8px;display:inline-flex}.fac-type-opt svg{flex:none;width:18px;height:18px}.fac-scale-btns button{padding:3px 6px}.fac-feed{white-space:nowrap;border-radius:10px;margin-left:6px;padding:2px 8px;font-size:12px;font-weight:600}.fac-feed[hidden]{display:none}.fac-delayed{color:#d97706;background:#d9770626}.fac-live{color:#26a69a;background:#26a69a26}.fac-account{white-space:nowrap;border-radius:6px;margin-left:6px;padding:4px 12px;font-weight:600;text-decoration:none}.fac-signup{background:var(--fac-accent,#4f8cff);color:#fff}.fac-signup:hover{filter:brightness(1.1)}.fac-tier{border:1px solid var(--fac-line,#262a33);color:var(--fac-text,#d6d9e0)}.fac-tier:hover{border-color:var(--fac-accent,#4f8cff)}.fac-nolegend .fac-legend,.fac-nolegend .fac-pane-lgs{display:none}.fac-fullscreen{width:100vw;height:100vh}.fac-narrow .fac-icon{width:32px;height:32px}.fac-narrow .fac-account{margin-left:2px;padding:4px 8px}.fac-narrow .fac-feed{margin-left:2px;padding:2px 6px;font-size:11px}.fac-narrow .fac-sym-panel{width:220px}.fac-legend .lv{white-space:nowrap;flex-wrap:nowrap;gap:0 12px;display:flex}.fac-legend .lv>*{flex:none}.fac-legend .lv>[hidden]{display:none}.fac-legend .fac-lg-top,.fac-legend .lv,.fac-legend>.sub:not(.fac-lg-foldrow){box-sizing:border-box;background:linear-gradient(var(--fac-shade,#0f111599), var(--fac-shade,#0f111599)), var(--fac-shade,#0f111599);border-radius:3px;width:-moz-fit-content;width:fit-content;max-width:100%;margin-left:-4px;padding:0 4px}.fac-legend .fac-lg-top{display:block}.fac-lg-more{pointer-events:auto;cursor:help;color:var(--fac-muted,#8a909c)}.fac-lg-foldrow{margin-top:2px}.fac-lg-btn.fac-lg-fold{border:1px solid var(--fac-line,#262a33);background:var(--fac-bg,#0f1115);width:auto;min-width:22px;height:18px;font:inherit;gap:2px;padding:0 4px;font-size:11px}.fac-lg-fold svg{width:14px;height:14px}.fac-lg-fold.on svg{transform:rotate(180deg)}.fac-legend .lv .k{margin-left:0}.fac-legend .ch{color:var(--fac-muted,#8a909c)}.fac-fx{margin-right:2px;font-family:Georgia,serif;font-style:italic;font-weight:700}.fac-ind-menu .fac-panel{min-width:270px}.fac-ind+.fac-ind{border-top:1px solid var(--fac-line,#262a33);margin-top:4px;padding-top:4px}.fac-ind-head{align-items:center;gap:4px;display:flex}.fac-ind-head label{flex:1;min-width:0}.fac-ind-head b{text-overflow:ellipsis;overflow:hidden}.fac-ind-head .fac-icon{flex:none;width:26px;height:24px}.fac-ind-head .fac-icon svg,.fac-lg-btn svg{width:15px;height:15px}.fac-ind-layers{padding-left:22px}.fac-ind-one .fac-ind-row b{text-overflow:ellipsis;overflow:hidden}.fac-ind-row{align-items:center;gap:2px;display:flex}.fac-ind-row>:first-child{flex:1;min-width:0}.fac-ind-row .fac-icon{width:26px;height:24px;color:var(--fac-muted,#8a909c);flex:none}.fac-ind-row .fac-icon svg{width:15px;height:15px}.fac-dlg-sub{text-overflow:ellipsis;white-space:nowrap;min-width:0;color:var(--fac-muted,#8a909c);flex:0 auto;font-size:11px;overflow:hidden}.fac-dlg-hint{color:var(--fac-muted,#8a909c);margin:0 0 4px;font-size:11px}.fac-panel .fac-lock .plan,.fac-dialog .fac-lock .plan{margin-left:auto}.fac-lg-name{color:var(--fac-text,#d6d9e0);font-weight:600}.fac-lg-head{pointer-events:auto;align-items:center;display:inline-flex;position:relative}.fac-lg-head .fac-lg-name{white-space:nowrap;min-width:64px}.fac-lg-btns{z-index:1;background:var(--fac-bg,#0f1115);visibility:hidden;border-radius:4px;align-items:center;gap:4px;padding:2px 2px 2px 6px;transition:visibility 0s linear .4s;display:inline-flex;position:absolute;top:50%;left:100%;transform:translateY(-50%)}.fac-lg-head:hover .fac-lg-btns,.fac-lg-head:focus-within .fac-lg-btns,.fac-lg-off .fac-lg-btns{visibility:visible;transition-delay:0s}.fac-lg-off .fac-lg-name{opacity:.5}.fac-lg-btn{pointer-events:auto;width:22px;height:22px;color:var(--fac-muted,#8a909c);cursor:pointer;background:0 0;border:0;border-radius:4px;justify-content:center;align-items:center;padding:0;display:inline-flex}.fac-lg-btn svg{width:16px;height:16px}.fac-lg-btn:hover{background:var(--fac-line,#262a33);color:var(--fac-text,#d6d9e0)}.fac-pane-lgs{z-index:3;pointer-events:none;position:absolute;top:0;bottom:0;left:0;right:0}.fac-legend.fac-pane-lg{top:0}@media (hover:none){.fac-lg-btns{visibility:visible;position:static;transform:none}.fac-legend .fac-lg-btns{display:none}}.fac-lg-note{pointer-events:auto;cursor:help;text-underline-offset:2px;-webkit-text-decoration:underline dotted;text-decoration:underline dotted}.fac-lg-up{pointer-events:auto;color:var(--fac-accent,#4f8cff);font-weight:600;text-decoration:none}.fac-lg-up:hover{text-decoration:underline}.fac-lg-info{pointer-events:auto;width:18px;height:18px;color:var(--fac-muted,#8a909c);cursor:help;background:0 0;border:0;border-radius:50%;justify-content:center;align-items:center;padding:0;display:inline-flex;position:relative}.fac-lg-info svg{width:14px;height:14px}.fac-lg-info:hover,.fac-lg-info.fac-tip-open{color:var(--fac-text,#d6d9e0)}.fac-lg-info:focus{outline:none}.fac-lg-info:focus-visible{outline:1px solid var(--fac-accent,#4f8cff)}.fac-lg-info .fac-tip{z-index:5;border:1px solid var(--fac-line,#262a33);background:var(--fac-bg,#0f1115);width:max-content;max-width:320px;color:var(--fac-text,#d6d9e0);text-align:left;white-space:pre-line;box-shadow:0 4px 14px var(--fac-shadow,#0006);border-radius:6px;margin-top:6px;padding:8px 10px;font-size:12px;font-weight:400;line-height:1.45;display:none;position:absolute;top:100%;left:0}.fac-lg-info:hover .fac-tip,.fac-lg-info.fac-tip-open .fac-tip{display:block}.fac-lg-info:focus-visible .fac-tip{display:block}.fac-lg-ramp{pointer-events:auto;cursor:help;color:var(--fac-muted,#8a909c);align-items:center;gap:4px;font-size:11px;display:inline-flex}.fac-lg-ramp i{border:1px solid var(--fac-line,#262a33);border-radius:2px;width:72px;height:8px;display:inline-block}.fac-dialog{z-index:20;background:#00000059;justify-content:center;align-items:center;padding:12px;display:flex;position:absolute;top:0;bottom:0;left:0;right:0}.fac-dialog[hidden]{display:none}.fac-dlg{border:1px solid var(--fac-line,#262a33);background:var(--fac-bg,#0f1115);width:min(440px,100%);max-height:100%;box-shadow:0 10px 40px var(--fac-shadow,#0006);border-radius:8px;flex-direction:column;display:flex}.fac-dlg-head{align-items:center;gap:8px;padding:10px 10px 6px 14px;font-size:14px;display:flex}.fac-dlg-head b{text-overflow:ellipsis;white-space:nowrap;flex:1;min-width:0;overflow:hidden}.fac-dlg-head .fac-icon{font-size:20px;line-height:1}.fac-tabs{border-bottom:1px solid var(--fac-line,#262a33);gap:4px;padding:0 12px;display:flex}.fac-tabs button{color:var(--fac-muted,#8a909c);font:inherit;cursor:pointer;background:0 0;border:0;border-bottom:2px solid #0000;padding:6px 10px}.fac-tabs button.on{border-bottom-color:var(--fac-accent,#4f8cff);color:var(--fac-text,#d6d9e0)}.fac-dlg-body{flex:1;min-height:0;padding:8px 14px;overflow-y:auto}.fac-dlg-body label{cursor:pointer;align-items:center;gap:8px;padding:4px 0;display:flex}.fac-dlg-body a.fac-lock{padding:4px 0}.fac-dlg-sec{color:var(--fac-muted,#8a909c);text-transform:uppercase;letter-spacing:.04em;margin:8px 0 2px;font-size:11px}.fac-dlg-sec:first-child{margin-top:0}.fac-dlg-inputs .fac-field{color:var(--fac-muted,#8a909c);cursor:default;flex-direction:column;align-items:stretch;gap:3px;font-size:11px;display:flex}.fac-sty{align-items:center;gap:8px;padding:3px 0;display:flex}.fac-sty-name{flex:1;min-width:0}.fac-sty input[type=color]{border:1px solid var(--fac-line,#262a33);cursor:pointer;background:0 0;border-radius:4px;width:30px;height:22px;padding:0 2px}.fac-sty select{max-width:90px}.fac-dlg-foot{border-top:1px solid var(--fac-line,#262a33);align-items:center;gap:8px;padding:10px 14px;display:flex}.fac-dlg-foot button{border:1px solid var(--fac-line,#262a33);color:var(--fac-text,#d6d9e0);font:inherit;cursor:pointer;background:0 0;border-radius:6px;padding:5px 12px}.fac-dlg-foot button:hover{border-color:var(--fac-accent,#4f8cff)}.fac-dlg-foot .fac-primary{border-color:var(--fac-accent,#4f8cff);background:var(--fac-accent,#4f8cff);color:#fff}.fac-narrow .fac-sty{flex-wrap:wrap}.fac-grp{background:var(--fac-bg,#0f1115);width:100%;height:100%;min-height:240px;color:var(--fac-text,#d6d9e0);flex-direction:column;font:12px/1.4 system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Noto Sans,Ubuntu,Cantarell,Helvetica Neue,sans-serif;display:flex;position:relative}.fac-grp-top{z-index:10;order:-1;position:relative}.fac-grp-grid{background:var(--fac-line,#262a33);flex:1;gap:1px;min-height:0;display:grid}.fac-cell{background:var(--fac-bg,#0f1115);min-width:0;min-height:0;display:flex;position:relative;overflow:hidden}.fac-cell[hidden]{display:none}.fac-cell>.fac{min-height:0}.fac-cell .fac-bar,.fac-cell .fac-timebar,.fac-cell .fac-credit{display:none}.fac-grp-multi .fac-cell.on:after{content:"";z-index:8;border:1px solid var(--fac-accent,#4f8cff);pointer-events:none;position:absolute;top:0;bottom:0;left:0;right:0}.fac-grp-single .fac-layouts{display:none}.fac-layouts>button{justify-content:center;align-items:center;display:inline-flex}.fac-layouts .fac-panel{white-space:nowrap;min-width:0}.fac-lay-row{border-top:1px solid var(--fac-line,#262a33);align-items:center;gap:2px;padding:4px 2px;display:flex}.fac-ttl+.fac-lay-row{border-top:0}.fac-lay-n{width:18px;color:var(--fac-muted,#8a909c);text-align:center;flex:none;font-size:11px}.fac-lay-row button{width:30px;height:26px;color:var(--fac-text,#d6d9e0);cursor:pointer;background:0 0;border:0;border-radius:4px;justify-content:center;align-items:center;padding:0;display:inline-flex}.fac-lay-row button:hover{background:var(--fac-line,#262a33)}.fac-lay-row button.on{background:var(--fac-text,#d6d9e0);color:var(--fac-bg,#0f1115)}.fac,.fac-grp{color-scheme:var(--fac-scheme,dark)}.fac input[type=checkbox],.fac input[type=radio],.fac-grp input[type=checkbox],.fac-grp input[type=radio]{all:revert}.fac select,.fac input[type=search],.fac-grp select,.fac-grp input[type=search]{-webkit-appearance:auto;appearance:auto;-webkit-print-color-adjust:economy;-moz-print-color-adjust:economy;print-color-adjust:economy}.fac select:focus,.fac input[type=search]:focus,.fac-grp select:focus,.fac-grp input[type=search]:focus{box-shadow:none}.fac select:focus,.fac-grp select:focus{outline:revert}.fac input[type=search]::placeholder,.fac-grp input[type=search]::placeholder{color:revert;opacity:revert}' : "";
|
|
83
|
+
function injectCss() {
|
|
84
|
+
if (!css || typeof document === "undefined" || document.getElementById("fac-css")) return;
|
|
85
|
+
const style = document.createElement("style");
|
|
86
|
+
style.id = "fac-css";
|
|
87
|
+
style.textContent = css;
|
|
88
|
+
document.head.appendChild(style);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// src/time.js
|
|
92
|
+
var fmtTime = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", hour12: false });
|
|
93
|
+
var fmtDay = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", month: "short", day: "numeric" });
|
|
94
|
+
var fmtClock = new Intl.DateTimeFormat("en-US", { timeZone: "UTC", hour: "numeric", minute: "numeric", hour12: false });
|
|
95
|
+
var etParts = new Intl.DateTimeFormat("en-US", {
|
|
96
|
+
timeZone: ET,
|
|
97
|
+
year: "numeric",
|
|
98
|
+
month: "numeric",
|
|
99
|
+
day: "numeric",
|
|
100
|
+
hour: "numeric",
|
|
101
|
+
minute: "numeric",
|
|
102
|
+
second: "numeric",
|
|
103
|
+
hour12: false
|
|
104
|
+
});
|
|
105
|
+
function etTime(iso) {
|
|
106
|
+
const p = Object.fromEntries(etParts.formatToParts(new Date(iso)).map((x) => [x.type, x.value]));
|
|
107
|
+
return Date.UTC(+p.year, +p.month - 1, +p.day, +p.hour % 24, +p.minute, +p.second) / 1e3;
|
|
108
|
+
}
|
|
109
|
+
var dayOf = (t) => new Date(t * 1e3).toISOString().slice(0, 10);
|
|
110
|
+
function sessionOf(t) {
|
|
111
|
+
const [h, m] = fmtClock.format(new Date(t * 1e3)).split(":").map(Number);
|
|
112
|
+
const mins = h * 60 + m;
|
|
113
|
+
return mins < 570 ? "pre" : mins >= 960 ? "post" : "rth";
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// src/util.js
|
|
117
|
+
var esc = (v) => String(v ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
118
|
+
var num = (v, d = 2) => v == null ? "—" : v.toLocaleString("en-US", { minimumFractionDigits: d, maximumFractionDigits: d });
|
|
119
|
+
var big = (v) => v == null ? "—" : Math.abs(v) >= 1e9 ? (v / 1e9).toFixed(2) + "B" : Math.abs(v) >= 1e6 ? (v / 1e6).toFixed(1) + "M" : Math.abs(v) >= 1e3 ? (v / 1e3).toFixed(1) + "K" : String(Math.round(v));
|
|
120
|
+
var GAP_KEYS = {
|
|
121
|
+
line: ["color"],
|
|
122
|
+
area: ["lineColor", "topColor", "bottomColor"],
|
|
123
|
+
baseline: ["topLineColor", "bottomLineColor", "topFillColor1", "topFillColor2", "bottomFillColor1", "bottomFillColor2"]
|
|
124
|
+
};
|
|
125
|
+
function cutGaps(points, type = "line") {
|
|
126
|
+
const keys = GAP_KEYS[type] || GAP_KEYS.line;
|
|
127
|
+
const has = (p) => p && p.value != null;
|
|
128
|
+
const out = points.slice();
|
|
129
|
+
let later = false;
|
|
130
|
+
for (let i = out.length - 1; i >= 0; i--) {
|
|
131
|
+
if (!has(out[i])) continue;
|
|
132
|
+
if (later && i + 1 < out.length && !has(out[i + 1])) {
|
|
133
|
+
const clear = {};
|
|
134
|
+
for (const k of keys) clear[k] = "transparent";
|
|
135
|
+
out[i] = Object.assign({}, out[i], clear);
|
|
136
|
+
}
|
|
137
|
+
later = true;
|
|
138
|
+
}
|
|
139
|
+
return out;
|
|
140
|
+
}
|
|
141
|
+
function floorIndex(times, t) {
|
|
142
|
+
let lo = 0, hi = times.length - 1, at = -1;
|
|
143
|
+
while (lo <= hi) {
|
|
144
|
+
const mid = lo + hi >> 1;
|
|
145
|
+
if (times[mid] <= t) {
|
|
146
|
+
at = mid;
|
|
147
|
+
lo = mid + 1;
|
|
148
|
+
} else hi = mid - 1;
|
|
149
|
+
}
|
|
150
|
+
return at;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/percent-levels.js
|
|
154
|
+
var OFF = { lineVisible: false, priceLineVisible: false, lastValueVisible: false, title: "" };
|
|
155
|
+
var KEYS = Object.keys(OFF);
|
|
156
|
+
var DASH = [[], [1, 1], [2, 2], [6, 6], [1, 4]];
|
|
157
|
+
function createPercentLevels(chart) {
|
|
158
|
+
const list = [];
|
|
159
|
+
let candles = null, on = false, update = null, attached = false;
|
|
160
|
+
function sync(e) {
|
|
161
|
+
if (!candles) return;
|
|
162
|
+
const o = e.s.options();
|
|
163
|
+
let last = null;
|
|
164
|
+
if (on && o.visible !== false) {
|
|
165
|
+
for (let i = e.data.length - 1; i >= 0; i--) if (e.data[i] && e.data[i].value != null) {
|
|
166
|
+
last = e.data[i];
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
if (!last || !(e.want.priceLineVisible || e.want.lastValueVisible)) {
|
|
171
|
+
if (e.line) {
|
|
172
|
+
candles.removePriceLine(e.line);
|
|
173
|
+
e.line = null;
|
|
174
|
+
}
|
|
175
|
+
} else {
|
|
176
|
+
const spec = {
|
|
177
|
+
price: last.value,
|
|
178
|
+
color: o.priceLineColor || o.color,
|
|
179
|
+
lineWidth: o.priceLineWidth || 1,
|
|
180
|
+
lineStyle: o.priceLineStyle ?? 1,
|
|
181
|
+
lineVisible: !!e.want.priceLineVisible,
|
|
182
|
+
axisLabelVisible: !!e.want.lastValueVisible,
|
|
183
|
+
title: e.want.title || ""
|
|
184
|
+
};
|
|
185
|
+
if (e.line) e.line.applyOptions(spec);
|
|
186
|
+
else e.line = candles.createPriceLine(spec);
|
|
187
|
+
}
|
|
188
|
+
if (update) update();
|
|
189
|
+
}
|
|
190
|
+
const renderer = {
|
|
191
|
+
draw(target) {
|
|
192
|
+
if (!on || !candles) return;
|
|
193
|
+
const ts = chart.timeScale();
|
|
194
|
+
target.useBitmapCoordinateSpace(({ context: c, horizontalPixelRatio: hr, verticalPixelRatio: vr }) => {
|
|
195
|
+
for (const e of list) {
|
|
196
|
+
const o = e.s.options();
|
|
197
|
+
if (!e.want.lineVisible || o.visible === false) continue;
|
|
198
|
+
const w = Math.max(1, Math.round((o.lineWidth || 1) * hr));
|
|
199
|
+
c.lineWidth = w;
|
|
200
|
+
c.setLineDash((DASH[o.lineStyle] || []).map((x) => x * w));
|
|
201
|
+
let prev = null;
|
|
202
|
+
for (const p of e.data) {
|
|
203
|
+
const x = p ? ts.timeToCoordinate(p.time) : null;
|
|
204
|
+
const y = p && p.value != null ? candles.priceToCoordinate(p.value) : null;
|
|
205
|
+
if (x == null || y == null) {
|
|
206
|
+
prev = null;
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (prev) {
|
|
210
|
+
c.strokeStyle = prev.color;
|
|
211
|
+
c.beginPath();
|
|
212
|
+
c.moveTo(prev.x * hr, prev.y * vr);
|
|
213
|
+
c.lineTo(x * hr, prev.y * vr);
|
|
214
|
+
c.lineTo(x * hr, y * vr);
|
|
215
|
+
c.stroke();
|
|
216
|
+
}
|
|
217
|
+
prev = { x, y, color: p.color || o.color };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
c.setLineDash([]);
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
};
|
|
224
|
+
const primitive = {
|
|
225
|
+
attached(p) {
|
|
226
|
+
update = p.requestUpdate;
|
|
227
|
+
},
|
|
228
|
+
detached() {
|
|
229
|
+
update = null;
|
|
230
|
+
},
|
|
231
|
+
paneViews: () => [{ zOrder: () => "normal", renderer: () => renderer }]
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
/** The candles series, once it exists: the primitive draws on it (attached the first time a percent scale is on). */
|
|
235
|
+
setCandles(s) {
|
|
236
|
+
candles = s;
|
|
237
|
+
},
|
|
238
|
+
/**
|
|
239
|
+
* Follows a level series: its options and data go through here, so the scale mode can turn its own drawing off and on
|
|
240
|
+
* while the series' style (plot style, titles, latest-session rule) keeps what the chart and the plugins set.
|
|
241
|
+
*/
|
|
242
|
+
track(s, opts) {
|
|
243
|
+
const real = s.applyOptions.bind(s), set = s.setData.bind(s);
|
|
244
|
+
const e = {
|
|
245
|
+
s,
|
|
246
|
+
real,
|
|
247
|
+
data: [],
|
|
248
|
+
line: null,
|
|
249
|
+
want: Object.fromEntries(KEYS.map((k) => [k, k === "title" ? opts.title || "" : opts[k] !== false]))
|
|
250
|
+
};
|
|
251
|
+
s.applyOptions = (x) => {
|
|
252
|
+
const v = Object.assign({}, x || {});
|
|
253
|
+
for (const k of KEYS) if (k in v) e.want[k] = v[k];
|
|
254
|
+
real(on ? Object.assign(v, OFF) : v);
|
|
255
|
+
sync(e);
|
|
256
|
+
};
|
|
257
|
+
s.setData = (d) => {
|
|
258
|
+
e.data = d || [];
|
|
259
|
+
set(d);
|
|
260
|
+
sync(e);
|
|
261
|
+
};
|
|
262
|
+
list.push(e);
|
|
263
|
+
if (on) real(OFF);
|
|
264
|
+
return s;
|
|
265
|
+
},
|
|
266
|
+
/** True for Percent or Indexed to 100 on the price scale. */
|
|
267
|
+
setMode(percent) {
|
|
268
|
+
percent = !!percent;
|
|
269
|
+
if (percent === on) return;
|
|
270
|
+
on = percent;
|
|
271
|
+
if (on && !attached && candles && typeof candles.attachPrimitive === "function") {
|
|
272
|
+
attached = true;
|
|
273
|
+
candles.attachPrimitive(primitive);
|
|
274
|
+
}
|
|
275
|
+
for (const e of list) {
|
|
276
|
+
e.real(on ? OFF : Object.assign({}, e.want));
|
|
277
|
+
sync(e);
|
|
278
|
+
}
|
|
279
|
+
},
|
|
280
|
+
get on() {
|
|
281
|
+
return on;
|
|
282
|
+
}
|
|
283
|
+
};
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// src/source.js
|
|
287
|
+
var SYMBOLS_MS = 6e4;
|
|
288
|
+
var symbolsAnswers = /* @__PURE__ */ new Map();
|
|
289
|
+
function chartEngineSource(baseUrl, apiKey) {
|
|
290
|
+
const root = (baseUrl || "").replace(/\/$/, "");
|
|
291
|
+
const headers = apiKey ? { "X-Api-Key": apiKey } : void 0;
|
|
292
|
+
const get = async (url) => {
|
|
293
|
+
const abort = typeof AbortController === "function" ? new AbortController() : null;
|
|
294
|
+
const timer = abort ? setTimeout(() => abort.abort(), 2e4) : null;
|
|
295
|
+
try {
|
|
296
|
+
const r = await fetch(root + url, { headers, signal: abort ? abort.signal : void 0 });
|
|
297
|
+
return await r.json().catch(() => ({ error: `http_${r.status}` }));
|
|
298
|
+
} catch (e) {
|
|
299
|
+
return { error: e && e.name === "AbortError" ? "timeout" : "network", message: String(e) };
|
|
300
|
+
} finally {
|
|
301
|
+
if (timer) clearTimeout(timer);
|
|
302
|
+
}
|
|
303
|
+
};
|
|
304
|
+
return {
|
|
305
|
+
symbols: () => {
|
|
306
|
+
const k = `${root}
|
|
307
|
+
${apiKey || ""}`, hit = symbolsAnswers.get(k);
|
|
308
|
+
const p = hit && Date.now() - hit.at < SYMBOLS_MS ? hit.p : get("/v1/symbols");
|
|
309
|
+
if (!hit || hit.p !== p) {
|
|
310
|
+
symbolsAnswers.set(k, { at: Date.now(), p });
|
|
311
|
+
p.then((l) => {
|
|
312
|
+
const cur = symbolsAnswers.get(k);
|
|
313
|
+
if (!Array.isArray(l) && cur && cur.p === p) symbolsAnswers.delete(k);
|
|
314
|
+
});
|
|
315
|
+
}
|
|
316
|
+
return p.then((l) => Array.isArray(l) ? l.slice() : l);
|
|
317
|
+
},
|
|
318
|
+
bars: (s, res, from, to, session, extra) => get(`/v1/bars/${encodeURIComponent(s)}?resolution=${res}&from=${from}&to=${to}&limit=10000&session=${session || "rth"}` + (extra && extra.sessions ? `&sessions=${extra.sessions}` : "")),
|
|
319
|
+
charts: (s, res, from, to, q) => {
|
|
320
|
+
const { layers, session, ...extra } = q;
|
|
321
|
+
const p = new URLSearchParams({ resolution: res, layers: layers.join(","), session: session || "rth", from, to });
|
|
322
|
+
for (const [k, v] of Object.entries(extra)) if (v != null) p.set(k, v);
|
|
323
|
+
return get(`/v1/charts/${encodeURIComponent(s)}?${p}`);
|
|
324
|
+
}
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// src/plans.js
|
|
329
|
+
var planRank = (p) => Math.max(0, PLANS.indexOf(String(p || "").toLowerCase()));
|
|
330
|
+
var licenseKey = null;
|
|
331
|
+
function setLicenseKey(key) {
|
|
332
|
+
licenseKey = key || null;
|
|
333
|
+
}
|
|
334
|
+
var getLicenseKey = () => licenseKey;
|
|
335
|
+
var siteOf = (host) => String(host || "").toLowerCase().replace(/^www\./, "");
|
|
336
|
+
function upgradeHref(upgradeUrl, what, campaign = "upgrade") {
|
|
337
|
+
const here = global.location;
|
|
338
|
+
const u = new URL(upgradeUrl, here ? here.href : void 0);
|
|
339
|
+
if (here && here.hostname && siteOf(u.hostname) === siteOf(here.hostname)) return u.toString();
|
|
340
|
+
u.searchParams.set("utm_source", "chart");
|
|
341
|
+
u.searchParams.set("utm_medium", "embed");
|
|
342
|
+
u.searchParams.set("utm_campaign", campaign);
|
|
343
|
+
if (what) u.searchParams.set("utm_content", what);
|
|
344
|
+
if (global.location && global.location.hostname) u.searchParams.set("utm_term", global.location.hostname);
|
|
345
|
+
return u.toString();
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/plugins/levels-overlay.js
|
|
349
|
+
var ZONE = {
|
|
350
|
+
dark: { pos: "rgba(52,211,153,0.06)", neg: "rgba(248,113,113,0.06)" },
|
|
351
|
+
light: { pos: "rgba(5,150,105,0.06)", neg: "rgba(220,38,38,0.06)" }
|
|
352
|
+
};
|
|
353
|
+
var VEIL_ALPHA = 0.6;
|
|
354
|
+
var DASH2 = { 1: [1, 1], 2: [2, 2] };
|
|
355
|
+
var FONT = "600 11px system-ui, -apple-system, Segoe UI, sans-serif";
|
|
356
|
+
var CHIP_H = 16;
|
|
357
|
+
var GAP = 4;
|
|
358
|
+
var PAD = 5;
|
|
359
|
+
function pct(value, from) {
|
|
360
|
+
if (value == null || !from) return "";
|
|
361
|
+
const d = Math.round((value - from) / from * 1e3) / 10;
|
|
362
|
+
return (d > 0 ? "+" : d < 0 ? "−" : "") + Math.abs(d).toFixed(1) + "%";
|
|
363
|
+
}
|
|
364
|
+
function regimeRuns(rows) {
|
|
365
|
+
const out = [];
|
|
366
|
+
let run = null;
|
|
367
|
+
for (const r of rows) {
|
|
368
|
+
if (r.flip == null) {
|
|
369
|
+
run = null;
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
if (run && run.flip === r.flip) run.to = r.time;
|
|
373
|
+
else out.push(run = { from: r.time, to: r.time, flip: r.flip });
|
|
374
|
+
}
|
|
375
|
+
return out;
|
|
376
|
+
}
|
|
377
|
+
function veil(bg, light) {
|
|
378
|
+
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(bg || "");
|
|
379
|
+
const h = hex && (hex[1].length === 3 ? hex[1].replace(/./g, "$&$&") : hex[1]);
|
|
380
|
+
const rgb = h ? [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16)) : (/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/i.exec(bg || "") || []).slice(1, 4);
|
|
381
|
+
const [r, g, b] = rgb.length === 3 ? rgb : light ? [255, 255, 255] : [15, 17, 21];
|
|
382
|
+
return `rgba(${r}, ${g}, ${b}, ${VEIL_ALPHA})`;
|
|
383
|
+
}
|
|
384
|
+
function levelRuns(points, split = () => false) {
|
|
385
|
+
const out = [];
|
|
386
|
+
let run = null, prev = null;
|
|
387
|
+
for (const p of points) {
|
|
388
|
+
if (p.value == null) run = null;
|
|
389
|
+
else if (run && run.value === p.value && run.color === p.color && !split(prev, p)) run.to = p.time;
|
|
390
|
+
else out.push(run = { from: p.time, to: p.time, value: p.value, color: p.color });
|
|
391
|
+
prev = p;
|
|
392
|
+
}
|
|
393
|
+
return out;
|
|
394
|
+
}
|
|
395
|
+
function edgeLabels(levels, yOf, height, spot) {
|
|
396
|
+
const top = [], bottom = [];
|
|
397
|
+
for (const l of levels) {
|
|
398
|
+
const y = yOf(l.value);
|
|
399
|
+
if (y == null || y >= 0 && y <= height) continue;
|
|
400
|
+
const d = pct(l.value, spot);
|
|
401
|
+
const text = `${y < 0 ? "▲" : "▼"} ${l.title} ${l.value.toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}${d ? ` (${d})` : ""}`;
|
|
402
|
+
(y < 0 ? top : bottom).push({ text, color: l.color });
|
|
403
|
+
}
|
|
404
|
+
return { top, bottom };
|
|
405
|
+
}
|
|
406
|
+
var LevelsOverlay = class {
|
|
407
|
+
/** `theme()` → { light, bg, right }: read at each repaint, so a theme change shows at once; right: px kept free at the
|
|
408
|
+
* pane's right edge (the edge labels end left of it). */
|
|
409
|
+
constructor(theme) {
|
|
410
|
+
this.theme = theme;
|
|
411
|
+
this.data = { runs: [], levels: [], spot: null, lines: [], hidden: [], focus: null };
|
|
412
|
+
this.chart = this.series = this.requestUpdate = null;
|
|
413
|
+
this.views = [
|
|
414
|
+
{ zOrder: () => "bottom", renderer: () => ({ draw: (target) => this.drawZones(target) }) },
|
|
415
|
+
// the veil before the edge labels: they stay readable
|
|
416
|
+
{ zOrder: () => "top", renderer: () => ({ draw: (target) => this.drawFocus(target) }) },
|
|
417
|
+
{ zOrder: () => "top", renderer: () => ({ draw: (target) => this.drawEdges(target) }) },
|
|
418
|
+
{ zOrder: () => "normal", renderer: () => ({ draw: (target) => this.drawLines(target) }) }
|
|
419
|
+
];
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* { runs: regimeRuns(..), levels: [{ id, title, value, color }], spot, lines: [{ from, to, value, color, width, style }],
|
|
423
|
+
* hidden: [level ids without an edge label], focus: { from, to } (the session under the crosshair, the others veiled)
|
|
424
|
+
* or null }; a missing key keeps its value.
|
|
425
|
+
*/
|
|
426
|
+
set(data) {
|
|
427
|
+
Object.assign(this.data, data);
|
|
428
|
+
if (this.requestUpdate) this.requestUpdate();
|
|
429
|
+
}
|
|
430
|
+
attached({ chart, series, requestUpdate }) {
|
|
431
|
+
this.chart = chart;
|
|
432
|
+
this.series = series;
|
|
433
|
+
this.requestUpdate = requestUpdate;
|
|
434
|
+
}
|
|
435
|
+
detached() {
|
|
436
|
+
this.chart = this.series = this.requestUpdate = null;
|
|
437
|
+
}
|
|
438
|
+
updateAllViews() {
|
|
439
|
+
}
|
|
440
|
+
paneViews() {
|
|
441
|
+
return this.views;
|
|
442
|
+
}
|
|
443
|
+
edges(height) {
|
|
444
|
+
const levels = this.data.levels.filter((l) => !this.data.hidden.includes(l.id));
|
|
445
|
+
return edgeLabels(levels, (v) => this.series.priceToCoordinate(v), height, this.data.spot);
|
|
446
|
+
}
|
|
447
|
+
/** The pane x span of the bars `from` to `to` (chart times), bar edge to bar edge; null when unknown or out of view. */
|
|
448
|
+
span(from, to, width) {
|
|
449
|
+
const ts = this.chart.timeScale(), half = (ts.options().barSpacing || 6) / 2;
|
|
450
|
+
const x0 = ts.timeToCoordinate(from), x1 = ts.timeToCoordinate(to);
|
|
451
|
+
if (x0 == null || x1 == null || x1 + half < 0 || x0 - half > width) return null;
|
|
452
|
+
return { left: Math.max(0, x0 - half), right: Math.min(width, x1 + half) };
|
|
453
|
+
}
|
|
454
|
+
drawZones(target) {
|
|
455
|
+
if (!this.series || !this.data.runs.length) return;
|
|
456
|
+
target.useMediaCoordinateSpace(({ context: c, mediaSize: { width, height } }) => {
|
|
457
|
+
const ts = this.chart.timeScale(), half = (ts.options().barSpacing || 6) / 2;
|
|
458
|
+
const colors = ZONE[this.theme().light ? "light" : "dark"];
|
|
459
|
+
for (const r of this.data.runs) {
|
|
460
|
+
const x0 = ts.timeToCoordinate(r.from), x1 = ts.timeToCoordinate(r.to), y = this.series.priceToCoordinate(r.flip);
|
|
461
|
+
if (x0 == null || x1 == null || y == null || x1 + half < 0 || x0 - half > width) continue;
|
|
462
|
+
const left = Math.max(0, x0 - half), right = Math.min(width, x1 + half), split = Math.max(0, Math.min(height, y));
|
|
463
|
+
c.fillStyle = colors.pos;
|
|
464
|
+
c.fillRect(left, 0, right - left, split);
|
|
465
|
+
c.fillStyle = colors.neg;
|
|
466
|
+
c.fillRect(left, split, right - left, height - split);
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
/** The sessions left and right of the one in focus, under a veil of the chart's background. */
|
|
471
|
+
drawFocus(target) {
|
|
472
|
+
const f = this.data.focus;
|
|
473
|
+
if (!this.series || !f) return;
|
|
474
|
+
target.useMediaCoordinateSpace(({ context: c, mediaSize: { width, height } }) => {
|
|
475
|
+
const x = this.span(f.from, f.to, width);
|
|
476
|
+
if (!x) return;
|
|
477
|
+
const t = this.theme();
|
|
478
|
+
c.fillStyle = veil(t.bg, t.light);
|
|
479
|
+
if (x.left > 0) c.fillRect(0, 0, x.left, height);
|
|
480
|
+
if (x.right < width) c.fillRect(x.right, 0, width - x.right, height);
|
|
481
|
+
});
|
|
482
|
+
}
|
|
483
|
+
drawLines(target) {
|
|
484
|
+
if (!this.series || !this.data.lines.length) return;
|
|
485
|
+
target.useMediaCoordinateSpace(({ context: c, mediaSize: { width } }) => {
|
|
486
|
+
for (const l of this.data.lines) {
|
|
487
|
+
const x = this.span(l.from, l.to, width), y = this.series.priceToCoordinate(l.value);
|
|
488
|
+
if (!x || y == null) continue;
|
|
489
|
+
c.strokeStyle = l.color;
|
|
490
|
+
c.lineWidth = l.width;
|
|
491
|
+
c.setLineDash((DASH2[l.style] || []).map((n) => n * l.width));
|
|
492
|
+
c.beginPath();
|
|
493
|
+
c.moveTo(x.left, y);
|
|
494
|
+
c.lineTo(x.right, y);
|
|
495
|
+
c.stroke();
|
|
496
|
+
}
|
|
497
|
+
c.setLineDash([]);
|
|
498
|
+
});
|
|
499
|
+
}
|
|
500
|
+
drawEdges(target) {
|
|
501
|
+
if (!this.series || !this.data.levels.length) return;
|
|
502
|
+
target.useMediaCoordinateSpace(({ context: c, mediaSize: { width, height } }) => {
|
|
503
|
+
const { top, bottom } = this.edges(height);
|
|
504
|
+
const { bg, right = 0 } = this.theme();
|
|
505
|
+
c.font = FONT;
|
|
506
|
+
c.textAlign = "left";
|
|
507
|
+
c.textBaseline = "middle";
|
|
508
|
+
const chip = (l, y) => {
|
|
509
|
+
const w = c.measureText(l.text).width + PAD * 2, x = width - right - w - 6;
|
|
510
|
+
c.globalAlpha = 0.9;
|
|
511
|
+
c.fillStyle = bg;
|
|
512
|
+
c.fillRect(x, y, w, CHIP_H);
|
|
513
|
+
c.globalAlpha = 1;
|
|
514
|
+
c.strokeStyle = l.color;
|
|
515
|
+
c.lineWidth = 1;
|
|
516
|
+
c.strokeRect(x + 0.5, y + 0.5, w - 1, CHIP_H - 1);
|
|
517
|
+
c.fillStyle = l.color;
|
|
518
|
+
c.fillText(l.text, x + PAD, y + CHIP_H / 2);
|
|
519
|
+
};
|
|
520
|
+
top.forEach((l, i) => chip(l, GAP + i * (CHIP_H + GAP)));
|
|
521
|
+
bottom.forEach((l, i) => chip(l, height - GAP - CHIP_H - i * (CHIP_H + GAP)));
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
// src/plugins/levels.js
|
|
527
|
+
var CORE_INDICATOR = "GEX Levels";
|
|
528
|
+
var STALE_MINUTES = 10;
|
|
529
|
+
var STALE_COLOR = "#f59e0b";
|
|
530
|
+
var dailyQuery = (q) => (q.scope || "all") === "all" && (q.basis || "settled") === "settled";
|
|
531
|
+
var WALLS = [
|
|
532
|
+
{ id: "callWall", broken: "callWallBroken", field: "call_wall", title: "Call wall", through: (close, wall) => close > wall, position: "aboveBar", shape: "arrowUp" },
|
|
533
|
+
{ id: "putWall", broken: "putWallBroken", field: "put_wall", title: "Put wall", through: (close, wall) => close < wall, position: "belowBar", shape: "arrowDown" }
|
|
534
|
+
];
|
|
535
|
+
var LEVEL_TITLES = [["callWall", "Call wall"], ["putWall", "Put wall"], ["flip", "Gamma flip"], ["maxPain", "Max pain"]];
|
|
536
|
+
var FLAT = ["callWall", "putWall", "flip", "maxPain"];
|
|
537
|
+
var LATEST_ONLY = ["callWall", "putWall", "flip"];
|
|
538
|
+
function faded(c) {
|
|
539
|
+
const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(c || "");
|
|
540
|
+
if (hex) {
|
|
541
|
+
const h = hex[1].length === 3 ? hex[1].replace(/./g, "$&$&") : hex[1];
|
|
542
|
+
return `rgba(${parseInt(h.slice(0, 2), 16)}, ${parseInt(h.slice(2, 4), 16)}, ${parseInt(h.slice(4, 6), 16)}, 0.35)`;
|
|
543
|
+
}
|
|
544
|
+
const rgb = /^rgba?\(\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s)]+)/i.exec(c || "");
|
|
545
|
+
return rgb ? `rgba(${rgb[1]}, ${rgb[2]}, ${rgb[3]}, 0.35)` : c;
|
|
546
|
+
}
|
|
547
|
+
var levelsPlugin = {
|
|
548
|
+
indicator: CORE_INDICATOR,
|
|
549
|
+
layers: [["levels", "Walls & gamma flip"], ["maxpain", "Max pain"]],
|
|
550
|
+
defaults: ["levels"],
|
|
551
|
+
plans: { levels: "basic", maxpain: "basic" },
|
|
552
|
+
plots: [
|
|
553
|
+
{ id: "callWall", title: "Call wall", layer: "levels", color: "#059669", lineWidth: 2 },
|
|
554
|
+
{ id: "putWall", title: "Put wall", layer: "levels", color: "#f84040", lineWidth: 2 },
|
|
555
|
+
{ id: "flip", title: "Gamma flip", layer: "levels", color: "#fbbf24", lineStyle: "dashed", lineWidth: 2 },
|
|
556
|
+
{ id: "flipUnverified", title: "Gamma flip (unverified)", layer: "levels", color: "rgba(251,191,36,0.45)", colorOnly: true },
|
|
557
|
+
{ id: "callWallBroken", title: "Call wall broken", layer: "levels", color: "#059669", visible: false, toggle: true },
|
|
558
|
+
{ id: "putWallBroken", title: "Put wall broken", layer: "levels", color: "#f84040", visible: false, toggle: true },
|
|
559
|
+
{ id: "maxPain", title: "Max pain", layer: "maxpain", color: "#a78bfa", lineStyle: "dashed", lineWidth: 2 }
|
|
560
|
+
],
|
|
561
|
+
apiLayers(ctx) {
|
|
562
|
+
if (!["levels", "maxpain"].some(ctx.on)) return [];
|
|
563
|
+
const out = ctx.intraday() ? ["exposure"] : [];
|
|
564
|
+
if (dailyQuery(ctx.query)) out.push("levels_daily");
|
|
565
|
+
return out;
|
|
566
|
+
},
|
|
567
|
+
attach(ctx) {
|
|
568
|
+
const { LW } = ctx;
|
|
569
|
+
const { dayOf: dayOf2 } = ctx.util;
|
|
570
|
+
const flip = (e) => e.gamma_flip || {};
|
|
571
|
+
const color = (id) => ctx.styleOf(id).color;
|
|
572
|
+
let s = null, daily = null, markers = null, overlay = null;
|
|
573
|
+
let dailyByTime = /* @__PURE__ */ new Map(), dailyCut = {};
|
|
574
|
+
let broken = {};
|
|
575
|
+
const showBreaks = (w) => ctx.styleOf(w.broken).visible !== false;
|
|
576
|
+
const isBroken = (w, e) => {
|
|
577
|
+
if (!showBreaks(w)) return false;
|
|
578
|
+
const t = broken[w.id] && broken[w.id].get(dayOf2(e.time) + "|" + e[w.field]);
|
|
579
|
+
return t != null && e.time >= t;
|
|
580
|
+
};
|
|
581
|
+
function findBreaks() {
|
|
582
|
+
const rows = new Map(ctx.exposure.map((e) => [e.time, e]));
|
|
583
|
+
broken = {};
|
|
584
|
+
for (const w of WALLS) broken[w.id] = /* @__PURE__ */ new Map();
|
|
585
|
+
for (const b of ctx.bars) {
|
|
586
|
+
const e = rows.get(b.time);
|
|
587
|
+
if (!e || b.close == null) continue;
|
|
588
|
+
for (const w of WALLS) {
|
|
589
|
+
const key = dayOf2(b.time) + "|" + e[w.field];
|
|
590
|
+
if (e[w.field] != null && w.through(b.close, e[w.field]) && !broken[w.id].has(key)) broken[w.id].set(key, b.time);
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
const newSession = (a, b) => dayOf2(a.time) !== dayOf2(b.time);
|
|
595
|
+
function freshness() {
|
|
596
|
+
const rows = ctx.exposure, row = rows[rows.length - 1];
|
|
597
|
+
if (!ctx.intraday() || !row) return null;
|
|
598
|
+
const at = row.as_of ? etTime(row.as_of) : row.time;
|
|
599
|
+
let bar = null;
|
|
600
|
+
for (let i = ctx.bars.length - 1; i >= 0 && !bar; i--) if (sessionOf(ctx.bars[i].time) === "rth") bar = ctx.bars[i];
|
|
601
|
+
const step = { "1m": 60, "5m": 300, "15m": 900, "1h": 3600 }[ctx.resolution] || 60;
|
|
602
|
+
const trading = !!bar && etTime((/* @__PURE__ */ new Date()).toISOString()) - (bar.time + step) < STALE_MINUTES * 60;
|
|
603
|
+
const lag = trading ? Math.round((bar.time - at) / 60) : 0;
|
|
604
|
+
const late = !trading ? "" : dayOf2(bar.time) !== dayOf2(at) ? "from the previous session" : lag > STALE_MINUTES ? `delayed ${lag} min` : "";
|
|
605
|
+
const clock = `${dayOf2(at) === dayOf2(bar ? bar.time : at) ? "" : fmtDay.format(new Date(at * 1e3)) + " "}${fmtClock.format(new Date(at * 1e3))} ET`;
|
|
606
|
+
return { row, at, clock, late, bar };
|
|
607
|
+
}
|
|
608
|
+
const levelsOn = () => ["levels", "maxpain"].some(ctx.on);
|
|
609
|
+
function flatLines(id, points, split, style) {
|
|
610
|
+
const st = ctx.styleOf(id);
|
|
611
|
+
if (st.visible === false) return [];
|
|
612
|
+
const width = Number(st.lineWidth) || 1, ls = style ?? LINE_STYLES[st.lineStyle] ?? 0;
|
|
613
|
+
return levelRuns(points.map((p) => ({ time: p.time, value: p.value, color: p.color || st.color })), split).map((r) => Object.assign(r, { width, style: ls }));
|
|
614
|
+
}
|
|
615
|
+
function sessions() {
|
|
616
|
+
const days = [];
|
|
617
|
+
for (const b of ctx.bars) {
|
|
618
|
+
const d = days[days.length - 1];
|
|
619
|
+
if (d && dayOf2(d.to) === dayOf2(b.time)) d.to = b.time;
|
|
620
|
+
else days.push({ from: b.time, to: b.time });
|
|
621
|
+
}
|
|
622
|
+
return days;
|
|
623
|
+
}
|
|
624
|
+
let focusable = [], focus = null;
|
|
625
|
+
function setFocus(f) {
|
|
626
|
+
if (f === focus) return;
|
|
627
|
+
focus = f;
|
|
628
|
+
overlay.set({ focus });
|
|
629
|
+
}
|
|
630
|
+
let latestShown = true;
|
|
631
|
+
function syncLatest(force) {
|
|
632
|
+
const bars = ctx.bars, last = bars[bars.length - 1];
|
|
633
|
+
const r = last ? ctx.chart.timeScale().getVisibleRange() : null;
|
|
634
|
+
let shown = true;
|
|
635
|
+
if (r) {
|
|
636
|
+
let i = bars.length - 1;
|
|
637
|
+
while (i > 0 && !newSession(bars[i - 1], last)) i--;
|
|
638
|
+
shown = r.to >= bars[i].time;
|
|
639
|
+
}
|
|
640
|
+
if (shown === latestShown && (shown || !force)) return;
|
|
641
|
+
latestShown = shown;
|
|
642
|
+
for (const id of LATEST_ONLY) {
|
|
643
|
+
const st = ctx.styleOf(id);
|
|
644
|
+
s[id].applyOptions({ priceLineVisible: st.priceLine && shown, lastValueVisible: st.axisLabel && shown });
|
|
645
|
+
}
|
|
646
|
+
overlay.set({ hidden: shown ? [] : LATEST_ONLY });
|
|
647
|
+
}
|
|
648
|
+
function drawDaily(rows) {
|
|
649
|
+
dailyByTime = /* @__PURE__ */ new Map();
|
|
650
|
+
const days = (rows || []).map((r) => Object.assign({}, r, { day: String(r.ts).slice(0, 10) })).sort((a, b) => a.day < b.day ? -1 : 1);
|
|
651
|
+
const exposure = ctx.exposure;
|
|
652
|
+
dailyCut = {
|
|
653
|
+
gex: ctx.intraday() ? -Infinity : Infinity,
|
|
654
|
+
maxPain: Math.min(Infinity, ...exposure.filter((e) => e.max_pain != null).map((e) => e.time))
|
|
655
|
+
};
|
|
656
|
+
const end = Math.max(dailyCut.gex, dailyCut.maxPain);
|
|
657
|
+
let i = -1, day = null, prev = null, row = null;
|
|
658
|
+
for (const b of ctx.bars) {
|
|
659
|
+
if (b.time >= end) break;
|
|
660
|
+
if (dayOf2(b.time) !== day) {
|
|
661
|
+
prev = day;
|
|
662
|
+
day = dayOf2(b.time);
|
|
663
|
+
while (i + 1 < days.length && days[i + 1].day < day) i++;
|
|
664
|
+
row = i >= 0 && (prev == null || days[i].day >= prev) && (days[i].status || "ok") === "ok" ? days[i] : null;
|
|
665
|
+
}
|
|
666
|
+
if (row) dailyByTime.set(b.time, row);
|
|
667
|
+
}
|
|
668
|
+
const pts = (show, id, until, pick, paint) => {
|
|
669
|
+
const st = ctx.styleOf(id);
|
|
670
|
+
daily[id].applyOptions({ color: st.color, visible: st.visible !== false });
|
|
671
|
+
return !show ? [] : ctx.bars.map((b) => {
|
|
672
|
+
const r = b.time < until ? dailyByTime.get(b.time) : null, v = r ? pick(r) : null;
|
|
673
|
+
return v == null ? { time: b.time } : paint ? { time: b.time, value: v, color: paint(r) } : { time: b.time, value: v };
|
|
674
|
+
});
|
|
675
|
+
};
|
|
676
|
+
const out = {
|
|
677
|
+
flip: pts(
|
|
678
|
+
ctx.on("levels"),
|
|
679
|
+
"flip",
|
|
680
|
+
dailyCut.gex,
|
|
681
|
+
(r) => r.gamma_flip,
|
|
682
|
+
(r) => r.gamma_flip_status === "available" ? color("flip") : color("flipUnverified")
|
|
683
|
+
),
|
|
684
|
+
callWall: pts(ctx.on("levels"), "callWall", dailyCut.gex, (r) => r.call_wall),
|
|
685
|
+
putWall: pts(ctx.on("levels"), "putWall", dailyCut.gex, (r) => r.put_wall),
|
|
686
|
+
maxPain: pts(ctx.on("maxpain"), "maxPain", dailyCut.maxPain, (r) => r.max_pain)
|
|
687
|
+
};
|
|
688
|
+
for (const [id, data] of Object.entries(out)) daily[id].setData(data);
|
|
689
|
+
return out;
|
|
690
|
+
}
|
|
691
|
+
function latestLevels(drawn, dailyDrawn, now) {
|
|
692
|
+
const last = (data) => {
|
|
693
|
+
for (let i = data.length - 1; i >= 0; i--) if (data[i].value != null) return data[i].value;
|
|
694
|
+
return null;
|
|
695
|
+
};
|
|
696
|
+
const pick = (id) => drawn[id].length ? now[id] ?? last(drawn[id]) : last(dailyDrawn[id]);
|
|
697
|
+
return LEVEL_TITLES.filter(([id]) => ctx.styleOf(id).visible !== false).map(([id, title]) => {
|
|
698
|
+
const value = pick(id);
|
|
699
|
+
return value == null ? null : { id, title, value, color: id === "flip" && !now.flipOk ? color("flipUnverified") : color(id) };
|
|
700
|
+
}).filter(Boolean);
|
|
701
|
+
}
|
|
702
|
+
return {
|
|
703
|
+
// After the candles, so the levels are drawn over them. The price-scale labels use the names of the menu and the
|
|
704
|
+
// legend ("Call wall", not "call wall"). The daily levels come first, without a title or a line across the chart, so
|
|
705
|
+
// they read as the backdrop of the intraday levels. Like the intraday levels, they do not drive the price scale.
|
|
706
|
+
ready() {
|
|
707
|
+
const dailyLevel = (c) => ctx.chart.addSeries(LW.LineSeries, {
|
|
708
|
+
color: c,
|
|
709
|
+
lineWidth: 1,
|
|
710
|
+
lineStyle: LW.LineStyle.Dashed,
|
|
711
|
+
lineType: LW.LineType.WithSteps,
|
|
712
|
+
priceLineVisible: false,
|
|
713
|
+
lastValueVisible: false,
|
|
714
|
+
crosshairMarkerVisible: false,
|
|
715
|
+
autoscaleInfoProvider: () => null
|
|
716
|
+
});
|
|
717
|
+
daily = {
|
|
718
|
+
flip: dailyLevel(color("flip")),
|
|
719
|
+
callWall: dailyLevel(color("callWall")),
|
|
720
|
+
putWall: dailyLevel(color("putWall")),
|
|
721
|
+
maxPain: dailyLevel(color("maxPain"))
|
|
722
|
+
};
|
|
723
|
+
s = {
|
|
724
|
+
flip: ctx.level(color("flip"), "Gamma flip", "flip", "Flip"),
|
|
725
|
+
callWall: ctx.level(color("callWall"), "Call wall", "callWall", "CW"),
|
|
726
|
+
putWall: ctx.level(color("putWall"), "Put wall", "putWall", "PW"),
|
|
727
|
+
maxPain: ctx.level(color("maxPain"), "Max pain", "maxPain", "MP")
|
|
728
|
+
};
|
|
729
|
+
for (const id of FLAT) for (const x of [s[id], daily[id]]) x.applyOptions({ lineVisible: false });
|
|
730
|
+
markers = LW.createSeriesMarkers(ctx.candles, []);
|
|
731
|
+
overlay = new LevelsOverlay(() => {
|
|
732
|
+
const st = ctx.root.style;
|
|
733
|
+
return {
|
|
734
|
+
light: st.getPropertyValue("--fac-text").trim() === THEMES.light.text,
|
|
735
|
+
bg: st.getPropertyValue("--fac-bg").trim() || THEMES.dark.bg,
|
|
736
|
+
right: ctx.reservedRight || 0
|
|
737
|
+
};
|
|
738
|
+
});
|
|
739
|
+
ctx.candles.attachPrimitive(overlay);
|
|
740
|
+
ctx.chart.timeScale().subscribeVisibleLogicalRangeChange(() => syncLatest(false));
|
|
741
|
+
},
|
|
742
|
+
draw(c) {
|
|
743
|
+
const rows = ctx.exposure;
|
|
744
|
+
const pts = (show, pick, paint, cut = true) => !show ? [] : rows.map((e, i) => {
|
|
745
|
+
if (cut && i > 0 && dayOf2(e.time) !== dayOf2(rows[i - 1].time)) return { time: e.time };
|
|
746
|
+
const v = pick(e), col = v != null && paint ? paint(e) : null;
|
|
747
|
+
return v == null ? { time: e.time } : col ? { time: e.time, value: v, color: col } : { time: e.time, value: v };
|
|
748
|
+
});
|
|
749
|
+
findBreaks();
|
|
750
|
+
const wall = (w, cut) => pts(ctx.on("levels"), (e) => e[w.field], (e) => isBroken(w, e) ? faded(color(w.id)) : null, cut);
|
|
751
|
+
const flipPts = (cut) => pts(
|
|
752
|
+
ctx.on("levels"),
|
|
753
|
+
(e) => flip(e).last,
|
|
754
|
+
(e) => flip(e).status === "available" ? color("flip") : color("flipUnverified"),
|
|
755
|
+
cut
|
|
756
|
+
);
|
|
757
|
+
const drawn = {
|
|
758
|
+
flip: flipPts(),
|
|
759
|
+
callWall: wall(WALLS[0]),
|
|
760
|
+
putWall: wall(WALLS[1]),
|
|
761
|
+
maxPain: pts(ctx.on("maxpain"), (e) => e.max_pain)
|
|
762
|
+
};
|
|
763
|
+
for (const [id, data] of Object.entries(drawn)) s[id].setData(data);
|
|
764
|
+
const flat = {
|
|
765
|
+
flip: flipPts(false),
|
|
766
|
+
callWall: wall(WALLS[0], false),
|
|
767
|
+
putWall: wall(WALLS[1], false),
|
|
768
|
+
maxPain: pts(ctx.on("maxpain"), (e) => e.max_pain, null, false)
|
|
769
|
+
};
|
|
770
|
+
markers.setMarkers(!ctx.on("levels") ? [] : WALLS.filter((w) => ctx.styleOf(w.id).visible !== false && showBreaks(w)).flatMap((w) => [...broken[w.id].values()].map((t) => ({
|
|
771
|
+
time: t,
|
|
772
|
+
position: w.position,
|
|
773
|
+
shape: w.shape,
|
|
774
|
+
color: color(w.broken),
|
|
775
|
+
text: `${w.title} broken ${fmtClock.format(new Date(t * 1e3))}`
|
|
776
|
+
}))).sort((a, b) => a.time - b.time));
|
|
777
|
+
const dailyDrawn = drawDaily(ctx.query && dailyQuery(ctx.query) && c && ["levels", "maxpain"].some(ctx.on) ? c.levels_daily : []);
|
|
778
|
+
const showRegime = ctx.on("levels") && ctx.styleOf("flip").visible !== false;
|
|
779
|
+
const flips = rows.length ? rows.map((e) => ({ time: e.time, flip: flip(e).last })) : dailyDrawn.flip.map((p) => ({ time: p.time, flip: p.value }));
|
|
780
|
+
const last = ctx.bars[ctx.bars.length - 1];
|
|
781
|
+
const lastRow = rows[rows.length - 1], lastDaily = [...dailyByTime.values()].pop();
|
|
782
|
+
const now = lastRow ? {
|
|
783
|
+
flip: flip(lastRow).last,
|
|
784
|
+
callWall: lastRow[WALLS[0].field],
|
|
785
|
+
putWall: lastRow[WALLS[1].field],
|
|
786
|
+
maxPain: lastRow.max_pain,
|
|
787
|
+
flipOk: flip(lastRow).status === "available" || flip(lastRow).last == null
|
|
788
|
+
} : { flipOk: !lastDaily || lastDaily.gamma_flip_status === "available" || lastDaily.gamma_flip == null };
|
|
789
|
+
const dailySplit = ctx.intraday() ? newSession : void 0, days = sessions();
|
|
790
|
+
const lines = FLAT.flatMap((id) => [...flatLines(id, flat[id], newSession), ...flatLines(id, dailyDrawn[id], dailySplit, LINE_STYLES.dashed)]);
|
|
791
|
+
overlay.set({
|
|
792
|
+
runs: showRegime ? regimeRuns(flips) : [],
|
|
793
|
+
levels: latestLevels(drawn, dailyDrawn, now),
|
|
794
|
+
spot: last ? last.close : null,
|
|
795
|
+
lines
|
|
796
|
+
});
|
|
797
|
+
syncLatest(true);
|
|
798
|
+
focusable = ctx.intraday() && ["levels", "maxpain"].some(ctx.on) && days.length > 1 ? days : [];
|
|
799
|
+
setFocus(focus && focusable.find((d) => d.from === focus.from) || null);
|
|
800
|
+
},
|
|
801
|
+
clear() {
|
|
802
|
+
dailyByTime = /* @__PURE__ */ new Map();
|
|
803
|
+
dailyCut = {};
|
|
804
|
+
broken = {};
|
|
805
|
+
for (const x of [...Object.values(s), ...Object.values(daily)]) x.setData([]);
|
|
806
|
+
markers.setMarkers([]);
|
|
807
|
+
focusable = [];
|
|
808
|
+
focus = null;
|
|
809
|
+
overlay.set({ runs: [], levels: [], spot: null, lines: [], focus: null });
|
|
810
|
+
},
|
|
811
|
+
/** True when the last draw has daily levels: on 1d/1w the chart then has levels to show (no "pick 1m to 1h" note). */
|
|
812
|
+
hasDaily: () => dailyByTime.size > 0,
|
|
813
|
+
// The session under the crosshair stands out: the overlay veils the other sessions (none off the chart).
|
|
814
|
+
crosshair(time) {
|
|
815
|
+
setFocus(time == null ? null : focusable.find((d) => time >= d.from && time <= d.to) || null);
|
|
816
|
+
},
|
|
817
|
+
// The indicator's line in the legend: { label, value, prev, plot } items (change vs the previous
|
|
818
|
+
// session; the value in the plot's colour, left out while the plot is hidden). A wall broken at or before the bar
|
|
819
|
+
// reads "(broken)".
|
|
820
|
+
legendLevels(g, parts, prev) {
|
|
821
|
+
const f = flip(g), pf = prev && prev.gamma_flip || {}, ok = f.status === "available" || f.last == null;
|
|
822
|
+
const spot = g.spot && g.spot.last;
|
|
823
|
+
const note = (value, w) => [pct(value, spot), w && isBroken(w, g) ? "broken" : ""].filter(Boolean).join(", ") || void 0;
|
|
824
|
+
if (ctx.on("levels")) parts.push(
|
|
825
|
+
{ label: "Call wall", value: g.call_wall, prev: prev && prev.call_wall, plot: "callWall", note: note(g.call_wall, WALLS[0]) },
|
|
826
|
+
{ label: "Put wall", value: g.put_wall, prev: prev && prev.put_wall, plot: "putWall", note: note(g.put_wall, WALLS[1]) },
|
|
827
|
+
{
|
|
828
|
+
label: ok ? "Gamma flip" : "Gamma flip (unverified)",
|
|
829
|
+
value: f.last,
|
|
830
|
+
prev: pf.last,
|
|
831
|
+
plot: "flip",
|
|
832
|
+
color: ok ? void 0 : color("flipUnverified"),
|
|
833
|
+
note: note(f.last)
|
|
834
|
+
}
|
|
835
|
+
);
|
|
836
|
+
const dm = g.max_pain == null && g.time < dailyCut.maxPain ? dailyByTime.get(g.time) : null;
|
|
837
|
+
if (ctx.on("maxpain") && dm && dm.max_pain != null) parts.push({ label: "Max pain (daily)", value: dm.max_pain, plot: "maxPain" });
|
|
838
|
+
else if (ctx.on("maxpain")) parts.push({ label: "Max pain", value: g.max_pain, prev: prev && prev.max_pain, plot: "maxPain" });
|
|
839
|
+
const fresh = levelsOn() ? freshness() : null;
|
|
840
|
+
if (fresh && fresh.row === g && fresh.late) parts.unshift({ label: "As of", value: fresh.clock, color: STALE_COLOR, note: fresh.late });
|
|
841
|
+
else if (fresh && fresh.row === g) parts.push({ label: "As of", value: fresh.clock });
|
|
842
|
+
},
|
|
843
|
+
// The levels stopped before the newest bar (no exposure row there, so no levels line values): a line says so.
|
|
844
|
+
legend(time) {
|
|
845
|
+
const f = levelsOn() ? freshness() : null;
|
|
846
|
+
if (!f || !f.late || !f.bar || time !== f.bar.time || f.row.time === f.bar.time) return [];
|
|
847
|
+
return [`⚠ GEX levels ${f.late}: last update ${f.clock}`];
|
|
848
|
+
}
|
|
849
|
+
};
|
|
850
|
+
}
|
|
851
|
+
};
|
|
852
|
+
|
|
853
|
+
// src/registry.js
|
|
854
|
+
var builtins = [levelsPlugin];
|
|
855
|
+
var plugins = [];
|
|
856
|
+
function registerLayers(plugin) {
|
|
857
|
+
if (!plugin || !Array.isArray(plugin.layers) || typeof plugin.attach !== "function")
|
|
858
|
+
throw new Error("registerLayers expects { layers: [[id, label]], attach(ctx) }");
|
|
859
|
+
plugins.push(plugin);
|
|
860
|
+
}
|
|
861
|
+
var activePlugins = () => builtins.concat(plugins);
|
|
862
|
+
var layerIds = () => activePlugins().flatMap((p) => p.layers).map((l) => l[0]);
|
|
863
|
+
|
|
864
|
+
// src/theme.js
|
|
865
|
+
function rgbOf(color) {
|
|
866
|
+
const c = String(color).trim();
|
|
867
|
+
let m = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i.exec(c);
|
|
868
|
+
if (m) {
|
|
869
|
+
const h = m[1].length <= 4 ? m[1].replace(/./g, (x) => x + x) : m[1];
|
|
870
|
+
return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
|
|
871
|
+
}
|
|
872
|
+
m = /^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(c);
|
|
873
|
+
return m ? [m[1], m[2], m[3]].map(Number) : null;
|
|
874
|
+
}
|
|
875
|
+
function backgroundFits(color, name) {
|
|
876
|
+
const rgb = rgbOf(color);
|
|
877
|
+
if (!rgb) return true;
|
|
878
|
+
const [r, g, b] = rgb.map((v) => {
|
|
879
|
+
v /= 255;
|
|
880
|
+
return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4;
|
|
881
|
+
});
|
|
882
|
+
return 0.2126 * r + 0.7152 * g + 0.0722 * b < 0.179 === (name === "dark");
|
|
883
|
+
}
|
|
884
|
+
function createTheme(root, chart, o, applied) {
|
|
885
|
+
const dark = global.matchMedia ? global.matchMedia("(prefers-color-scheme: dark)") : null;
|
|
886
|
+
function apply() {
|
|
887
|
+
const want = o.theme === "auto" ? dark && !dark.matches ? "light" : "dark" : o.theme;
|
|
888
|
+
const name = THEMES[want] ? want : "dark", t = THEMES[name];
|
|
889
|
+
for (const [k, v] of Object.entries(t)) root.style.setProperty("--fac-" + k, v);
|
|
890
|
+
if (o.background && backgroundFits(o.background, name)) root.style.setProperty("--fac-bg", o.background);
|
|
891
|
+
chart.applyOptions({
|
|
892
|
+
layout: { textColor: t.muted, panes: { separatorColor: t.line } },
|
|
893
|
+
grid: { vertLines: { color: t.grid }, horzLines: { color: t.grid } },
|
|
894
|
+
rightPriceScale: { borderColor: t.line },
|
|
895
|
+
leftPriceScale: { borderColor: t.line },
|
|
896
|
+
timeScale: { borderColor: t.line }
|
|
897
|
+
});
|
|
898
|
+
if (applied) applied(name);
|
|
899
|
+
}
|
|
900
|
+
apply();
|
|
901
|
+
const onScheme = () => {
|
|
902
|
+
if (o.theme === "auto") apply();
|
|
903
|
+
};
|
|
904
|
+
if (dark && dark.addEventListener) dark.addEventListener("change", onScheme);
|
|
905
|
+
return {
|
|
906
|
+
apply,
|
|
907
|
+
destroy() {
|
|
908
|
+
if (dark && dark.removeEventListener) dark.removeEventListener("change", onScheme);
|
|
909
|
+
}
|
|
910
|
+
};
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/display.js
|
|
914
|
+
var CHART_TYPES = [
|
|
915
|
+
["candles", "Candles"],
|
|
916
|
+
["hollow", "Hollow candles"],
|
|
917
|
+
["bars", "Bars"],
|
|
918
|
+
["line", "Line"],
|
|
919
|
+
["area", "Area"],
|
|
920
|
+
["baseline", "Baseline"],
|
|
921
|
+
["heikin", "Heikin Ashi"]
|
|
922
|
+
];
|
|
923
|
+
var SCALE_MODES = [["normal", "Regular", 0], ["log", "Logarithmic", 1], ["percent", "Percent", 2], ["indexed", "Indexed to 100", 3]];
|
|
924
|
+
var CROSSHAIRS = [["normal", "Free", 0], ["magnet", "Magnet (close)", 1], ["magnetOHLC", "Magnet (OHLC)", 3], ["hidden", "Hidden", 2]];
|
|
925
|
+
var DISPLAY_DEFAULTS = {
|
|
926
|
+
chartType: "candles",
|
|
927
|
+
scaleMode: "normal",
|
|
928
|
+
scaleSide: "right",
|
|
929
|
+
autoScale: true,
|
|
930
|
+
invert: false,
|
|
931
|
+
crosshair: "normal",
|
|
932
|
+
priceLine: true,
|
|
933
|
+
priceLabel: true,
|
|
934
|
+
watermark: false
|
|
935
|
+
};
|
|
936
|
+
var CLEAR = { color: "transparent", wickColor: "transparent", borderColor: "transparent" };
|
|
937
|
+
var LINE_LIKE = ["line", "area", "baseline"];
|
|
938
|
+
var KIND = { hollow: "CandlestickSeries", heikin: "CandlestickSeries", bars: "BarSeries", area: "AreaSeries", baseline: "BaselineSeries" };
|
|
939
|
+
var SCALE_IDS = ["right", "left"];
|
|
940
|
+
var WATERMARK = { dark: "rgba(214,217,224,0.07)", light: "rgba(31,36,48,0.07)" };
|
|
941
|
+
function createDisplay(view, chart, LW, candles, closeLine) {
|
|
942
|
+
const { root, state } = view;
|
|
943
|
+
const set = state.view;
|
|
944
|
+
let extra = null, extraType = null;
|
|
945
|
+
let rows = [];
|
|
946
|
+
let ha = [];
|
|
947
|
+
let wm = null, themeName = "dark";
|
|
948
|
+
let lineMode = false;
|
|
949
|
+
const drawn = () => {
|
|
950
|
+
const t = KIND[set.chartType] && !LW[KIND[set.chartType]] ? "candles" : set.chartType;
|
|
951
|
+
return lineMode && !LINE_LIKE.includes(t) ? "line" : t;
|
|
952
|
+
};
|
|
953
|
+
const side = () => set.scaleSide === "left" ? "left" : "right";
|
|
954
|
+
const muted = (up) => up ? COLORS.spotUp : COLORS.spotDown;
|
|
955
|
+
function seriesFor(type) {
|
|
956
|
+
if (extraType === type) return extra;
|
|
957
|
+
if (extra) {
|
|
958
|
+
try {
|
|
959
|
+
chart.removeSeries(extra);
|
|
960
|
+
} catch (e) {
|
|
961
|
+
}
|
|
962
|
+
}
|
|
963
|
+
extra = null;
|
|
964
|
+
extraType = null;
|
|
965
|
+
const make = (opts) => LW[KIND[type]] ? chart.addSeries(LW[KIND[type]], Object.assign({ priceScaleId: side() }, opts)) : null;
|
|
966
|
+
const up = COLORS.up, down = COLORS.down;
|
|
967
|
+
if (type === "hollow") extra = make({
|
|
968
|
+
upColor: "transparent",
|
|
969
|
+
downColor: down,
|
|
970
|
+
borderVisible: true,
|
|
971
|
+
borderUpColor: up,
|
|
972
|
+
borderDownColor: down,
|
|
973
|
+
wickUpColor: up,
|
|
974
|
+
wickDownColor: down
|
|
975
|
+
});
|
|
976
|
+
else if (type === "heikin") extra = make({ upColor: up, downColor: down, borderVisible: false, wickUpColor: up, wickDownColor: down });
|
|
977
|
+
else if (type === "bars") extra = make({ upColor: up, downColor: down, thinBars: false });
|
|
978
|
+
else if (type === "area") extra = make({
|
|
979
|
+
lineColor: COLORS.line,
|
|
980
|
+
lineWidth: 2,
|
|
981
|
+
topColor: "rgba(79,140,255,0.32)",
|
|
982
|
+
bottomColor: "rgba(79,140,255,0.02)"
|
|
983
|
+
});
|
|
984
|
+
else if (type === "baseline") extra = make({
|
|
985
|
+
lineWidth: 2,
|
|
986
|
+
baseValue: { type: "price", price: 0 },
|
|
987
|
+
topLineColor: up,
|
|
988
|
+
topFillColor1: "rgba(38,166,154,0.28)",
|
|
989
|
+
topFillColor2: "rgba(38,166,154,0.04)",
|
|
990
|
+
bottomLineColor: down,
|
|
991
|
+
bottomFillColor1: "rgba(239,83,80,0.04)",
|
|
992
|
+
bottomFillColor2: "rgba(239,83,80,0.28)"
|
|
993
|
+
});
|
|
994
|
+
if (extra) {
|
|
995
|
+
extraType = type;
|
|
996
|
+
if (typeof extra.setSeriesOrder === "function" && typeof candles.seriesOrder === "function") extra.setSeriesOrder(candles.seriesOrder() + 1);
|
|
997
|
+
}
|
|
998
|
+
return extra;
|
|
999
|
+
}
|
|
1000
|
+
function haOf(r, prev) {
|
|
1001
|
+
const close = (r.open + r.high + r.low + r.close) / 4;
|
|
1002
|
+
const open = prev ? (prev.open + prev.close) / 2 : (r.open + r.close) / 2;
|
|
1003
|
+
return { open, high: Math.max(r.high, open, close), low: Math.min(r.low, open, close), close };
|
|
1004
|
+
}
|
|
1005
|
+
function pointOf(type, r, h) {
|
|
1006
|
+
if (LINE_LIKE.includes(type)) return { time: r.time, value: r.close };
|
|
1007
|
+
const b = type === "heikin" ? h : r, up = b.close >= b.open, out = { time: r.time, open: b.open, high: b.high, low: b.low, close: b.close };
|
|
1008
|
+
if (!r.muted) return out;
|
|
1009
|
+
const c = muted(up);
|
|
1010
|
+
if (type === "bars") return Object.assign(out, { color: c });
|
|
1011
|
+
return Object.assign(out, { color: type === "hollow" && up ? "transparent" : c, wickColor: c, borderColor: c });
|
|
1012
|
+
}
|
|
1013
|
+
const candleOf = (r) => {
|
|
1014
|
+
const b = { time: r.time, open: r.open, high: r.high, low: r.low, close: r.close };
|
|
1015
|
+
if (drawn() !== "candles") return Object.assign(b, CLEAR);
|
|
1016
|
+
if (!r.muted) return b;
|
|
1017
|
+
const c = muted(r.close >= r.open);
|
|
1018
|
+
return Object.assign(b, { color: c, wickColor: c });
|
|
1019
|
+
};
|
|
1020
|
+
function applyMarks() {
|
|
1021
|
+
const type = drawn(), main = type === "candles" ? candles : type === "line" ? closeLine : extra;
|
|
1022
|
+
for (const s of [candles, closeLine, extra]) {
|
|
1023
|
+
if (s) s.applyOptions({ lastValueVisible: s === main && set.priceLabel, priceLineVisible: s === main && set.priceLine });
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
function setData(list, flat) {
|
|
1027
|
+
rows = list;
|
|
1028
|
+
lineMode = !!flat;
|
|
1029
|
+
const type = drawn();
|
|
1030
|
+
const s = type === "candles" || type === "line" ? seriesFor(null) : seriesFor(type);
|
|
1031
|
+
ha = [];
|
|
1032
|
+
if (type === "heikin") {
|
|
1033
|
+
let prev = null;
|
|
1034
|
+
for (const r of list) {
|
|
1035
|
+
prev = haOf(r, prev);
|
|
1036
|
+
ha.push([r.time, prev]);
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
applyMarks();
|
|
1040
|
+
closeLine.applyOptions({ visible: type === "line" });
|
|
1041
|
+
closeLine.setData(type === "line" ? list.map((r) => ({ time: r.time, value: r.close })) : []);
|
|
1042
|
+
candles.setData(list.map(candleOf));
|
|
1043
|
+
if (s) s.setData(list.map((r, i) => pointOf(type, r, ha[i] && ha[i][1])));
|
|
1044
|
+
if (type === "baseline" && s && list.length) s.applyOptions({ baseValue: { type: "price", price: list[0].close } });
|
|
1045
|
+
watermark();
|
|
1046
|
+
}
|
|
1047
|
+
function update(r, old) {
|
|
1048
|
+
const type = drawn();
|
|
1049
|
+
candles.update(candleOf(r), old);
|
|
1050
|
+
if (type === "line") closeLine.update({ time: r.time, value: r.close }, old);
|
|
1051
|
+
if (!extra) return;
|
|
1052
|
+
let h = null;
|
|
1053
|
+
if (type === "heikin") {
|
|
1054
|
+
let i = ha.length - 1;
|
|
1055
|
+
while (i >= 0 && ha[i][0] > r.time) i--;
|
|
1056
|
+
const same = i >= 0 && ha[i][0] === r.time, prev = same ? (ha[i - 1] || [])[1] : (ha[i] || [])[1];
|
|
1057
|
+
h = haOf(r, prev || null);
|
|
1058
|
+
if (same) ha[i] = [r.time, h];
|
|
1059
|
+
else ha.splice(i + 1, 0, [r.time, h]);
|
|
1060
|
+
}
|
|
1061
|
+
extra.update(pointOf(type, r, h), old);
|
|
1062
|
+
}
|
|
1063
|
+
function clear() {
|
|
1064
|
+
rows = [];
|
|
1065
|
+
ha = [];
|
|
1066
|
+
for (const s of [candles, closeLine, extra]) if (s) s.setData([]);
|
|
1067
|
+
}
|
|
1068
|
+
function placeSeries() {
|
|
1069
|
+
const to = side();
|
|
1070
|
+
for (const pane of chart.panes()) {
|
|
1071
|
+
if (typeof pane.getSeries !== "function") continue;
|
|
1072
|
+
const list = pane.getSeries().slice().sort((a, b) => (b === candles) - (a === candles));
|
|
1073
|
+
for (const s of list) {
|
|
1074
|
+
const id = s.options().priceScaleId;
|
|
1075
|
+
if (id != null && !SCALE_IDS.includes(id)) continue;
|
|
1076
|
+
if (id === to) s.applyOptions({ priceScaleId: "fac-hop" });
|
|
1077
|
+
s.applyOptions({ priceScaleId: to });
|
|
1078
|
+
}
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
function applyScale() {
|
|
1082
|
+
const to = side(), mode = (SCALE_MODES.find((x) => x[0] === set.scaleMode) || SCALE_MODES[0])[2];
|
|
1083
|
+
chart.applyOptions({ rightPriceScale: { visible: to === "right" }, leftPriceScale: { visible: to === "left" } });
|
|
1084
|
+
chart.priceScale(to, 0).applyOptions({ mode, autoScale: !!set.autoScale, invertScale: !!set.invert });
|
|
1085
|
+
placeAxis();
|
|
1086
|
+
}
|
|
1087
|
+
function placeAxis() {
|
|
1088
|
+
const go = () => {
|
|
1089
|
+
let w = 0;
|
|
1090
|
+
if (side() === "left") {
|
|
1091
|
+
try {
|
|
1092
|
+
w = chart.priceScale("left", 0).width() || 0;
|
|
1093
|
+
} catch (e) {
|
|
1094
|
+
w = 0;
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
root.style.setProperty("--fac-axis-left", w + "px");
|
|
1098
|
+
};
|
|
1099
|
+
go();
|
|
1100
|
+
if (typeof requestAnimationFrame === "function") requestAnimationFrame(go);
|
|
1101
|
+
}
|
|
1102
|
+
function watermark() {
|
|
1103
|
+
const make = LW.createTextWatermark;
|
|
1104
|
+
if (!set.watermark || typeof make !== "function") {
|
|
1105
|
+
if (wm) {
|
|
1106
|
+
try {
|
|
1107
|
+
wm.detach();
|
|
1108
|
+
} catch (e) {
|
|
1109
|
+
}
|
|
1110
|
+
wm = null;
|
|
1111
|
+
}
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
const color = WATERMARK[themeName] || WATERMARK.dark;
|
|
1115
|
+
const lines = [
|
|
1116
|
+
{ text: String(state.symbol || ""), color, fontSize: 56, fontStyle: "bold" },
|
|
1117
|
+
{ text: RES_LABELS[state.res] || state.res || "", color, fontSize: 18 }
|
|
1118
|
+
];
|
|
1119
|
+
const opts = { horzAlign: "center", vertAlign: "center", lines };
|
|
1120
|
+
if (wm) wm.applyOptions(opts);
|
|
1121
|
+
else wm = make(chart.panes()[0], opts);
|
|
1122
|
+
}
|
|
1123
|
+
function apply(k, v) {
|
|
1124
|
+
set[k] = v;
|
|
1125
|
+
if (k === "chartType") setData(rows, lineMode);
|
|
1126
|
+
else if (k === "scaleSide") {
|
|
1127
|
+
placeSeries();
|
|
1128
|
+
applyScale();
|
|
1129
|
+
} else if (k === "scaleMode") {
|
|
1130
|
+
if (v === "percent" || v === "indexed") placeSeries();
|
|
1131
|
+
applyScale();
|
|
1132
|
+
} else if (k === "autoScale" || k === "invert") applyScale();
|
|
1133
|
+
else if (k === "crosshair") chart.applyOptions({ crosshair: { mode: (CROSSHAIRS.find((x) => x[0] === v) || CROSSHAIRS[0])[2] } });
|
|
1134
|
+
else if (k === "priceLine" || k === "priceLabel") applyMarks();
|
|
1135
|
+
else if (k === "watermark") watermark();
|
|
1136
|
+
}
|
|
1137
|
+
return {
|
|
1138
|
+
setData,
|
|
1139
|
+
update,
|
|
1140
|
+
clear,
|
|
1141
|
+
apply,
|
|
1142
|
+
placeAxis,
|
|
1143
|
+
watermark,
|
|
1144
|
+
/** The theme changed: the watermark's colour follows. */
|
|
1145
|
+
theme(name) {
|
|
1146
|
+
themeName = name;
|
|
1147
|
+
if (wm) watermark();
|
|
1148
|
+
},
|
|
1149
|
+
/** True while the price scale fits the data (dragging the scale turns it off). */
|
|
1150
|
+
autoScale() {
|
|
1151
|
+
try {
|
|
1152
|
+
const x = chart.priceScale(side(), 0).options();
|
|
1153
|
+
return x.autoScale !== false;
|
|
1154
|
+
} catch (e) {
|
|
1155
|
+
return !!set.autoScale;
|
|
1156
|
+
}
|
|
1157
|
+
}
|
|
1158
|
+
};
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
// src/components/brand.js
|
|
1162
|
+
function brandLink(o) {
|
|
1163
|
+
return o.brand ? `<a class="fac-brand" href="${esc(o.brand.href)}" target="_blank" rel="noopener" title="${esc(o.brand.name)}"><img src="${esc(o.brand.logo)}" alt="">${o.brand.name ? `<span>${esc(o.brand.name)}</span>` : ""}</a>` : "";
|
|
1164
|
+
}
|
|
1165
|
+
function creditLine(o) {
|
|
1166
|
+
return o.brand ? `<div class="fac-credit"><span></span>${o.note && o.exposure ? `<span class="fac-note" title="${esc(o.note)}">${esc(o.note)}</span>` : ""}<a href="https://www.tradingview.com/" target="_blank" rel="noopener">Charts by TradingView</a></div>` : "";
|
|
1167
|
+
}
|
|
1168
|
+
function placeBrand(el, chart) {
|
|
1169
|
+
if (!el) return;
|
|
1170
|
+
requestAnimationFrame(() => {
|
|
1171
|
+
const ph = chart.panes()[0].getHeight();
|
|
1172
|
+
if (ph > 0) {
|
|
1173
|
+
el.style.top = Math.max(0, ph - 26) + "px";
|
|
1174
|
+
el.style.bottom = "auto";
|
|
1175
|
+
}
|
|
1176
|
+
});
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// src/components/layout.js
|
|
1180
|
+
var svg = (path) => `<svg viewBox="0 0 24 24" width="18" height="18" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round" stroke-linejoin="round">${path}</svg>`;
|
|
1181
|
+
var ICONS = {
|
|
1182
|
+
search: svg('<circle cx="11" cy="11" r="6"/><path d="m20 20-4.5-4.5"/>'),
|
|
1183
|
+
settings: svg('<circle cx="12" cy="12" r="3"/><path d="M19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z"/>'),
|
|
1184
|
+
fullscreen: svg('<path d="M4 9V4h5M15 4h5v5M20 15v5h-5M9 20H4v-5"/>'),
|
|
1185
|
+
exitFullscreen: svg('<path d="M9 4v5H4M20 9h-5V4M15 20v-5h5M4 15h5v5"/>'),
|
|
1186
|
+
camera: svg('<path d="M4 8h3l2-3h6l2 3h3v11H4z"/><circle cx="12" cy="13" r="3.5"/>'),
|
|
1187
|
+
lock: svg('<rect x="5" y="10.5" width="14" height="10" rx="2"/><path d="M8 10.5V7.5a4 4 0 0 1 8 0v3"/>'),
|
|
1188
|
+
key: svg('<circle cx="8" cy="15" r="4"/><path d="m11 12 8.5-8.5M16.5 6.5 19 9M14.5 8.5 16.5 10.5"/>'),
|
|
1189
|
+
eye: svg('<path d="M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>'),
|
|
1190
|
+
eyeOff: svg('<path d="M2 12s3.6-6.5 10-6.5S22 12 22 12s-3.6 6.5-10 6.5S2 12 2 12z"/><circle cx="12" cy="12" r="3"/><path d="m4 4 16 16"/>'),
|
|
1191
|
+
trash: svg('<path d="M4 7h16M9 7V4.5h6V7M6.5 7l1 13h9l1-13M10 11v6M14 11v6"/>'),
|
|
1192
|
+
info: svg('<circle cx="12" cy="12" r="9"/><path d="M12 11v6M12 7.5v.5"/>'),
|
|
1193
|
+
chevron: svg('<path d="m6 14 6-6 6 6"/>')
|
|
1194
|
+
};
|
|
1195
|
+
var TYPE_ICONS = {
|
|
1196
|
+
candles: svg('<path d="M8 3v18M16 5v14"/><rect x="5.5" y="7" width="5" height="9" rx=".5" fill="currentColor"/><rect x="13.5" y="9" width="5" height="6" rx=".5" fill="currentColor"/>'),
|
|
1197
|
+
hollow: svg('<path d="M8 3v4M8 16v5M16 5v4M16 15v4"/><rect x="5.5" y="7" width="5" height="9" rx=".5"/><rect x="13.5" y="9" width="5" height="6" rx=".5"/>'),
|
|
1198
|
+
bars: svg('<path d="M8 4v16M5 8h3M8 16h3M16 6v13M13 10h3M16 15h3"/>'),
|
|
1199
|
+
line: svg('<path d="m3 17 5-6 4 3 8-9"/>'),
|
|
1200
|
+
area: svg('<path d="m3 17 5-6 4 3 8-9v15H3z" fill="currentColor" fill-opacity=".25" stroke="none"/><path d="m3 17 5-6 4 3 8-9"/>'),
|
|
1201
|
+
baseline: svg('<path d="M3 12h18" stroke-dasharray="2 2"/><path d="m3 15 4-6 4 5 4-8 6 9"/>'),
|
|
1202
|
+
heikin: svg('<path d="M6 4v16M12 3v15M18 7v13"/><rect x="4" y="7" width="4" height="8" rx=".5" fill="currentColor"/><rect x="10" y="5" width="4" height="9" rx=".5" fill="currentColor"/><rect x="16" y="9" width="4" height="7" rx=".5"/>')
|
|
1203
|
+
};
|
|
1204
|
+
var options = (list) => list.map(([v, l]) => `<option value="${v}">${l}</option>`).join("");
|
|
1205
|
+
function createLayout(o) {
|
|
1206
|
+
const root = document.createElement("div");
|
|
1207
|
+
root.className = "fac";
|
|
1208
|
+
root.innerHTML = `${o.controls ? `<div class="fac-bar">
|
|
1209
|
+
${o.symbolButtons ? `<div class="fac-menu fac-dd" data-g="symbols"><button type="button" class="fac-dd-btn" aria-haspopup="listbox" aria-expanded="false" title="Symbol search">${ICONS.search}<b class="fac-dd-val"></b></button>
|
|
1210
|
+
<div class="fac-panel fac-sym-panel"><input type="search" class="fac-search" placeholder="Search symbol" aria-label="Search symbol" autocomplete="off" spellcheck="false">
|
|
1211
|
+
<div class="fac-list" role="listbox" aria-label="Symbols"></div></div></div>` : ""}
|
|
1212
|
+
<div class="fac-menu fac-dd" data-g="res"><button type="button" class="fac-dd-btn" aria-haspopup="listbox" aria-expanded="false" title="Interval"><span class="fac-dd-val"></span> ▾</button>
|
|
1213
|
+
<div class="fac-panel"><div class="fac-list" role="listbox" aria-label="Interval"></div></div></div>
|
|
1214
|
+
<div class="fac-menu fac-dd fac-type" data-g="type"><button type="button" class="fac-dd-btn" aria-haspopup="listbox" aria-expanded="false" title="Chart type" aria-label="Chart type"><span class="fac-dd-val"></span></button>
|
|
1215
|
+
<div class="fac-panel"><div class="fac-list" role="listbox" aria-label="Chart type"></div></div></div>
|
|
1216
|
+
${o.exposure ? '<div class="fac-menu fac-ind-menu"><button type="button" aria-haspopup="true" aria-expanded="false" title="Indicators"><i class="fac-fx">ƒx</i> Indicators ▾</button><div class="fac-panel"><div class="fac-ind-list"></div><div class="fac-more"></div></div></div>' : ""}
|
|
1217
|
+
<span class="fac-spacer"></span><span class="fac-status"></span>
|
|
1218
|
+
<div class="fac-right">
|
|
1219
|
+
${o.layoutMenu ? '<div class="fac-menu fac-layouts"><button type="button" class="fac-icon" aria-haspopup="true" aria-expanded="false" title="Layout" aria-label="Layout"></button><div class="fac-panel"></div></div>' : ""}
|
|
1220
|
+
<div class="fac-menu fac-settings"><button type="button" class="fac-icon" aria-haspopup="true" aria-expanded="false" title="Settings" aria-label="Settings">${ICONS.settings}</button>
|
|
1221
|
+
<div class="fac-panel"><div class="fac-ttl">Settings</div>
|
|
1222
|
+
<div class="fac-sec">Appearance</div>
|
|
1223
|
+
<label class="fac-field"><span>Theme</span><select data-s="theme"><option value="dark">Dark</option><option value="light">Light</option><option value="auto">Auto (system)</option></select></label>
|
|
1224
|
+
<label><input type="checkbox" data-s="grid"> Grid lines</label>
|
|
1225
|
+
<label><input type="checkbox" data-s="watermark"> Watermark</label>
|
|
1226
|
+
<div class="fac-sec">Scales</div>
|
|
1227
|
+
<label class="fac-field"><span>Price scale</span><select data-s="scaleMode">${options(SCALE_MODES)}</select></label>
|
|
1228
|
+
<label class="fac-field"><span>Scale placement</span><select data-s="scaleSide"><option value="right">Right</option><option value="left">Left</option></select></label>
|
|
1229
|
+
<label><input type="checkbox" data-s="autoScale"> Auto scale</label>
|
|
1230
|
+
<label><input type="checkbox" data-s="invert"> Invert scale</label>
|
|
1231
|
+
<label><input type="checkbox" data-s="priceLabel"> Price label</label>
|
|
1232
|
+
<label><input type="checkbox" data-s="priceLine"> Last price line</label>
|
|
1233
|
+
<div class="fac-sec">Crosshair</div>
|
|
1234
|
+
<label class="fac-field"><span>Mode</span><select data-s="crosshair">${options(CROSSHAIRS)}</select></label>
|
|
1235
|
+
<div class="fac-sec">Status line</div>
|
|
1236
|
+
<label><input type="checkbox" data-s="legend"> Legend</label>
|
|
1237
|
+
<label><input type="checkbox" data-s="volume"> Volume</label></div></div>
|
|
1238
|
+
<button type="button" class="fac-icon" data-a="fullscreen" title="Fullscreen" aria-label="Fullscreen">${ICONS.fullscreen}</button>
|
|
1239
|
+
<button type="button" class="fac-icon" data-a="screenshot" title="Take a screenshot" aria-label="Take a screenshot">${ICONS.camera}</button>
|
|
1240
|
+
<span class="fac-feed" hidden></span>
|
|
1241
|
+
${o.account ? '<a class="fac-account" target="_blank" rel="noopener" hidden></a>' : ""}
|
|
1242
|
+
</div></div>` : ""}
|
|
1243
|
+
<div class="fac-body"><div class="fac-canvas"></div><div class="fac-legend"></div><div class="fac-pane-lgs"></div><div class="fac-empty"></div>
|
|
1244
|
+
<div class="fac-upsell" hidden></div>${brandLink(o)}</div>
|
|
1245
|
+
${o.controls ? `<div class="fac-timebar"><div class="fac-group" data-g="range"></div><span class="fac-spacer"></span>
|
|
1246
|
+
<div class="fac-group" data-g="session"></div><span class="fac-clock" title="US Eastern time"></span>
|
|
1247
|
+
<div class="fac-group fac-scale-btns" data-g="scale"></div></div>` : ""}
|
|
1248
|
+
${creditLine(o)}
|
|
1249
|
+
${o.controls && o.exposure ? '<div class="fac-dialog" hidden></div>' : ""}`;
|
|
1250
|
+
return root;
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
// src/components/toolbar.js
|
|
1254
|
+
var fmtClock2 = new Intl.DateTimeFormat("en-US", { timeZone: ET, hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23" });
|
|
1255
|
+
var FEATURED = ["SPY", "SPX", "QQQ", "TSLA", "NVDA"];
|
|
1256
|
+
var featured = (s) => {
|
|
1257
|
+
const i = FEATURED.indexOf(s);
|
|
1258
|
+
return i < 0 ? FEATURED.length : i;
|
|
1259
|
+
};
|
|
1260
|
+
var fullscreenElement = () => document.fullscreenElement || document.webkitFullscreenElement || null;
|
|
1261
|
+
var fullscreenEnabled = () => !!(document.fullscreenEnabled || document.webkitFullscreenEnabled);
|
|
1262
|
+
function createToolbar(view) {
|
|
1263
|
+
const { root, $, o, state } = view;
|
|
1264
|
+
const extraControls = [];
|
|
1265
|
+
const movable = (el) => {
|
|
1266
|
+
const mark = document.createComment("fac");
|
|
1267
|
+
el.after(mark);
|
|
1268
|
+
extraControls.push([el, mark]);
|
|
1269
|
+
};
|
|
1270
|
+
const clock = $(".fac-clock");
|
|
1271
|
+
const tick = () => {
|
|
1272
|
+
clock.textContent = fmtClock2.format(/* @__PURE__ */ new Date()) + " ET";
|
|
1273
|
+
};
|
|
1274
|
+
const clockTimer = clock ? setInterval(tick, 1e3) : null;
|
|
1275
|
+
if (clock) tick();
|
|
1276
|
+
function addControl(el, where = "panel", group = null) {
|
|
1277
|
+
const spacer = $(".fac-bar > .fac-spacer"), more = $(".fac-more");
|
|
1278
|
+
if (!spacer) return false;
|
|
1279
|
+
const box = group && $(".fac-dialog") ? group.inputs : more;
|
|
1280
|
+
if (where === "toolbar" || !box) {
|
|
1281
|
+
spacer.before(el);
|
|
1282
|
+
if (more) movable(el);
|
|
1283
|
+
return true;
|
|
1284
|
+
}
|
|
1285
|
+
const field = document.createElement("label");
|
|
1286
|
+
field.className = "fac-field";
|
|
1287
|
+
field.innerHTML = `<span>${esc(el.title || "")}</span>`;
|
|
1288
|
+
field.appendChild(el);
|
|
1289
|
+
box.appendChild(field);
|
|
1290
|
+
return true;
|
|
1291
|
+
}
|
|
1292
|
+
function placeControls(narrow) {
|
|
1293
|
+
const more = $(".fac-more");
|
|
1294
|
+
if (!more) return;
|
|
1295
|
+
for (const [el, mark] of extraControls) if (narrow) more.appendChild(el);
|
|
1296
|
+
else mark.before(el);
|
|
1297
|
+
}
|
|
1298
|
+
function buttons(group, items, isOn, onClick) {
|
|
1299
|
+
const box = $(`[data-g="${group}"]`);
|
|
1300
|
+
if (!box) return;
|
|
1301
|
+
box.innerHTML = "";
|
|
1302
|
+
for (const [label, value, tip] of items) {
|
|
1303
|
+
const b = document.createElement("button");
|
|
1304
|
+
b.textContent = label;
|
|
1305
|
+
if (tip) b.title = tip;
|
|
1306
|
+
b.classList.toggle("on", isOn(value));
|
|
1307
|
+
b.onclick = () => onClick(value);
|
|
1308
|
+
box.appendChild(b);
|
|
1309
|
+
}
|
|
1310
|
+
}
|
|
1311
|
+
const menus = [...root.querySelectorAll(".fac-menu")];
|
|
1312
|
+
function closeMenus(except) {
|
|
1313
|
+
for (const m of menus) if (m !== except && m.classList.contains("open")) {
|
|
1314
|
+
m.classList.remove("open");
|
|
1315
|
+
m.querySelector("button").setAttribute("aria-expanded", "false");
|
|
1316
|
+
}
|
|
1317
|
+
}
|
|
1318
|
+
const onDocClick = () => closeMenus();
|
|
1319
|
+
function openMenu(m) {
|
|
1320
|
+
closeMenus(m);
|
|
1321
|
+
m.classList.add("open");
|
|
1322
|
+
m.querySelector("button").setAttribute("aria-expanded", "true");
|
|
1323
|
+
const panel = m.querySelector(".fac-panel"), box = view.frame().getBoundingClientRect();
|
|
1324
|
+
panel.style.left = "";
|
|
1325
|
+
panel.style.right = "";
|
|
1326
|
+
panel.style.maxHeight = "";
|
|
1327
|
+
panel.style.minWidth = "";
|
|
1328
|
+
panel.style.maxWidth = "";
|
|
1329
|
+
panel.style.boxSizing = "";
|
|
1330
|
+
if (box.width > 0 && panel.getBoundingClientRect().width > box.width) {
|
|
1331
|
+
panel.style.minWidth = "0";
|
|
1332
|
+
panel.style.maxWidth = box.width + "px";
|
|
1333
|
+
panel.style.boxSizing = "border-box";
|
|
1334
|
+
}
|
|
1335
|
+
if (panel.getBoundingClientRect().right > box.right) {
|
|
1336
|
+
panel.style.left = "auto";
|
|
1337
|
+
panel.style.right = "0";
|
|
1338
|
+
}
|
|
1339
|
+
if (panel.getBoundingClientRect().left < box.left) {
|
|
1340
|
+
panel.style.left = "0";
|
|
1341
|
+
panel.style.right = "auto";
|
|
1342
|
+
const p = panel.getBoundingClientRect();
|
|
1343
|
+
if (p.right > box.right) panel.style.left = Math.max(box.left, box.right - p.width) - p.left + "px";
|
|
1344
|
+
}
|
|
1345
|
+
const room = box.bottom - panel.getBoundingClientRect().top - 6;
|
|
1346
|
+
if (room > 0) panel.style.maxHeight = Math.max(140, room) + "px";
|
|
1347
|
+
if (m.dataset.g === "symbols") openSymbols();
|
|
1348
|
+
if (m.dataset.g === "res") {
|
|
1349
|
+
const at = m.querySelector(".on");
|
|
1350
|
+
if (at && at.scrollIntoView) at.scrollIntoView({ block: "nearest" });
|
|
1351
|
+
}
|
|
1352
|
+
if (m.classList.contains("fac-settings")) syncSettings();
|
|
1353
|
+
}
|
|
1354
|
+
for (const m of menus) {
|
|
1355
|
+
m.querySelector("button").onclick = (e) => {
|
|
1356
|
+
e.stopPropagation();
|
|
1357
|
+
if (m.classList.contains("open")) closeMenus();
|
|
1358
|
+
else openMenu(m);
|
|
1359
|
+
};
|
|
1360
|
+
m.querySelector(".fac-panel").onclick = (e) => e.stopPropagation();
|
|
1361
|
+
m.addEventListener("keydown", (e) => {
|
|
1362
|
+
if (e.key === "Escape" && m.classList.contains("open")) {
|
|
1363
|
+
e.stopPropagation();
|
|
1364
|
+
closeMenus();
|
|
1365
|
+
m.querySelector("button").focus();
|
|
1366
|
+
}
|
|
1367
|
+
});
|
|
1368
|
+
}
|
|
1369
|
+
document.addEventListener("click", onDocClick);
|
|
1370
|
+
view.closeMenus = () => closeMenus();
|
|
1371
|
+
function fillList(list, items, isOn, onPick, empty) {
|
|
1372
|
+
list.innerHTML = items.length ? items.map(([value, label, hint], i) => `<div class="fac-opt${isOn(value) ? " on" : ""}" role="option" aria-selected="${isOn(value)}" data-v="${esc(value)}" data-i="${i}"><span>${esc(label)}</span>${hint ? `<span class="fac-hint">${esc(hint)}</span>` : ""}</div>`).join("") : `<div class="fac-none">${esc(empty || "")}</div>`;
|
|
1373
|
+
list.querySelectorAll(".fac-opt").forEach((el) => {
|
|
1374
|
+
el.onclick = () => {
|
|
1375
|
+
closeMenus();
|
|
1376
|
+
onPick(el.dataset.v);
|
|
1377
|
+
};
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
const symMenu = $('[data-g="symbols"]');
|
|
1381
|
+
const search = symMenu && symMenu.querySelector(".fac-search");
|
|
1382
|
+
const symList = symMenu && symMenu.querySelector(".fac-list");
|
|
1383
|
+
let active = -1;
|
|
1384
|
+
function matches() {
|
|
1385
|
+
const q = search.value.trim().toUpperCase();
|
|
1386
|
+
const all = state.symbols.map((x) => ({ symbol: x.symbol, name: x.name || x.description || "" })).sort((a, b) => featured(a.symbol) - featured(b.symbol) || a.symbol.localeCompare(b.symbol));
|
|
1387
|
+
if (!q) return all;
|
|
1388
|
+
const starts = all.filter((x) => x.symbol.toUpperCase().startsWith(q));
|
|
1389
|
+
return starts.concat(all.filter((x) => !starts.includes(x) && (x.symbol.toUpperCase().includes(q) || x.name.toUpperCase().includes(q))));
|
|
1390
|
+
}
|
|
1391
|
+
function renderSymbols() {
|
|
1392
|
+
const found = matches();
|
|
1393
|
+
fillList(symList, found.map((x) => [x.symbol, x.symbol, x.name]), (v) => v === state.symbol, (v) => view.api.setSymbol(v), "No symbols match");
|
|
1394
|
+
active = found.length ? 0 : -1;
|
|
1395
|
+
markActive();
|
|
1396
|
+
}
|
|
1397
|
+
function markActive() {
|
|
1398
|
+
symList.querySelectorAll(".fac-opt").forEach((el2) => el2.classList.toggle("active", +el2.dataset.i === active));
|
|
1399
|
+
const el = symList.querySelector(".fac-opt.active");
|
|
1400
|
+
if (el && el.scrollIntoView) el.scrollIntoView({ block: "nearest" });
|
|
1401
|
+
}
|
|
1402
|
+
function openSymbols() {
|
|
1403
|
+
search.value = "";
|
|
1404
|
+
renderSymbols();
|
|
1405
|
+
const at = symList.querySelector(".fac-opt.on");
|
|
1406
|
+
if (at) {
|
|
1407
|
+
active = +at.dataset.i;
|
|
1408
|
+
markActive();
|
|
1409
|
+
}
|
|
1410
|
+
search.focus();
|
|
1411
|
+
}
|
|
1412
|
+
if (search) {
|
|
1413
|
+
search.oninput = renderSymbols;
|
|
1414
|
+
search.onkeydown = (e) => {
|
|
1415
|
+
const n = symList.querySelectorAll(".fac-opt").length;
|
|
1416
|
+
if (e.key === "ArrowDown" && n) {
|
|
1417
|
+
e.preventDefault();
|
|
1418
|
+
active = (active + 1) % n;
|
|
1419
|
+
markActive();
|
|
1420
|
+
} else if (e.key === "ArrowUp" && n) {
|
|
1421
|
+
e.preventDefault();
|
|
1422
|
+
active = (active - 1 + n) % n;
|
|
1423
|
+
markActive();
|
|
1424
|
+
} else if (e.key === "Enter") {
|
|
1425
|
+
e.preventDefault();
|
|
1426
|
+
const el = symList.querySelector(".fac-opt.active");
|
|
1427
|
+
if (el) el.click();
|
|
1428
|
+
}
|
|
1429
|
+
};
|
|
1430
|
+
}
|
|
1431
|
+
const typeMenu = $('[data-g="type"]');
|
|
1432
|
+
function renderDisplay(scaleOnly) {
|
|
1433
|
+
if (typeMenu && !scaleOnly) {
|
|
1434
|
+
const t = state.view.chartType, label = (CHART_TYPES.find((x) => x[0] === t) || CHART_TYPES[0])[1];
|
|
1435
|
+
typeMenu.querySelector(".fac-dd-val").innerHTML = TYPE_ICONS[t] || TYPE_ICONS.candles;
|
|
1436
|
+
typeMenu.querySelector("button").title = "Chart type: " + label;
|
|
1437
|
+
const list = typeMenu.querySelector(".fac-list");
|
|
1438
|
+
list.innerHTML = CHART_TYPES.map(([v, l]) => `<div class="fac-opt${v === t ? " on" : ""}" role="option" aria-selected="${v === t}" data-v="${v}"><span class="fac-type-opt">${TYPE_ICONS[v]}${esc(l)}</span></div>`).join("");
|
|
1439
|
+
list.querySelectorAll(".fac-opt").forEach((el) => {
|
|
1440
|
+
el.onclick = () => {
|
|
1441
|
+
closeMenus();
|
|
1442
|
+
view.applySetting("chartType", el.dataset.v);
|
|
1443
|
+
};
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
if (view.scaleAuto) state.view.autoScale = view.scaleAuto();
|
|
1447
|
+
const mode = state.view.scaleMode;
|
|
1448
|
+
buttons(
|
|
1449
|
+
"scale",
|
|
1450
|
+
[
|
|
1451
|
+
["%", "percent", "Percent scale"],
|
|
1452
|
+
["log", "log", "Logarithmic scale"],
|
|
1453
|
+
["auto", "auto", "Auto scale: the price scale fits the bars"]
|
|
1454
|
+
],
|
|
1455
|
+
(v) => v === "auto" ? !!state.view.autoScale : v === mode,
|
|
1456
|
+
(v) => v === "auto" ? view.applySetting("autoScale", !state.view.autoScale) : view.applySetting("scaleMode", v === mode ? "normal" : v)
|
|
1457
|
+
);
|
|
1458
|
+
}
|
|
1459
|
+
const settings = $(".fac-settings");
|
|
1460
|
+
const PICKS = ["scaleMode", "scaleSide", "crosshair"];
|
|
1461
|
+
const SWITCHES = ["autoScale", "invert", "volume", "grid", "legend", "priceLine", "priceLabel", "watermark"];
|
|
1462
|
+
function syncSettings() {
|
|
1463
|
+
if (!settings) return;
|
|
1464
|
+
if (view.scaleAuto) state.view.autoScale = view.scaleAuto();
|
|
1465
|
+
settings.querySelector('[data-s="theme"]').value = o.theme;
|
|
1466
|
+
for (const k of PICKS) settings.querySelector(`[data-s="${k}"]`).value = state.view[k];
|
|
1467
|
+
for (const k of SWITCHES) settings.querySelector(`[data-s="${k}"]`).checked = !!state.view[k];
|
|
1468
|
+
}
|
|
1469
|
+
if (settings) {
|
|
1470
|
+
settings.querySelector('[data-s="theme"]').onchange = (e) => view.api.setTheme(e.target.value);
|
|
1471
|
+
for (const k of PICKS) settings.querySelector(`[data-s="${k}"]`).onchange = (e) => view.applySetting(k, e.target.value);
|
|
1472
|
+
for (const k of SWITCHES)
|
|
1473
|
+
settings.querySelector(`[data-s="${k}"]`).onchange = (e) => view.applySetting(k, e.target.checked);
|
|
1474
|
+
}
|
|
1475
|
+
const fsBtn = $('[data-a="fullscreen"]');
|
|
1476
|
+
function syncFullscreen() {
|
|
1477
|
+
if (!fsBtn) return;
|
|
1478
|
+
const frame = view.frame(), on = fullscreenElement() === frame;
|
|
1479
|
+
frame.classList.toggle("fac-fullscreen", on);
|
|
1480
|
+
fsBtn.innerHTML = on ? ICONS.exitFullscreen : ICONS.fullscreen;
|
|
1481
|
+
fsBtn.title = on ? "Exit fullscreen" : "Fullscreen";
|
|
1482
|
+
fsBtn.setAttribute("aria-label", fsBtn.title);
|
|
1483
|
+
}
|
|
1484
|
+
if (fsBtn) {
|
|
1485
|
+
if (!fullscreenEnabled()) fsBtn.hidden = true;
|
|
1486
|
+
fsBtn.onclick = () => {
|
|
1487
|
+
closeMenus();
|
|
1488
|
+
const frame = view.frame();
|
|
1489
|
+
const p = fullscreenElement() === frame ? (document.exitFullscreen || document.webkitExitFullscreen).call(document) : (frame.requestFullscreen || frame.webkitRequestFullscreen).call(frame);
|
|
1490
|
+
if (p && p.catch) p.catch(() => {
|
|
1491
|
+
});
|
|
1492
|
+
};
|
|
1493
|
+
document.addEventListener("fullscreenchange", syncFullscreen);
|
|
1494
|
+
document.addEventListener("webkitfullscreenchange", syncFullscreen);
|
|
1495
|
+
}
|
|
1496
|
+
const shotBtn = $('[data-a="screenshot"]');
|
|
1497
|
+
if (shotBtn) shotBtn.onclick = () => {
|
|
1498
|
+
closeMenus();
|
|
1499
|
+
view.screenshot();
|
|
1500
|
+
};
|
|
1501
|
+
const feed = $(".fac-feed");
|
|
1502
|
+
function renderFeed() {
|
|
1503
|
+
if (!feed) return;
|
|
1504
|
+
const f = state.feed || (state.answered && state.noKey ? { mode: "delayed", delay: null } : null);
|
|
1505
|
+
feed.hidden = !f;
|
|
1506
|
+
if (!f) return;
|
|
1507
|
+
const delayed = f.mode === "delayed";
|
|
1508
|
+
feed.className = `fac-feed ${delayed ? "fac-delayed" : "fac-live"}`;
|
|
1509
|
+
feed.textContent = delayed ? f.delay ? `${f.delay} min delayed` : "Delayed" : "Live";
|
|
1510
|
+
feed.title = delayed ? `Prices are ${f.delay ? `${f.delay} minutes ` : ""}behind the market.` : "Live prices";
|
|
1511
|
+
}
|
|
1512
|
+
const account = $(".fac-account");
|
|
1513
|
+
function renderAccount() {
|
|
1514
|
+
renderFeed();
|
|
1515
|
+
if (!account || !state.answered) return;
|
|
1516
|
+
const plan = state.plan != null && !state.noKey ? String(state.plan).toLowerCase() : null;
|
|
1517
|
+
if (plan) {
|
|
1518
|
+
account.className = "fac-account fac-tier";
|
|
1519
|
+
account.textContent = PLAN_NAMES[plan] || state.plan;
|
|
1520
|
+
account.title = `Your plan: ${PLAN_NAMES[plan] || state.plan}`;
|
|
1521
|
+
account.href = view.upgradeHref("account");
|
|
1522
|
+
account.setAttribute("data-fac-cta", "upgrade");
|
|
1523
|
+
account.setAttribute("data-fac-content", "account");
|
|
1524
|
+
} else {
|
|
1525
|
+
account.className = "fac-account fac-signup";
|
|
1526
|
+
account.textContent = "Sign up";
|
|
1527
|
+
account.title = "Create a free FlashAlpha account";
|
|
1528
|
+
account.href = view.signupHref();
|
|
1529
|
+
account.setAttribute("data-fac-cta", "signup");
|
|
1530
|
+
account.setAttribute("data-fac-content", "toolbar");
|
|
1531
|
+
}
|
|
1532
|
+
account.hidden = false;
|
|
1533
|
+
}
|
|
1534
|
+
function render() {
|
|
1535
|
+
const api = view.api;
|
|
1536
|
+
if (symMenu) {
|
|
1537
|
+
symMenu.querySelector(".fac-dd-val").textContent = state.symbol || "Symbol";
|
|
1538
|
+
if (symMenu.classList.contains("open")) renderSymbols();
|
|
1539
|
+
}
|
|
1540
|
+
const resMenu = $('[data-g="res"]');
|
|
1541
|
+
if (resMenu) {
|
|
1542
|
+
resMenu.querySelector(".fac-dd-val").textContent = state.res;
|
|
1543
|
+
fillList(resMenu.querySelector(".fac-list"), RESOLUTIONS.map((r) => [r, RES_LABELS[r] || r, r]), (v) => v === state.res, (v) => api.setResolution(v));
|
|
1544
|
+
}
|
|
1545
|
+
buttons("range", RANGES.filter(([, d]) => d <= (MAX_DAYS[state.res] || d)), (v) => v === state.days, (v) => api.setRange(v));
|
|
1546
|
+
buttons("session", [
|
|
1547
|
+
["RTH", "rth", "Regular trading hours: 9:30 to 16:00 ET"],
|
|
1548
|
+
["ETH", "eth", "Extended trading hours: adds pre-market and after-hours"]
|
|
1549
|
+
], (v) => v === o.session, (v) => api.setSession(v));
|
|
1550
|
+
if (view.indicators) view.indicators.render();
|
|
1551
|
+
renderDisplay();
|
|
1552
|
+
renderAccount();
|
|
1553
|
+
}
|
|
1554
|
+
return {
|
|
1555
|
+
addControl,
|
|
1556
|
+
placeControls,
|
|
1557
|
+
render,
|
|
1558
|
+
renderAccount,
|
|
1559
|
+
renderDisplay,
|
|
1560
|
+
destroy() {
|
|
1561
|
+
document.removeEventListener("click", onDocClick);
|
|
1562
|
+
document.removeEventListener("fullscreenchange", syncFullscreen);
|
|
1563
|
+
document.removeEventListener("webkitfullscreenchange", syncFullscreen);
|
|
1564
|
+
if (fullscreenElement() === view.frame()) {
|
|
1565
|
+
const p = (document.exitFullscreen || document.webkitExitFullscreen).call(document);
|
|
1566
|
+
if (p && p.catch) p.catch(() => {
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
clearInterval(clockTimer);
|
|
1570
|
+
}
|
|
1571
|
+
};
|
|
1572
|
+
}
|
|
1573
|
+
|
|
1574
|
+
// src/components/legend.js
|
|
1575
|
+
var change = (v, p, fmt = num) => typeof v !== "number" || typeof p !== "number" || v === p ? "" : ` <span class="ch">(${v > p ? "+" : "−"}${esc(fmt(Math.abs(v - p)))})</span>`;
|
|
1576
|
+
var keyItem = (label, v, p, cls = "", color = "", fmt = num, note = "") => v == null ? "" : `<span>${label ? `<span class="k">${label}</span> ` : ""}<span class="${cls}"${color ? ` style="color:${esc(color)}"` : ""}>${esc(typeof v === "number" ? fmt(v) : v)}</span>${note ? ` <span class="ch">(${esc(note)})</span>` : ""}${change(v, p, fmt)}</span>`;
|
|
1577
|
+
function createLegend(view, chart) {
|
|
1578
|
+
const { root, $, state, data } = view;
|
|
1579
|
+
const legend = $(".fac-legend");
|
|
1580
|
+
const paneBox = $(".fac-pane-lgs");
|
|
1581
|
+
let extras = [];
|
|
1582
|
+
let tips = 0, openTip = null;
|
|
1583
|
+
function previousSession(g) {
|
|
1584
|
+
const rows = data.exposure, day = dayOf(g.time);
|
|
1585
|
+
let i = rows.indexOf(g);
|
|
1586
|
+
while (i >= 0 && dayOf(rows[i].time) === day) i--;
|
|
1587
|
+
return i >= 0 ? rows[i] : null;
|
|
1588
|
+
}
|
|
1589
|
+
function part(p) {
|
|
1590
|
+
if (!p) return "";
|
|
1591
|
+
if (typeof p !== "object") return `<span>${esc(p)}</span>`;
|
|
1592
|
+
if (p.info != null) return `<button type="button" class="fac-lg-info" data-tip="${tips++}" aria-label="${esc(p.about ? "About " + p.about : "About")}">${ICONS.info}<span class="fac-tip" role="tooltip">${esc(p.info)}</span></button>`;
|
|
1593
|
+
if (Array.isArray(p.ramp)) return `<span class="fac-lg-ramp"${p.title ? ` title="${esc(p.title)}"` : ""}><span>${esc(p.from || "")}</span><i style="background:linear-gradient(90deg, ${p.ramp.map((c) => esc(c)).join(", ")})"></i><span>${esc(p.to || "")}</span></span>`;
|
|
1594
|
+
if (p.text != null) return `<span class="fac-lg-note"${p.title ? ` title="${esc(p.title)}"` : ""}>${esc(p.text)}</span>`;
|
|
1595
|
+
const st = p.plot ? view.styles[p.plot] : null;
|
|
1596
|
+
if (st && st.visible === false) return "";
|
|
1597
|
+
return keyItem(
|
|
1598
|
+
esc(p.label),
|
|
1599
|
+
p.value,
|
|
1600
|
+
p.prev,
|
|
1601
|
+
p.cls || "",
|
|
1602
|
+
p.color || st && st.color || "",
|
|
1603
|
+
typeof p.format === "function" ? p.format : num,
|
|
1604
|
+
p.note || ""
|
|
1605
|
+
);
|
|
1606
|
+
}
|
|
1607
|
+
const isInfo = (p) => !!p && typeof p === "object" && p.info != null;
|
|
1608
|
+
function title(name, id, hidden = false, extra = null) {
|
|
1609
|
+
if (!(view.o.controls && view.$(".fac-dialog"))) return `<span class="fac-lg-head"><span class="fac-lg-name">${esc(name)}</span></span>`;
|
|
1610
|
+
const btn = (act, icon, label) => `<button type="button" class="fac-lg-btn" data-act="${act}" data-ind="${esc(id || "")}"${extra != null ? ` data-extra="${extra}"` : ""} title="${label}" aria-label="${esc(name)}: ${label}">${icon}</button>`;
|
|
1611
|
+
return `<span class="fac-lg-head"><span class="fac-lg-name">${esc(name)}</span><span class="fac-lg-btns">` + (extra == null ? btn("eye", hidden ? ICONS.eyeOff : ICONS.eye, hidden ? "Show" : "Hide") : "") + (id ? btn("settings", ICONS.settings, "Options") : "") + btn("remove", ICONS.trash, "Remove") + "</span></span>";
|
|
1612
|
+
}
|
|
1613
|
+
function groupLine(gr, g, prev, at) {
|
|
1614
|
+
if (gr.hidden) return `<div class="sub lv fac-lg-off">${title(gr.name, gr.id, true)}</div>`;
|
|
1615
|
+
const layerOf = (p) => p && typeof p === "object" && (p.layer || p.plot && (gr.plots.find((x) => x.id === p.plot) || {}).layer);
|
|
1616
|
+
const shows = gr.layers.some(([k]) => view.active(k) && !gr.statusOff.has(k));
|
|
1617
|
+
if (!shows) g = null;
|
|
1618
|
+
const parts = [];
|
|
1619
|
+
if (g) view.callFor(gr.plugins, "legendLevels", g, parts, prev, gr.name, at);
|
|
1620
|
+
else if (shows && at.time != null) {
|
|
1621
|
+
view.callFor(gr.plugins.filter((p) => p !== view.corePlugin), "legendLevels", { time: at.time }, parts, null, gr.name, at);
|
|
1622
|
+
}
|
|
1623
|
+
const kept = parts.filter((p) => !gr.statusOff.has(layerOf(p))), infos = kept.filter(isInfo);
|
|
1624
|
+
const items = infos.map(part).concat(g && gr.plugins.includes(view.corePlugin) ? [keyItem("Spot", g.spot && g.spot.last, prev && prev.spot && prev.spot.last)] : []).concat(kept.filter((p) => !isInfo(p)).map(part)).filter(Boolean);
|
|
1625
|
+
return `<div class="sub lv">${title(gr.name, gr.id)}${items.join("")}</div>`;
|
|
1626
|
+
}
|
|
1627
|
+
function paneOf(series) {
|
|
1628
|
+
const pane = series && typeof series.getPane === "function" ? series.getPane() : null;
|
|
1629
|
+
return pane && pane.paneIndex() > 0 ? pane : null;
|
|
1630
|
+
}
|
|
1631
|
+
function linesByPane(time, g, y) {
|
|
1632
|
+
const prev = g ? previousSession(g) : null, out = /* @__PURE__ */ new Map(), at = { time, y: y == null ? null : y };
|
|
1633
|
+
const add = (i, html) => out.set(i, (out.get(i) || []).concat(html));
|
|
1634
|
+
for (const gr of view.groups) {
|
|
1635
|
+
if (!view.groupOn(gr)) {
|
|
1636
|
+
gr.hidden = false;
|
|
1637
|
+
continue;
|
|
1638
|
+
}
|
|
1639
|
+
const pane = paneOf(view.callFor(gr.plugins, "paneOf", gr.name).find(Boolean));
|
|
1640
|
+
add(pane ? pane.paneIndex() : 0, groupLine(gr, g, prev, at));
|
|
1641
|
+
}
|
|
1642
|
+
extras = time != null ? view.call("paneLegends", time).flat().filter((x) => x && paneOf(x.series)) : [];
|
|
1643
|
+
extras.forEach((x, i) => {
|
|
1644
|
+
const gr = view.groups.find((y2) => y2.name === x.indicator);
|
|
1645
|
+
const ps = x.parts || [];
|
|
1646
|
+
add(paneOf(x.series).paneIndex(), `<div class="sub lv">${title(x.name, gr && gr.id, false, i)}${ps.filter(isInfo).concat(ps.filter((p) => !isInfo(p))).map(part).join("")}</div>`);
|
|
1647
|
+
});
|
|
1648
|
+
return out;
|
|
1649
|
+
}
|
|
1650
|
+
const paneWatch = typeof ResizeObserver === "function" ? new ResizeObserver(() => {
|
|
1651
|
+
const before = plotRight;
|
|
1652
|
+
place();
|
|
1653
|
+
if (plotRight !== before) render(...last);
|
|
1654
|
+
}) : null;
|
|
1655
|
+
let plotRight = null;
|
|
1656
|
+
const watched = /* @__PURE__ */ new WeakSet();
|
|
1657
|
+
const paneEl = (p) => p && typeof p.getHTMLElement === "function" ? p.getHTMLElement() : null;
|
|
1658
|
+
function place() {
|
|
1659
|
+
if (!chart || typeof chart.panes !== "function") return;
|
|
1660
|
+
const panes = chart.panes(), els = panes.map(paneEl);
|
|
1661
|
+
if (paneWatch) {
|
|
1662
|
+
for (const el of els) if (el && !watched.has(el)) {
|
|
1663
|
+
watched.add(el);
|
|
1664
|
+
paneWatch.observe(el);
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
const body = $(".fac-body");
|
|
1668
|
+
const r0 = els[0] && els[0].getBoundingClientRect(), rb = body && body.getBoundingClientRect();
|
|
1669
|
+
const cells = els[0] ? [...els[0].children].map((x) => x.getBoundingClientRect()) : [];
|
|
1670
|
+
const plot = cells.length ? cells.reduce((a, b) => b.width > a.width ? b : a) : r0;
|
|
1671
|
+
if (plot && rb && plot.width > 0) {
|
|
1672
|
+
plotRight = Math.max(0, Math.round(rb.right - plot.right));
|
|
1673
|
+
root.style.setProperty("--fac-plot-right", `${plotRight}px`);
|
|
1674
|
+
}
|
|
1675
|
+
if (!paneBox) return;
|
|
1676
|
+
const tops = [];
|
|
1677
|
+
if (r0 && r0.height > 0 && els.every(Boolean)) for (const el of els) tops.push(el.getBoundingClientRect().top - r0.top);
|
|
1678
|
+
else {
|
|
1679
|
+
let top = 0;
|
|
1680
|
+
for (const p of panes) {
|
|
1681
|
+
tops.push(top);
|
|
1682
|
+
top += (p.getHeight() || 0) + 1;
|
|
1683
|
+
}
|
|
1684
|
+
}
|
|
1685
|
+
paneBox.querySelectorAll("[data-pane]").forEach((el) => {
|
|
1686
|
+
el.style.top = `${Math.round(tops[+el.dataset.pane] || 0) + 4}px`;
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
function fit(box) {
|
|
1690
|
+
const lim = box.clientWidth;
|
|
1691
|
+
if (!lim) return;
|
|
1692
|
+
for (const line of box.querySelectorAll(".lv")) {
|
|
1693
|
+
if (line.scrollWidth <= lim) continue;
|
|
1694
|
+
const parts = [...line.children].filter((x) => !x.matches(".fac-lg-head, .fac-lg-info"));
|
|
1695
|
+
const more = document.createElement("span");
|
|
1696
|
+
more.className = "fac-lg-more";
|
|
1697
|
+
more.textContent = "…";
|
|
1698
|
+
line.appendChild(more);
|
|
1699
|
+
const cut = [];
|
|
1700
|
+
while (parts.length && line.scrollWidth > lim) {
|
|
1701
|
+
const x = parts.pop();
|
|
1702
|
+
x.hidden = true;
|
|
1703
|
+
cut.unshift(x.textContent);
|
|
1704
|
+
}
|
|
1705
|
+
more.title = cut.join(" ");
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
function showTip() {
|
|
1709
|
+
root.querySelectorAll(".fac-lg-info").forEach((x) => x.classList.toggle("fac-tip-open", x.dataset.tip === openTip));
|
|
1710
|
+
}
|
|
1711
|
+
root.addEventListener("click", (e) => {
|
|
1712
|
+
if (e.target.closest && e.target.closest(".fac-tip")) return;
|
|
1713
|
+
const info = e.target.closest && e.target.closest(".fac-lg-info");
|
|
1714
|
+
if (!info && openTip == null) return;
|
|
1715
|
+
openTip = info && info.dataset.tip !== openTip ? info.dataset.tip : null;
|
|
1716
|
+
showTip();
|
|
1717
|
+
});
|
|
1718
|
+
const doc = root.ownerDocument;
|
|
1719
|
+
function onKey(e) {
|
|
1720
|
+
if (!root.isConnected) {
|
|
1721
|
+
doc.removeEventListener("keydown", onKey);
|
|
1722
|
+
return;
|
|
1723
|
+
}
|
|
1724
|
+
if (e.key !== "Escape") return;
|
|
1725
|
+
const f = doc.activeElement, info = f && root.contains(f) && f.closest && f.closest(".fac-lg-info");
|
|
1726
|
+
if (openTip == null && !info) return;
|
|
1727
|
+
openTip = null;
|
|
1728
|
+
showTip();
|
|
1729
|
+
if (info) info.blur();
|
|
1730
|
+
}
|
|
1731
|
+
doc.addEventListener("keydown", onKey);
|
|
1732
|
+
let folded = false, last = [null, null];
|
|
1733
|
+
function onClick(e) {
|
|
1734
|
+
const b = e.target.closest && e.target.closest("[data-act]");
|
|
1735
|
+
if (!b) return;
|
|
1736
|
+
if (b.dataset.act === "fold") {
|
|
1737
|
+
folded = !folded;
|
|
1738
|
+
render(...last);
|
|
1739
|
+
return;
|
|
1740
|
+
}
|
|
1741
|
+
const gr = view.groups.find((x) => x.id === b.dataset.ind), act = b.dataset.act;
|
|
1742
|
+
if (act === "settings") {
|
|
1743
|
+
if (gr && view.indicators) view.indicators.open(gr.id);
|
|
1744
|
+
return;
|
|
1745
|
+
}
|
|
1746
|
+
if (b.dataset.extra != null) {
|
|
1747
|
+
const x = extras[+b.dataset.extra];
|
|
1748
|
+
if (act === "remove" && x && typeof x.remove === "function") x.remove();
|
|
1749
|
+
return;
|
|
1750
|
+
}
|
|
1751
|
+
if (!gr) return;
|
|
1752
|
+
if (act === "remove") {
|
|
1753
|
+
gr.hidden = false;
|
|
1754
|
+
view.setGroup(gr, false);
|
|
1755
|
+
} else if (act === "eye") gr.hidden = !gr.hidden;
|
|
1756
|
+
view.redraw();
|
|
1757
|
+
}
|
|
1758
|
+
legend.addEventListener("click", onClick);
|
|
1759
|
+
if (paneBox) paneBox.addEventListener("click", onClick);
|
|
1760
|
+
function render(t, y) {
|
|
1761
|
+
last = [t, y];
|
|
1762
|
+
const b = t != null ? data.byTime.get(t) : [...data.byTime.values()].at(-1);
|
|
1763
|
+
const time = b ? b.time : null;
|
|
1764
|
+
const g = time != null ? data.gexByTime.get(time) : null;
|
|
1765
|
+
const head = `<b>${esc(state.symbol)}</b>`;
|
|
1766
|
+
tips = 0;
|
|
1767
|
+
const byPane = linesByPane(time, g, t != null ? y : null);
|
|
1768
|
+
if (paneBox) {
|
|
1769
|
+
paneBox.innerHTML = [...byPane].filter(([i]) => i > 0).map(([i, html]) => `<div class="fac-legend fac-pane-lg" data-pane="${i}">${html.join("")}</div>`).join("");
|
|
1770
|
+
place();
|
|
1771
|
+
if (paneBox.firstChild && typeof requestAnimationFrame === "function") requestAnimationFrame(place);
|
|
1772
|
+
paneBox.querySelectorAll(".fac-pane-lg").forEach(fit);
|
|
1773
|
+
} else place();
|
|
1774
|
+
if (t == null && root.classList.contains("fac-narrow")) {
|
|
1775
|
+
legend.innerHTML = `<span class="fac-lg-top">${head}${b ? `<span class="${b.close >= b.open ? "up" : "dn"}">${num(b.close)}</span>` : ""}</span>`;
|
|
1776
|
+
showTip();
|
|
1777
|
+
return;
|
|
1778
|
+
}
|
|
1779
|
+
const price = b ? `<span class="${b.close >= b.open ? "up" : "dn"}">${num(b.close)}</span><span class="k">O</span> ${num(b.open)}<span class="k">H</span> ${num(b.high)}<span class="k">L</span> ${num(b.low)}` + (b.volume != null && !view.quoteMid(b) && !view.partVolume(b) ? `<span class="k">Vol</span> ${big(b.volume)}` : "") + (b.source === "spot" ? '<span class="k">index spot</span>' : view.quoteMid(b) ? '<span class="k">quote mid (no trades)</span>' : view.partVolume(b) ? '<span class="k">some days quote mid (no volume)</span>' : view.intraday() && sessionOf(b.time) !== "rth" ? `<span class="k">${sessionOf(b.time)}-market</span>` : "") : "";
|
|
1780
|
+
const lines = [];
|
|
1781
|
+
const extra = time != null ? view.call("legend", time, y).flat().filter(Boolean) : [];
|
|
1782
|
+
const isGated = (x) => x && typeof x === "object" && x.gated;
|
|
1783
|
+
const menuAt = (name) => {
|
|
1784
|
+
const i = view.groups.findIndex((gr) => gr.name === name);
|
|
1785
|
+
return i < 0 ? Infinity : i;
|
|
1786
|
+
};
|
|
1787
|
+
const gatedNames = [...new Set(data.notes.concat(extra).filter(isGated).map((x) => String(x.gated)))].sort((a, b2) => menuAt(a) - menuAt(b2));
|
|
1788
|
+
const gatedLine = !gatedNames.length ? "" : `<div class="sub fac-lg-gated">Not in your plan: ${esc(gatedNames.join(", "))} ` + (view.state.noKey ? `<a class="fac-lg-up" href="${esc(view.signupHref("legend"))}" ${view.ctaAttrs("legend", "signup")} target="_blank" rel="noopener">Sign up</a>` : `<a class="fac-lg-up" href="${esc(view.upgradeHref("legend"))}" ${view.ctaAttrs("legend")} target="_blank" rel="noopener">Upgrade</a>`) + "</div>";
|
|
1789
|
+
lines.push(...extra.filter((x) => !isGated(x)));
|
|
1790
|
+
const notes = data.notes.filter((x) => !isGated(x));
|
|
1791
|
+
if (notes.length) lines.push(notes.join(" · "));
|
|
1792
|
+
const inds = byPane.get(0) || [];
|
|
1793
|
+
const fold = !inds.length || !(view.o.controls && view.$(".fac-dialog")) ? "" : `<div class="sub fac-lg-foldrow"><button type="button" class="fac-lg-btn fac-lg-fold${folded ? " on" : ""}" data-act="fold" aria-expanded="${!folded}" title="${folded ? "Show indicator legend" : "Hide indicator legend"}" aria-label="${folded ? "Show indicator legend" : "Hide indicator legend"}">${ICONS.chevron}${folded ? `<span>${inds.length}</span>` : ""}</button></div>`;
|
|
1794
|
+
legend.innerHTML = `<span class="fac-lg-top">${head}${price}</span>` + (folded ? "" : inds.join("")) + fold + gatedLine + (folded ? "" : lines.filter(Boolean).map((l) => `<div class="sub">${esc(l)}</div>`).join(""));
|
|
1795
|
+
fit(legend);
|
|
1796
|
+
showTip();
|
|
1797
|
+
}
|
|
1798
|
+
return { render, place };
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
// src/components/upsell.js
|
|
1802
|
+
function createUpsell(view) {
|
|
1803
|
+
const box = view.$(".fac-upsell");
|
|
1804
|
+
function render() {
|
|
1805
|
+
if (!view.o.upsell) {
|
|
1806
|
+
box.hidden = true;
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
const { layerPlan, layerList } = view;
|
|
1810
|
+
const wanted = [...view.state.layers].filter(view.locked);
|
|
1811
|
+
if (!wanted.length) {
|
|
1812
|
+
box.hidden = true;
|
|
1813
|
+
return;
|
|
1814
|
+
}
|
|
1815
|
+
const need = wanted.map((k) => layerPlan[k]).sort((a, b) => planRank(a) - planRank(b))[0];
|
|
1816
|
+
const names = layerList.filter(([k]) => wanted.includes(k) && layerPlan[k] === need).map(([, l]) => l);
|
|
1817
|
+
box.innerHTML = `<span>🔒 ${esc(names.slice(0, 2).join(", "))}${names.length > 2 ? ` +${names.length - 2}` : ""}</span>` + (PLAN_PITCH[need] ? `<span class="pitch">${esc(PLAN_PITCH[need])}</span>` : "") + `<span class="plan">${esc(PLAN_NAMES[need] || need)}</span>` + (view.state.noKey ? `<a href="${esc(view.signupHref("upsell"))}" ${view.ctaAttrs("upsell", "signup")} target="_blank" rel="noopener">Sign up free</a>` : `<a href="${esc(view.upgradeHref(wanted[0]))}" ${view.ctaAttrs(wanted[0])} target="_blank" rel="noopener">Upgrade</a>`);
|
|
1818
|
+
box.hidden = false;
|
|
1819
|
+
}
|
|
1820
|
+
return { render };
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
// src/components/empty-state.js
|
|
1824
|
+
var PREVIEW = (() => {
|
|
1825
|
+
const n = 48, w = 600 / n, mid = (t) => 150 + 38 * Math.sin(t / 7) + 14 * Math.sin(t / 2.3);
|
|
1826
|
+
let body = "";
|
|
1827
|
+
for (let i = 0; i < n; i++) {
|
|
1828
|
+
const o = mid(i), c = mid(i + 1), hi = Math.min(o, c) - 6 - 4 * Math.abs(Math.sin(i * 1.7)), lo = Math.max(o, c) + 6 + 4 * Math.abs(Math.cos(i * 1.3));
|
|
1829
|
+
const color = c <= o ? COLORS.up : COLORS.down, x = i * w + w / 2, vol = 18 + 22 * Math.abs(Math.sin(i * 0.9));
|
|
1830
|
+
body += `<line x1="${x.toFixed(1)}" y1="${hi.toFixed(1)}" x2="${x.toFixed(1)}" y2="${lo.toFixed(1)}" stroke="${color}" stroke-width="1.5"/><rect x="${(x - w * 0.3).toFixed(1)}" y="${Math.min(o, c).toFixed(1)}" width="${(w * 0.6).toFixed(1)}" height="${Math.max(2, Math.abs(c - o)).toFixed(1)}" fill="${color}"/><rect x="${(x - w * 0.3).toFixed(1)}" y="${(300 - vol).toFixed(1)}" width="${(w * 0.6).toFixed(1)}" height="${vol.toFixed(1)}" fill="${color}" opacity="0.5"/>`;
|
|
1831
|
+
}
|
|
1832
|
+
const level = (y, color) => `<line x1="0" y1="${y}" x2="600" y2="${y}" stroke="${color}" stroke-width="2" stroke-dasharray="8 6"/>`;
|
|
1833
|
+
return `<svg class="fac-gate-bg" viewBox="0 0 600 300" preserveAspectRatio="none" aria-hidden="true" focusable="false">${body}${level(96, COLORS.up)}${level(158, COLORS.flip)}${level(212, COLORS.down)}</svg>`;
|
|
1834
|
+
})();
|
|
1835
|
+
function createEmptyState(view) {
|
|
1836
|
+
const box = view.$(".fac-empty");
|
|
1837
|
+
function show(error) {
|
|
1838
|
+
const { state } = view;
|
|
1839
|
+
state.noData = error;
|
|
1840
|
+
box.classList.remove("fac-loading");
|
|
1841
|
+
box.classList.toggle("fac-gate", error === "api_key_required");
|
|
1842
|
+
if (!error) {
|
|
1843
|
+
box.style.display = "none";
|
|
1844
|
+
return;
|
|
1845
|
+
}
|
|
1846
|
+
if (error === "api_key_required") {
|
|
1847
|
+
box.innerHTML = `${PREVIEW}<div class="fac-gate-box">${ICONS.lock}<p class="fac-gate-ttl">${esc(GATE.title(state.symbol))}</p><p class="fac-gate-txt">${esc(GATE.text)}</p><a class="fac-gate-cta" href="${esc(view.signupHref("gate"))}" ${view.ctaAttrs("gate", "signup")} target="_blank" rel="noopener">${ICONS.key}${esc(GATE.cta)}</a></div>`;
|
|
1848
|
+
} else {
|
|
1849
|
+
box.textContent = (error === "unknown_symbol" || error === "no bars") && state.symbol ? `No chart data for ${state.symbol} yet.` : ERRORS[error] || "Chart data is unavailable right now.";
|
|
1850
|
+
}
|
|
1851
|
+
box.style.display = "flex";
|
|
1852
|
+
view.container.dispatchEvent(new CustomEvent("flashalpha:nodata", { bubbles: true, detail: { symbol: state.symbol, error } }));
|
|
1853
|
+
}
|
|
1854
|
+
function loading() {
|
|
1855
|
+
box.classList.remove("fac-gate");
|
|
1856
|
+
box.classList.add("fac-loading");
|
|
1857
|
+
box.textContent = view.state.symbol ? `Loading ${view.state.symbol}…` : "Loading…";
|
|
1858
|
+
box.style.display = "flex";
|
|
1859
|
+
}
|
|
1860
|
+
return { show, loading };
|
|
1861
|
+
}
|
|
1862
|
+
|
|
1863
|
+
// src/components/screenshot.js
|
|
1864
|
+
var etParts2 = new Intl.DateTimeFormat("en-CA", {
|
|
1865
|
+
timeZone: ET,
|
|
1866
|
+
year: "numeric",
|
|
1867
|
+
month: "2-digit",
|
|
1868
|
+
day: "2-digit",
|
|
1869
|
+
hour: "2-digit",
|
|
1870
|
+
minute: "2-digit",
|
|
1871
|
+
hourCycle: "h23"
|
|
1872
|
+
});
|
|
1873
|
+
function etNow() {
|
|
1874
|
+
const p = Object.fromEntries(etParts2.formatToParts(/* @__PURE__ */ new Date()).map((x) => [x.type, x.value]));
|
|
1875
|
+
return { day: `${p.year}-${p.month}-${p.day}`, time: `${p.hour}:${p.minute}` };
|
|
1876
|
+
}
|
|
1877
|
+
function createScreenshot(view, chart) {
|
|
1878
|
+
const { root, o, state } = view;
|
|
1879
|
+
return function screenshot() {
|
|
1880
|
+
if (typeof chart.takeScreenshot !== "function") return null;
|
|
1881
|
+
const shot = chart.takeScreenshot(true, false);
|
|
1882
|
+
const canvasBox = root.querySelector(".fac-canvas");
|
|
1883
|
+
const ratio = canvasBox && canvasBox.clientWidth ? shot.width / canvasBox.clientWidth : global.devicePixelRatio || 1;
|
|
1884
|
+
const head = Math.round(30 * ratio);
|
|
1885
|
+
const out = document.createElement("canvas");
|
|
1886
|
+
out.width = shot.width;
|
|
1887
|
+
out.height = shot.height + head;
|
|
1888
|
+
const g = out.getContext("2d");
|
|
1889
|
+
if (!g) return null;
|
|
1890
|
+
const css2 = (name2) => root.style.getPropertyValue("--fac-" + name2).trim();
|
|
1891
|
+
const bg = css2("bg") || THEMES.dark.bg, text = css2("text") || THEMES.dark.text, muted = css2("muted") || THEMES.dark.muted;
|
|
1892
|
+
g.fillStyle = bg;
|
|
1893
|
+
g.fillRect(0, 0, out.width, out.height);
|
|
1894
|
+
const now = etNow(), pad = 10 * ratio, mid = head / 2;
|
|
1895
|
+
g.textBaseline = "middle";
|
|
1896
|
+
g.font = `600 ${13 * ratio}px system-ui, -apple-system, Segoe UI, sans-serif`;
|
|
1897
|
+
g.fillStyle = text;
|
|
1898
|
+
const title = state.symbol || "";
|
|
1899
|
+
g.fillText(title, pad, mid);
|
|
1900
|
+
g.font = `${12 * ratio}px system-ui, -apple-system, Segoe UI, sans-serif`;
|
|
1901
|
+
g.fillStyle = muted;
|
|
1902
|
+
g.fillText(
|
|
1903
|
+
` · ${state.res} · ${String(o.session).toUpperCase()}${o.brand && o.brand.name ? " · " + o.brand.name : ""}`,
|
|
1904
|
+
pad + g.measureText(title).width + 2 * ratio,
|
|
1905
|
+
mid
|
|
1906
|
+
);
|
|
1907
|
+
g.textAlign = "right";
|
|
1908
|
+
g.fillText(`${now.day} ${now.time} ET`, out.width - pad, mid);
|
|
1909
|
+
g.drawImage(shot, 0, head);
|
|
1910
|
+
const name = `${title || "chart"}_${state.res}_${now.day}_${now.time.replace(":", "")}.png`;
|
|
1911
|
+
const save = (href) => {
|
|
1912
|
+
const a = document.createElement("a");
|
|
1913
|
+
a.href = href;
|
|
1914
|
+
a.download = name;
|
|
1915
|
+
a.style.display = "none";
|
|
1916
|
+
root.appendChild(a);
|
|
1917
|
+
a.click();
|
|
1918
|
+
a.remove();
|
|
1919
|
+
};
|
|
1920
|
+
if (out.toBlob && global.URL && URL.createObjectURL) {
|
|
1921
|
+
out.toBlob((blob) => {
|
|
1922
|
+
if (!blob) return;
|
|
1923
|
+
const url = URL.createObjectURL(blob);
|
|
1924
|
+
save(url);
|
|
1925
|
+
setTimeout(() => URL.revokeObjectURL(url), 1e3);
|
|
1926
|
+
}, "image/png");
|
|
1927
|
+
} else save(out.toDataURL("image/png"));
|
|
1928
|
+
return name;
|
|
1929
|
+
};
|
|
1930
|
+
}
|
|
1931
|
+
|
|
1932
|
+
// src/components/indicators.js
|
|
1933
|
+
var WIDTHS = [1, 2, 3, 4];
|
|
1934
|
+
var STYLES = [["solid", "Solid"], ["dotted", "Dotted"], ["dashed", "Dashed"]];
|
|
1935
|
+
function createIndicators(view) {
|
|
1936
|
+
const { $, state } = view;
|
|
1937
|
+
const list = $(".fac-ind-list");
|
|
1938
|
+
const dlg = $(".fac-dialog");
|
|
1939
|
+
let open = null;
|
|
1940
|
+
const plotsOf = (g, k) => g.plots.filter((p) => !p.layer || p.layer === k);
|
|
1941
|
+
const planName = (p) => PLAN_NAMES[p] || p;
|
|
1942
|
+
function layerRow(k, label, bold = false) {
|
|
1943
|
+
const plan = view.layerPlan[k] || "free", name = bold ? `<b>${esc(label)}</b>` : esc(label);
|
|
1944
|
+
if (view.locked(k)) return `<a class="fac-lock" href="${esc(view.upgradeHref(k))}" ${view.ctaAttrs(k)} target="_blank" rel="noopener">🔒 ${name} <span class="plan">${esc(planName(plan))}</span></a>`;
|
|
1945
|
+
return `<label><input type="checkbox" data-layer="${esc(k)}" ${view.active(k) ? "checked" : ""}> ${name}</label>`;
|
|
1946
|
+
}
|
|
1947
|
+
function toggleGroup(g, wanted, input) {
|
|
1948
|
+
if (wanted && g.layers.length && g.layers.every(([k]) => view.locked(k))) {
|
|
1949
|
+
input.checked = false;
|
|
1950
|
+
const [k] = g.layers.slice().sort(([a], [b]) => planRank(view.layerPlan[a]) - planRank(view.layerPlan[b]))[0];
|
|
1951
|
+
view.openUpgrade(k);
|
|
1952
|
+
return;
|
|
1953
|
+
}
|
|
1954
|
+
return view.setGroup(g, wanted);
|
|
1955
|
+
}
|
|
1956
|
+
function layersFrom(box, g) {
|
|
1957
|
+
const mine = new Set(g.layers.map(([k]) => k));
|
|
1958
|
+
const keep = [...state.layers].filter((k) => !mine.has(k));
|
|
1959
|
+
return keep.concat([...box.querySelectorAll("input[data-layer]:checked")].map((x) => x.dataset.layer));
|
|
1960
|
+
}
|
|
1961
|
+
function renderList() {
|
|
1962
|
+
if (!list) return;
|
|
1963
|
+
const row = (g, k, l, bold) => `<div class="fac-ind-row">${layerRow(k, l, bold)}${view.locked(k) ? "" : `<button type="button" class="fac-icon" data-settings="${esc(k)}" title="Options" aria-label="${esc(l)} options">${ICONS.settings}</button>`}</div>`;
|
|
1964
|
+
list.innerHTML = view.groups.map((g) => g.layers.length === 1 ? `<div class="fac-ind fac-ind-one" data-ind="${esc(g.id)}">${row(g, g.layers[0][0], g.name, true)}</div>` : `<div class="fac-ind" data-ind="${esc(g.id)}">
|
|
1965
|
+
<div class="fac-ind-head"><label><input type="checkbox" data-group> <b>${esc(g.name)}</b></label></div>
|
|
1966
|
+
<div class="fac-ind-layers">${g.layers.map(([k, l]) => row(g, k, l)).join("")}</div></div>`).join("");
|
|
1967
|
+
list.querySelectorAll(".fac-ind").forEach((box) => {
|
|
1968
|
+
const g = view.groups.find((x) => x.id === box.dataset.ind);
|
|
1969
|
+
const sw = box.querySelector("[data-group]");
|
|
1970
|
+
if (sw) {
|
|
1971
|
+
const open2 = g.layers.filter(([k]) => !view.locked(k)), on = open2.filter(([k]) => view.active(k)).length;
|
|
1972
|
+
sw.checked = open2.length > 0 && on === open2.length;
|
|
1973
|
+
sw.indeterminate = on > 0 && on < open2.length;
|
|
1974
|
+
sw.onchange = (e) => toggleGroup(g, e.target.checked, e.target);
|
|
1975
|
+
}
|
|
1976
|
+
box.querySelectorAll("[data-settings]").forEach((b) => {
|
|
1977
|
+
b.onclick = () => {
|
|
1978
|
+
view.closeMenus();
|
|
1979
|
+
openSettings(g.id, b.dataset.settings);
|
|
1980
|
+
};
|
|
1981
|
+
});
|
|
1982
|
+
box.querySelectorAll("input[data-layer]").forEach((i) => {
|
|
1983
|
+
i.onchange = () => view.api.setLayers(layersFrom(box, g));
|
|
1984
|
+
});
|
|
1985
|
+
});
|
|
1986
|
+
}
|
|
1987
|
+
function snapshot(g, k) {
|
|
1988
|
+
return {
|
|
1989
|
+
layers: [...state.layers],
|
|
1990
|
+
statusOff: new Set(g.statusOff),
|
|
1991
|
+
styles: Object.fromEntries(plotsOf(g, k).map((p) => [p.id, Object.assign({}, view.styles[p.id])]))
|
|
1992
|
+
};
|
|
1993
|
+
}
|
|
1994
|
+
function openSettings(id, k, tab) {
|
|
1995
|
+
const g = view.groups.find((x) => x.id === id);
|
|
1996
|
+
if (!dlg || !g) return;
|
|
1997
|
+
const open1 = g.layers.filter(([x]) => !view.locked(x));
|
|
1998
|
+
const layer = open1.find(([x]) => x === k) || !k && (open1.find(([x]) => view.active(x)) || open1[0]);
|
|
1999
|
+
if (!layer) return;
|
|
2000
|
+
open = { g, k: layer[0], label: layer[1], tab: tab || (plotsOf(g, layer[0]).length ? "style" : "inputs"), snapshot: snapshot(g, layer[0]) };
|
|
2001
|
+
dlg.hidden = false;
|
|
2002
|
+
renderDialog();
|
|
2003
|
+
const first = dlg.querySelector(".fac-tabs .on");
|
|
2004
|
+
if (first) first.focus();
|
|
2005
|
+
}
|
|
2006
|
+
function close() {
|
|
2007
|
+
if (dlg) dlg.hidden = true;
|
|
2008
|
+
open = null;
|
|
2009
|
+
}
|
|
2010
|
+
function cancel() {
|
|
2011
|
+
if (!open) return;
|
|
2012
|
+
const { g, snapshot: s } = open;
|
|
2013
|
+
for (const [id, st] of Object.entries(s.styles)) view.setStyle(id, st, true);
|
|
2014
|
+
g.statusOff = s.statusOff;
|
|
2015
|
+
view.redraw();
|
|
2016
|
+
const changed = s.layers.length !== state.layers.size || s.layers.some((k) => !state.layers.has(k));
|
|
2017
|
+
close();
|
|
2018
|
+
if (changed) view.api.setLayers(s.layers);
|
|
2019
|
+
}
|
|
2020
|
+
function inputsTab(g, k, label) {
|
|
2021
|
+
const shared = g.layers.length > 1 ? `<div class="fac-dlg-hint">Apply to every layer of ${esc(g.name)}.</div>` : "";
|
|
2022
|
+
return `<div class="fac-dlg-sec">Layer</div><div class="fac-dlg-layers">${layerRow(k, label)}</div>` + (g.inputs.children.length ? `<div class="fac-dlg-sec">Options</div>${shared}<div class="fac-dlg-inputs"></div>` : "");
|
|
2023
|
+
}
|
|
2024
|
+
function styleTab(g, k) {
|
|
2025
|
+
const plots = plotsOf(g, k);
|
|
2026
|
+
const rows = plots.map((p) => {
|
|
2027
|
+
const st = view.styles[p.id];
|
|
2028
|
+
const color = `<input type="color" data-p="${esc(p.id)}" data-k="color" value="${esc(st.color)}" aria-label="${esc(p.title)} colour">`;
|
|
2029
|
+
if (p.colorOnly) return `<div class="fac-sty"><span class="fac-sty-name">${esc(p.title)}</span>${color}</div>`;
|
|
2030
|
+
const visible = `<label class="fac-sty-name"><input type="checkbox" data-p="${esc(p.id)}" data-k="visible" ${st.visible ? "checked" : ""}> ${esc(p.title)}</label>`;
|
|
2031
|
+
if (p.toggle) return `<div class="fac-sty">${visible}${p.color ? color : ""}</div>`;
|
|
2032
|
+
return `<div class="fac-sty">${visible}${color}<select data-p="${esc(p.id)}" data-k="lineWidth" aria-label="${esc(p.title)} width">${WIDTHS.map((w) => `<option value="${w}"${st.lineWidth === w ? " selected" : ""}>${w}px</option>`).join("")}</select><select data-p="${esc(p.id)}" data-k="lineStyle" aria-label="${esc(p.title)} line style">${STYLES.map(([v, l]) => `<option value="${v}"${st.lineStyle === v ? " selected" : ""}>${l}</option>`).join("")}</select></div>`;
|
|
2033
|
+
}).join("");
|
|
2034
|
+
const lines = plots.filter((p) => !p.colorOnly && !p.toggle);
|
|
2035
|
+
const all = (key) => lines.length && lines.every((p) => view.styles[p.id][key]);
|
|
2036
|
+
return `${rows || '<div class="fac-none">Nothing to style.</div>'}<div class="fac-dlg-sec">Show</div>` + (lines.length ? `<label><input type="checkbox" data-all="priceLine" ${all("priceLine") ? "checked" : ""}> Price lines (latest value)</label>
|
|
2037
|
+
<label><input type="checkbox" data-all="axisLabel" ${all("axisLabel") ? "checked" : ""}> Labels on price scale</label>` : "") + `<label><input type="checkbox" data-status ${g.statusOff.has(k) ? "" : "checked"}> Values in status line (legend)</label>`;
|
|
2038
|
+
}
|
|
2039
|
+
function renderDialog() {
|
|
2040
|
+
if (!open || !dlg) return;
|
|
2041
|
+
const { g, k, label, tab } = open;
|
|
2042
|
+
const plots = plotsOf(g, k);
|
|
2043
|
+
dlg.innerHTML = `<div class="fac-dlg" role="dialog" aria-modal="true" aria-label="${esc(label)} options">
|
|
2044
|
+
<div class="fac-dlg-head"><b>${esc(label)}</b><span class="fac-dlg-sub">${esc(g.name)}</span><button type="button" class="fac-icon" data-x title="Close" aria-label="Close">×</button></div>
|
|
2045
|
+
<div class="fac-tabs" role="tablist">${[["inputs", "Inputs"], ["style", "Style"]].map(([t, l]) => `<button type="button" role="tab" data-tab="${t}" aria-selected="${t === tab}" class="${t === tab ? "on" : ""}">${l}</button>`).join("")}</div>
|
|
2046
|
+
<div class="fac-dlg-body">${tab === "inputs" ? inputsTab(g, k, label) : styleTab(g, k)}</div>
|
|
2047
|
+
<div class="fac-dlg-foot"><button type="button" data-defaults title="Reset the style to the layer's defaults">Defaults</button><span class="fac-spacer"></span>
|
|
2048
|
+
<button type="button" data-cancel>Cancel</button><button type="button" class="fac-primary" data-ok>Ok</button></div></div>`;
|
|
2049
|
+
const slot = dlg.querySelector(".fac-dlg-inputs");
|
|
2050
|
+
if (slot) slot.appendChild(g.inputs);
|
|
2051
|
+
dlg.querySelectorAll("[data-tab]").forEach((b) => {
|
|
2052
|
+
b.onclick = () => {
|
|
2053
|
+
open.tab = b.dataset.tab;
|
|
2054
|
+
renderDialog();
|
|
2055
|
+
};
|
|
2056
|
+
});
|
|
2057
|
+
const sw = dlg.querySelector(".fac-dlg-layers input[data-layer]");
|
|
2058
|
+
if (sw) sw.onchange = () => view.api.setLayers(sw.checked ? [...state.layers, k] : [...state.layers].filter((x) => x !== k));
|
|
2059
|
+
dlg.querySelectorAll("[data-p]").forEach((el) => {
|
|
2060
|
+
el.onchange = el.oninput = () => {
|
|
2061
|
+
const k2 = el.dataset.k;
|
|
2062
|
+
const v = k2 === "visible" ? el.checked : k2 === "lineWidth" ? +el.value : el.value;
|
|
2063
|
+
view.setStyle(el.dataset.p, { [k2]: v });
|
|
2064
|
+
};
|
|
2065
|
+
});
|
|
2066
|
+
dlg.querySelectorAll("[data-all]").forEach((el) => {
|
|
2067
|
+
el.onchange = () => {
|
|
2068
|
+
for (const p of plots) if (!p.colorOnly && !p.toggle) view.setStyle(p.id, { [el.dataset.all]: el.checked }, true);
|
|
2069
|
+
view.redraw();
|
|
2070
|
+
};
|
|
2071
|
+
});
|
|
2072
|
+
const status = dlg.querySelector("[data-status]");
|
|
2073
|
+
if (status) status.onchange = () => {
|
|
2074
|
+
if (status.checked) g.statusOff.delete(k);
|
|
2075
|
+
else g.statusOff.add(k);
|
|
2076
|
+
view.redraw();
|
|
2077
|
+
};
|
|
2078
|
+
dlg.querySelector("[data-defaults]").onclick = () => {
|
|
2079
|
+
for (const p of plots) view.setStyle(p.id, view.defaultStyle(p.id), true);
|
|
2080
|
+
g.statusOff.delete(k);
|
|
2081
|
+
view.redraw();
|
|
2082
|
+
renderDialog();
|
|
2083
|
+
};
|
|
2084
|
+
dlg.querySelector("[data-x]").onclick = dlg.querySelector("[data-cancel]").onclick = cancel;
|
|
2085
|
+
dlg.querySelector("[data-ok]").onclick = close;
|
|
2086
|
+
}
|
|
2087
|
+
if (dlg) {
|
|
2088
|
+
dlg.addEventListener("keydown", (e) => {
|
|
2089
|
+
if (e.key === "Escape") {
|
|
2090
|
+
e.stopPropagation();
|
|
2091
|
+
cancel();
|
|
2092
|
+
}
|
|
2093
|
+
});
|
|
2094
|
+
dlg.addEventListener("click", (e) => {
|
|
2095
|
+
if (e.target === dlg) cancel();
|
|
2096
|
+
});
|
|
2097
|
+
}
|
|
2098
|
+
return {
|
|
2099
|
+
/** The menu, and the dialog's layer list when it is open (the plan or the layers changed). */
|
|
2100
|
+
render() {
|
|
2101
|
+
renderList();
|
|
2102
|
+
if (open && open.tab === "inputs") renderDialog();
|
|
2103
|
+
},
|
|
2104
|
+
open: openSettings,
|
|
2105
|
+
close,
|
|
2106
|
+
get isOpen() {
|
|
2107
|
+
return !!open;
|
|
2108
|
+
}
|
|
2109
|
+
};
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
// src/live.js
|
|
2113
|
+
var FATAL = ["invalid_api_key", "embed_key_expired", "embed_key_revoked", "origin_not_allowed", "delay_not_streamed"];
|
|
2114
|
+
var BACKOFF = [1e3, 2e3, 4e3, 8e3, 15e3];
|
|
2115
|
+
var IDLE_MS = 4e4;
|
|
2116
|
+
var HIDDEN_MS = 6e4;
|
|
2117
|
+
function liveUrl(baseUrl, origin) {
|
|
2118
|
+
return String(baseUrl || origin || "").replace(/\/$/, "").replace(/^http/, "ws") + "/v1/live";
|
|
2119
|
+
}
|
|
2120
|
+
function createLive({ url, key, WebSocket: WS, onMessage, onState, doc, random = Math.random }) {
|
|
2121
|
+
let ws = null, up = false, symbol = null, tries = 0, stopped = false, paused = false;
|
|
2122
|
+
let retry = null, watchdog = null, hiddenTimer = null;
|
|
2123
|
+
const send = (sock, msg) => {
|
|
2124
|
+
try {
|
|
2125
|
+
sock.send(JSON.stringify(msg));
|
|
2126
|
+
} catch (e) {
|
|
2127
|
+
}
|
|
2128
|
+
};
|
|
2129
|
+
const kick = (sock) => {
|
|
2130
|
+
clearTimeout(watchdog);
|
|
2131
|
+
watchdog = setTimeout(() => drop(sock), IDLE_MS);
|
|
2132
|
+
};
|
|
2133
|
+
const drop = (sock) => {
|
|
2134
|
+
try {
|
|
2135
|
+
sock.close();
|
|
2136
|
+
} catch (e) {
|
|
2137
|
+
}
|
|
2138
|
+
};
|
|
2139
|
+
function connect() {
|
|
2140
|
+
clearTimeout(retry);
|
|
2141
|
+
if (stopped || paused || ws) return;
|
|
2142
|
+
let sock;
|
|
2143
|
+
try {
|
|
2144
|
+
sock = new WS(url);
|
|
2145
|
+
} catch (e) {
|
|
2146
|
+
schedule();
|
|
2147
|
+
return;
|
|
2148
|
+
}
|
|
2149
|
+
ws = sock;
|
|
2150
|
+
let fatal = false;
|
|
2151
|
+
kick(sock);
|
|
2152
|
+
sock.onopen = () => {
|
|
2153
|
+
if (ws === sock) send(sock, { op: "hello", key: key || null, v: 1 });
|
|
2154
|
+
};
|
|
2155
|
+
sock.onmessage = (ev) => {
|
|
2156
|
+
if (ws !== sock) return;
|
|
2157
|
+
let m;
|
|
2158
|
+
try {
|
|
2159
|
+
m = JSON.parse(ev.data);
|
|
2160
|
+
} catch (e) {
|
|
2161
|
+
return;
|
|
2162
|
+
}
|
|
2163
|
+
if (!m || typeof m !== "object") return;
|
|
2164
|
+
kick(sock);
|
|
2165
|
+
if (m.t === "ping") {
|
|
2166
|
+
send(sock, { op: "pong", ts: m.ts });
|
|
2167
|
+
return;
|
|
2168
|
+
}
|
|
2169
|
+
if (m.t === "welcome") {
|
|
2170
|
+
up = true;
|
|
2171
|
+
tries = 0;
|
|
2172
|
+
if (symbol) send(sock, { op: "sub", s: symbol });
|
|
2173
|
+
onState("up", m);
|
|
2174
|
+
return;
|
|
2175
|
+
}
|
|
2176
|
+
if (m.t === "error" && FATAL.includes(m.code)) fatal = true;
|
|
2177
|
+
onMessage(m);
|
|
2178
|
+
};
|
|
2179
|
+
sock.onclose = () => {
|
|
2180
|
+
if (ws !== sock) return;
|
|
2181
|
+
ws = null;
|
|
2182
|
+
clearTimeout(watchdog);
|
|
2183
|
+
const was = up;
|
|
2184
|
+
up = false;
|
|
2185
|
+
if (fatal) stopped = true;
|
|
2186
|
+
onState("down", { was, off: stopped });
|
|
2187
|
+
schedule();
|
|
2188
|
+
};
|
|
2189
|
+
sock.onerror = () => {
|
|
2190
|
+
};
|
|
2191
|
+
}
|
|
2192
|
+
function schedule() {
|
|
2193
|
+
if (stopped || paused) return;
|
|
2194
|
+
const wait = tries === 0 ? random() * 3e3 : BACKOFF[Math.min(tries - 1, BACKOFF.length - 1)];
|
|
2195
|
+
tries++;
|
|
2196
|
+
retry = setTimeout(connect, wait);
|
|
2197
|
+
}
|
|
2198
|
+
const onVisibility = () => {
|
|
2199
|
+
if (doc.hidden) {
|
|
2200
|
+
clearTimeout(hiddenTimer);
|
|
2201
|
+
hiddenTimer = setTimeout(() => {
|
|
2202
|
+
paused = true;
|
|
2203
|
+
clearTimeout(retry);
|
|
2204
|
+
const sock = ws;
|
|
2205
|
+
ws = null;
|
|
2206
|
+
clearTimeout(watchdog);
|
|
2207
|
+
if (sock) {
|
|
2208
|
+
drop(sock);
|
|
2209
|
+
if (up) {
|
|
2210
|
+
up = false;
|
|
2211
|
+
onState("down", { was: true, off: false });
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
}, HIDDEN_MS);
|
|
2215
|
+
} else {
|
|
2216
|
+
clearTimeout(hiddenTimer);
|
|
2217
|
+
if (paused) {
|
|
2218
|
+
paused = false;
|
|
2219
|
+
tries = 0;
|
|
2220
|
+
connect();
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
};
|
|
2224
|
+
if (doc && doc.addEventListener) doc.addEventListener("visibilitychange", onVisibility);
|
|
2225
|
+
if (doc && doc.hidden) onVisibility();
|
|
2226
|
+
connect();
|
|
2227
|
+
return {
|
|
2228
|
+
/** Subscribes `s` (unsubscribing the previous symbol); sent after the welcome when not connected yet. */
|
|
2229
|
+
set(s) {
|
|
2230
|
+
if (s === symbol) return;
|
|
2231
|
+
if (ws && up && symbol) send(ws, { op: "unsub", s: symbol });
|
|
2232
|
+
symbol = s;
|
|
2233
|
+
if (ws && up && s) send(ws, { op: "sub", s });
|
|
2234
|
+
},
|
|
2235
|
+
get up() {
|
|
2236
|
+
return up;
|
|
2237
|
+
},
|
|
2238
|
+
close() {
|
|
2239
|
+
stopped = true;
|
|
2240
|
+
up = false;
|
|
2241
|
+
clearTimeout(retry);
|
|
2242
|
+
clearTimeout(watchdog);
|
|
2243
|
+
clearTimeout(hiddenTimer);
|
|
2244
|
+
if (doc && doc.removeEventListener) doc.removeEventListener("visibilitychange", onVisibility);
|
|
2245
|
+
const sock = ws;
|
|
2246
|
+
ws = null;
|
|
2247
|
+
if (sock) drop(sock);
|
|
2248
|
+
}
|
|
2249
|
+
};
|
|
2250
|
+
}
|
|
2251
|
+
function bucketOf(t, step, offset = 0) {
|
|
2252
|
+
return Math.floor((t - offset) / step) * step + offset;
|
|
2253
|
+
}
|
|
2254
|
+
function foldBars(list) {
|
|
2255
|
+
const bars = list.filter((b) => b && b.open != null);
|
|
2256
|
+
if (!bars.length) return null;
|
|
2257
|
+
const vols = bars.filter((b) => b.volume != null);
|
|
2258
|
+
return {
|
|
2259
|
+
open: bars[0].open,
|
|
2260
|
+
high: Math.max(...bars.map((b) => b.high)),
|
|
2261
|
+
low: Math.min(...bars.map((b) => b.low)),
|
|
2262
|
+
close: bars[bars.length - 1].close,
|
|
2263
|
+
volume: vols.length ? vols.reduce((s, b) => s + b.volume, 0) : null,
|
|
2264
|
+
source: bars[bars.length - 1].source
|
|
2265
|
+
};
|
|
2266
|
+
}
|
|
2267
|
+
var RANGED = ["net_gex", "spot", "gamma_flip"];
|
|
2268
|
+
function foldLevels(old, row, ts) {
|
|
2269
|
+
const out = Object.assign({}, old || {}, row, { ts });
|
|
2270
|
+
for (const k of RANGED) {
|
|
2271
|
+
const a = old && old[k], b = row[k];
|
|
2272
|
+
if (!a || !b || typeof a !== "object" || typeof b !== "object") continue;
|
|
2273
|
+
const lo = [a.min, b.min].filter((x) => x != null), hi = [a.max, b.max].filter((x) => x != null);
|
|
2274
|
+
out[k] = Object.assign({}, b, {
|
|
2275
|
+
first: a.first != null ? a.first : b.first,
|
|
2276
|
+
min: lo.length ? Math.min(...lo) : null,
|
|
2277
|
+
max: hi.length ? Math.max(...hi) : null
|
|
2278
|
+
});
|
|
2279
|
+
}
|
|
2280
|
+
return out;
|
|
2281
|
+
}
|
|
2282
|
+
function percentile(list, p) {
|
|
2283
|
+
if (!list.length) return null;
|
|
2284
|
+
const s = list.slice().sort((a, b) => a - b);
|
|
2285
|
+
return s[Math.min(s.length - 1, Math.max(0, Math.ceil(p / 100 * s.length) - 1))];
|
|
2286
|
+
}
|
|
2287
|
+
|
|
2288
|
+
// src/chart.js
|
|
2289
|
+
function buildIndicators(plugins2) {
|
|
2290
|
+
const groups = [];
|
|
2291
|
+
const groupOf = (name) => {
|
|
2292
|
+
let g = groups.find((x) => x.name === name);
|
|
2293
|
+
if (!g) {
|
|
2294
|
+
g = {
|
|
2295
|
+
id: "ind" + groups.length,
|
|
2296
|
+
name,
|
|
2297
|
+
layers: [],
|
|
2298
|
+
plots: [],
|
|
2299
|
+
plugins: [],
|
|
2300
|
+
statusOff: /* @__PURE__ */ new Set(),
|
|
2301
|
+
hidden: false,
|
|
2302
|
+
inputs: typeof document !== "undefined" ? document.createElement("div") : null
|
|
2303
|
+
};
|
|
2304
|
+
groups.push(g);
|
|
2305
|
+
}
|
|
2306
|
+
return g;
|
|
2307
|
+
};
|
|
2308
|
+
const homes = /* @__PURE__ */ new Map();
|
|
2309
|
+
for (const p of plugins2) {
|
|
2310
|
+
const own = String(p.indicator || p.name || p.layers[0] && p.layers[0][1] || "Indicator");
|
|
2311
|
+
const of = (id) => String(p.indicators && p.indicators[id] || own);
|
|
2312
|
+
for (const l of p.layers) {
|
|
2313
|
+
const g = groupOf(of(l[0]));
|
|
2314
|
+
g.layers.push(l);
|
|
2315
|
+
if (!g.plugins.includes(p)) g.plugins.push(p);
|
|
2316
|
+
}
|
|
2317
|
+
const home = groupOf(p.indicator || !p.layers.length ? own : of(p.layers[0][0]));
|
|
2318
|
+
if (!home.plugins.includes(p)) home.plugins.push(p);
|
|
2319
|
+
homes.set(p, home);
|
|
2320
|
+
for (const pl of p.plots || []) groupOf(pl.layer ? of(pl.layer) : home.name).plots.push(pl);
|
|
2321
|
+
}
|
|
2322
|
+
return { groups, homes };
|
|
2323
|
+
}
|
|
2324
|
+
var PLOT_DEFAULTS = { lineWidth: 1, lineStyle: "solid", visible: true, priceLine: true, axisLabel: true };
|
|
2325
|
+
function mountChart(container, options2, hooks = {}) {
|
|
2326
|
+
const LW = options2 && options2.lightweightCharts || global.LightweightCharts;
|
|
2327
|
+
if (!LW) throw new Error("FlashAlphaChart needs lightweight-charts 5 (global LightweightCharts or options.lightweightCharts)");
|
|
2328
|
+
if (!options2 || options2.injectCss !== false) injectCss();
|
|
2329
|
+
const plugins2 = activePlugins();
|
|
2330
|
+
const o = Object.assign({
|
|
2331
|
+
// No layer by default: price and volume only, until the reader turns indicators on (remembered, see `storage`).
|
|
2332
|
+
symbol: null,
|
|
2333
|
+
resolution: "5m",
|
|
2334
|
+
days: null,
|
|
2335
|
+
session: "rth",
|
|
2336
|
+
layers: [],
|
|
2337
|
+
controls: true,
|
|
2338
|
+
symbolButtons: true,
|
|
2339
|
+
exposure: true,
|
|
2340
|
+
source: null,
|
|
2341
|
+
baseUrl: "",
|
|
2342
|
+
apiKey: null,
|
|
2343
|
+
refresh: 60,
|
|
2344
|
+
background: null,
|
|
2345
|
+
brand: null,
|
|
2346
|
+
theme: "dark",
|
|
2347
|
+
upgradeUrl: UPGRADE_URL,
|
|
2348
|
+
signupUrl: SIGNUP_URL,
|
|
2349
|
+
account: true,
|
|
2350
|
+
debug: false,
|
|
2351
|
+
note: NOTE,
|
|
2352
|
+
styles: null,
|
|
2353
|
+
storage: true,
|
|
2354
|
+
storageKey: STORAGE_KEY,
|
|
2355
|
+
upsell: false,
|
|
2356
|
+
live: false
|
|
2357
|
+
}, options2 || {});
|
|
2358
|
+
const { groups, homes } = buildIndicators(plugins2);
|
|
2359
|
+
const plotDefs = new Map(groups.flatMap((g) => g.plots.map((p) => [p.id, p])));
|
|
2360
|
+
const defaultStyle = (id) => {
|
|
2361
|
+
const p = plotDefs.get(id) || {};
|
|
2362
|
+
const own = Object.fromEntries(Object.keys(PLOT_DEFAULTS).filter((k) => p[k] != null).map((k) => [k, p[k]]));
|
|
2363
|
+
return Object.assign({}, PLOT_DEFAULTS, { color: p.color || "#4f8cff" }, own, o.styles && o.styles[id] || null);
|
|
2364
|
+
};
|
|
2365
|
+
const styles = Object.fromEntries([...plotDefs.keys()].map((id) => [id, defaultStyle(id)]));
|
|
2366
|
+
if (!o.apiKey) o.apiKey = getLicenseKey();
|
|
2367
|
+
const source = o.source || chartEngineSource(o.baseUrl, o.apiKey);
|
|
2368
|
+
const layerList = plugins2.flatMap((p) => p.layers);
|
|
2369
|
+
const layerPlan = Object.assign({}, ...plugins2.map((p) => p.plans || {}));
|
|
2370
|
+
const store = o.storage === false ? null : String(o.storageKey || STORAGE_KEY);
|
|
2371
|
+
function storedLayers() {
|
|
2372
|
+
if (!store) return null;
|
|
2373
|
+
try {
|
|
2374
|
+
const v = JSON.parse(global.localStorage.getItem(store));
|
|
2375
|
+
return Array.isArray(v) ? v.filter((k) => layerList.some(([id]) => id === k)) : null;
|
|
2376
|
+
} catch (e) {
|
|
2377
|
+
return null;
|
|
2378
|
+
}
|
|
2379
|
+
}
|
|
2380
|
+
function storeLayers(list) {
|
|
2381
|
+
if (!store) return;
|
|
2382
|
+
try {
|
|
2383
|
+
global.localStorage.setItem(store, JSON.stringify(list));
|
|
2384
|
+
} catch (e) {
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
const stored = storedLayers();
|
|
2388
|
+
const state = {
|
|
2389
|
+
symbol: o.symbol,
|
|
2390
|
+
res: o.resolution,
|
|
2391
|
+
days: o.days || DEFAULT_DAYS[o.resolution] || 5,
|
|
2392
|
+
symbols: [],
|
|
2393
|
+
loading: 0,
|
|
2394
|
+
layers: new Set(o.exposure ? stored || o.layers : []),
|
|
2395
|
+
picked: !!stored,
|
|
2396
|
+
noData: null,
|
|
2397
|
+
plan: null,
|
|
2398
|
+
answered: false,
|
|
2399
|
+
feed: null,
|
|
2400
|
+
// the live lane's {mode: 'live' | 'delayed', delay} (welcome); kept after it closes
|
|
2401
|
+
noKey: !o.source && !o.apiKey,
|
|
2402
|
+
// locks like the free plan until a key's plan comes back (see lockedPlan)
|
|
2403
|
+
right: 0,
|
|
2404
|
+
// px a plugin keeps free at the price pane's right edge (ctx.reserveRight)
|
|
2405
|
+
view: Object.assign({ volume: true, grid: true, legend: true }, DISPLAY_DEFAULTS)
|
|
2406
|
+
};
|
|
2407
|
+
const data = { bars: [], byTime: /* @__PURE__ */ new Map(), exposure: [], gexByTime: /* @__PURE__ */ new Map(), notes: [], gated: [] };
|
|
2408
|
+
const query = {};
|
|
2409
|
+
const intraday = () => INTRADAY.includes(state.res);
|
|
2410
|
+
const lockedPlan = (plan) => {
|
|
2411
|
+
const mine = state.plan != null ? state.plan : state.noKey ? "free" : null;
|
|
2412
|
+
return mine != null && planRank(mine) < planRank(plan);
|
|
2413
|
+
};
|
|
2414
|
+
const locked = (layer) => lockedPlan(layerPlan[layer] || "free");
|
|
2415
|
+
const active = (layer) => state.layers.has(layer) && !locked(layer);
|
|
2416
|
+
const hiddenLayer = (layer) => active(layer) && groups.some((g) => g.hidden && g.layers.some(([k]) => k === layer));
|
|
2417
|
+
let asking = false;
|
|
2418
|
+
const on = (layer) => active(layer) && (asking || !hiddenLayer(layer));
|
|
2419
|
+
const root = createLayout(o);
|
|
2420
|
+
container.appendChild(root);
|
|
2421
|
+
let outside = [];
|
|
2422
|
+
const $ = (sel) => root.querySelector(sel) || outside.map((el) => el.matches(sel) ? el : el.querySelector(sel)).find(Boolean) || null;
|
|
2423
|
+
const status = (text) => {
|
|
2424
|
+
const s = $(".fac-status");
|
|
2425
|
+
if (s) s.textContent = o.debug ? text : "";
|
|
2426
|
+
};
|
|
2427
|
+
const upgradeEvent = (campaign, content, href) => container.dispatchEvent(new CustomEvent("flashalpha:upgrade", {
|
|
2428
|
+
bubbles: true,
|
|
2429
|
+
detail: { campaign, content: content || null, href, symbol: state.symbol }
|
|
2430
|
+
}));
|
|
2431
|
+
const ctaClick = (e) => {
|
|
2432
|
+
const a = e.target && e.target.closest ? e.target.closest("a[data-fac-cta]") : null;
|
|
2433
|
+
if (a) upgradeEvent(a.getAttribute("data-fac-cta"), a.getAttribute("data-fac-content"), a.href);
|
|
2434
|
+
};
|
|
2435
|
+
root.addEventListener("click", ctaClick, true);
|
|
2436
|
+
const view = {
|
|
2437
|
+
container,
|
|
2438
|
+
root,
|
|
2439
|
+
$,
|
|
2440
|
+
o,
|
|
2441
|
+
state,
|
|
2442
|
+
data,
|
|
2443
|
+
layerList,
|
|
2444
|
+
layerPlan,
|
|
2445
|
+
locked,
|
|
2446
|
+
on,
|
|
2447
|
+
active,
|
|
2448
|
+
intraday,
|
|
2449
|
+
frame: () => hooks.frame && hooks.frame() || root,
|
|
2450
|
+
upgradeHref: (what) => upgradeHref(o.upgradeUrl, what),
|
|
2451
|
+
signupHref: (what = "toolbar") => upgradeHref(o.signupUrl, what, "signup"),
|
|
2452
|
+
/** The data-fac-cta / data-fac-content attributes of a Sign up ('signup') or Upgrade link, for ctaClick. */
|
|
2453
|
+
ctaAttrs: (what, campaign = "upgrade") => `data-fac-cta="${esc(campaign)}" data-fac-content="${esc(what || "")}"`,
|
|
2454
|
+
/** Opens the upgrade page in a new tab (a prompt that is not a link) and tells the page. */
|
|
2455
|
+
openUpgrade(what) {
|
|
2456
|
+
const href = view.upgradeHref(what);
|
|
2457
|
+
upgradeEvent("upgrade", what, href);
|
|
2458
|
+
global.open(href, "_blank", "noopener");
|
|
2459
|
+
},
|
|
2460
|
+
call,
|
|
2461
|
+
api: null,
|
|
2462
|
+
applySetting: null,
|
|
2463
|
+
screenshot: null,
|
|
2464
|
+
closeMenus: () => {
|
|
2465
|
+
},
|
|
2466
|
+
groups,
|
|
2467
|
+
styles,
|
|
2468
|
+
defaultStyle,
|
|
2469
|
+
corePlugin: levelsPlugin,
|
|
2470
|
+
/** An indicator is on when one of its layers is on (drawn, or hidden with the legend's 👁). */
|
|
2471
|
+
groupOn: (g) => g.layers.some(([k]) => active(k)),
|
|
2472
|
+
/** An indicator's switch: all its layers on (those the key's plan includes) or all off. */
|
|
2473
|
+
setGroup(g, wanted) {
|
|
2474
|
+
const mine = g.layers.map(([k]) => k);
|
|
2475
|
+
const rest = [...state.layers].filter((k) => !mine.includes(k));
|
|
2476
|
+
return view.api.setLayers(wanted ? rest.concat(mine.filter((k) => !locked(k))) : rest);
|
|
2477
|
+
},
|
|
2478
|
+
/** Sets a plot's style and applies it (quiet: the caller redraws once after several). */
|
|
2479
|
+
setStyle(id, patch, quiet) {
|
|
2480
|
+
if (!styles[id]) return;
|
|
2481
|
+
Object.assign(styles[id], patch);
|
|
2482
|
+
applyPlotStyle(id);
|
|
2483
|
+
if (!quiet) view.redraw();
|
|
2484
|
+
},
|
|
2485
|
+
/** Plugins redraw their series (colours per point) and the legend follows the new style. */
|
|
2486
|
+
redraw() {
|
|
2487
|
+
if (raw.bars.length) call("draw", raw.charts);
|
|
2488
|
+
legend.render(null, null);
|
|
2489
|
+
},
|
|
2490
|
+
/** `name` on the handles of these plugins only. */
|
|
2491
|
+
callFor(list, name, ...args) {
|
|
2492
|
+
const out = [];
|
|
2493
|
+
for (const { plugin, h } of handles) {
|
|
2494
|
+
if (!list.includes(plugin) || typeof h[name] !== "function") continue;
|
|
2495
|
+
try {
|
|
2496
|
+
out.push(h[name](...args));
|
|
2497
|
+
} catch (e) {
|
|
2498
|
+
if (global.console) console.error("[flashalpha-chart] layer plugin", e);
|
|
2499
|
+
}
|
|
2500
|
+
}
|
|
2501
|
+
return out;
|
|
2502
|
+
},
|
|
2503
|
+
indicators: null
|
|
2504
|
+
};
|
|
2505
|
+
const toolbar = createToolbar(view);
|
|
2506
|
+
view.indicators = createIndicators(view);
|
|
2507
|
+
const chart = LW.createChart($(".fac-canvas"), {
|
|
2508
|
+
autoSize: true,
|
|
2509
|
+
layout: { background: { color: "transparent" }, attributionLogo: !o.brand },
|
|
2510
|
+
crosshair: { mode: LW.CrosshairMode.Normal },
|
|
2511
|
+
timeScale: {
|
|
2512
|
+
timeVisible: true,
|
|
2513
|
+
secondsVisible: false,
|
|
2514
|
+
tickMarkFormatter: (t, type) => (type <= 2 ? fmtDay : fmtClock).format(new Date(t * 1e3))
|
|
2515
|
+
},
|
|
2516
|
+
localization: { timeFormatter: (t) => intraday() ? fmtTime.format(new Date(t * 1e3)) + " ET" : fmtDay.format(new Date(t * 1e3)) }
|
|
2517
|
+
});
|
|
2518
|
+
let display = null;
|
|
2519
|
+
const theme = createTheme(root, chart, o, (name) => {
|
|
2520
|
+
if (display) display.theme(name);
|
|
2521
|
+
});
|
|
2522
|
+
const levels = [];
|
|
2523
|
+
const titlesOff = () => !!state.tiny || state.right > 0;
|
|
2524
|
+
const titleOf = (title, short) => titlesOff() ? short || "" : title;
|
|
2525
|
+
const applyTitles = () => {
|
|
2526
|
+
for (const [x, title, short] of levels) x.applyOptions({ title: titleOf(title, short) });
|
|
2527
|
+
};
|
|
2528
|
+
const percentLevels = createPercentLevels(chart);
|
|
2529
|
+
const level = (color, title, plotId, short) => {
|
|
2530
|
+
const opts = {
|
|
2531
|
+
color,
|
|
2532
|
+
title: titleOf(title, short),
|
|
2533
|
+
lineWidth: 1,
|
|
2534
|
+
lineType: LW.LineType.WithSteps,
|
|
2535
|
+
priceLineVisible: true,
|
|
2536
|
+
priceLineStyle: LW.LineStyle.Dotted,
|
|
2537
|
+
priceLineWidth: 1,
|
|
2538
|
+
priceLineColor: color,
|
|
2539
|
+
lastValueVisible: true,
|
|
2540
|
+
crosshairMarkerVisible: false,
|
|
2541
|
+
autoscaleInfoProvider: () => null
|
|
2542
|
+
};
|
|
2543
|
+
const x = percentLevels.track(chart.addSeries(LW.LineSeries, opts), opts);
|
|
2544
|
+
const setData = x.setData;
|
|
2545
|
+
x.setData = (d) => setData(cutGaps(d || []));
|
|
2546
|
+
levels.push([x, title, short]);
|
|
2547
|
+
if (plotId) bindPlot(plotId, x);
|
|
2548
|
+
return x;
|
|
2549
|
+
};
|
|
2550
|
+
const bound = /* @__PURE__ */ new Map();
|
|
2551
|
+
function applyPlotStyle(id) {
|
|
2552
|
+
const st = styles[id];
|
|
2553
|
+
if (!st) return;
|
|
2554
|
+
for (const x of bound.get(id) || []) x.applyOptions({
|
|
2555
|
+
color: st.color,
|
|
2556
|
+
lineWidth: st.lineWidth,
|
|
2557
|
+
lineStyle: LINE_STYLES[st.lineStyle] != null ? LINE_STYLES[st.lineStyle] : 0,
|
|
2558
|
+
visible: st.visible,
|
|
2559
|
+
priceLineVisible: st.priceLine,
|
|
2560
|
+
priceLineColor: st.color,
|
|
2561
|
+
lastValueVisible: st.axisLabel
|
|
2562
|
+
});
|
|
2563
|
+
}
|
|
2564
|
+
function bindPlot(id, series) {
|
|
2565
|
+
if (!styles[id] || !series) return series;
|
|
2566
|
+
bound.set(id, (bound.get(id) || []).concat(series));
|
|
2567
|
+
applyPlotStyle(id);
|
|
2568
|
+
return series;
|
|
2569
|
+
}
|
|
2570
|
+
let candles = null, started = false, destroyed = false;
|
|
2571
|
+
const ctx = {
|
|
2572
|
+
LW,
|
|
2573
|
+
chart,
|
|
2574
|
+
root,
|
|
2575
|
+
options: o,
|
|
2576
|
+
colors: COLORS,
|
|
2577
|
+
level,
|
|
2578
|
+
intraday,
|
|
2579
|
+
on,
|
|
2580
|
+
lockedPlan,
|
|
2581
|
+
upgradeHref: view.upgradeHref,
|
|
2582
|
+
openUpgrade: view.openUpgrade,
|
|
2583
|
+
/** True for a layer that is on but hidden with the legend's 👁 (on() is false for it): e.g. keep its pane, empty. */
|
|
2584
|
+
hidden: hiddenLayer,
|
|
2585
|
+
/** True when the last load's answer gave API layer `apiLayer` as status "gated" (the key's plan does not include it). */
|
|
2586
|
+
gated: (apiLayer) => data.gated.includes(apiLayer),
|
|
2587
|
+
get plan() {
|
|
2588
|
+
return state.plan;
|
|
2589
|
+
},
|
|
2590
|
+
get candles() {
|
|
2591
|
+
return candles;
|
|
2592
|
+
},
|
|
2593
|
+
get bars() {
|
|
2594
|
+
return data.bars;
|
|
2595
|
+
},
|
|
2596
|
+
/** The exposure rows of the last load on bar times, each with its chart `time`. */
|
|
2597
|
+
get exposure() {
|
|
2598
|
+
return data.exposure;
|
|
2599
|
+
},
|
|
2600
|
+
get symbol() {
|
|
2601
|
+
return state.symbol;
|
|
2602
|
+
},
|
|
2603
|
+
get resolution() {
|
|
2604
|
+
return state.res;
|
|
2605
|
+
},
|
|
2606
|
+
get query() {
|
|
2607
|
+
return Object.assign({}, query);
|
|
2608
|
+
},
|
|
2609
|
+
setQuery(x) {
|
|
2610
|
+
Object.assign(query, x);
|
|
2611
|
+
return started ? load() : Promise.resolve();
|
|
2612
|
+
},
|
|
2613
|
+
addControl: toolbar.addControl,
|
|
2614
|
+
bindPlot,
|
|
2615
|
+
/** A plot's current style: { color, lineWidth, lineStyle, visible, priceLine, axisLabel }. */
|
|
2616
|
+
styleOf: (id) => styles[id] || defaultStyle(id),
|
|
2617
|
+
note(text) {
|
|
2618
|
+
data.notes.push(text);
|
|
2619
|
+
},
|
|
2620
|
+
/**
|
|
2621
|
+
* Keeps `px` free at the right edge of the price pane for what a plugin draws there (0: gives it back): the room right
|
|
2622
|
+
* of the latest bar (rightOffsetPixels; setting it scrolls to the latest bar, so only on a change), the level lines
|
|
2623
|
+
* without their titles (their axis labels stay) and the edge labels left of it.
|
|
2624
|
+
*/
|
|
2625
|
+
reserveRight(px) {
|
|
2626
|
+
px = Math.max(0, Math.round(px || 0));
|
|
2627
|
+
if (px === state.right) return;
|
|
2628
|
+
state.right = px;
|
|
2629
|
+
chart.timeScale().applyOptions({ rightOffsetPixels: px });
|
|
2630
|
+
applyTitles();
|
|
2631
|
+
},
|
|
2632
|
+
/** The width reserveRight keeps free (0 for none). */
|
|
2633
|
+
get reservedRight() {
|
|
2634
|
+
return state.right;
|
|
2635
|
+
},
|
|
2636
|
+
/** Draws again from the last answer, no request: every plugin's draw(), then the legend. */
|
|
2637
|
+
redraw: () => view.redraw(),
|
|
2638
|
+
util: { etTime, dayOf, sessionOf, floorIndex, esc, num, big, cutGaps, RES_SECONDS }
|
|
2639
|
+
};
|
|
2640
|
+
const handles = plugins2.map((p) => {
|
|
2641
|
+
const home = homes.get(p);
|
|
2642
|
+
const pctx = Object.create(ctx);
|
|
2643
|
+
pctx.addControl = (el, where, indicator) => toolbar.addControl(
|
|
2644
|
+
el,
|
|
2645
|
+
where,
|
|
2646
|
+
indicator && groups.find((x) => x.name === indicator) || home
|
|
2647
|
+
);
|
|
2648
|
+
return { plugin: p, pctx, h: p.attach(pctx) || {} };
|
|
2649
|
+
});
|
|
2650
|
+
function call(name, ...args) {
|
|
2651
|
+
const out = [];
|
|
2652
|
+
for (const { h } of handles) {
|
|
2653
|
+
if (typeof h[name] !== "function") continue;
|
|
2654
|
+
try {
|
|
2655
|
+
out.push(h[name](...args));
|
|
2656
|
+
} catch (e) {
|
|
2657
|
+
if (global.console) console.error("[flashalpha-chart] layer plugin", e);
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
return out;
|
|
2661
|
+
}
|
|
2662
|
+
candles = chart.addSeries(
|
|
2663
|
+
LW.CandlestickSeries,
|
|
2664
|
+
{ upColor: COLORS.up, downColor: COLORS.down, borderVisible: false, wickUpColor: COLORS.up, wickDownColor: COLORS.down }
|
|
2665
|
+
);
|
|
2666
|
+
percentLevels.setCandles(candles);
|
|
2667
|
+
const volume = chart.addSeries(LW.HistogramSeries, { priceScaleId: "vol", priceFormat: { type: "volume" }, priceLineVisible: false, lastValueVisible: false });
|
|
2668
|
+
chart.priceScale("vol").applyOptions({ visible: false, scaleMargins: { top: 0.82, bottom: 0 } });
|
|
2669
|
+
view.applySetting = (k, v) => {
|
|
2670
|
+
if (k in DISPLAY_DEFAULTS) {
|
|
2671
|
+
display.apply(k, v);
|
|
2672
|
+
if (k === "scaleMode") percentLevels.setMode(v === "percent" || v === "indexed");
|
|
2673
|
+
toolbar.renderDisplay();
|
|
2674
|
+
return;
|
|
2675
|
+
}
|
|
2676
|
+
state.view[k] = !!v;
|
|
2677
|
+
if (k === "volume") volume.applyOptions({ visible: !!v });
|
|
2678
|
+
if (k === "grid") chart.applyOptions({ grid: { vertLines: { visible: !!v }, horzLines: { visible: !!v } } });
|
|
2679
|
+
if (k === "legend") root.classList.toggle("fac-nolegend", !v);
|
|
2680
|
+
};
|
|
2681
|
+
view.screenshot = createScreenshot(view, chart);
|
|
2682
|
+
call("ready");
|
|
2683
|
+
const closeLine = chart.addSeries(LW.LineSeries, {
|
|
2684
|
+
color: COLORS.line,
|
|
2685
|
+
lineWidth: 2,
|
|
2686
|
+
priceLineVisible: true,
|
|
2687
|
+
lastValueVisible: true,
|
|
2688
|
+
crosshairMarkerVisible: true,
|
|
2689
|
+
visible: false
|
|
2690
|
+
});
|
|
2691
|
+
let lineMode = false;
|
|
2692
|
+
display = createDisplay(view, chart, LW, candles, closeLine);
|
|
2693
|
+
view.scaleAuto = () => display.autoScale();
|
|
2694
|
+
const legend = createLegend(view, chart);
|
|
2695
|
+
const upsell = createUpsell(view);
|
|
2696
|
+
const emptyState = createEmptyState(view);
|
|
2697
|
+
const brandEl = $(".fac-body > .fac-brand");
|
|
2698
|
+
const sizePanes = () => {
|
|
2699
|
+
const panes = chart.panes(), h = $(".fac-body").clientHeight;
|
|
2700
|
+
if (h > 0) for (let i = 1; i < panes.length; i++) panes[i].setHeight(Math.max(60, Math.round(h * 0.2)));
|
|
2701
|
+
placeBrand(brandEl, chart);
|
|
2702
|
+
legend.place();
|
|
2703
|
+
if (display) display.placeAxis();
|
|
2704
|
+
};
|
|
2705
|
+
const resizeObserver = new ResizeObserver(() => {
|
|
2706
|
+
const narrow = root.clientWidth < NARROW;
|
|
2707
|
+
if (narrow !== root.classList.contains("fac-narrow")) {
|
|
2708
|
+
root.classList.toggle("fac-narrow", narrow);
|
|
2709
|
+
toolbar.placeControls(narrow);
|
|
2710
|
+
legend.render(null, null);
|
|
2711
|
+
}
|
|
2712
|
+
const tiny = root.clientWidth < TINY;
|
|
2713
|
+
if (tiny !== state.tiny) {
|
|
2714
|
+
state.tiny = tiny;
|
|
2715
|
+
applyTitles();
|
|
2716
|
+
}
|
|
2717
|
+
sizePanes();
|
|
2718
|
+
});
|
|
2719
|
+
resizeObserver.observe(root);
|
|
2720
|
+
chart.subscribeCrosshairMove((p) => {
|
|
2721
|
+
const t = p.time != null ? p.time : null, y = p.point ? p.point.y : null;
|
|
2722
|
+
legend.render(t, y);
|
|
2723
|
+
call("crosshair", t, y);
|
|
2724
|
+
});
|
|
2725
|
+
function window_() {
|
|
2726
|
+
const meta = state.symbols.find((x) => x.symbol === state.symbol);
|
|
2727
|
+
const last = meta && meta.last_bar ? Date.parse(meta.last_bar) + 6e4 : 0;
|
|
2728
|
+
const to = new Date(Math.ceil(Math.max(Date.now(), last) / 6e4) * 6e4);
|
|
2729
|
+
const end = last ? Math.min(to.getTime(), last) : to.getTime();
|
|
2730
|
+
const max = (MAX_DAYS[state.res] || state.days) * 864e5;
|
|
2731
|
+
const from = Math.max(end - Math.min(state.days * 864e5, max), to.getTime() - max);
|
|
2732
|
+
const sessions = intraday() && Number.isInteger(state.days) && state.days >= 1 && state.days <= 5 ? state.days : null;
|
|
2733
|
+
return { from: new Date(from), to, sessions };
|
|
2734
|
+
}
|
|
2735
|
+
function apiLayers() {
|
|
2736
|
+
const l = /* @__PURE__ */ new Set();
|
|
2737
|
+
asking = true;
|
|
2738
|
+
try {
|
|
2739
|
+
for (const { plugin, pctx } of handles) {
|
|
2740
|
+
if (typeof plugin.apiLayers !== "function") continue;
|
|
2741
|
+
try {
|
|
2742
|
+
for (const x of plugin.apiLayers(pctx) || []) l.add(x);
|
|
2743
|
+
} catch (e) {
|
|
2744
|
+
if (global.console) console.error("[flashalpha-chart] layer plugin", e);
|
|
2745
|
+
}
|
|
2746
|
+
}
|
|
2747
|
+
} finally {
|
|
2748
|
+
asking = false;
|
|
2749
|
+
}
|
|
2750
|
+
return [...l];
|
|
2751
|
+
}
|
|
2752
|
+
const raw = { bars: [], charts: {}, layers: [], q: [] };
|
|
2753
|
+
const lazy = { armed: false, older: false, newer: false, noOlder: false, newerAt: 0 };
|
|
2754
|
+
const EDGE = 10;
|
|
2755
|
+
let pending = 0;
|
|
2756
|
+
const ms = (ts) => Date.parse(ts);
|
|
2757
|
+
function mergeByTs(a, b) {
|
|
2758
|
+
const m = /* @__PURE__ */ new Map();
|
|
2759
|
+
for (const x of a) m.set(ms(x.ts), x);
|
|
2760
|
+
for (const x of b) m.set(ms(x.ts), x);
|
|
2761
|
+
return [...m.entries()].sort((x, y) => x[0] - y[0]).map((x) => x[1]);
|
|
2762
|
+
}
|
|
2763
|
+
const hasTs = (v) => Array.isArray(v) && v.length > 0 && !!v[0] && typeof v[0] === "object" && "ts" in v[0];
|
|
2764
|
+
function mergeCharts(base, add, newer) {
|
|
2765
|
+
if (!add || add.error) return base;
|
|
2766
|
+
const out = Object.assign({}, base);
|
|
2767
|
+
for (const [k, v] of Object.entries(add)) {
|
|
2768
|
+
const b = base[k];
|
|
2769
|
+
if (Array.isArray(v) && Array.isArray(b) && (hasTs(v) || hasTs(b))) out[k] = newer ? mergeByTs(b, v) : mergeByTs(v, b);
|
|
2770
|
+
else if (k === "layers" && v && typeof v === "object") out[k] = newer ? Object.assign({}, b, v) : Object.assign({}, v, b);
|
|
2771
|
+
else if (newer || !(k in base)) out[k] = v;
|
|
2772
|
+
}
|
|
2773
|
+
return out;
|
|
2774
|
+
}
|
|
2775
|
+
function fetchWindow(from, to, q, sessions) {
|
|
2776
|
+
const f = new Date(from).toISOString(), t = new Date(to).toISOString();
|
|
2777
|
+
const s = sessions ? { sessions } : {};
|
|
2778
|
+
return Promise.all([
|
|
2779
|
+
Promise.resolve(source.bars(state.symbol, state.res, f, t, o.session, s)).catch((e) => ({ error: String(e) })),
|
|
2780
|
+
q.length ? Promise.resolve(source.charts(
|
|
2781
|
+
state.symbol,
|
|
2782
|
+
state.res,
|
|
2783
|
+
f,
|
|
2784
|
+
t,
|
|
2785
|
+
Object.assign({}, query, s, { session: o.session, layers: q })
|
|
2786
|
+
)).catch((e) => ({ error: String(e) })) : {}
|
|
2787
|
+
]);
|
|
2788
|
+
}
|
|
2789
|
+
function updatePlan(c) {
|
|
2790
|
+
if (c && "plan" in c && c.plan !== state.plan) {
|
|
2791
|
+
state.plan = c.plan;
|
|
2792
|
+
toolbar.render();
|
|
2793
|
+
}
|
|
2794
|
+
}
|
|
2795
|
+
function noteKeyError(r) {
|
|
2796
|
+
if (r && KEY_ERRORS.includes(r.error) && !state.noKey) {
|
|
2797
|
+
state.noKey = true;
|
|
2798
|
+
toolbar.render();
|
|
2799
|
+
upsell.render();
|
|
2800
|
+
}
|
|
2801
|
+
}
|
|
2802
|
+
async function load({ keepView = false } = {}) {
|
|
2803
|
+
if (!state.symbol) return;
|
|
2804
|
+
if (keepView && raw.bars.length) return loadNewer();
|
|
2805
|
+
pending++;
|
|
2806
|
+
const ticket = state.loading + 1;
|
|
2807
|
+
try {
|
|
2808
|
+
await loadAll(keepView);
|
|
2809
|
+
} finally {
|
|
2810
|
+
pending--;
|
|
2811
|
+
}
|
|
2812
|
+
if (ticket === state.loading) liveSync();
|
|
2813
|
+
}
|
|
2814
|
+
async function loadAll(keepView) {
|
|
2815
|
+
const ticket = ++state.loading;
|
|
2816
|
+
const { from, to, sessions } = window_();
|
|
2817
|
+
const t0 = performance.now();
|
|
2818
|
+
if (!keepView) status("loading…");
|
|
2819
|
+
if (!keepView && !raw.bars.length) emptyState.loading();
|
|
2820
|
+
const layers = apiLayers();
|
|
2821
|
+
const q = o.exposure && intraday() && !layers.includes("exposure") ? [...layers, "exposure"] : layers;
|
|
2822
|
+
const [r, c] = await fetchWindow(from, to, q, sessions);
|
|
2823
|
+
if (ticket !== state.loading || destroyed) return;
|
|
2824
|
+
if (!state.answered) {
|
|
2825
|
+
state.answered = true;
|
|
2826
|
+
toolbar.renderAccount();
|
|
2827
|
+
}
|
|
2828
|
+
noteKeyError(r);
|
|
2829
|
+
noteKeyError(c);
|
|
2830
|
+
if (keepView && (r.error || !Array.isArray(r.bars))) {
|
|
2831
|
+
status(`refresh failed: ${r.error || "no bars"}`);
|
|
2832
|
+
return;
|
|
2833
|
+
}
|
|
2834
|
+
Object.assign(lazy, { armed: false, noOlder: false, newerAt: Date.now() });
|
|
2835
|
+
if (r.error || !Array.isArray(r.bars)) {
|
|
2836
|
+
status(`${r.error || "no bars"}${r.message ? ": " + r.message : ""}`);
|
|
2837
|
+
emptyState.show(r.error || "no bars");
|
|
2838
|
+
Object.assign(raw, { bars: [], charts: {}, layers, q });
|
|
2839
|
+
data.bars = [];
|
|
2840
|
+
data.byTime = /* @__PURE__ */ new Map();
|
|
2841
|
+
data.exposure = [];
|
|
2842
|
+
data.gexByTime = /* @__PURE__ */ new Map();
|
|
2843
|
+
volume.setData([]);
|
|
2844
|
+
display.clear();
|
|
2845
|
+
call("clear");
|
|
2846
|
+
legend.render(null, null);
|
|
2847
|
+
return;
|
|
2848
|
+
}
|
|
2849
|
+
Object.assign(raw, { bars: r.bars.filter((b) => b.open != null), charts: c || {}, layers, q });
|
|
2850
|
+
updatePlan(c);
|
|
2851
|
+
draw(keepView ? "keep" : "fit");
|
|
2852
|
+
status(`${data.bars.length} bars · ${Math.round(performance.now() - t0)} ms`);
|
|
2853
|
+
}
|
|
2854
|
+
async function loadOlder() {
|
|
2855
|
+
if (lazy.older || lazy.noOlder || pending || !raw.bars.length) return;
|
|
2856
|
+
lazy.older = true;
|
|
2857
|
+
const ticket = state.loading, t0 = performance.now();
|
|
2858
|
+
try {
|
|
2859
|
+
const first = ms(raw.bars[0].ts);
|
|
2860
|
+
const meta = state.symbols.find((x) => x.symbol === state.symbol);
|
|
2861
|
+
const floor = meta && meta.first_bar ? ms(meta.first_bar) : -Infinity;
|
|
2862
|
+
const max = MAX_DAYS[state.res] || state.days;
|
|
2863
|
+
let to = first, span = Math.min(Math.max(state.days, 1), max);
|
|
2864
|
+
for (let tries = 0; tries < 4 && to > floor; tries++) {
|
|
2865
|
+
status("loading older bars…");
|
|
2866
|
+
const from = Math.max(to - span * 864e5, floor);
|
|
2867
|
+
const [r, c] = await fetchWindow(from, to, raw.q);
|
|
2868
|
+
if (ticket !== state.loading || destroyed) return;
|
|
2869
|
+
if (r.error || !Array.isArray(r.bars)) {
|
|
2870
|
+
lazy.noOlder = true;
|
|
2871
|
+
status(`older bars: ${r.error || "no bars"}`);
|
|
2872
|
+
return;
|
|
2873
|
+
}
|
|
2874
|
+
const bars = r.bars.filter((b) => b.open != null && ms(b.ts) < first);
|
|
2875
|
+
if (bars.length) {
|
|
2876
|
+
raw.bars = mergeByTs(bars, raw.bars);
|
|
2877
|
+
raw.charts = mergeCharts(raw.charts, c, false);
|
|
2878
|
+
draw("prepend");
|
|
2879
|
+
status(`${data.bars.length} bars · +${bars.length} older · ${Math.round(performance.now() - t0)} ms`);
|
|
2880
|
+
return;
|
|
2881
|
+
}
|
|
2882
|
+
to = from;
|
|
2883
|
+
span = Math.min(span * 2, max);
|
|
2884
|
+
}
|
|
2885
|
+
lazy.noOlder = true;
|
|
2886
|
+
status("no older bars");
|
|
2887
|
+
} finally {
|
|
2888
|
+
lazy.older = false;
|
|
2889
|
+
}
|
|
2890
|
+
}
|
|
2891
|
+
async function loadNewer() {
|
|
2892
|
+
if (lazy.newer || pending || !raw.bars.length) return;
|
|
2893
|
+
lazy.newer = true;
|
|
2894
|
+
pending++;
|
|
2895
|
+
const ticket = state.loading, t0 = performance.now();
|
|
2896
|
+
try {
|
|
2897
|
+
const step = (RES_SECONDS[state.res] || 60) * 1e3;
|
|
2898
|
+
const from = ms(raw.bars[raw.bars.length - 1].ts) - Math.max(3 * step, 15 * 6e4);
|
|
2899
|
+
const to = Math.ceil(Date.now() / 6e4) * 6e4;
|
|
2900
|
+
const [r, c] = await fetchWindow(from, to, raw.q);
|
|
2901
|
+
if (ticket !== state.loading || destroyed) return;
|
|
2902
|
+
lazy.newerAt = Date.now();
|
|
2903
|
+
if (r.error || !Array.isArray(r.bars)) {
|
|
2904
|
+
status(`refresh failed: ${r.error || "no bars"}`);
|
|
2905
|
+
return;
|
|
2906
|
+
}
|
|
2907
|
+
raw.bars = mergeByTs(raw.bars, r.bars.filter((b) => b.open != null));
|
|
2908
|
+
raw.charts = mergeCharts(raw.charts, c, true);
|
|
2909
|
+
updatePlan(c);
|
|
2910
|
+
draw("keep");
|
|
2911
|
+
status(`${data.bars.length} bars · ${Math.round(performance.now() - t0)} ms`);
|
|
2912
|
+
} finally {
|
|
2913
|
+
lazy.newer = false;
|
|
2914
|
+
pending--;
|
|
2915
|
+
}
|
|
2916
|
+
}
|
|
2917
|
+
async function loadLayers(missing) {
|
|
2918
|
+
const ticket = state.loading, t0 = performance.now();
|
|
2919
|
+
const last = ms(raw.bars[raw.bars.length - 1].ts);
|
|
2920
|
+
const from = new Date(ms(raw.bars[0].ts)).toISOString();
|
|
2921
|
+
const to = new Date(Math.max(window_().to.getTime(), last + 6e4)).toISOString();
|
|
2922
|
+
let c;
|
|
2923
|
+
pending++;
|
|
2924
|
+
try {
|
|
2925
|
+
c = await Promise.resolve(source.charts(
|
|
2926
|
+
state.symbol,
|
|
2927
|
+
state.res,
|
|
2928
|
+
from,
|
|
2929
|
+
to,
|
|
2930
|
+
Object.assign({}, query, { session: o.session, layers: missing })
|
|
2931
|
+
)).catch((e) => ({ error: String(e) }));
|
|
2932
|
+
} finally {
|
|
2933
|
+
pending--;
|
|
2934
|
+
}
|
|
2935
|
+
if (ticket !== state.loading || destroyed) return;
|
|
2936
|
+
noteKeyError(c);
|
|
2937
|
+
if (!c || c.error) return load();
|
|
2938
|
+
raw.charts = Object.assign({}, raw.charts, { layers: Object.assign({}, raw.charts.layers, c.layers) });
|
|
2939
|
+
for (const k of missing) if (k in c) raw.charts[k] = c[k];
|
|
2940
|
+
raw.q = [...new Set(raw.q.concat(missing))];
|
|
2941
|
+
raw.layers = apiLayers().filter((x) => raw.q.includes(x));
|
|
2942
|
+
updatePlan(c);
|
|
2943
|
+
draw("keep");
|
|
2944
|
+
status(`${data.bars.length} bars · +${missing.join(", ")} · ${Math.round(performance.now() - t0)} ms`);
|
|
2945
|
+
}
|
|
2946
|
+
const busyEl = global.document ? global.document.createElement("div") : null;
|
|
2947
|
+
if (busyEl) {
|
|
2948
|
+
busyEl.className = "fac-busy";
|
|
2949
|
+
busyEl.textContent = "Loading…";
|
|
2950
|
+
const body = $(".fac-body");
|
|
2951
|
+
if (body) body.appendChild(busyEl);
|
|
2952
|
+
}
|
|
2953
|
+
let busyCount = 0;
|
|
2954
|
+
function whileBusy(p) {
|
|
2955
|
+
const set = (d) => {
|
|
2956
|
+
busyCount += d;
|
|
2957
|
+
if (busyEl) busyEl.classList.toggle("on", busyCount > 0);
|
|
2958
|
+
};
|
|
2959
|
+
set(1);
|
|
2960
|
+
return Promise.resolve(p).finally(() => set(-1));
|
|
2961
|
+
}
|
|
2962
|
+
function draw(mode) {
|
|
2963
|
+
const ts = chart.timeScale();
|
|
2964
|
+
const view_ = mode === "keep" ? currentView() : null;
|
|
2965
|
+
const lr = mode === "prepend" ? ts.getVisibleLogicalRange() : null;
|
|
2966
|
+
const firstBefore = data.bars.length ? data.bars[0].time : null;
|
|
2967
|
+
const c = raw.charts, layers = raw.layers;
|
|
2968
|
+
data.bars = raw.bars.map((b) => Object.assign({}, b, { time: intraday() ? etTime(b.ts) : ms(b.ts) / 1e3 }));
|
|
2969
|
+
data.bars = data.bars.concat(spotBars(c.exposure || []));
|
|
2970
|
+
emptyState.show(data.bars.length ? null : "no bars");
|
|
2971
|
+
data.byTime = new Map(data.bars.map((b) => [b.time, b]));
|
|
2972
|
+
const stored2 = data.bars.filter((b) => b.source !== "spot"), allQuotes = stored2.length > 0 && stored2.every(quoteMid);
|
|
2973
|
+
lineMode = intraday() && stored2.length > 0 && stored2.filter((b) => b.open === b.high && b.high === b.low && b.low === b.close).length >= 0.8 * stored2.length;
|
|
2974
|
+
display.setData(data.bars.map((b) => ({
|
|
2975
|
+
time: b.time,
|
|
2976
|
+
open: b.open,
|
|
2977
|
+
high: b.high,
|
|
2978
|
+
low: b.low,
|
|
2979
|
+
close: b.close,
|
|
2980
|
+
muted: b.source === "spot" || quoteMid(b) && (allQuotes || state.res === "1m" || intraday() && sessionOf(b.time) !== "rth")
|
|
2981
|
+
})), lineMode);
|
|
2982
|
+
volume.setData(data.bars.map((b) => b.volume == null || quoteMid(b) || partVolume(b) ? { time: b.time } : {
|
|
2983
|
+
time: b.time,
|
|
2984
|
+
value: b.volume,
|
|
2985
|
+
color: b.close >= b.open ? COLORS.volUp : COLORS.volDown
|
|
2986
|
+
}));
|
|
2987
|
+
data.notes = [];
|
|
2988
|
+
if (c.error && o.debug) data.notes.push(`layers: ${c.error}`);
|
|
2989
|
+
const gated = layers.filter((x) => c.layers && c.layers[x] && c.layers[x].status === "gated");
|
|
2990
|
+
data.gated = gated;
|
|
2991
|
+
if (gated.includes("exposure") && ["levels", "maxpain"].some(on)) data.notes.push({ gated: CORE_INDICATOR });
|
|
2992
|
+
upsell.render();
|
|
2993
|
+
setExposure(layers.includes("exposure") ? c.exposure || [] : []);
|
|
2994
|
+
call("draw", c);
|
|
2995
|
+
requestAnimationFrame(sizePanes);
|
|
2996
|
+
const hasDaily = view.callFor([levelsPlugin], "hasDaily").some(Boolean);
|
|
2997
|
+
if (!intraday() && state.picked && ["levels", "maxpain"].some(on) && !hasDaily) data.notes.push("GEX levels: pick 1m to 1h");
|
|
2998
|
+
else if (layers.includes("exposure") && !gated.includes("exposure") && !(c.exposure || []).length) data.notes.push("GEX levels: none yet in this window (they start at the 9:30 ET open)");
|
|
2999
|
+
if (mode === "prepend") {
|
|
3000
|
+
const shift = firstBefore == null ? -1 : data.bars.findIndex((b) => b.time === firstBefore);
|
|
3001
|
+
if (lr && shift > 0) ts.setVisibleLogicalRange({ from: lr.from + shift, to: lr.to + shift });
|
|
3002
|
+
} else {
|
|
3003
|
+
if (mode === "fit") {
|
|
3004
|
+
autoScalePrices();
|
|
3005
|
+
toolbar.renderDisplay();
|
|
3006
|
+
}
|
|
3007
|
+
restoreView(view_);
|
|
3008
|
+
}
|
|
3009
|
+
liveRender();
|
|
3010
|
+
legend.render(null, null);
|
|
3011
|
+
}
|
|
3012
|
+
function autoScalePrices() {
|
|
3013
|
+
const n = chart.panes().length;
|
|
3014
|
+
for (let i = 0; i < n; i++) {
|
|
3015
|
+
for (const id of ["right", "left"]) {
|
|
3016
|
+
try {
|
|
3017
|
+
chart.priceScale(id, i).applyOptions({ autoScale: true });
|
|
3018
|
+
} catch (e) {
|
|
3019
|
+
}
|
|
3020
|
+
}
|
|
3021
|
+
}
|
|
3022
|
+
}
|
|
3023
|
+
function currentView() {
|
|
3024
|
+
const ts = chart.timeScale(), lr = ts.getVisibleLogicalRange(), last = data.bars.length - 1;
|
|
3025
|
+
return lr && last >= 0 ? { fromEnd: last - lr.from, toEnd: last - lr.to, range: ts.getVisibleRange() } : null;
|
|
3026
|
+
}
|
|
3027
|
+
function restoreView(v) {
|
|
3028
|
+
const ts = chart.timeScale(), last = data.bars.length - 1;
|
|
3029
|
+
if (!v || last < 0) ts.fitContent();
|
|
3030
|
+
else if (v.toEnd <= 0.5) ts.setVisibleLogicalRange({ from: last - v.fromEnd, to: last - v.toEnd });
|
|
3031
|
+
else if (v.range) ts.setVisibleRange(v.range);
|
|
3032
|
+
else ts.fitContent();
|
|
3033
|
+
}
|
|
3034
|
+
function spotBars(rows) {
|
|
3035
|
+
if (!intraday()) return [];
|
|
3036
|
+
const last = data.bars.length ? data.bars[data.bars.length - 1].time : -Infinity;
|
|
3037
|
+
return rows.filter((e) => e.spot && e.spot.first != null && e.spot.last != null).map((e) => ({
|
|
3038
|
+
time: etTime(e.ts),
|
|
3039
|
+
open: e.spot.first,
|
|
3040
|
+
high: e.spot.max,
|
|
3041
|
+
low: e.spot.min,
|
|
3042
|
+
close: e.spot.last,
|
|
3043
|
+
volume: null,
|
|
3044
|
+
source: "spot"
|
|
3045
|
+
})).filter((b) => b.time > last);
|
|
3046
|
+
}
|
|
3047
|
+
function quoteMid(b) {
|
|
3048
|
+
const meta = state.symbols.find((x) => x.symbol === state.symbol);
|
|
3049
|
+
return b.source === "quotes" && !(meta && meta.asset_class === "index");
|
|
3050
|
+
}
|
|
3051
|
+
view.quoteMid = quoteMid;
|
|
3052
|
+
function partVolume(b) {
|
|
3053
|
+
return b.source === "mixed" && !intraday();
|
|
3054
|
+
}
|
|
3055
|
+
view.partVolume = partVolume;
|
|
3056
|
+
function setExposure(rows) {
|
|
3057
|
+
data.exposure = rows.map((e) => Object.assign({}, e, { time: etTime(e.ts) })).filter((e) => data.byTime.has(e.time));
|
|
3058
|
+
data.gexByTime = new Map(data.exposure.map((e) => [e.time, e]));
|
|
3059
|
+
}
|
|
3060
|
+
const live = {
|
|
3061
|
+
conn: null,
|
|
3062
|
+
up: false,
|
|
3063
|
+
symbol: null,
|
|
3064
|
+
key: null,
|
|
3065
|
+
mode: null,
|
|
3066
|
+
parts: /* @__PURE__ */ new Map(),
|
|
3067
|
+
newest: -Infinity,
|
|
3068
|
+
seeded: false,
|
|
3069
|
+
seeding: 0,
|
|
3070
|
+
seedFailAt: 0,
|
|
3071
|
+
from: -Infinity,
|
|
3072
|
+
lastMsg: 0,
|
|
3073
|
+
barAt: 0,
|
|
3074
|
+
lags: [],
|
|
3075
|
+
lagAt: 0
|
|
3076
|
+
};
|
|
3077
|
+
const liveKey = () => state.res + " " + o.session;
|
|
3078
|
+
const bucketMs = (m) => {
|
|
3079
|
+
const t = etTime(m);
|
|
3080
|
+
return m - (t - bucketOf(t, RES_SECONDS[state.res] || 60, state.res === "1h" && o.session === "rth" ? 1800 : 0)) * 1e3;
|
|
3081
|
+
};
|
|
3082
|
+
const previousBucket = (m) => bucketMs(bucketMs(m) - 6e4);
|
|
3083
|
+
const oldestPart = (m) => Math.min(previousBucket(m), m - 18e4);
|
|
3084
|
+
const seedDue = () => state.res !== "1m" && live.seeded === false && live.newest > -Infinity && Date.now() - live.seedFailAt > 6e4;
|
|
3085
|
+
function liveSync() {
|
|
3086
|
+
if (!(o.live && !o.source && intraday() && state.symbol && !destroyed && typeof global.WebSocket === "function")) {
|
|
3087
|
+
liveStop();
|
|
3088
|
+
return;
|
|
3089
|
+
}
|
|
3090
|
+
if (!live.conn) live.conn = createLive({
|
|
3091
|
+
url: liveUrl(o.baseUrl, global.location && global.location.origin),
|
|
3092
|
+
key: o.apiKey,
|
|
3093
|
+
WebSocket: global.WebSocket,
|
|
3094
|
+
doc: global.document,
|
|
3095
|
+
onMessage: liveMessage,
|
|
3096
|
+
onState: liveState
|
|
3097
|
+
});
|
|
3098
|
+
if (live.symbol !== state.symbol) {
|
|
3099
|
+
live.symbol = state.symbol;
|
|
3100
|
+
live.parts.clear();
|
|
3101
|
+
live.newest = -Infinity;
|
|
3102
|
+
live.key = null;
|
|
3103
|
+
live.barAt = 0;
|
|
3104
|
+
}
|
|
3105
|
+
if (live.key !== liveKey()) {
|
|
3106
|
+
live.key = liveKey();
|
|
3107
|
+
live.seeded = false;
|
|
3108
|
+
live.seedFailAt = 0;
|
|
3109
|
+
if (state.res === "1m") liveRender();
|
|
3110
|
+
else if (live.newest > -Infinity) liveSeed();
|
|
3111
|
+
}
|
|
3112
|
+
live.conn.set(state.symbol);
|
|
3113
|
+
}
|
|
3114
|
+
function liveStop() {
|
|
3115
|
+
if (live.conn) live.conn.close();
|
|
3116
|
+
Object.assign(live, { conn: null, up: false, symbol: null, key: null, newest: -Infinity, seeded: false });
|
|
3117
|
+
live.parts.clear();
|
|
3118
|
+
}
|
|
3119
|
+
function liveState(s, m) {
|
|
3120
|
+
if (s === "up") {
|
|
3121
|
+
if (live.lastMsg && Date.now() - live.lastMsg > 9 * 6e4) load({ keepView: true });
|
|
3122
|
+
live.up = true;
|
|
3123
|
+
live.mode = m.mode;
|
|
3124
|
+
live.seeded = false;
|
|
3125
|
+
live.seedFailAt = 0;
|
|
3126
|
+
state.feed = { mode: m.mode, delay: m.delay };
|
|
3127
|
+
toolbar.renderAccount();
|
|
3128
|
+
} else live.up = false;
|
|
3129
|
+
}
|
|
3130
|
+
function liveMessage(m) {
|
|
3131
|
+
live.lastMsg = Date.now();
|
|
3132
|
+
if (m.t === "error") {
|
|
3133
|
+
status(`live: ${m.code}`);
|
|
3134
|
+
return;
|
|
3135
|
+
}
|
|
3136
|
+
if (!m.s || !live.symbol || m.s.toUpperCase() !== live.symbol.toUpperCase()) return;
|
|
3137
|
+
if (m.t === "snap") {
|
|
3138
|
+
for (const b of m.bars || []) livePart(b, false);
|
|
3139
|
+
if (m.levels) liveLevels(m.levels, true);
|
|
3140
|
+
if (seedDue()) liveSeed();
|
|
3141
|
+
else if (!m.levels) liveRender();
|
|
3142
|
+
} else if (m.t === "bar") {
|
|
3143
|
+
live.barAt = Date.now();
|
|
3144
|
+
const t = livePart(m.bar, true);
|
|
3145
|
+
if (t == null) return;
|
|
3146
|
+
if (o.debug === "latency" && m.bar.lt && Date.now() - live.lagAt > 1e3) {
|
|
3147
|
+
live.lagAt = Date.now();
|
|
3148
|
+
status(`live ${live.mode || ""} · lag p50 ${percentile(live.lags, 50)} ms · p95 ${percentile(live.lags, 95)} ms`);
|
|
3149
|
+
}
|
|
3150
|
+
if (seedDue()) liveSeed();
|
|
3151
|
+
else liveRender(bucketMs(t));
|
|
3152
|
+
} else if (m.t === "levels") liveLevels(m.row, true);
|
|
3153
|
+
}
|
|
3154
|
+
function livePart(b, update) {
|
|
3155
|
+
const m = b ? ms(b.ts) : NaN;
|
|
3156
|
+
if (!Number.isFinite(m) || b.open == null) return null;
|
|
3157
|
+
if (o.session === "rth" && sessionOf(etTime(m)) !== "rth") return null;
|
|
3158
|
+
if (update && live.newest > -Infinity && m < oldestPart(live.newest)) return null;
|
|
3159
|
+
live.parts.set(m, b);
|
|
3160
|
+
if (m > live.newest) live.newest = m;
|
|
3161
|
+
if (update && b.lt) {
|
|
3162
|
+
live.lags.push(Date.now() - b.lt);
|
|
3163
|
+
if (live.lags.length > 500) live.lags.shift();
|
|
3164
|
+
}
|
|
3165
|
+
const keep = Math.min(oldestPart(live.newest), raw.bars.length ? ms(raw.bars[raw.bars.length - 1].ts) : Infinity);
|
|
3166
|
+
for (const k of live.parts.keys()) if (k < keep) live.parts.delete(k);
|
|
3167
|
+
return m;
|
|
3168
|
+
}
|
|
3169
|
+
async function liveSeed() {
|
|
3170
|
+
const last = raw.bars.length ? ms(raw.bars[raw.bars.length - 1].ts) : Infinity;
|
|
3171
|
+
const from = Math.max(Math.min(previousBucket(live.newest), last), bucketMs(live.newest - 120 * 6e4));
|
|
3172
|
+
const ticket = ++live.seeding, key = live.key, symbol = live.symbol;
|
|
3173
|
+
live.seeded = "pending";
|
|
3174
|
+
live.from = from;
|
|
3175
|
+
const to = new Date(Math.ceil(Date.now() / 6e4) * 6e4).toISOString();
|
|
3176
|
+
const r = await Promise.resolve(source.bars(symbol, "1m", new Date(from).toISOString(), to, o.session)).catch(() => null);
|
|
3177
|
+
if (ticket !== live.seeding || destroyed || live.symbol !== symbol || live.key !== key) return;
|
|
3178
|
+
if (!r || r.error || !Array.isArray(r.bars)) {
|
|
3179
|
+
live.seeded = false;
|
|
3180
|
+
live.seedFailAt = Date.now();
|
|
3181
|
+
return;
|
|
3182
|
+
}
|
|
3183
|
+
for (const b of r.bars) {
|
|
3184
|
+
const m = ms(b.ts);
|
|
3185
|
+
if (b.open != null && m >= from && !live.parts.has(m)) live.parts.set(m, b);
|
|
3186
|
+
}
|
|
3187
|
+
live.seeded = true;
|
|
3188
|
+
liveRender();
|
|
3189
|
+
}
|
|
3190
|
+
function liveRender(onlyMs) {
|
|
3191
|
+
if (!live.conn || live.symbol !== state.symbol || live.key !== liveKey() || state.res !== "1m" && live.seeded !== true) return;
|
|
3192
|
+
const from = raw.bars.length ? etTime(raw.bars[raw.bars.length - 1].ts) : -Infinity;
|
|
3193
|
+
const buckets = /* @__PURE__ */ new Map();
|
|
3194
|
+
for (const m of [...live.parts.keys()].sort((a, b) => a - b)) {
|
|
3195
|
+
const start = bucketMs(m);
|
|
3196
|
+
if (onlyMs != null && start !== onlyMs || state.res !== "1m" && start < live.from) continue;
|
|
3197
|
+
if (!buckets.has(start)) buckets.set(start, []);
|
|
3198
|
+
buckets.get(start).push(live.parts.get(m));
|
|
3199
|
+
}
|
|
3200
|
+
let drawn = 0;
|
|
3201
|
+
for (const [start, list] of buckets) {
|
|
3202
|
+
const t = etTime(start);
|
|
3203
|
+
if (t >= from && liveBar(t, start, foldBars(list))) drawn++;
|
|
3204
|
+
}
|
|
3205
|
+
if (drawn) legend.render(null, null);
|
|
3206
|
+
}
|
|
3207
|
+
function liveBar(t, start, f) {
|
|
3208
|
+
const last = data.bars.length ? data.bars[data.bars.length - 1].time : -Infinity;
|
|
3209
|
+
if (!f || t < last && !data.byTime.has(t)) return false;
|
|
3210
|
+
const old = t < last;
|
|
3211
|
+
try {
|
|
3212
|
+
display.update({ time: t, open: f.open, high: f.high, low: f.low, close: f.close }, old);
|
|
3213
|
+
volume.update(f.volume == null ? { time: t } : {
|
|
3214
|
+
time: t,
|
|
3215
|
+
value: f.volume,
|
|
3216
|
+
color: f.close >= f.open ? COLORS.volUp : COLORS.volDown
|
|
3217
|
+
}, old);
|
|
3218
|
+
} catch (e) {
|
|
3219
|
+
return false;
|
|
3220
|
+
}
|
|
3221
|
+
const bar = Object.assign({ ts: new Date(start).toISOString(), time: t }, f);
|
|
3222
|
+
if (data.byTime.has(t)) {
|
|
3223
|
+
for (let i = data.bars.length - 1; i >= 0; i--) if (data.bars[i].time === t) {
|
|
3224
|
+
data.bars[i] = bar;
|
|
3225
|
+
break;
|
|
3226
|
+
}
|
|
3227
|
+
} else data.bars.push(bar);
|
|
3228
|
+
data.byTime.set(t, bar);
|
|
3229
|
+
return true;
|
|
3230
|
+
}
|
|
3231
|
+
function liveLevels(row, redraw) {
|
|
3232
|
+
const m = row ? ms(row.ts) : NaN;
|
|
3233
|
+
if (!Number.isFinite(m) || !started) return;
|
|
3234
|
+
const rows = Array.isArray(raw.charts.exposure) ? raw.charts.exposure : [];
|
|
3235
|
+
let add = row;
|
|
3236
|
+
if (state.res !== "1m") {
|
|
3237
|
+
const start = bucketMs(m);
|
|
3238
|
+
add = foldLevels(rows.find((x) => ms(x.ts) === start), row, new Date(start).toISOString());
|
|
3239
|
+
}
|
|
3240
|
+
raw.charts = Object.assign({}, raw.charts, { exposure: mergeByTs(rows, [add]) });
|
|
3241
|
+
if (redraw) draw("keep");
|
|
3242
|
+
}
|
|
3243
|
+
const arm = () => {
|
|
3244
|
+
lazy.armed = true;
|
|
3245
|
+
};
|
|
3246
|
+
for (const ev of ["pointerdown", "mousedown", "touchstart", "wheel"]) $(".fac-canvas").addEventListener(ev, arm, { passive: true });
|
|
3247
|
+
const scaleChanged = () => setTimeout(() => {
|
|
3248
|
+
if (!destroyed) toolbar.renderDisplay(true);
|
|
3249
|
+
}, 0);
|
|
3250
|
+
for (const ev of ["pointerup", "touchend", "dblclick", "wheel"]) $(".fac-canvas").addEventListener(ev, scaleChanged, { passive: true });
|
|
3251
|
+
const timeScale = chart.timeScale();
|
|
3252
|
+
if (typeof timeScale.subscribeVisibleLogicalRangeChange === "function") timeScale.subscribeVisibleLogicalRangeChange((lr) => {
|
|
3253
|
+
if (!lr || !lazy.armed || !started || destroyed || !raw.bars.length) return;
|
|
3254
|
+
if (lr.from < EDGE) loadOlder();
|
|
3255
|
+
const newest = ms(raw.bars[raw.bars.length - 1].ts);
|
|
3256
|
+
const stale = Date.now() - newest > Math.max(2 * (RES_SECONDS[state.res] || 60) * 1e3, 12e4);
|
|
3257
|
+
if (lr.to > data.bars.length - 1 - EDGE / 2 && stale && Date.now() - lazy.newerAt > 6e4) loadNewer();
|
|
3258
|
+
});
|
|
3259
|
+
const announce = () => container.dispatchEvent(new CustomEvent("flashalpha:change", {
|
|
3260
|
+
bubbles: true,
|
|
3261
|
+
detail: { symbol: state.symbol, resolution: state.res, range: state.days, session: o.session, layers: [...state.layers] }
|
|
3262
|
+
}));
|
|
3263
|
+
const changed = (p) => {
|
|
3264
|
+
if (hooks.changed) hooks.changed(api);
|
|
3265
|
+
announce();
|
|
3266
|
+
return p;
|
|
3267
|
+
};
|
|
3268
|
+
const api = {
|
|
3269
|
+
setSymbol(x) {
|
|
3270
|
+
state.symbol = x;
|
|
3271
|
+
toolbar.render();
|
|
3272
|
+
const p = load();
|
|
3273
|
+
if (hooks.symbol) hooks.symbol(x, api);
|
|
3274
|
+
announce();
|
|
3275
|
+
return p;
|
|
3276
|
+
},
|
|
3277
|
+
setResolution(r) {
|
|
3278
|
+
state.res = r;
|
|
3279
|
+
state.days = DEFAULT_DAYS[r] || state.days;
|
|
3280
|
+
toolbar.render();
|
|
3281
|
+
return changed(load());
|
|
3282
|
+
},
|
|
3283
|
+
/** Days back from now; capped per resolution (MAX_DAYS). */
|
|
3284
|
+
setRange(days) {
|
|
3285
|
+
state.days = days;
|
|
3286
|
+
toolbar.render();
|
|
3287
|
+
return changed(load());
|
|
3288
|
+
},
|
|
3289
|
+
/** 'rth' (regular hours, the default) or 'eth' (with pre- and post-market). */
|
|
3290
|
+
setSession(x) {
|
|
3291
|
+
o.session = x;
|
|
3292
|
+
toolbar.render();
|
|
3293
|
+
return changed(load());
|
|
3294
|
+
},
|
|
3295
|
+
/** Any of 'levels', 'maxpain', plus the ids of registered layer plugins. Remembered for the next visit (`storage`). */
|
|
3296
|
+
setLayers(list) {
|
|
3297
|
+
state.layers = new Set(list);
|
|
3298
|
+
state.picked = true;
|
|
3299
|
+
storeLayers([...state.layers]);
|
|
3300
|
+
toolbar.render();
|
|
3301
|
+
upsell.render();
|
|
3302
|
+
const want = apiLayers();
|
|
3303
|
+
if (!pending && raw.bars.length && !raw.charts.error) {
|
|
3304
|
+
const missing = want.filter((x) => !raw.q.includes(x));
|
|
3305
|
+
if (!missing.length) {
|
|
3306
|
+
raw.layers = want;
|
|
3307
|
+
draw("keep");
|
|
3308
|
+
return changed(Promise.resolve());
|
|
3309
|
+
}
|
|
3310
|
+
return changed(whileBusy(loadLayers(missing)));
|
|
3311
|
+
}
|
|
3312
|
+
return changed(whileBusy(load()));
|
|
3313
|
+
},
|
|
3314
|
+
/** 'dark', 'light' or 'auto'. */
|
|
3315
|
+
setTheme(t) {
|
|
3316
|
+
o.theme = t;
|
|
3317
|
+
theme.apply();
|
|
3318
|
+
if (hooks.theme) hooks.theme(t, api);
|
|
3319
|
+
},
|
|
3320
|
+
get symbol() {
|
|
3321
|
+
return state.symbol;
|
|
3322
|
+
},
|
|
3323
|
+
get resolution() {
|
|
3324
|
+
return state.res;
|
|
3325
|
+
},
|
|
3326
|
+
/** Days back from now (setRange). */
|
|
3327
|
+
get range() {
|
|
3328
|
+
return state.days;
|
|
3329
|
+
},
|
|
3330
|
+
get session() {
|
|
3331
|
+
return o.session;
|
|
3332
|
+
},
|
|
3333
|
+
/** For a chart group: the toolbar, time bar and credit line, and where they are now (see `outside`). */
|
|
3334
|
+
_parts: () => ({ bar: root.querySelector(".fac-bar"), time: root.querySelector(".fac-timebar"), credit: root.querySelector(".fac-credit") }),
|
|
3335
|
+
_outside(list) {
|
|
3336
|
+
outside.forEach((el) => el.removeEventListener("click", ctaClick, true));
|
|
3337
|
+
outside = list.filter(Boolean);
|
|
3338
|
+
outside.forEach((el) => el.addEventListener("click", ctaClick, true));
|
|
3339
|
+
},
|
|
3340
|
+
_closeMenus: () => view.closeMenus(),
|
|
3341
|
+
/** The key's plan from the last answer ('free', 'basic', ...), or null before it / without auth. */
|
|
3342
|
+
get plan() {
|
|
3343
|
+
return state.plan;
|
|
3344
|
+
},
|
|
3345
|
+
get layers() {
|
|
3346
|
+
return [...state.layers];
|
|
3347
|
+
},
|
|
3348
|
+
/** Every plot's style by plot id (a copy): { color, lineWidth, lineStyle, visible, priceLine, axisLabel }. */
|
|
3349
|
+
get styles() {
|
|
3350
|
+
return JSON.parse(JSON.stringify(styles));
|
|
3351
|
+
},
|
|
3352
|
+
/** Changes a plot's style, as the indicator Settings do, e.g. setStyle('callWall', { color: '#00ff00', lineWidth: 2 }). */
|
|
3353
|
+
setStyle(id, style) {
|
|
3354
|
+
view.setStyle(id, style || {});
|
|
3355
|
+
},
|
|
3356
|
+
reload: () => load(),
|
|
3357
|
+
destroy() {
|
|
3358
|
+
destroyed = true;
|
|
3359
|
+
state.loading++;
|
|
3360
|
+
clearInterval(timer);
|
|
3361
|
+
liveStop();
|
|
3362
|
+
toolbar.destroy();
|
|
3363
|
+
theme.destroy();
|
|
3364
|
+
call("destroy");
|
|
3365
|
+
resizeObserver.disconnect();
|
|
3366
|
+
chart.remove();
|
|
3367
|
+
root.remove();
|
|
3368
|
+
},
|
|
3369
|
+
get chart() {
|
|
3370
|
+
return chart;
|
|
3371
|
+
}
|
|
3372
|
+
};
|
|
3373
|
+
view.api = api;
|
|
3374
|
+
for (const { h } of handles)
|
|
3375
|
+
for (const [name, fn] of Object.entries(h.methods || {})) if (!(name in api) && typeof fn === "function") api[name] = fn;
|
|
3376
|
+
const timer = o.refresh > 0 ? setInterval(() => {
|
|
3377
|
+
if (!root.isConnected) {
|
|
3378
|
+
api.destroy();
|
|
3379
|
+
return;
|
|
3380
|
+
}
|
|
3381
|
+
if (live.up && Date.now() - live.barAt < 12e4 && Date.now() - lazy.newerAt < 3e5) return;
|
|
3382
|
+
if (!document.hidden && !pending && state.noData !== "unknown_symbol" && !(hooks.hidden && hooks.hidden())) load({ keepView: true });
|
|
3383
|
+
}, o.refresh * 1e3) : null;
|
|
3384
|
+
(async () => {
|
|
3385
|
+
emptyState.loading();
|
|
3386
|
+
try {
|
|
3387
|
+
state.symbols = await source.symbols();
|
|
3388
|
+
} catch (e) {
|
|
3389
|
+
state.symbols = [];
|
|
3390
|
+
}
|
|
3391
|
+
if (destroyed) return;
|
|
3392
|
+
noteKeyError(state.symbols);
|
|
3393
|
+
const symbolsError = state.symbols && state.symbols.error;
|
|
3394
|
+
if (!Array.isArray(state.symbols)) state.symbols = [];
|
|
3395
|
+
if (!state.symbol) state.symbol = (state.symbols.find((x) => x.last_bar) || state.symbols[0] || {}).symbol;
|
|
3396
|
+
if (state.symbol && !state.symbols.some((x) => x.symbol === state.symbol)) state.symbols.push({ symbol: state.symbol });
|
|
3397
|
+
toolbar.render();
|
|
3398
|
+
if (!state.symbol) {
|
|
3399
|
+
state.answered = true;
|
|
3400
|
+
toolbar.renderAccount();
|
|
3401
|
+
emptyState.show(symbolsError || "no bars");
|
|
3402
|
+
}
|
|
3403
|
+
started = true;
|
|
3404
|
+
await load();
|
|
3405
|
+
})();
|
|
3406
|
+
return api;
|
|
3407
|
+
}
|
|
3408
|
+
|
|
3409
|
+
// src/layouts.js
|
|
3410
|
+
var LAYOUTS = [
|
|
3411
|
+
{ id: "1", areas: ["a"] },
|
|
3412
|
+
{ id: "2v", areas: ["a b"] },
|
|
3413
|
+
{ id: "2h", areas: ["a", "b"] },
|
|
3414
|
+
{ id: "3v", areas: ["a b c"] },
|
|
3415
|
+
{ id: "3h", areas: ["a", "b", "c"] },
|
|
3416
|
+
{ id: "3l", areas: ["a b", "a c"] },
|
|
3417
|
+
{ id: "3r", areas: ["a c", "b c"] },
|
|
3418
|
+
{ id: "3t", areas: ["a b", "c c"] },
|
|
3419
|
+
{ id: "3b", areas: ["a a", "b c"] },
|
|
3420
|
+
{ id: "4", areas: ["a b", "c d"] },
|
|
3421
|
+
{ id: "4h", areas: ["a", "b", "c", "d"] },
|
|
3422
|
+
{ id: "4v", areas: ["a b c d"] },
|
|
3423
|
+
{ id: "4l", areas: ["a b", "a c", "a d"] },
|
|
3424
|
+
{ id: "4r", areas: ["a d", "b d", "c d"] },
|
|
3425
|
+
{ id: "4t", areas: ["a a a", "b c d"] },
|
|
3426
|
+
{ id: "4b", areas: ["a b c", "d d d"] },
|
|
3427
|
+
{ id: "4lc", areas: ["a b c", "a b d"] },
|
|
3428
|
+
{ id: "4rc", areas: ["a c d", "b c d"] },
|
|
3429
|
+
{ id: "4tr", areas: ["a b", "c c", "d d"], rows: [2, 1, 1] }
|
|
3430
|
+
].map((l) => {
|
|
3431
|
+
const grid = l.areas.map((r) => r.split(" "));
|
|
3432
|
+
const n = new Set(grid.flat()).size;
|
|
3433
|
+
return Object.assign({ n, cols: grid[0].map(() => 1), rows: grid.map(() => 1) }, l, { grid });
|
|
3434
|
+
});
|
|
3435
|
+
var MAX_CHARTS = 4;
|
|
3436
|
+
var layoutById = (id) => LAYOUTS.find((l) => l.id === id) || LAYOUTS[0];
|
|
3437
|
+
function gridStyle(l) {
|
|
3438
|
+
return {
|
|
3439
|
+
gridTemplateAreas: l.areas.map((r) => `"${r}"`).join(" "),
|
|
3440
|
+
gridTemplateColumns: l.cols.map((x) => x + "fr").join(" "),
|
|
3441
|
+
gridTemplateRows: l.rows.map((x) => x + "fr").join(" ")
|
|
3442
|
+
};
|
|
3443
|
+
}
|
|
3444
|
+
var areaOf = (i) => String.fromCharCode(97 + i);
|
|
3445
|
+
function layoutIcon(l, size = 18) {
|
|
3446
|
+
const W = 20, H = 16, x0 = 1, y0 = 1, w = W - 2, h = H - 2;
|
|
3447
|
+
const sum = (a) => a.reduce((s, v) => s + v, 0);
|
|
3448
|
+
const at = (tracks, i, len) => len * sum(tracks.slice(0, i)) / sum(tracks);
|
|
3449
|
+
let lines = "";
|
|
3450
|
+
for (const c of new Set(l.grid.flat())) {
|
|
3451
|
+
const rs = l.grid.map((r, i) => r.includes(c) ? i : -1).filter((i) => i >= 0);
|
|
3452
|
+
const cs = l.grid[rs[0]].map((x2, i) => x2 === c ? i : -1).filter((i) => i >= 0);
|
|
3453
|
+
const x = x0 + at(l.cols, cs[0], w), y = y0 + at(l.rows, rs[0], h);
|
|
3454
|
+
const xe = x0 + at(l.cols, cs[cs.length - 1] + 1, w), ye = y0 + at(l.rows, rs[rs.length - 1] + 1, h);
|
|
3455
|
+
lines += `<rect x="${x.toFixed(2)}" y="${y.toFixed(2)}" width="${(xe - x).toFixed(2)}" height="${(ye - y).toFixed(2)}"/>`;
|
|
3456
|
+
}
|
|
3457
|
+
return `<svg viewBox="0 0 ${W} ${H}" width="${size}" height="${Math.round(size * H / W)}" aria-hidden="true" focusable="false" fill="none" stroke="currentColor" stroke-width="1.3" stroke-linejoin="round"><rect x="${x0}" y="${y0}" width="${w}" height="${h}" rx="2.5"/>${lines}</svg>`;
|
|
3458
|
+
}
|
|
3459
|
+
|
|
3460
|
+
// src/group.js
|
|
3461
|
+
var SINGLE = 640;
|
|
3462
|
+
var NEW_RESOLUTIONS = ["1m", "5m", "15m", "1h", "1d", "1w"];
|
|
3463
|
+
function mount(container, options2) {
|
|
3464
|
+
const o = Object.assign({}, options2 || {});
|
|
3465
|
+
if (o.layouts === false || o.controls === false) return mountChart(container, o);
|
|
3466
|
+
if (!(o.lightweightCharts || global.LightweightCharts))
|
|
3467
|
+
throw new Error("FlashAlphaChart needs lightweight-charts 5 (global LightweightCharts or options.lightweightCharts)");
|
|
3468
|
+
if (o.injectCss !== false) injectCss();
|
|
3469
|
+
const base = o.storage === false ? null : String(o.storageKey || STORAGE_KEY);
|
|
3470
|
+
const groupKey = base && base + ":group";
|
|
3471
|
+
const saved = read();
|
|
3472
|
+
let layout = layoutById(saved && saved.layout || o.layout || "1");
|
|
3473
|
+
const slots = Array.from({ length: MAX_CHARTS }, (_, i) => saved && Array.isArray(saved.charts) && saved.charts[i] || null);
|
|
3474
|
+
const root = document.createElement("div");
|
|
3475
|
+
root.className = "fac-grp";
|
|
3476
|
+
root.innerHTML = '<div class="fac-grp-grid"></div><div class="fac-grp-top"></div><div class="fac-grp-foot"></div>';
|
|
3477
|
+
container.appendChild(root);
|
|
3478
|
+
const grid = root.querySelector(".fac-grp-grid"), top = root.querySelector(".fac-grp-top"), foot = root.querySelector(".fac-grp-foot");
|
|
3479
|
+
const charts = [];
|
|
3480
|
+
let active = -1, single = false, syncing = false, destroyed = false;
|
|
3481
|
+
const resizeObserver = new ResizeObserver(() => {
|
|
3482
|
+
const w = root.clientWidth;
|
|
3483
|
+
root.classList.toggle("fac-narrow", w > 0 && w < NARROW);
|
|
3484
|
+
const s = w > 0 && w < SINGLE;
|
|
3485
|
+
if (s !== single) {
|
|
3486
|
+
single = s;
|
|
3487
|
+
arrange();
|
|
3488
|
+
}
|
|
3489
|
+
});
|
|
3490
|
+
resizeObserver.observe(root);
|
|
3491
|
+
function read() {
|
|
3492
|
+
if (!groupKey) return null;
|
|
3493
|
+
try {
|
|
3494
|
+
const v = JSON.parse(global.localStorage.getItem(groupKey));
|
|
3495
|
+
return v && typeof v === "object" ? v : null;
|
|
3496
|
+
} catch (e) {
|
|
3497
|
+
return null;
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
function save() {
|
|
3501
|
+
if (!groupKey || destroyed) return;
|
|
3502
|
+
charts.forEach((c, i) => {
|
|
3503
|
+
slots[i] = { res: c.api.resolution, days: c.api.range, session: c.api.session };
|
|
3504
|
+
});
|
|
3505
|
+
try {
|
|
3506
|
+
global.localStorage.setItem(groupKey, JSON.stringify({ layout: layout.id, active, charts: slots }));
|
|
3507
|
+
} catch (e) {
|
|
3508
|
+
}
|
|
3509
|
+
}
|
|
3510
|
+
function sync(method, value, from) {
|
|
3511
|
+
if (syncing) return;
|
|
3512
|
+
syncing = true;
|
|
3513
|
+
try {
|
|
3514
|
+
for (const c of charts) if (c.api !== from) c.api[method](value);
|
|
3515
|
+
} finally {
|
|
3516
|
+
syncing = false;
|
|
3517
|
+
}
|
|
3518
|
+
}
|
|
3519
|
+
function copyTheme() {
|
|
3520
|
+
const r = charts[active] && charts[active].cell.querySelector(".fac");
|
|
3521
|
+
if (!r) return;
|
|
3522
|
+
for (let i = 0; i < r.style.length; i++) {
|
|
3523
|
+
const k = r.style[i];
|
|
3524
|
+
if (k.startsWith("--fac-")) root.style.setProperty(k, r.style.getPropertyValue(k));
|
|
3525
|
+
}
|
|
3526
|
+
}
|
|
3527
|
+
function addChart(i) {
|
|
3528
|
+
const cell = document.createElement("div");
|
|
3529
|
+
cell.className = "fac-cell";
|
|
3530
|
+
grid.appendChild(cell);
|
|
3531
|
+
const slot = slots[i], focused = charts[active];
|
|
3532
|
+
const used = charts.map((c) => c.api.resolution);
|
|
3533
|
+
const own = slot ? { resolution: slot.res, days: slot.days, session: slot.session } : i === 0 ? {} : { resolution: NEW_RESOLUTIONS.find((r) => !used.includes(r)) || "5m", days: null };
|
|
3534
|
+
const entry = { cell };
|
|
3535
|
+
const hooks = {
|
|
3536
|
+
frame: () => root,
|
|
3537
|
+
symbol: (x, api) => sync("setSymbol", x, api),
|
|
3538
|
+
theme: (t, api) => {
|
|
3539
|
+
sync("setTheme", t, api);
|
|
3540
|
+
copyTheme();
|
|
3541
|
+
},
|
|
3542
|
+
changed: () => save(),
|
|
3543
|
+
hidden: () => single && charts.indexOf(entry) !== active
|
|
3544
|
+
};
|
|
3545
|
+
entry.api = mountChart(cell, Object.assign({}, o, own, {
|
|
3546
|
+
layoutMenu: true,
|
|
3547
|
+
symbol: focused && focused.api.symbol || o.symbol || null,
|
|
3548
|
+
storageKey: base ? i ? `${base}:${i + 1}` : base : o.storageKey
|
|
3549
|
+
}), hooks);
|
|
3550
|
+
entry.parts = entry.api._parts();
|
|
3551
|
+
entry.marks = {};
|
|
3552
|
+
for (const [k, el] of Object.entries(entry.parts)) {
|
|
3553
|
+
if (!el) continue;
|
|
3554
|
+
const mark = document.createComment("fac-" + k);
|
|
3555
|
+
el.after(mark);
|
|
3556
|
+
entry.marks[k] = mark;
|
|
3557
|
+
}
|
|
3558
|
+
const panel = entry.parts.bar && entry.parts.bar.querySelector(".fac-layouts .fac-panel");
|
|
3559
|
+
if (panel) {
|
|
3560
|
+
panel.innerHTML = '<div class="fac-ttl">Layout</div>' + [1, 2, 3, 4].map((n) => `<div class="fac-lay-row"><span class="fac-lay-n">${n}</span>` + LAYOUTS.filter((l) => l.n === n).map((l) => {
|
|
3561
|
+
const t = l.n === 1 ? "1 chart" : `${l.n} charts`;
|
|
3562
|
+
return `<button type="button" data-layout="${l.id}" title="${t}" aria-label="${t}">${layoutIcon(l)}</button>`;
|
|
3563
|
+
}).join("") + "</div>").join("");
|
|
3564
|
+
panel.addEventListener("click", (e) => {
|
|
3565
|
+
const b = e.target.closest("[data-layout]");
|
|
3566
|
+
if (!b) return;
|
|
3567
|
+
entry.api._closeMenus();
|
|
3568
|
+
setLayout(b.dataset.layout);
|
|
3569
|
+
});
|
|
3570
|
+
}
|
|
3571
|
+
cell.addEventListener("pointerdown", () => focus(charts.indexOf(entry)), true);
|
|
3572
|
+
charts.push(entry);
|
|
3573
|
+
}
|
|
3574
|
+
function focus(i) {
|
|
3575
|
+
if (i < 0 || i >= charts.length || i === active) return;
|
|
3576
|
+
const was = charts[active];
|
|
3577
|
+
if (was) {
|
|
3578
|
+
was.api._closeMenus();
|
|
3579
|
+
for (const [k, el] of Object.entries(was.parts)) if (el && was.marks[k]) was.marks[k].before(el);
|
|
3580
|
+
was.api._outside([]);
|
|
3581
|
+
was.cell.classList.remove("on");
|
|
3582
|
+
}
|
|
3583
|
+
active = i;
|
|
3584
|
+
const c = charts[i];
|
|
3585
|
+
if (c.parts.bar) top.appendChild(c.parts.bar);
|
|
3586
|
+
for (const el of [c.parts.time, c.parts.credit]) if (el) foot.appendChild(el);
|
|
3587
|
+
c.api._outside([c.parts.bar, c.parts.time, c.parts.credit]);
|
|
3588
|
+
c.cell.classList.add("on");
|
|
3589
|
+
copyTheme();
|
|
3590
|
+
arrange();
|
|
3591
|
+
save();
|
|
3592
|
+
}
|
|
3593
|
+
function arrange() {
|
|
3594
|
+
root.classList.toggle("fac-grp-multi", charts.length > 1 && !single);
|
|
3595
|
+
root.classList.toggle("fac-grp-single", single);
|
|
3596
|
+
Object.assign(grid.style, single ? { gridTemplateAreas: '"a"', gridTemplateColumns: "1fr", gridTemplateRows: "1fr" } : gridStyle(layout));
|
|
3597
|
+
charts.forEach((c, i) => {
|
|
3598
|
+
const hide = single && i !== active;
|
|
3599
|
+
c.cell.style.gridArea = single ? "a" : areaOf(i);
|
|
3600
|
+
if (c.cell.hidden && !hide) c.api.reload();
|
|
3601
|
+
c.cell.hidden = hide;
|
|
3602
|
+
});
|
|
3603
|
+
}
|
|
3604
|
+
function renderMenus() {
|
|
3605
|
+
for (const c of charts) {
|
|
3606
|
+
const bar = c.parts.bar;
|
|
3607
|
+
if (!bar) continue;
|
|
3608
|
+
const btn = bar.querySelector(".fac-layouts > button");
|
|
3609
|
+
if (btn) btn.innerHTML = layoutIcon(layout);
|
|
3610
|
+
bar.querySelectorAll("[data-layout]").forEach((b) => {
|
|
3611
|
+
const on = b.dataset.layout === layout.id;
|
|
3612
|
+
b.classList.toggle("on", on);
|
|
3613
|
+
b.setAttribute("aria-pressed", String(on));
|
|
3614
|
+
});
|
|
3615
|
+
}
|
|
3616
|
+
}
|
|
3617
|
+
function setLayout(id) {
|
|
3618
|
+
const l = layoutById(id);
|
|
3619
|
+
if (active >= l.n) focus(0);
|
|
3620
|
+
save();
|
|
3621
|
+
while (charts.length > l.n) {
|
|
3622
|
+
const c = charts.pop();
|
|
3623
|
+
c.api.destroy();
|
|
3624
|
+
c.cell.remove();
|
|
3625
|
+
}
|
|
3626
|
+
layout = l;
|
|
3627
|
+
while (charts.length < l.n) addChart(charts.length);
|
|
3628
|
+
arrange();
|
|
3629
|
+
renderMenus();
|
|
3630
|
+
save();
|
|
3631
|
+
}
|
|
3632
|
+
for (let i = 0; i < layout.n; i++) addChart(i);
|
|
3633
|
+
focus(saved && saved.active > 0 && saved.active < charts.length ? saved.active : 0);
|
|
3634
|
+
renderMenus();
|
|
3635
|
+
const group = {
|
|
3636
|
+
/** Any id of LAYOUTS: '1', '2v', '2h', '3v' ... '4tr'. */
|
|
3637
|
+
setLayout,
|
|
3638
|
+
get layout() {
|
|
3639
|
+
return layout.id;
|
|
3640
|
+
},
|
|
3641
|
+
/** The methods of every chart, in layout order. */
|
|
3642
|
+
get charts() {
|
|
3643
|
+
return charts.map((c) => c.api);
|
|
3644
|
+
},
|
|
3645
|
+
/** The position of the chart in focus. */
|
|
3646
|
+
get active() {
|
|
3647
|
+
return active;
|
|
3648
|
+
},
|
|
3649
|
+
focus,
|
|
3650
|
+
setSymbol(x) {
|
|
3651
|
+
return charts[active].api.setSymbol(x);
|
|
3652
|
+
},
|
|
3653
|
+
setTheme(t) {
|
|
3654
|
+
charts[active].api.setTheme(t);
|
|
3655
|
+
},
|
|
3656
|
+
reload: () => Promise.all(charts.map((c) => c.api.reload())),
|
|
3657
|
+
destroy() {
|
|
3658
|
+
destroyed = true;
|
|
3659
|
+
resizeObserver.disconnect();
|
|
3660
|
+
for (const c of charts) c.api.destroy();
|
|
3661
|
+
charts.length = 0;
|
|
3662
|
+
root.remove();
|
|
3663
|
+
}
|
|
3664
|
+
};
|
|
3665
|
+
return new Proxy(group, {
|
|
3666
|
+
get(t, k) {
|
|
3667
|
+
if (k in t) return t[k];
|
|
3668
|
+
const api = charts[active] && charts[active].api;
|
|
3669
|
+
const v = api ? api[k] : void 0;
|
|
3670
|
+
return typeof v === "function" ? v.bind(api) : v;
|
|
3671
|
+
},
|
|
3672
|
+
has(t, k) {
|
|
3673
|
+
return k in t || !!(charts[active] && k in charts[active].api);
|
|
3674
|
+
}
|
|
3675
|
+
});
|
|
3676
|
+
}
|
|
3677
|
+
|
|
3678
|
+
// src/index.js
|
|
3679
|
+
var plans = PLANS;
|
|
3680
|
+
var version = true ? "1.2.0" : "0.0.0-dev";
|
|
3681
|
+
var FlashAlphaChart = {
|
|
3682
|
+
mount,
|
|
3683
|
+
chartEngineSource,
|
|
3684
|
+
registerLayers,
|
|
3685
|
+
setLicenseKey,
|
|
3686
|
+
plans,
|
|
3687
|
+
get layers() {
|
|
3688
|
+
return layerIds();
|
|
3689
|
+
},
|
|
3690
|
+
version
|
|
3691
|
+
};
|
|
3692
|
+
var index_default = FlashAlphaChart;
|
|
3693
|
+
export {
|
|
3694
|
+
chartEngineSource,
|
|
3695
|
+
index_default as default,
|
|
3696
|
+
mount,
|
|
3697
|
+
plans,
|
|
3698
|
+
registerLayers,
|
|
3699
|
+
setLicenseKey,
|
|
3700
|
+
version
|
|
3701
|
+
};
|