@tradecanvas/chart 0.14.0 → 1.0.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.
@@ -1,2 +1,6 @@
1
1
  export { PluginManager } from './PluginManager.js';
2
+ export type { PluginManagerOptions } from './PluginManager.js';
3
+ export { registerPlugin, unregisterPlugin, getGlobalPlugins, clearGlobalPlugins, } from './registry.js';
4
+ export { PLUGIN_API_VERSION, pluginKey, overlaysForLayer } from './contracts.js';
5
+ export type { ChartPlugin, ChartTypePlugin, OverlayPlugin, OverlayRenderContext, } from './contracts.js';
2
6
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugins/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugins/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AACnD,YAAY,EAAE,oBAAoB,EAAE,MAAM,oBAAoB,CAAC;AAC/D,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,GACnB,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,kBAAkB,EAAE,SAAS,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AACjF,YAAY,EACV,WAAW,EACX,eAAe,EACf,aAAa,EACb,oBAAoB,GACrB,MAAM,gBAAgB,CAAC"}
@@ -0,0 +1,10 @@
1
+ import { ChartPlugin } from './contracts.js';
2
+ /** Register a plugin globally. Re-registering the same key replaces it. */
3
+ export declare function registerPlugin(plugin: ChartPlugin): void;
4
+ /** Remove a global plugin by its `pluginKey`. Returns true if it existed. */
5
+ export declare function unregisterPlugin(key: string): boolean;
6
+ /** Snapshot of all globally registered plugins. */
7
+ export declare function getGlobalPlugins(): ChartPlugin[];
8
+ /** Clear the global registry (test/teardown helper). */
9
+ export declare function clearGlobalPlugins(): void;
10
+ //# sourceMappingURL=registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/plugins/registry.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAUlD,2EAA2E;AAC3E,wBAAgB,cAAc,CAAC,MAAM,EAAE,WAAW,GAAG,IAAI,CAExD;AAED,6EAA6E;AAC7E,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAErD;AAED,mDAAmD;AACnD,wBAAgB,gBAAgB,IAAI,WAAW,EAAE,CAEhD;AAED,wDAAwD;AACxD,wBAAgB,kBAAkB,IAAI,IAAI,CAEzC"}
@@ -0,0 +1,26 @@
1
+ import { ExecutionAdapter, ExecutionError, TradingOrder, TradingPosition } from '@tradecanvas/commons';
2
+ /** The five order/position intents the chart emits and an adapter consumes. */
3
+ export type ExecutionIntentType = 'orderPlace' | 'orderModify' | 'orderCancel' | 'positionModify' | 'positionClose';
4
+ /**
5
+ * Surface the host (the Chart) provides so execution can be bridged without
6
+ * the helper knowing anything about chart internals — which keeps it pure and
7
+ * unit-testable.
8
+ */
9
+ export interface ExecutionHost {
10
+ /** Subscribe to an emitted intent; returns an unsubscribe function. */
11
+ onIntent(type: ExecutionIntentType, handler: (payload: unknown) => void): () => void;
12
+ /** Render the adapter's authoritative pending orders. */
13
+ setOrders(orders: TradingOrder[]): void;
14
+ /** Render the adapter's authoritative open positions. */
15
+ setPositions(positions: TradingPosition[]): void;
16
+ /** Surface an execution failure (adapter-reported or a failed command). */
17
+ onError(error: ExecutionError): void;
18
+ }
19
+ /**
20
+ * Bridge an `ExecutionAdapter` to a host: render the adapter's authoritative
21
+ * orders/positions, and route the host's emitted intents into adapter
22
+ * commands. The adapter is the single source of truth. Returns a teardown that
23
+ * removes every subscription.
24
+ */
25
+ export declare function wireExecution(adapter: ExecutionAdapter, host: ExecutionHost): () => void;
26
+ //# sourceMappingURL=wireExecution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"wireExecution.d.ts","sourceRoot":"","sources":["../../src/trading/wireExecution.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,gBAAgB,EAEhB,cAAc,EACd,YAAY,EACZ,eAAe,EAMhB,MAAM,sBAAsB,CAAC;AAE9B,+EAA+E;AAC/E,MAAM,MAAM,mBAAmB,GAC3B,YAAY,GACZ,aAAa,GACb,aAAa,GACb,gBAAgB,GAChB,eAAe,CAAC;AAEpB;;;;GAIG;AACH,MAAM,WAAW,aAAa;IAC5B,uEAAuE;IACvE,QAAQ,CAAC,IAAI,EAAE,mBAAmB,EAAE,OAAO,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,GAAG,MAAM,IAAI,CAAC;IACrF,yDAAyD;IACzD,SAAS,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,IAAI,CAAC;IACxC,yDAAyD;IACzD,YAAY,CAAC,SAAS,EAAE,eAAe,EAAE,GAAG,IAAI,CAAC;IACjD,2EAA2E;IAC3E,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,IAAI,CAAC;CACtC;AAaD;;;;;GAKG;AACH,wBAAgB,aAAa,CAAC,OAAO,EAAE,gBAAgB,EAAE,IAAI,EAAE,aAAa,GAAG,MAAM,IAAI,CA+BxF"}
@@ -2,7 +2,7 @@
2
2
  * Replay scrubber bar — surfaces the chart's existing replay engine as a
3
3
  * visible bottom-of-chart control. Mounts under the chart container, owns
4
4
  * its own lifecycle, and reports user intent up via callbacks (no chart
5
- * coupling — the host calls chart.replay() / replayPause() / etc.).
5
+ * coupling — the host calls chart.replayStart() / replayPause() / etc.).
6
6
  */
7
7
  export interface ReplayBarCallbacks {
8
8
  onPlay: () => void;
@@ -1,4 +1,16 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../DragDropImporter-ycI_Tcs6.cjs`);let t=require(`@tradecanvas/commons`);function n(e,n,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,t.timeframeBucketStart)(r.time,n,i);o===null||e!==s?(o!==null&&a.push(o),o={time:e,open:r.open,high:r.high,low:r.low,close:r.close,volume:r.volume},s=e):o={time:o.time,open:o.open,high:Math.max(o.high,r.high),low:Math.min(o.low,r.low),close:r.close,volume:o.volume+r.volume}}return o!==null&&a.push(o),a}function r(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var i=[{label:`1m`,value:`1m`},{label:`5m`,value:`5m`},{label:`15m`,value:`15m`},{label:`1H`,value:`1h`},{label:`4H`,value:`4h`},{label:`1D`,value:`1d`}],a=[{label:`Candlestick`,value:`candlestick`},{label:`Line`,value:`line`},{label:`Area`,value:`area`},{label:`Bar`,value:`bar`},{label:`Heikin-Ashi`,value:`heikinAshi`},{label:`Hollow Candle`,value:`hollowCandle`},{label:`Baseline`,value:`baseline`},{label:`Volume Candles`,value:`volumeCandles`},{label:`Equivolume`,value:`equivolume`},{label:`HLC Area`,value:`hlcArea`},{label:`Step Line`,value:`stepLine`},{label:`Line + Markers`,value:`lineWithMarkers`}],o=[{label:`Lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`}]},{label:`Horizontal/Vertical`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Vertical Line`,value:`verticalLine`}]},{label:`Channels`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`}]},{label:`Shapes`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`}]},{label:`Gann & Advanced`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Elliott Wave`,value:`elliottWave`}]},{label:`Measure`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Measure`,value:`measure`}]},{label:`Annotation`,tools:[{label:`Text`,value:`text`},{label:`Arrow`,value:`arrow`}]}],s=[{id:`sma`,name:`SMA`,type:`overlay`},{id:`ema`,name:`EMA`,type:`overlay`},{id:`hma`,name:`Hull MA`,type:`overlay`},{id:`mtfma`,name:`MTF Moving Average`,type:`overlay`},{id:`bb`,name:`Bollinger Bands`,type:`overlay`},{id:`vwap`,name:`VWAP`,type:`overlay`},{id:`avwap`,name:`Anchored VWAP`,type:`overlay`},{id:`svwap`,name:`Session VWAP`,type:`overlay`},{id:`ichimoku`,name:`Ichimoku Cloud`,type:`overlay`},{id:`psar`,name:`Parabolic SAR`,type:`overlay`},{id:`supertrend`,name:`Supertrend`,type:`overlay`},{id:`keltner`,name:`Keltner Channel`,type:`overlay`},{id:`donchian`,name:`Donchian Channel`,type:`overlay`},{id:`pivots`,name:`Pivot Points`,type:`overlay`},{id:`zigzag`,name:`ZigZag`,type:`overlay`},{id:`lrc`,name:`Linear Regression Channel`,type:`overlay`},{id:`chandelier`,name:`Chandelier Exit`,type:`overlay`},{id:`alligator`,name:`Alligator`,type:`overlay`},{id:`rsi`,name:`RSI`,type:`panel`},{id:`macd`,name:`MACD`,type:`panel`},{id:`stochastic`,name:`Stochastic`,type:`panel`},{id:`atr`,name:`ATR`,type:`panel`},{id:`adx`,name:`ADX`,type:`panel`},{id:`obv`,name:`OBV`,type:`panel`},{id:`williamsR`,name:`Williams %R`,type:`panel`},{id:`cci`,name:`CCI`,type:`panel`},{id:`mfi`,name:`MFI`,type:`panel`},{id:`roc`,name:`ROC`,type:`panel`},{id:`tsi`,name:`TSI`,type:`panel`},{id:`cmf`,name:`CMF`,type:`panel`},{id:`aroon`,name:`Aroon`,type:`panel`},{id:`stddev`,name:`Std Deviation`,type:`panel`},{id:`vroc`,name:`Volume ROC`,type:`panel`},{id:`ad`,name:`Acc/Dist`,type:`panel`},{id:`ao`,name:`Awesome Oscillator`,type:`panel`},{id:`chaikinOsc`,name:`Chaikin Oscillator`,type:`panel`},{id:`voldelta`,name:`Volume Delta`,type:`panel`},{id:`vortex`,name:`Vortex Indicator`,type:`panel`},{id:`chop`,name:`Choppiness Index`,type:`panel`},{id:`uo`,name:`Ultimate Oscillator`,type:`panel`},{id:`fi`,name:`Force Index`,type:`panel`},{id:`crsi`,name:`Connors RSI`,type:`panel`},{id:`coppock`,name:`Coppock Curve`,type:`panel`},{id:`kst`,name:`Know Sure Thing`,type:`panel`},{id:`elderray`,name:`Elder Ray`,type:`panel`},{id:`stc`,name:`Schaff Trend Cycle`,type:`panel`},{id:`kvo`,name:`Klinger Oscillator`,type:`panel`},{id:`fisher`,name:`Fisher Transform`,type:`panel`},{id:`dpo`,name:`Detrended Price Osc`,type:`panel`},{id:`bop`,name:`Balance of Power`,type:`panel`},{id:`massindex`,name:`Mass Index`,type:`panel`},{id:`cmo`,name:`Chande Momentum`,type:`panel`},{id:`trix`,name:`TRIX`,type:`panel`},{id:`emv`,name:`Ease of Movement`,type:`panel`},{id:`pvt`,name:`Price Volume Trend`,type:`panel`},{id:`wad`,name:`Williams A/D`,type:`panel`},{id:`chaikinvol`,name:`Chaikin Volatility`,type:`panel`},{id:`rvi`,name:`Relative Vigor Index`,type:`panel`},{id:`stochrsi`,name:`Stochastic RSI`,type:`panel`},{id:`ppo`,name:`Percentage Price Oscillator`,type:`panel`},{id:`ac`,name:`Accelerator Oscillator`,type:`panel`},{id:`rmi`,name:`Relative Momentum Index`,type:`panel`},{id:`disparity`,name:`Disparity Index`,type:`panel`},{id:`qstick`,name:`Qstick`,type:`panel`},{id:`pgo`,name:`Pretty Good Oscillator`,type:`panel`},{id:`volumeProfile`,name:`Volume Profile`,type:`panel`}],c=[`sma`,`ema`,`bb`,`rsi`,`macd`,`stochastic`,`vwap`,`atr`,`obv`,`ichimoku`],l=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],u={candleUpColor:`#26A69A`,candleDownColor:`#EF5350`,candleUpWick:`#26A69A`,candleDownWick:`#EF5350`,backgroundColor:`#131722`,gridColor:`#1E222D`,gridVisible:!0,volumeVisible:!0,volumeProfileVisible:!1,marketProfileVisible:!1,marketProfileSplit:!1,marketProfileLetters:!1,marketProfileBuckets:48,marketProfileOpacity:.32,depthHeatmapVisible:!1,depthHeatmapOpacity:.7,sessionShadingVisible:!1,pivotMarkersVisible:!1,pivotStrength:5,pivotStructureLabels:!1,periodLevelsVisible:!1,periodLevelsPeriod:`day`,legendVisible:!0,barCountdown:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`},d=`/* === TradeCanvas Widget — Premium Styles === */
1
+ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../DragDropImporter-DeXlngof.cjs`);let t=require(`@tradecanvas/commons`);function n(e,n,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,t.timeframeBucketStart)(r.time,n,i);o===null||e!==s?(o!==null&&a.push(o),o={time:e,open:r.open,high:r.high,low:r.low,close:r.close,volume:r.volume},s=e):o={time:o.time,open:o.open,high:Math.max(o.high,r.high),low:Math.min(o.low,r.low),close:r.close,volume:o.volume+r.volume}}return o!==null&&a.push(o),a}function r(e){if(e.length<2)return 0;let t=[];for(let n=1;n<e.length;n++){let r=e[n].time-e[n-1].time;r>0&&t.push(r)}return t.length===0?0:(t.sort((e,t)=>e-t),t[Math.floor(t.length/2)])}var i=[{label:`1m`,value:`1m`},{label:`5m`,value:`5m`},{label:`15m`,value:`15m`},{label:`1H`,value:`1h`},{label:`4H`,value:`4h`},{label:`1D`,value:`1d`}],a=[{label:`Candlestick`,value:`candlestick`},{label:`Line`,value:`line`},{label:`Area`,value:`area`},{label:`Bar`,value:`bar`},{label:`Heikin-Ashi`,value:`heikinAshi`},{label:`Hollow Candle`,value:`hollowCandle`},{label:`Baseline`,value:`baseline`},{label:`Volume Candles`,value:`volumeCandles`},{label:`Equivolume`,value:`equivolume`},{label:`HLC Area`,value:`hlcArea`},{label:`Step Line`,value:`stepLine`},{label:`Line + Markers`,value:`lineWithMarkers`}],o=[{label:`Lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`}]},{label:`Horizontal/Vertical`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Vertical Line`,value:`verticalLine`}]},{label:`Channels`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`}]},{label:`Shapes`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`}]},{label:`Gann & Advanced`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Elliott Wave`,value:`elliottWave`}]},{label:`Measure`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Measure`,value:`measure`}]},{label:`Annotation`,tools:[{label:`Text`,value:`text`},{label:`Arrow`,value:`arrow`}]}],s=[{id:`sma`,name:`SMA`,type:`overlay`},{id:`ema`,name:`EMA`,type:`overlay`},{id:`hma`,name:`Hull MA`,type:`overlay`},{id:`mtfma`,name:`MTF Moving Average`,type:`overlay`},{id:`bb`,name:`Bollinger Bands`,type:`overlay`},{id:`vwap`,name:`VWAP`,type:`overlay`},{id:`avwap`,name:`Anchored VWAP`,type:`overlay`},{id:`svwap`,name:`Session VWAP`,type:`overlay`},{id:`ichimoku`,name:`Ichimoku Cloud`,type:`overlay`},{id:`psar`,name:`Parabolic SAR`,type:`overlay`},{id:`supertrend`,name:`Supertrend`,type:`overlay`},{id:`keltner`,name:`Keltner Channel`,type:`overlay`},{id:`donchian`,name:`Donchian Channel`,type:`overlay`},{id:`pivots`,name:`Pivot Points`,type:`overlay`},{id:`zigzag`,name:`ZigZag`,type:`overlay`},{id:`lrc`,name:`Linear Regression Channel`,type:`overlay`},{id:`chandelier`,name:`Chandelier Exit`,type:`overlay`},{id:`alligator`,name:`Alligator`,type:`overlay`},{id:`rsi`,name:`RSI`,type:`panel`},{id:`macd`,name:`MACD`,type:`panel`},{id:`stochastic`,name:`Stochastic`,type:`panel`},{id:`atr`,name:`ATR`,type:`panel`},{id:`adx`,name:`ADX`,type:`panel`},{id:`obv`,name:`OBV`,type:`panel`},{id:`williamsR`,name:`Williams %R`,type:`panel`},{id:`cci`,name:`CCI`,type:`panel`},{id:`mfi`,name:`MFI`,type:`panel`},{id:`roc`,name:`ROC`,type:`panel`},{id:`tsi`,name:`TSI`,type:`panel`},{id:`cmf`,name:`CMF`,type:`panel`},{id:`aroon`,name:`Aroon`,type:`panel`},{id:`stddev`,name:`Std Deviation`,type:`panel`},{id:`vroc`,name:`Volume ROC`,type:`panel`},{id:`ad`,name:`Acc/Dist`,type:`panel`},{id:`ao`,name:`Awesome Oscillator`,type:`panel`},{id:`chaikinOsc`,name:`Chaikin Oscillator`,type:`panel`},{id:`voldelta`,name:`Volume Delta`,type:`panel`},{id:`vortex`,name:`Vortex Indicator`,type:`panel`},{id:`chop`,name:`Choppiness Index`,type:`panel`},{id:`uo`,name:`Ultimate Oscillator`,type:`panel`},{id:`fi`,name:`Force Index`,type:`panel`},{id:`crsi`,name:`Connors RSI`,type:`panel`},{id:`coppock`,name:`Coppock Curve`,type:`panel`},{id:`kst`,name:`Know Sure Thing`,type:`panel`},{id:`elderray`,name:`Elder Ray`,type:`panel`},{id:`stc`,name:`Schaff Trend Cycle`,type:`panel`},{id:`kvo`,name:`Klinger Oscillator`,type:`panel`},{id:`fisher`,name:`Fisher Transform`,type:`panel`},{id:`dpo`,name:`Detrended Price Osc`,type:`panel`},{id:`bop`,name:`Balance of Power`,type:`panel`},{id:`massindex`,name:`Mass Index`,type:`panel`},{id:`cmo`,name:`Chande Momentum`,type:`panel`},{id:`trix`,name:`TRIX`,type:`panel`},{id:`emv`,name:`Ease of Movement`,type:`panel`},{id:`pvt`,name:`Price Volume Trend`,type:`panel`},{id:`wad`,name:`Williams A/D`,type:`panel`},{id:`chaikinvol`,name:`Chaikin Volatility`,type:`panel`},{id:`rvi`,name:`Relative Vigor Index`,type:`panel`},{id:`stochrsi`,name:`Stochastic RSI`,type:`panel`},{id:`ppo`,name:`Percentage Price Oscillator`,type:`panel`},{id:`ac`,name:`Accelerator Oscillator`,type:`panel`},{id:`rmi`,name:`Relative Momentum Index`,type:`panel`},{id:`disparity`,name:`Disparity Index`,type:`panel`},{id:`qstick`,name:`Qstick`,type:`panel`},{id:`pgo`,name:`Pretty Good Oscillator`,type:`panel`},{id:`volumeProfile`,name:`Volume Profile`,type:`panel`}],c=[`sma`,`ema`,`bb`,`rsi`,`macd`,`stochastic`,`vwap`,`atr`,`obv`,`ichimoku`],l=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],u={candleUpColor:`#26A69A`,candleDownColor:`#EF5350`,candleUpWick:`#26A69A`,candleDownWick:`#EF5350`,backgroundColor:`#131722`,gridColor:`#1E222D`,gridVisible:!0,volumeVisible:!0,volumeProfileVisible:!1,marketProfileVisible:!1,marketProfileSplit:!1,marketProfileLetters:!1,marketProfileBuckets:48,marketProfileOpacity:.32,depthHeatmapVisible:!1,depthHeatmapOpacity:.7,sessionShadingVisible:!1,pivotMarkersVisible:!1,pivotStrength:5,pivotStructureLabels:!1,periodLevelsVisible:!1,periodLevelsPeriod:`day`,legendVisible:!0,barCountdown:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`},d=`/* === TradeCanvas Widget — Premium Styles === */
2
+
3
+ /*
4
+ * The HTML \`hidden\` attribute only sets \`display: none\` via the UA stylesheet,
5
+ * which any author \`display\` rule (e.g. \`.tcw-alerts-panel { display: flex }\`)
6
+ * silently overrides — leaving panels stuck open when JS sets \`el.hidden = true\`.
7
+ * Force \`hidden\` to win for every namespaced widget element. Scoped to \`tcw-\`
8
+ * so it never touches the host page.
9
+ */
10
+ [class^="tcw-"][hidden],
11
+ [class*=" tcw-"][hidden] {
12
+ display: none !important;
13
+ }
2
14
 
3
15
  .tcw-root {
4
16
  display: flex;
@@ -1617,6 +1629,9 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
1617
1629
 
1618
1630
  .tcw-alerts-form input,
1619
1631
  .tcw-alerts-form select {
1632
+ width: 100%;
1633
+ min-width: 0;
1634
+ box-sizing: border-box;
1620
1635
  height: 32px;
1621
1636
  padding: 0 8px;
1622
1637
  font-size: 12px;
@@ -2369,5 +2384,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
2369
2384
  <input type="range" class="tcw-replay-scrubber" data-act="seek" min="0" max="${Math.max(0,this.total-1)}" value="0" step="1" />
2370
2385
  <span class="tcw-replay-progress" data-tcw="progress">1 / ${this.total}</span>
2371
2386
  <select class="tcw-replay-speed" data-act="speed">${e}</select>
2372
- `}wireEvents(){this.root&&(this.scrubber=this.root.querySelector(`input[data-act="seek"]`),this.progressLabel=this.root.querySelector(`[data-tcw="progress"]`),this.playBtn=this.root.querySelector(`button[data-act="play"]`),this.root.querySelector(`[data-act="close"]`)?.addEventListener(`click`,()=>this.callbacks.onClose()),this.root.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),this.root.querySelector(`[data-act="stepForward"]`)?.addEventListener(`click`,()=>this.callbacks.onStepForward()),this.playBtn?.addEventListener(`click`,()=>{this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}),this.scrubber?.addEventListener(`input`,()=>{let e=Number(this.scrubber.value);this.callbacks.onSeek(e)}),this.root.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.speed=t,this.callbacks.onSpeedChange(t)}))}syncUi(){this.playBtn&&(this.playBtn.innerHTML=this.state===`playing`?N():M(),this.playBtn.title=this.state===`playing`?`Pause`:`Play`)}};function M(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7L8 5z"/></svg>`}function N(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>`}function P(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M6 6h2v12H6zM20 6L9 12l11 6V6z"/></svg>`}function F(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M4 6l11 6L4 18V6zM16 6h2v12h-2z"/></svg>`}function I(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>`}var L=class{el;listEl;rowMap=new Map;entries=new Map;active=null;callbacks;constructor(e,t,n){this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`;let r=document.createElement(`div`);r.className=`tcw-watchlist-header`,r.textContent=`Watchlist`,this.el.appendChild(r),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.el.appendChild(this.listEl);for(let e of t)this.entries.set(e,{symbol:e}),this.appendRow(e);e.appendChild(this.el)}setSymbols(e){let t=new Set(e);for(let e of this.rowMap.keys())t.has(e)||this.removeRow(e);for(let t of e)this.rowMap.has(t)||(this.entries.set(t,this.entries.get(t)??{symbol:t}),this.appendRow(t))}setActive(e){if(this.active===e)return;this.active&&this.rowMap.has(this.active)&&this.rowMap.get(this.active).row.classList.remove(`tcw-watchlist-active`),this.active=e;let t=this.rowMap.get(e);t&&t.row.classList.add(`tcw-watchlist-active`)}setEntry(e,t){let n={...this.entries.get(e)??{symbol:e},...t};this.entries.set(e,n),this.renderRow(e)}destroy(){this.el.remove(),this.rowMap.clear(),this.entries.clear()}appendRow(e){let t=document.createElement(`div`);t.className=`tcw-watchlist-row`,t.tabIndex=0;let n=document.createElement(`div`);n.className=`tcw-watchlist-symbol`,n.textContent=R(e);let r=document.createElement(`canvas`);r.className=`tcw-watchlist-spark`,r.width=64,r.height=22;let i=document.createElement(`div`);i.className=`tcw-watchlist-stats`;let a=document.createElement(`span`);a.className=`tcw-watchlist-price`,a.textContent=`—`;let o=document.createElement(`span`);o.className=`tcw-watchlist-change`,o.textContent=``,i.appendChild(a),i.appendChild(o),t.appendChild(n),t.appendChild(r),t.appendChild(i),t.addEventListener(`click`,()=>this.callbacks.onSelect(e)),t.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),this.callbacks.onSelect(e))}),this.listEl.appendChild(t),this.rowMap.set(e,{row:t,priceEl:a,changeEl:o,sparkCanvas:r}),e===this.active&&t.classList.add(`tcw-watchlist-active`)}removeRow(e){let t=this.rowMap.get(e);t&&(t.row.remove(),this.rowMap.delete(e))}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=z(n.lastPrice)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:``;t.changeEl.textContent=`${i}${r.toFixed(2)}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&B(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}};function R(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function z(e){if(e===0)return`0`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function B(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#26a17b`:`#f23645`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}var V=[{value:`crossing`,label:`Crossing`},{value:`crossingUp`,label:`Crossing up`},{value:`crossingDown`,label:`Crossing down`},{value:`greaterThan`,label:`Greater than`},{value:`lessThan`,label:`Less than`}],H=new Map(V.map(e=>[e.value,e.label]));function U(e){return Math.round(e*1e6)/1e6}function W(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var G=class{el;listEl;priceInput;conditionSelect;sourceSelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources=[{channel:`price`,label:`Price`}];constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-alerts-header`;let r=document.createElement(`span`);r.textContent=`Price Alerts`;let i=document.createElement(`button`);i.className=`tcw-alerts-close`,i.type=`button`,i.setAttribute(`aria-label`,`Close alerts`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n);let a=document.createElement(`form`);a.className=`tcw-alerts-form`,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.addEventListener(`change`,()=>this.prefillPrice()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=`Value`,this.priceInput.className=`tcw-alerts-price`,this.priceInput.required=!0,this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`;for(let e of V){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,this.conditionSelect.appendChild(t)}this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=`Note (optional)`,this.messageInput.className=`tcw-alerts-message`;let o=document.createElement(`button`);o.type=`submit`,o.className=`tcw-alerts-add`,o.innerHTML=`${_(`plus`,14)}<span>Add alert</span>`,a.appendChild(this.sourceSelect),a.appendChild(this.priceInput),a.appendChild(this.conditionSelect),a.appendChild(this.messageInput),a.appendChild(o),a.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(a),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=`No alerts yet. Add one above, or right-click the chart.`,this.listEl.appendChild(this.emptyEl),this.renderSources(),e.appendChild(this.el)}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:`Price`}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(U(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=Number(this.priceInput.value);if(!Number.isFinite(e))return;let t=this.conditionSelect.value,n=this.messageInput.value.trim()||void 0,r=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===r)?.label??`Price`;this.callbacks.onAdd(e,t,n,r,i),this.messageInput.value=``,this.prefillPrice()}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let t=document.createElement(`div`);t.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``);let n=document.createElement(`div`);n.className=`tcw-alerts-info`;let r=document.createElement(`div`);r.className=`tcw-alerts-row-main`;let i=H.get(e.condition)??e.condition,a=e.channel&&e.channel!==`price`,o=a?W(e.price):this.callbacks.formatPrice(e.price);if(r.textContent=`${a&&e.label?`${e.label} `:``}${i} ${o}`,n.appendChild(r),e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,n.appendChild(t)}if(e.triggered){let e=document.createElement(`span`);e.className=`tcw-alerts-badge`,e.textContent=`triggered`,r.appendChild(e)}let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-alerts-del`,s.setAttribute(`aria-label`,`Delete alert`),s.innerHTML=_(`trash`,14),s.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),t.appendChild(n),t.appendChild(s),this.listEl.appendChild(t)}}},K=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-tree-header`;let r=document.createElement(`span`);r.textContent=`Objects`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-tree-close`,i.setAttribute(`aria-label`,`Close objects`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n),this.indicatorsEl=this.makeSection(`Indicators`),this.drawingsEl=this.makeSection(`Drawings`),this.callbacks.onAddCompare&&(this.compareEl=this.makeSection(`Compare`,()=>this.callbacks.onAddCompare?.())),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),t){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-tree-add`,n.setAttribute(`aria-label`,`Add ${e.toLowerCase()}`),n.title=`Add ${e.toLowerCase()}`,n.innerHTML=_(`plus`,13),n.addEventListener(`click`,t),r.appendChild(n)}let a=document.createElement(`div`);return a.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(a),this.el.appendChild(n),a}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(`No indicators`));return}for(let t of e){let e=this.row(t.name);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?`Hide`:`Show`,``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator&&n.appendChild(this.iconButton(`settings`,`Indicator settings`,``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId))),n.appendChild(this.iconButton(`trash`,`Remove indicator`,`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.drawingsEl.replaceChildren(),e.length===0){this.drawingsEl.appendChild(this.emptyRow(`No drawings`));return}for(let t of e){let e=this.row(t.label);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?`Hide`:`Show`,``,()=>this.callbacks.onToggleDrawingVisible(t.id,!t.visible))),n.appendChild(this.iconButton(t.locked?`lock`:`unlock`,t.locked?`Unlock`:`Lock`,t.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(t.id,!t.locked))),n.appendChild(this.iconButton(`trash`,`Remove drawing`,`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(t.id))),e.appendChild(n),this.drawingsEl.appendChild(e)}}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(`No comparisons`));return}for(let t of e){let e=this.row(t.label),n=document.createElement(`span`);n.className=`tcw-tree-dot`,n.style.background=t.color,e.insertBefore(n,e.firstChild),this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,`Remove comparison`,`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(t.id))),this.compareEl.appendChild(e)}}}row(e){let t=document.createElement(`div`);t.className=`tcw-tree-row`;let n=document.createElement(`span`);return n.className=`tcw-tree-name`,n.textContent=e,n.title=e,t.appendChild(n),t}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn ${n}`.trim(),i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=_(e,14),i.addEventListener(`click`,r),i}},q={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`};function se(e){return q[e]??e}var ce=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function le(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}var ue=class{backdrop;modal;bodyEl;titleEl;callbacks;target=null;draft={};constructor(e,t){this.callbacks=t,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0,this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&this.close()}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow`;let n=document.createElement(`div`);n.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.textContent=`Indicator`;let r=document.createElement(`button`);r.className=`tcw-modal-close`,r.setAttribute(`aria-label`,`Close`),r.innerHTML=_(`x`,16),r.addEventListener(`click`,()=>this.close()),n.appendChild(this.titleEl),n.appendChild(r),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`;let i=document.createElement(`div`);i.className=`tcw-modal-footer`;let a=document.createElement(`button`);a.className=`tcw-reset-link`,a.textContent=`Reset to defaults`,a.addEventListener(`click`,()=>this.resetDefaults());let o=document.createElement(`button`);o.className=`tcw-done-btn`,o.textContent=`Done`,o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.modal.appendChild(n),this.modal.appendChild(this.bodyEl),this.modal.appendChild(i),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.target=e,this.titleEl.textContent=`${e.name} settings`,this.draft={},this.renderFields(),this.backdrop.hidden=!1}close(){this.backdrop.hidden=!0,this.target=null,this.callbacks.onClose()}isOpen(){return!this.backdrop.hidden}destroy(){this.backdrop.remove()}currentValue(e){if(e in this.draft)return this.draft[e];let t=this.target?.params[e],n=this.target?.defaults[e];return t??n}setValue(e,t){this.target&&(this.draft[e]=t,this.callbacks.onApply(this.target.instanceId,{...this.draft}))}resetDefaults(){if(!this.target)return;let e={};for(let[t,n]of Object.entries(this.target.defaults))e[t]=n;this.draft=e,this.callbacks.onApply(this.target.instanceId,{...e}),this.renderFields()}renderFields(){if(this.bodyEl.replaceChildren(),!this.target)return;let e=document.createElement(`div`);e.className=`tcw-settings-section`;let t=Object.keys(this.target.defaults);if(t.length===0){let t=document.createElement(`div`);t.className=`tcw-settings-label`,t.textContent=`This indicator has no adjustable parameters.`,e.appendChild(t)}for(let n of t)e.appendChild(this.fieldRow(n));this.bodyEl.appendChild(e)}fieldRow(e){let t=document.createElement(`div`);t.className=`tcw-settings-row`;let n=document.createElement(`span`);n.className=`tcw-settings-label`,n.textContent=le(e),t.appendChild(n);let r=this.currentValue(e),i=typeof(this.target?.defaults[e]??r);return i===`boolean`?t.appendChild(this.toggleControl(e,!!r)):i===`number`?t.appendChild(this.numberControl(e,Number(r))):typeof r==`string`&&ce.test(r)?t.appendChild(this.colorControl(e,r)):t.appendChild(this.textControl(e,String(r??``))),t}toggleControl(e,t){let n=document.createElement(`button`);return n.className=`tcw-toggle${t?` tcw-on`:``}`,n.type=`button`,n.addEventListener(`click`,()=>{let t=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,t),this.setValue(e,t)}),n}numberControl(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.value=String(t),n.step=Number.isInteger(t)?`1`:`0.1`,n.addEventListener(`change`,()=>{let t=Number(n.value);Number.isFinite(t)&&this.setValue(e,t)}),n}colorControl(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=t.length===4?de(t):t,n.addEventListener(`input`,()=>this.setValue(e,n.value)),n}textControl(e,t){let n=document.createElement(`input`);return n.type=`text`,n.className=`tcw-indi-input`,n.value=t,n.addEventListener(`change`,()=>this.setValue(e,n.value)),n}};function de(e){let t=e[1],n=e[2],r=e[3];return`#${t}${t}${n}${n}${r}${r}`}function fe(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var pe=[`color`,`lineWidth`,`lineStyle`,`fillColor`,`fillOpacity`,`fontSize`];function J(e){if(!e||typeof e!=`object`)return{};let t={},n=e;for(let e of pe)n[e]!==void 0&&(t[e]=n[e]);return t}var me=class{templates=[];constructor(e=`tcw:draw-templates`,t=fe()){this.storageKey=e,this.storage=t,this.load()}list(){return this.templates.map(e=>({name:e.name,style:{...e.style}}))}get(e){let t=this.templates.find(t=>t.name===e);return t?{name:t.name,style:{...t.style}}:null}save(e,t){let n=e.trim();if(!n)return;let r=J(t);this.templates=this.templates.filter(e=>e.name!==n),this.templates.push({name:n,style:r}),this.persist()}remove(e){let t=this.templates.filter(t=>t.name!==e);t.length!==this.templates.length&&(this.templates=t,this.persist())}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`).map(e=>({name:e.name,style:J(e.style)}))}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},he=[`#2962ff`,`#089981`,`#f23645`,`#ff9800`,`#ab47bc`,`#26c6da`,`#ffffff`,`#787b86`],ge=[1,2,3,4],_e=[`solid`,`dashed`,`dotted`],ve=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,t,n){this.callbacks=t,this.store=n,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let r=document.createElement(`div`);r.className=`tcw-style-header`;let i=document.createElement(`span`);i.textContent=`Drawing Style`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-close`,a.setAttribute(`aria-label`,`Close`),a.innerHTML=_(`x`,14),a.addEventListener(`click`,()=>this.close()),r.appendChild(i),r.appendChild(a),this.el.appendChild(r),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let o=document.createElement(`div`);o.className=`tcw-style-subhead`,o.textContent=`Templates`,this.el.appendChild(o);let s=document.createElement(`div`);s.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=`Template name`,this.nameInput.className=`tcw-style-name`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-style-savebtn`,c.innerHTML=`${_(`plus`,13)}<span>Save</span>`,c.addEventListener(`click`,()=>this.saveTemplate()),s.appendChild(this.nameInput),s.appendChild(c),this.el.appendChild(s),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of he){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of ge){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of _e){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=`No saved templates`,this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let i=document.createElement(`span`);i.textContent=t.name,n.appendChild(r),n.appendChild(i),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-tdel`,a.setAttribute(`aria-label`,`Delete template`),a.innerHTML=_(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}};function ye(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var be=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ye()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}},xe=class{el;labelEl;callbacks;visible=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let n=document.createElement(`span`);n.className=`tcw-bracket-hint`,n.textContent=`drag lines to adjust`,this.el.appendChild(n);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-bracket-cancel`,r.innerHTML=`${_(`x`,14)}<span>Cancel</span>`,r.addEventListener(`click`,()=>this.callbacks.onCancel());let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-bracket-confirm`,i.innerHTML=`${_(`check`,14)}<span>Place</span>`,i.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(r),this.el.appendChild(i),e.appendChild(this.el)}show(e){this.visible=!0,this.labelEl.textContent=e===`buy`?`Long bracket`:`Short bracket`,this.labelEl.dataset.side=e,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Se=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function Ce(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o}}var we=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,t,n=12){this.callbacks=t,this.levels=n,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,this.el.hidden=!0;let r=document.createElement(`div`);r.className=`tcw-ladder-header`;let i=document.createElement(`span`);i.textContent=`Depth Ladder`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-close`,a.setAttribute(`aria-label`,`Close`),a.innerHTML=_(`x`,14),a.addEventListener(`click`,()=>this.close()),r.appendChild(i),r.appendChild(a),this.el.appendChild(r);let o=document.createElement(`div`);o.className=`tcw-ladder-cols`,o.innerHTML=`<span>Bid</span><span>Price</span><span>Ask</span>`,this.el.appendChild(o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}setData(e){if(!e){this.renderEmpty();return}this.render(Ce(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=`No order-book data`,this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let t=e.maxVolume>0?1/e.maxVolume:0;for(let n of e.rows){let e=n.askVolume>0,r=document.createElement(`div`);r.className=`tcw-ladder-row`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ladder-cell tcw-ladder-bid`,n.bidVolume>0?(i.textContent=Y(n.bidVolume),i.style.setProperty(`--w`,`${(n.bidVolume*t*100).toFixed(1)}%`),i.title=`Sell @ ${this.callbacks.formatPrice(n.price)}`,i.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,n.price))):i.disabled=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,a.textContent=this.callbacks.formatPrice(n.price);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-ladder-cell tcw-ladder-ask`,n.askVolume>0?(o.textContent=Y(n.askVolume),o.style.setProperty(`--w`,`${(n.askVolume*t*100).toFixed(1)}%`),o.title=`Buy @ ${this.callbacks.formatPrice(n.price)}`,o.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,n.price))):o.disabled=!0,r.appendChild(i),r.appendChild(a),r.appendChild(o),this.bodyEl.appendChild(r)}}};function Y(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var Te=class{el;bodyEl;callbacks;open=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-datawin-header`;let r=document.createElement(`span`);r.textContent=`Data Window`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-datawin-close`,i.setAttribute(`aria-label`,`Close`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=`Hover the chart`,this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(`Open`,t(n.open))),this.bodyEl.appendChild(this.row(`High`,t(n.high))),this.bodyEl.appendChild(this.row(`Low`,t(n.low))),this.bodyEl.appendChild(this.row(`Close`,t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``;this.bodyEl.appendChild(this.row(`Change`,`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(`Volume`,De(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,Ee(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function Ee(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function De(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}var X=globalThis.Buffer;function Oe(e){if(X)return X.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function ke(e){if(X)return X.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function Z(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ae(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function je(e){return Z(Oe(JSON.stringify(e)))}function Me(e){if(!e)return null;try{let t=ke(Ae(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:n.scaleMode??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[]}}catch{return null}}var Q=`tcw`;function Ne(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(t>0&&e.slice(0,t)===Q)return decodeURIComponent(e.slice(t+1))}return null}function Pe(e,t){let[n]=e.split(`#`);return`${n}#${Q}=${t}`}var $=[`#f7931a`,`#627eea`,`#26a17b`,`#e84142`,`#8247e5`,`#f3ba2f`],Fe=class{chart;state;toolbar=null;sidebar=null;settings=null;statusBar=null;commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;drawingStyle=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;favoritesStore=new be;watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;watchlistInterval=null;replayOriginalData=null;replayPollInterval=null;replaySpeed=5;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;destroyed=!1;options;symbols;settingsState;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;compares=[];constructor(t,n={}){if(this.options=n,this.symbols=n.symbols??l,this.settingsState={...u},n.persistLayouts){let e=n.persistLayouts===!0?{}:n.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let r=this.resolveIsDark(n.theme),d=this.resolveTheme(n.theme);this.state={symbol:n.symbol??this.symbols[0]??`BTCUSDT`,timeframe:n.timeframe??`5m`,chartType:n.chartOptions?.chartType??`candlestick`,isDark:r,activeIndicators:new Map,activeTool:null,magnetEnabled:!0,connectionState:`connecting`,connectionMessage:`Connecting...`},m(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=r?`dark`:`light`,t.appendChild(this.root),n.toolbar!==!1&&(this.toolbar=new y(this.root,{symbols:this.symbols,timeframes:n.timeframes?i.filter(e=>n.timeframes.includes(e.value)):i,chartTypes:n.chartTypes?a.filter(e=>n.chartTypes.includes(e.value)):a,indicators:s,popularIndicatorIds:c},{onSymbolClick:()=>this.handleSymbolClick(),onTimeframe:e=>this.handleTimeframe(e),onChartType:e=>this.handleChartType(e),onAddIndicator:e=>this.handleAddIndicator(e),onRemoveIndicator:e=>this.handleRemoveIndicator(e),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:n.alerts===!1?void 0:()=>this.toggleAlerts(),onToggleObjects:n.objectTree===!1?void 0:()=>this.toggleObjects(),onBracket:n.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:n.trading!==!1&&n.depthLadder?()=>this.depthLadder?.toggle():void 0}));let f=document.createElement(`div`);if(f.className=`tcw-body`,n.drawingTools!==!1&&(n.drawingFavorites&&this.favoritesStore.seedDefaults(n.drawingFavorites),this.sidebar=new ie(f,{drawingToolGroups:o,favorites:this.favoritesStore.list()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:()=>this.handleToggleMagnet(),onToggleFavorite:e=>this.handleToggleFavorite(e),onUndo:()=>this.chart.undo(),onRedo:()=>this.chart.redo(),onClearDrawings:()=>{this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI()},onToggleStyle:()=>this.drawingStyle?.toggle()})),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,f.appendChild(this.chartContainer),n.watchlist&&(this.watchlist=new L(f,this.symbols,{onSelect:e=>{this.setSymbol(e)}}),this.watchlist.setActive(this.state.symbol)),this.root.appendChild(f),this.chart=new e.r(this.chartContainer,{chartType:this.state.chartType,theme:d,autoScale:!0,crosshair:{mode:`magnet`},features:{drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:n.trading!==!1,tradingContextMenu:n.trading!==!1,volume:!0,legend:!0,crosshair:!0,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0},...n.chartOptions}),n.dragDropImport!==!1&&(this.dragDrop=new e.t(this.chartContainer,{onData:(e,t,n)=>{this.setData(e),this.toast(`Loaded ${t.data.length} bars from ${n.name}`+(t.skipped>0?` (${t.skipped} skipped)`:``))},onError:(e,t)=>{this.toast(`${t.name}: ${e.message}`,`error`)}}),this.dragDrop.attach()),n.statusBar!==!1&&(this.statusBar=new b(this.root)),n.settings!==!1&&(this.settings=new oe({onChange:e=>this.applySettings(e),onReset:()=>this.resetSettings(),onClose:()=>{}})),this.symbolSearch=new S({onPick:e=>{this.setSymbol(e)},onClose:()=>{}}),this.hotkeySheet=new k({onClose:()=>{}}),this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;typeof t==`number`&&(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(t),this.replayBar.setState(`paused`))}),this.dataWindow=new Te(this.root,{formatPrice:e=>this.formatAlertPrice(e)}),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}),n.drawingTools!==!1&&(this.drawingStyle=new ve(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},new me)),n.trading!==!1&&(this.bracketBar=new xe(this.root,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}}),this.chart.on(`bracketPlace`,e=>{let t=e.payload;this.bracketBar?.hide(),this.toast(`${t.side===`buy`?`Long`:`Short`} bracket placed · ${t.riskReward.toFixed(2)}R`)}),n.depthLadder&&(this.depthLadder=new we(this.root,{onTrade:(e,t)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:t}),this.toast(`${e===`buy`?`Buy`:`Sell`} limit @ ${this.formatAlertPrice(t)}`)},formatPrice:e=>this.formatAlertPrice(e)})),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),n.alerts!==!1&&(this.alertsPanel=new G(this.root,{onAdd:(e,t,n,r,i)=>{this.chart.addAlert(e,t,n,r,i)},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)}),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),n.alertNotifications&&(this.alertNotifier=new Se(n.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let t=e.payload,n=`Price ${this.formatAlertPrice(t.price)}${t.message?` — ${t.message}`:``}`;this.toast(`🔔 Alert: ${n}`,`info`),this.alertNotifier?.notify(n),this.refreshAlerts()})),n.objectTree!==!1){this.indicatorSettings=new ue(this.root,{onApply:(e,t)=>this.chart.updateIndicator(e,t),onClose:()=>{}}),this.objectTree=new K(this.root,{onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects()},onRemoveDrawing:e=>{this.chart.removeDrawing(e),this.refreshObjects()},onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onAddCompare:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)});let e=()=>{this.objectTree?.isOpen()&&this.refreshObjects()};this.chart.on(`drawingCreate`,e),this.chart.on(`drawingRemove`,e),this.chart.on(`indicatorAdd`,e),this.chart.on(`indicatorRemove`,e)}if(this.commandPalette=new x({onIndicator:e=>this.handleAddIndicator(e),onChartType:e=>this.handleChartType(e),onDrawingTool:e=>this.handleDrawingTool(e),onTimeframe:e=>this.handleTimeframe(e),onAction:e=>this.handleAction(e),onClose:()=>{}}),this.boundGlobalKeydown=e=>{if((e.ctrlKey||e.metaKey)&&e.key===`k`)e.preventDefault(),this.toggleCommandPalette();else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`))e.preventDefault(),this.symbolSearch?.open(this.symbols,this.state.symbol);else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let t=document.activeElement;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))return;e.preventDefault(),this.hotkeySheet?.open()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),n.adapter&&(this.adapter=n.adapter,this.connectStream()),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.updateUI(),n.onReady?.(this.chart),n.shareUrl&&typeof location<`u`){let e=Ne(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e,this.watchlist?.setSymbols(e)}async setSymbol(e){this.flushActiveLayout(),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.watchlist?.setActive(e),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist)return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1];this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let n=this.watchlistSparkBuffer.get(this.state.symbol)??[];n.push(t.close),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(this.state.symbol,n),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:this.sessionRefPrice,sparkline:n.slice()})}async setTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.adapter){await this.connectStream();return}this.options.resampleTimeframes!==!1&&this.applyTimeframeData()}setTheme(e){let t=this.resolveIsDark(e),n=this.resolveTheme(e);this.state={...this.state,isDark:t},this.root.dataset.tcwTheme=t?`dark`:`light`,this.chart.setTheme(n),this.updateUI()}getChart(){return this.chart}destroy(){this.destroyed||(this.destroyed=!0,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.drawingStyle?.destroy(),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.chart.destroy(),this.root.remove(),h())}handleSymbolClick(){this.symbolSearch?.open(this.symbols,this.state.symbol)}handleTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.adapter){this.connectStream();return}if(this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=r(e))}this.applyTimeframeData()}}setData(e){this.baseSeries=e,this.baseTimeframeMs=r(e),this.applyTimeframeData()}applyTimeframeData(){if(!this.baseSeries)return;let e=(0,t.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&e>this.baseTimeframeMs){let e=this.options.weekStartsOn??1;this.chart.setData(n(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries)}toggleAlerts(){this.alertsPanel&&(this.alertsPanel.toggle(),this.alertsPanel.isOpen()&&this.refreshAlerts())}handleToggleFavorite(e){let t=this.favoritesStore.toggle(e);this.sidebar?.setFavorites(this.favoritesStore.list()),this.toast(t?`Pinned to favorites`:`Unpinned`)}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params}));return je({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:this.chart.getScaleMode(),indicators:e,drawings:this.chart.getDrawings()})}async importState(e){let t=Me(e);if(!t)return!1;t.symbol&&t.symbol!==this.state.symbol&&await this.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.state.timeframe&&await this.setTimeframe(t.timeframe),t.chartType&&this.handleChartType(t.chartType),this.chart.setScaleMode(t.scaleMode);for(let[,e]of this.state.activeIndicators)this.chart.removeIndicator(e);let n=new Map;for(let e of t.indicators){let t=this.chart.addIndicator(e.id,e.params);t&&n.set(e.id,t)}return this.state={...this.state,activeIndicators:n},this.chart.setDrawings(t.drawings),this.updateUI(),!0}async copyChartImage(){let e=await this.chart.copyScreenshot();this.toast(e?`Chart image copied`:`Copy failed — image clipboard unavailable`,e?`info`:`error`)}async copyShareLink(){let e=Pe(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.toast(`Share link copied`)}catch{this.toast(`Copy failed — clipboard unavailable`,`error`)}}setDepth(e){this.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.chart.pushDepthSnapshot(e)}startBracket(e){this.chart.startBracket(e)&&this.bracketBar?.show(e)}buildDataWindowModel(){let e=this.chart.getData(),t=this.lastHoverIndex;if(t===null||t<0||t>=e.length)return{ohlc:null,change:0,changePct:0,indicators:[]};let n=e[t],r=t>0?e[t-1].close:n.open,i=n.close-r,a=r===0?0:i/r*100,o=this.chart.getActiveIndicators().map(e=>{let n=this.chart.getIndicatorOutput(e.instanceId)?.series?.[t]??null,r=n?Object.entries(n).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)).map(([e,t])=>({key:e,value:t})):[];return{name:e.descriptor.name,values:r}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changePct:a,indicators:o}}toggleDataWindow(){this.dataWindow&&(this.dataWindow.toggle(),this.dataWindow.isOpen()&&this.dataWindow.render(this.buildDataWindowModel()))}toggleObjects(){this.objectTree&&(this.objectTree.toggle(),this.objectTree.isOpen()&&this.refreshObjects())}openIndicatorSettings(e){if(!this.indicatorSettings)return;let t=this.chart.getActiveIndicators().find(t=>t.instanceId===e);t&&this.indicatorSettings.open({instanceId:e,name:t.descriptor.name,defaults:t.descriptor.defaultConfig,params:t.params})}refreshObjects(){if(!this.objectTree)return;let e=this.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:se(e.type),visible:e.visible,locked:e.locked})),n=this.compares.map(e=>({id:e.id,label:e.symbol,color:e.color}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(!this.adapter){this.toast(`Comparison needs a live data adapter`,`error`);return}let e=new Set([this.state.symbol,...this.compares.map(e=>e.symbol)]),t=this.symbols.filter(t=>!e.has(t));this.symbolSearch?.open(t.length?t:this.symbols,this.state.symbol,e=>{this.addCompareSymbol(e)})}async addCompareSymbol(e){if(!this.adapter||this.compares.some(t=>t.symbol===e))return;let t=$[this.compares.length%$.length],n=`cmp_${e}`;try{let r=await this.adapter.fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(n,e,r,t),this.compares=[...this.compares,{id:n,symbol:e,color:t}],this.refreshObjects(),this.toast(`Comparing ${e}`)}catch(t){this.toast(`${e}: ${t instanceof Error?t.message:`failed to load`}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}async refetchCompares(){if(!this.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);for(let e of this.compares)try{let t=await this.adapter.fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}refreshAlerts(){this.alertsPanel&&(this.alertsPanel.setSources(this.buildAlertSources()),this.alertsPanel.setAlerts(this.chart.getAlerts().map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label}))))}buildAlertSources(){let e=[{channel:`price`,label:`Price`}];for(let t of this.chart.getActiveIndicators()){let n=this.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.chart.getData();if(e===`price`)return t.length>0?t[t.length-1].close:null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=this.chart.getIndicatorOutput(r)?.series?.[t.length-1]?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatAlertPrice(e){let t=Math.abs(e),n=t>=1e3?2:t>=1?4:6,r=this.settingsState.numberLocale||void 0;return e.toLocaleString(r,{minimumFractionDigits:2,maximumFractionDigits:n})}handleChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.updateUI()}handleAddIndicator(e){if(this.state.activeIndicators.has(e)){let t=this.state.activeIndicators.get(e);this.chart.removeIndicator(t);let n=new Map(this.state.activeIndicators);n.delete(e),this.state={...this.state,activeIndicators:n}}else{let t=this.chart.addIndicator(e);if(t){let n=new Map(this.state.activeIndicators);n.set(e,t),this.state={...this.state,activeIndicators:n}}}this.updateUI()}handleRemoveIndicator(e){this.chart.removeIndicator(e);let t=new Map(this.state.activeIndicators);for(let[n,r]of t.entries())if(r===e){t.delete(n);break}this.state={...this.state,activeIndicators:t},this.updateUI()}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of s)e.push({id:t.id,label:t.name,category:`indicator`,active:this.state.activeIndicators.has(t.id)});for(let t of a)e.push({id:t.value,label:t.label,category:`chartType`,active:this.state.chartType===t.value});for(let t of o)for(let n of t.tools)e.push({id:n.value,label:n.label,category:`drawing`,active:this.state.activeTool===n.value});for(let t of i)e.push({id:t.value,label:t.label,category:`timeframe`,active:this.state.timeframe===t.value});return e.push({id:`screenshot`,label:`Screenshot`,category:`action`,shortcut:``},{id:`copyImage`,label:`Copy Chart Image`,category:`action`},{id:`toggleTheme`,label:`Toggle Theme`,category:`action`},{id:`settings`,label:`Settings`,category:`action`},{id:`shareView`,label:`Share View (copy link)`,category:`action`},{id:`autoFib`,label:`Auto Fibonacci (visible swing)`,category:`action`},{id:`dataWindow`,label:`Toggle Data Window`,category:`action`},{id:`clearDrawings`,label:`Clear All Drawings`,category:`action`}),e}handleAction(e){switch(e){case`screenshot`:this.chart.screenshot();break;case`toggleTheme`:this.handleToggleTheme();break;case`settings`:this.openSettings();break;case`copyImage`:this.copyChartImage();break;case`shareView`:this.copyShareLink();break;case`autoFib`:{let e=this.chart.autoFib();this.toast(e?`Auto Fibonacci added`:`No clear swing in view`);break}case`dataWindow`:this.toggleDataWindow();break;case`clearDrawings`:this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI();break}}handleDrawingTool(e){this.state={...this.state,activeTool:e},this.chart.setDrawingTool(e),this.updateUI()}handleCancelDrawing(){this.state={...this.state,activeTool:null},this.chart.setDrawingTool(null),this.updateUI()}handleToggleMagnet(){let e=!this.state.magnetEnabled;this.state={...this.state,magnetEnabled:e},this.chart.setDrawingMagnet(e),this.updateUI()}handleToggleTheme(){let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.chart.setTheme(e?t.DARK_THEME:t.LIGHT_THEME),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:e?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.updateUI()}openSettings(){this.settings?.open(this.settingsState)}toast(e,t=`info`){let n=document.createElement(`div`);n.className=`tcw-toast ${t===`error`?`tcw-toast-error`:``}`,n.textContent=e,this.root.appendChild(n),requestAnimationFrame(()=>n.classList.add(`tcw-toast-in`)),setTimeout(()=>{n.classList.remove(`tcw-toast-in`),n.addEventListener(`transitionend`,()=>n.remove(),{once:!0}),setTimeout(()=>n.remove(),400)},3500)}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.chart.loadStateFromStorage(t)&&this.rebuildActiveIndicatorsMapFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}rebuildActiveIndicatorsMapFromChart(){let e=new Map;for(let t of this.chart.getActiveIndicators())e.set(t.id,t.instanceId);this.state={...this.state,activeIndicators:e},this.updateUI()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.enterReplay()}enterReplay(){let e=this.chart.getData();e.length<2||(this.replayOriginalData=e.slice(),this.replayBar=new j({onPlay:()=>{this.chart.getReplayState()===`paused`?this.chart.replayResume():this.chart.replay({speed:this.replaySpeed,interval:200}),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStop:()=>{this.chart.replayStop(),this.replayBar?.setState(`paused`)},onStepBack:()=>{let e=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,e.current-1)),this.replayBar?.setState(`paused`)},onStepForward:()=>{let e=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.min(e.total-1,e.current+1)),this.replayBar?.setState(`paused`)},onSeek:e=>{this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`)},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onClose:()=>this.exitReplay()}),this.replayBar.mount(this.chartContainer,{total:e.length,speed:this.replaySpeed}),this.chart.replay({speed:this.replaySpeed,interval:200,startIndex:1}),this.chart.replayPause(),this.replayBar.setState(`paused`),this.replayPollInterval=setInterval(()=>{if(!this.replayBar?.isMounted())return;let e=this.chart.getReplayProgress();this.replayBar.setProgress(e.current,e.total);let t=this.chart.getReplayState();t===`stopped`?this.replayBar.setState(`paused`):this.replayBar.setState(t)},150))}exitReplay(){this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.chart.replayStop(),this.replayBar?.unmount(),this.replayBar=null,this.replayOriginalData&&=(this.chart.setData(this.replayOriginalData),null)}applySettings(e){this.settingsState={...this.settingsState,...e},e.gridVisible!==void 0&&this.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.scaleMode===void 0?e.logScale!==void 0&&(this.chart.setLogScale(e.logScale),this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`}):(this.chart.setScaleMode(e.scaleMode),this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`}),e.numberLocale!==void 0&&this.chart.setNumberLocale(e.numberLocale),e.timezone!==void 0&&this.chart.setTimezoneOffset(e.timezone===`local`?null:Number(e.timezone));let t={...this.chart.getTheme()},n=!1;e.candleUpColor!==void 0&&(t.candleUp=e.candleUpColor,n=!0),e.candleDownColor!==void 0&&(t.candleDown=e.candleDownColor,n=!0),e.candleUpWick!==void 0&&(t.candleUpWick=e.candleUpWick,n=!0),e.candleDownWick!==void 0&&(t.candleDownWick=e.candleDownWick,n=!0),e.backgroundColor!==void 0&&(t.background=e.backgroundColor,n=!0),e.gridColor!==void 0&&(t.grid=e.gridColor,n=!0),n&&this.chart.setTheme(t)}resetSettings(){this.settingsState={...u},this.applySettings(this.settingsState)}async connectStream(){if(this.adapter){this.state={...this.state,connectionState:`connecting`,connectionMessage:`Connecting...`},this.updateUI();try{this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500}),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:this.state.isDark?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.applySymbolLayout(this.state.symbol),this.state={...this.state,connectionState:`connected`,connectionMessage:`Live`},this.refetchCompares()}catch(e){this.state={...this.state,connectionState:`error`,connectionMessage:e instanceof Error?e.message:`Connection failed`}}this.updateUI()}}updateUI(){this.toolbar?.update(this.state),this.sidebar?.update(this.state),this.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,symbol:this.state.symbol,timeframe:this.state.timeframe})}resolveIsDark(e){return e===void 0||e===`dark`?!0:e===`light`?!1:typeof e==`object`&&e.background?this.isColorDark(e.background):!0}resolveTheme(e){return e===void 0||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:typeof e==`object`?e:t.DARK_THEME}isColorDark(e){if(e.startsWith(`#`)&&e.length>=7){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return t+n+r<384}return!0}};exports.ChartWidget=Fe;
2387
+ `}wireEvents(){this.root&&(this.scrubber=this.root.querySelector(`input[data-act="seek"]`),this.progressLabel=this.root.querySelector(`[data-tcw="progress"]`),this.playBtn=this.root.querySelector(`button[data-act="play"]`),this.root.querySelector(`[data-act="close"]`)?.addEventListener(`click`,()=>this.callbacks.onClose()),this.root.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),this.root.querySelector(`[data-act="stepForward"]`)?.addEventListener(`click`,()=>this.callbacks.onStepForward()),this.playBtn?.addEventListener(`click`,()=>{this.state===`playing`?this.callbacks.onPause():this.callbacks.onPlay()}),this.scrubber?.addEventListener(`input`,()=>{let e=Number(this.scrubber.value);this.callbacks.onSeek(e)}),this.root.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.speed=t,this.callbacks.onSpeedChange(t)}))}syncUi(){this.playBtn&&(this.playBtn.innerHTML=this.state===`playing`?N():M(),this.playBtn.title=this.state===`playing`?`Pause`:`Play`)}};function M(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7L8 5z"/></svg>`}function N(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>`}function P(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M6 6h2v12H6zM20 6L9 12l11 6V6z"/></svg>`}function F(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M4 6l11 6L4 18V6zM16 6h2v12h-2z"/></svg>`}function I(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M18 6L6 18M6 6l12 12"/></svg>`}var L=class{el;listEl;rowMap=new Map;entries=new Map;active=null;callbacks;constructor(e,t,n){this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`;let r=document.createElement(`div`);r.className=`tcw-watchlist-header`,r.textContent=`Watchlist`,this.el.appendChild(r),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.el.appendChild(this.listEl);for(let e of t)this.entries.set(e,{symbol:e}),this.appendRow(e);e.appendChild(this.el)}setSymbols(e){let t=new Set(e);for(let e of this.rowMap.keys())t.has(e)||this.removeRow(e);for(let t of e)this.rowMap.has(t)||(this.entries.set(t,this.entries.get(t)??{symbol:t}),this.appendRow(t))}setActive(e){if(this.active===e)return;this.active&&this.rowMap.has(this.active)&&this.rowMap.get(this.active).row.classList.remove(`tcw-watchlist-active`),this.active=e;let t=this.rowMap.get(e);t&&t.row.classList.add(`tcw-watchlist-active`)}setEntry(e,t){let n={...this.entries.get(e)??{symbol:e},...t};this.entries.set(e,n),this.renderRow(e)}destroy(){this.el.remove(),this.rowMap.clear(),this.entries.clear()}appendRow(e){let t=document.createElement(`div`);t.className=`tcw-watchlist-row`,t.tabIndex=0;let n=document.createElement(`div`);n.className=`tcw-watchlist-symbol`,n.textContent=R(e);let r=document.createElement(`canvas`);r.className=`tcw-watchlist-spark`,r.width=64,r.height=22;let i=document.createElement(`div`);i.className=`tcw-watchlist-stats`;let a=document.createElement(`span`);a.className=`tcw-watchlist-price`,a.textContent=`—`;let o=document.createElement(`span`);o.className=`tcw-watchlist-change`,o.textContent=``,i.appendChild(a),i.appendChild(o),t.appendChild(n),t.appendChild(r),t.appendChild(i),t.addEventListener(`click`,()=>this.callbacks.onSelect(e)),t.addEventListener(`keydown`,t=>{(t.key===`Enter`||t.key===` `)&&(t.preventDefault(),this.callbacks.onSelect(e))}),this.listEl.appendChild(t),this.rowMap.set(e,{row:t,priceEl:a,changeEl:o,sparkCanvas:r}),e===this.active&&t.classList.add(`tcw-watchlist-active`)}removeRow(e){let t=this.rowMap.get(e);t&&(t.row.remove(),this.rowMap.delete(e))}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=z(n.lastPrice)),n.lastPrice!==void 0&&n.refPrice!==void 0&&n.refPrice!==0){let e=n.lastPrice-n.refPrice,r=e/n.refPrice*100,i=e>=0?`+`:``;t.changeEl.textContent=`${i}${r.toFixed(2)}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&B(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}};function R(e){for(let t of[`USDT`,`USD`,`BTC`,`ETH`,`EUR`])if(e.length>t.length&&e.endsWith(t))return e.slice(0,-t.length)+`/`+t;return e}function z(e){if(e===0)return`0`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function B(e,t,n){let r=e.getContext(`2d`);if(!r)return;let i=window.devicePixelRatio||1;e.width!==e.clientWidth*i&&(e.width=(e.clientWidth||64)*i,e.height=(e.clientHeight||22)*i);let a=e.width,o=e.height,s=1/0,c=-1/0;for(let e of t)e<s&&(s=e),e>c&&(c=e);let l=Math.max(c-s,1e-9),u=t[t.length-1]>=n?`#26a17b`:`#f23645`;r.clearRect(0,0,a,o),r.lineWidth=1.4*i,r.strokeStyle=u,r.beginPath();let d=a/(t.length-1);for(let e=0;e<t.length;e++){let n=e*d,i=o-(t[e]-s)/l*(o-4)-2;e===0?r.moveTo(n,i):r.lineTo(n,i)}r.stroke()}var V=[{value:`crossing`,label:`Crossing`},{value:`crossingUp`,label:`Crossing up`},{value:`crossingDown`,label:`Crossing down`},{value:`greaterThan`,label:`Greater than`},{value:`lessThan`,label:`Less than`}],H=new Map(V.map(e=>[e.value,e.label]));function U(e){return Math.round(e*1e6)/1e6}function W(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var G=class{el;listEl;priceInput;conditionSelect;sourceSelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources=[{channel:`price`,label:`Price`}];constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-alerts-header`;let r=document.createElement(`span`);r.textContent=`Price Alerts`;let i=document.createElement(`button`);i.className=`tcw-alerts-close`,i.type=`button`,i.setAttribute(`aria-label`,`Close alerts`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n);let a=document.createElement(`form`);a.className=`tcw-alerts-form`,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.addEventListener(`change`,()=>this.prefillPrice()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=`Value`,this.priceInput.className=`tcw-alerts-price`,this.priceInput.required=!0,this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`;for(let e of V){let t=document.createElement(`option`);t.value=e.value,t.textContent=e.label,this.conditionSelect.appendChild(t)}this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=`Note (optional)`,this.messageInput.className=`tcw-alerts-message`;let o=document.createElement(`button`);o.type=`submit`,o.className=`tcw-alerts-add`,o.innerHTML=`${_(`plus`,14)}<span>Add alert</span>`,a.appendChild(this.sourceSelect),a.appendChild(this.priceInput),a.appendChild(this.conditionSelect),a.appendChild(this.messageInput),a.appendChild(o),a.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(a),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-alerts-list`,this.el.appendChild(this.listEl),this.emptyEl=document.createElement(`div`),this.emptyEl.className=`tcw-alerts-empty`,this.emptyEl.textContent=`No alerts yet. Add one above, or right-click the chart.`,this.listEl.appendChild(this.emptyEl),this.renderSources(),e.appendChild(this.el)}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:`Price`}],this.renderSources()}renderSources(){let e=this.sourceSelect.value||`price`;this.sourceSelect.replaceChildren();for(let e of this.sources){let t=document.createElement(`option`);t.value=e.channel,t.textContent=e.label,this.sourceSelect.appendChild(t)}this.sourceSelect.value=this.sources.some(t=>t.channel===e)?e:`price`}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.priceInput.value===``&&this.prefillPrice()}prefillPrice(){let e=this.callbacks.getChannelValue(this.sourceSelect.value||`price`);this.priceInput.value=e===null?``:String(U(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=Number(this.priceInput.value);if(!Number.isFinite(e))return;let t=this.conditionSelect.value,n=this.messageInput.value.trim()||void 0,r=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===r)?.label??`Price`;this.callbacks.onAdd(e,t,n,r,i),this.messageInput.value=``,this.prefillPrice()}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let t=document.createElement(`div`);t.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``);let n=document.createElement(`div`);n.className=`tcw-alerts-info`;let r=document.createElement(`div`);r.className=`tcw-alerts-row-main`;let i=H.get(e.condition)??e.condition,a=e.channel&&e.channel!==`price`,o=a?W(e.price):this.callbacks.formatPrice(e.price);if(r.textContent=`${a&&e.label?`${e.label} `:``}${i} ${o}`,n.appendChild(r),e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,n.appendChild(t)}if(e.triggered){let e=document.createElement(`span`);e.className=`tcw-alerts-badge`,e.textContent=`triggered`,r.appendChild(e)}let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-alerts-del`,s.setAttribute(`aria-label`,`Delete alert`),s.innerHTML=_(`trash`,14),s.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),t.appendChild(n),t.appendChild(s),this.listEl.appendChild(t)}}},K=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-tree-header`;let r=document.createElement(`span`);r.textContent=`Objects`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-tree-close`,i.setAttribute(`aria-label`,`Close objects`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n),this.indicatorsEl=this.makeSection(`Indicators`),this.drawingsEl=this.makeSection(`Drawings`),this.callbacks.onAddCompare&&(this.compareEl=this.makeSection(`Compare`,()=>this.callbacks.onAddCompare?.())),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}setObjects(e,t,n=[]){this.renderIndicators(e),this.renderDrawings(t),this.renderCompares(n)}makeSection(e,t){let n=document.createElement(`div`);n.className=`tcw-tree-section`;let r=document.createElement(`div`);r.className=`tcw-tree-section-head`;let i=document.createElement(`span`);if(i.textContent=e,r.appendChild(i),t){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-tree-add`,n.setAttribute(`aria-label`,`Add ${e.toLowerCase()}`),n.title=`Add ${e.toLowerCase()}`,n.innerHTML=_(`plus`,13),n.addEventListener(`click`,t),r.appendChild(n)}let a=document.createElement(`div`);return a.className=`tcw-tree-list`,n.appendChild(r),n.appendChild(a),this.el.appendChild(n),a}renderIndicators(e){if(this.indicatorsEl.replaceChildren(),e.length===0){this.indicatorsEl.appendChild(this.emptyRow(`No indicators`));return}for(let t of e){let e=this.row(t.name);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);n.className=`tcw-tree-actions`,this.callbacks.onToggleIndicatorVisible&&n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?`Hide`:`Show`,``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator&&n.appendChild(this.iconButton(`settings`,`Indicator settings`,``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId))),n.appendChild(this.iconButton(`trash`,`Remove indicator`,`tcw-tree-del`,()=>this.callbacks.onRemoveIndicator(t.instanceId))),e.appendChild(n),this.indicatorsEl.appendChild(e)}}renderDrawings(e){if(this.drawingsEl.replaceChildren(),e.length===0){this.drawingsEl.appendChild(this.emptyRow(`No drawings`));return}for(let t of e){let e=this.row(t.label);t.visible||e.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(t.visible?`eye`:`eyeOff`,t.visible?`Hide`:`Show`,``,()=>this.callbacks.onToggleDrawingVisible(t.id,!t.visible))),n.appendChild(this.iconButton(t.locked?`lock`:`unlock`,t.locked?`Unlock`:`Lock`,t.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(t.id,!t.locked))),n.appendChild(this.iconButton(`trash`,`Remove drawing`,`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(t.id))),e.appendChild(n),this.drawingsEl.appendChild(e)}}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(`No comparisons`));return}for(let t of e){let e=this.row(t.label),n=document.createElement(`span`);n.className=`tcw-tree-dot`,n.style.background=t.color,e.insertBefore(n,e.firstChild),this.callbacks.onRemoveCompare&&e.appendChild(this.iconButton(`trash`,`Remove comparison`,`tcw-tree-del`,()=>this.callbacks.onRemoveCompare?.(t.id))),this.compareEl.appendChild(e)}}}row(e){let t=document.createElement(`div`);t.className=`tcw-tree-row`;let n=document.createElement(`span`);return n.className=`tcw-tree-name`,n.textContent=e,n.title=e,t.appendChild(n),t}emptyRow(e){let t=document.createElement(`div`);return t.className=`tcw-tree-empty`,t.textContent=e,t}iconButton(e,t,n,r){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn ${n}`.trim(),i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=_(e,14),i.addEventListener(`click`,r),i}},q={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,verticalLine:`Vertical Line`,rectangle:`Rectangle`,ellipse:`Ellipse`,triangle:`Triangle`,arrow:`Arrow`,parallelChannel:`Parallel Channel`,regressionChannel:`Regression Channel`,pitchfork:`Pitchfork`,fibRetracement:`Fib Retracement`,fibExtension:`Fib Extension`,fibTimeZones:`Fib Time Zones`,gannBox:`Gann Box`,gannFan:`Gann Fan`,elliottWave:`Elliott Wave`,priceRange:`Price Range`,dateRange:`Date Range`,measure:`Measure`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`};function se(e){return q[e]??e}var ce=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function le(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}var ue=class{backdrop;modal;bodyEl;titleEl;callbacks;target=null;draft={};constructor(e,t){this.callbacks=t,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0,this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&this.close()}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow`;let n=document.createElement(`div`);n.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.textContent=`Indicator`;let r=document.createElement(`button`);r.className=`tcw-modal-close`,r.setAttribute(`aria-label`,`Close`),r.innerHTML=_(`x`,16),r.addEventListener(`click`,()=>this.close()),n.appendChild(this.titleEl),n.appendChild(r),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`;let i=document.createElement(`div`);i.className=`tcw-modal-footer`;let a=document.createElement(`button`);a.className=`tcw-reset-link`,a.textContent=`Reset to defaults`,a.addEventListener(`click`,()=>this.resetDefaults());let o=document.createElement(`button`);o.className=`tcw-done-btn`,o.textContent=`Done`,o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.modal.appendChild(n),this.modal.appendChild(this.bodyEl),this.modal.appendChild(i),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.target=e,this.titleEl.textContent=`${e.name} settings`,this.draft={},this.renderFields(),this.backdrop.hidden=!1}close(){this.backdrop.hidden=!0,this.target=null,this.callbacks.onClose()}isOpen(){return!this.backdrop.hidden}destroy(){this.backdrop.remove()}currentValue(e){if(e in this.draft)return this.draft[e];let t=this.target?.params[e],n=this.target?.defaults[e];return t??n}setValue(e,t){this.target&&(this.draft[e]=t,this.callbacks.onApply(this.target.instanceId,{...this.draft}))}resetDefaults(){if(!this.target)return;let e={};for(let[t,n]of Object.entries(this.target.defaults))e[t]=n;this.draft=e,this.callbacks.onApply(this.target.instanceId,{...e}),this.renderFields()}renderFields(){if(this.bodyEl.replaceChildren(),!this.target)return;let e=document.createElement(`div`);e.className=`tcw-settings-section`;let t=Object.keys(this.target.defaults);if(t.length===0){let t=document.createElement(`div`);t.className=`tcw-settings-label`,t.textContent=`This indicator has no adjustable parameters.`,e.appendChild(t)}for(let n of t)e.appendChild(this.fieldRow(n));this.bodyEl.appendChild(e)}fieldRow(e){let t=document.createElement(`div`);t.className=`tcw-settings-row`;let n=document.createElement(`span`);n.className=`tcw-settings-label`,n.textContent=le(e),t.appendChild(n);let r=this.currentValue(e),i=typeof(this.target?.defaults[e]??r);return i===`boolean`?t.appendChild(this.toggleControl(e,!!r)):i===`number`?t.appendChild(this.numberControl(e,Number(r))):typeof r==`string`&&ce.test(r)?t.appendChild(this.colorControl(e,r)):t.appendChild(this.textControl(e,String(r??``))),t}toggleControl(e,t){let n=document.createElement(`button`);return n.className=`tcw-toggle${t?` tcw-on`:``}`,n.type=`button`,n.addEventListener(`click`,()=>{let t=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,t),this.setValue(e,t)}),n}numberControl(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.value=String(t),n.step=Number.isInteger(t)?`1`:`0.1`,n.addEventListener(`change`,()=>{let t=Number(n.value);Number.isFinite(t)&&this.setValue(e,t)}),n}colorControl(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=t.length===4?de(t):t,n.addEventListener(`input`,()=>this.setValue(e,n.value)),n}textControl(e,t){let n=document.createElement(`input`);return n.type=`text`,n.className=`tcw-indi-input`,n.value=t,n.addEventListener(`change`,()=>this.setValue(e,n.value)),n}};function de(e){let t=e[1],n=e[2],r=e[3];return`#${t}${t}${n}${n}${r}${r}`}function fe(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var pe=[`color`,`lineWidth`,`lineStyle`,`fillColor`,`fillOpacity`,`fontSize`];function J(e){if(!e||typeof e!=`object`)return{};let t={},n=e;for(let e of pe)n[e]!==void 0&&(t[e]=n[e]);return t}var me=class{templates=[];constructor(e=`tcw:draw-templates`,t=fe()){this.storageKey=e,this.storage=t,this.load()}list(){return this.templates.map(e=>({name:e.name,style:{...e.style}}))}get(e){let t=this.templates.find(t=>t.name===e);return t?{name:t.name,style:{...t.style}}:null}save(e,t){let n=e.trim();if(!n)return;let r=J(t);this.templates=this.templates.filter(e=>e.name!==n),this.templates.push({name:n,style:r}),this.persist()}remove(e){let t=this.templates.filter(t=>t.name!==e);t.length!==this.templates.length&&(this.templates=t,this.persist())}clear(){this.templates=[],this.persist()}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);if(!Array.isArray(t))return;this.templates=t.filter(e=>e&&typeof e.name==`string`).map(e=>({name:e.name,style:J(e.style)}))}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},he=[`#2962ff`,`#089981`,`#f23645`,`#ff9800`,`#ab47bc`,`#26c6da`,`#ffffff`,`#787b86`],ge=[1,2,3,4],_e=[`solid`,`dashed`,`dotted`],ve=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,t,n){this.callbacks=t,this.store=n,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let r=document.createElement(`div`);r.className=`tcw-style-header`;let i=document.createElement(`span`);i.textContent=`Drawing Style`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-close`,a.setAttribute(`aria-label`,`Close`),a.innerHTML=_(`x`,14),a.addEventListener(`click`,()=>this.close()),r.appendChild(i),r.appendChild(a),this.el.appendChild(r),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let o=document.createElement(`div`);o.className=`tcw-style-subhead`,o.textContent=`Templates`,this.el.appendChild(o);let s=document.createElement(`div`);s.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=`Template name`,this.nameInput.className=`tcw-style-name`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-style-savebtn`,c.innerHTML=`${_(`plus`,13)}<span>Save</span>`,c.addEventListener(`click`,()=>this.saveTemplate()),s.appendChild(this.nameInput),s.appendChild(c),this.el.appendChild(s),this.templatesEl=document.createElement(`div`),this.templatesEl.className=`tcw-style-templates`,this.el.appendChild(this.templatesEl),e.appendChild(this.el),this.renderTemplates()}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.syncActiveControls(),this.renderTemplates()}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}colorRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-colors`;for(let t of he){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-swatch`,n.style.background=t,n.dataset.color=t,n.setAttribute(`aria-label`,t),n.addEventListener(`click`,()=>this.applyStyle({color:t})),e.appendChild(n)}let t=document.createElement(`input`);return t.type=`color`,t.className=`tcw-style-picker`,t.addEventListener(`input`,()=>this.applyStyle({color:t.value})),e.appendChild(t),e}widthRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-widths`;for(let t of ge){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-width`,n.dataset.width=String(t);let r=document.createElement(`span`);r.style.height=`${t}px`,n.appendChild(r),n.addEventListener(`click`,()=>this.applyStyle({lineWidth:t})),e.appendChild(n)}return e}lineStyleRow(){let e=document.createElement(`div`);e.className=`tcw-style-row tcw-style-dashes`;for(let t of _e){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-dash`,n.dataset.linestyle=t,n.textContent=t===`solid`?`──`:t===`dashed`?`╌╌`:`┄┄`,n.title=t,n.addEventListener(`click`,()=>this.applyStyle({lineStyle:t})),e.appendChild(n)}return e}applyStyle(e){this.callbacks.onStyleChange(e),this.syncActiveControls()}syncActiveControls(){let e=this.callbacks.getStyle();this.el.querySelectorAll(`.tcw-style-swatch`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.color?.toLowerCase()===e.color?.toLowerCase())}),this.el.querySelectorAll(`.tcw-style-width`).forEach(t=>{t.classList.toggle(`tcw-on`,Number(t.dataset.width)===e.lineWidth)}),this.el.querySelectorAll(`.tcw-style-dash`).forEach(t=>{t.classList.toggle(`tcw-on`,t.dataset.linestyle===e.lineStyle)})}saveTemplate(){let e=this.nameInput.value.trim();e&&(this.store.save(e,this.callbacks.getStyle()),this.nameInput.value=``,this.renderTemplates())}renderTemplates(){this.templatesEl.replaceChildren();let e=this.store.list();if(e.length===0){let e=document.createElement(`div`);e.className=`tcw-style-empty`,e.textContent=`No saved templates`,this.templatesEl.appendChild(e);return}for(let t of e){let e=document.createElement(`div`);e.className=`tcw-style-template`;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-style-apply`;let r=document.createElement(`span`);r.className=`tcw-style-tdot`,r.style.background=t.style.color??`var(--tcw-text-muted)`;let i=document.createElement(`span`);i.textContent=t.name,n.appendChild(r),n.appendChild(i),n.addEventListener(`click`,()=>{this.callbacks.onStyleChange({...t.style}),this.syncActiveControls()});let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-style-tdel`,a.setAttribute(`aria-label`,`Delete template`),a.innerHTML=_(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}};function ye(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var be=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=ye()){this.storageKey=e,this.storage=t,this.load()}list(){return[...this.favorites]}has(e){return this.favorites.includes(e)}add(e){!e||this.favorites.includes(e)||(this.favorites=[...this.favorites,e],this.persist())}remove(e){this.favorites.includes(e)&&(this.favorites=this.favorites.filter(t=>t!==e),this.persist())}toggle(e){return this.has(e)?(this.remove(e),!1):(this.add(e),!0)}seedDefaults(e){this.favorites.length>0||(this.favorites=[...new Set(e.filter(Boolean))],this.persist())}load(){if(this.storage)try{let e=this.storage.getItem(this.storageKey);if(!e)return;let t=JSON.parse(e);Array.isArray(t)&&(this.favorites=[...new Set(t.filter(e=>typeof e==`string`))])}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.favorites))}catch{}}},xe=class{el;labelEl;callbacks;visible=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-bracket-bar`,this.el.hidden=!0,this.labelEl=document.createElement(`span`),this.labelEl.className=`tcw-bracket-label`,this.el.appendChild(this.labelEl);let n=document.createElement(`span`);n.className=`tcw-bracket-hint`,n.textContent=`drag lines to adjust`,this.el.appendChild(n);let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-bracket-cancel`,r.innerHTML=`${_(`x`,14)}<span>Cancel</span>`,r.addEventListener(`click`,()=>this.callbacks.onCancel());let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-bracket-confirm`,i.innerHTML=`${_(`check`,14)}<span>Place</span>`,i.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(r),this.el.appendChild(i),e.appendChild(this.el)}show(e){this.visible=!0,this.labelEl.textContent=e===`buy`?`Long bracket`:`Short bracket`,this.labelEl.dataset.side=e,this.el.hidden=!1}hide(){this.visible=!1,this.el.hidden=!0}isVisible(){return this.visible}destroy(){this.el.remove()}},Se=class{options;audioCtx=null;audioEl=null;permissionAsked=!1;constructor(e={}){if(this.options=e,typeof e.sound==`string`)try{this.audioEl=new Audio(e.sound),this.audioEl.preload=`auto`}catch{this.audioEl=null}e.desktop&&this.ensurePermission()}setOptions(e){this.options={...this.options,...e}}notify(e){this.options.sound&&this.playSound(),this.options.desktop&&this.showDesktop(e)}playSound(){if(this.audioEl){this.audioEl.currentTime=0,this.audioEl.play().catch(()=>{});return}this.beep()}beep(){try{let e=window.AudioContext??window.webkitAudioContext;if(!e)return;this.audioCtx||=new e;let t=this.audioCtx,n=t.currentTime,r=t.createGain();r.gain.setValueAtTime(1e-4,n),r.gain.exponentialRampToValueAtTime(.2,n+.01),r.gain.exponentialRampToValueAtTime(1e-4,n+.35),r.connect(t.destination);let i=t.createOscillator();i.type=`sine`,i.frequency.setValueAtTime(880,n),i.frequency.setValueAtTime(1320,n+.16),i.connect(r),i.start(n),i.stop(n+.36)}catch{}}ensurePermission(){this.permissionAsked||(this.permissionAsked=!0,!(typeof Notification>`u`)&&Notification.permission===`default`&&Notification.requestPermission().catch(()=>{}))}showDesktop(e){if(!(typeof Notification>`u`)){if(Notification.permission!==`granted`){this.ensurePermission();return}try{new Notification(this.options.title??`Price alert`,{body:e})}catch{}}}destroy(){try{this.audioCtx?.close()}catch{}this.audioCtx=null,this.audioEl=null}};function Ce(e,t=12){let n=[...e.asks].sort((e,t)=>e.price-t.price).slice(0,t),r=[...e.bids].sort((e,t)=>t.price-e.price).slice(0,t),i=n.length>0?n[0].price:null,a=r.length>0?r[0].price:null,o=i!==null&&a!==null?(i+a)/2:null,s=new Map,c=e=>{let t=s.get(e);return t||(t={price:e,bidVolume:0,askVolume:0},s.set(e,t)),t};for(let e of n)c(e.price).askVolume+=e.volume;for(let e of r)c(e.price).bidVolume+=e.volume;let l=[...s.values()].sort((e,t)=>t.price-e.price),u=0;for(let e of l)u=Math.max(u,e.bidVolume,e.askVolume);return{rows:l,maxVolume:u,mid:o}}var we=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,t,n=12){this.callbacks=t,this.levels=n,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,this.el.hidden=!0;let r=document.createElement(`div`);r.className=`tcw-ladder-header`;let i=document.createElement(`span`);i.textContent=`Depth Ladder`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-close`,a.setAttribute(`aria-label`,`Close`),a.innerHTML=_(`x`,14),a.addEventListener(`click`,()=>this.close()),r.appendChild(i),r.appendChild(a),this.el.appendChild(r);let o=document.createElement(`div`);o.className=`tcw-ladder-cols`,o.innerHTML=`<span>Bid</span><span>Price</span><span>Ask</span>`,this.el.appendChild(o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-ladder-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}setData(e){if(!e){this.renderEmpty();return}this.render(Ce(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=`No order-book data`,this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let t=e.maxVolume>0?1/e.maxVolume:0;for(let n of e.rows){let e=n.askVolume>0,r=document.createElement(`div`);r.className=`tcw-ladder-row`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-ladder-cell tcw-ladder-bid`,n.bidVolume>0?(i.textContent=Y(n.bidVolume),i.style.setProperty(`--w`,`${(n.bidVolume*t*100).toFixed(1)}%`),i.title=`Sell @ ${this.callbacks.formatPrice(n.price)}`,i.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,n.price))):i.disabled=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,a.textContent=this.callbacks.formatPrice(n.price);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-ladder-cell tcw-ladder-ask`,n.askVolume>0?(o.textContent=Y(n.askVolume),o.style.setProperty(`--w`,`${(n.askVolume*t*100).toFixed(1)}%`),o.title=`Buy @ ${this.callbacks.formatPrice(n.price)}`,o.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,n.price))):o.disabled=!0,r.appendChild(i),r.appendChild(a),r.appendChild(o),this.bodyEl.appendChild(r)}}};function Y(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var Te=class{el;bodyEl;callbacks;open=!1;constructor(e,t){this.callbacks=t,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,this.el.hidden=!0;let n=document.createElement(`div`);n.className=`tcw-datawin-header`;let r=document.createElement(`span`);r.textContent=`Data Window`;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-datawin-close`,i.setAttribute(`aria-label`,`Close`),i.innerHTML=_(`x`,14),i.addEventListener(`click`,()=>this.close()),n.appendChild(r),n.appendChild(i),this.el.appendChild(n),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-datawin-body`,this.el.appendChild(this.bodyEl),e.appendChild(this.el)}isOpen(){return this.open}toggle(){this.open?this.close():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1}close(){this.open=!1,this.el.hidden=!0}destroy(){this.el.remove()}render(e){if(!this.open)return;if(this.bodyEl.replaceChildren(),!e.ohlc){let e=document.createElement(`div`);e.className=`tcw-datawin-empty`,e.textContent=`Hover the chart`,this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(`Open`,t(n.open))),this.bodyEl.appendChild(this.row(`High`,t(n.high))),this.bodyEl.appendChild(this.row(`Low`,t(n.low))),this.bodyEl.appendChild(this.row(`Close`,t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``;this.bodyEl.appendChild(this.row(`Change`,`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(`Volume`,De(n.volume)));for(let t of e.indicators){let e=document.createElement(`div`);e.className=`tcw-datawin-sub`,e.textContent=t.name,this.bodyEl.appendChild(e);for(let e of t.values)this.bodyEl.appendChild(this.row(e.key,Ee(e.value)))}}row(e,t,n=``){let r=document.createElement(`div`);r.className=`tcw-datawin-row`;let i=document.createElement(`span`);i.className=`tcw-datawin-label`,i.textContent=e;let a=document.createElement(`span`);return a.className=`tcw-datawin-value${n?` tcw-${n}`:``}`,a.textContent=t,r.appendChild(i),r.appendChild(a),r}};function Ee(e){if(!Number.isFinite(e))return`—`;let t=Math.abs(e);return t>=1e3?e.toFixed(2):t>=1?e.toFixed(4):e.toPrecision(4)}function De(e){return e>=1e9?(e/1e9).toFixed(2)+`B`:e>=1e6?(e/1e6).toFixed(2)+`M`:e>=1e3?(e/1e3).toFixed(2)+`K`:e.toFixed(0)}var X=globalThis.Buffer;function Oe(e){if(X)return X.from(e,`utf8`).toString(`base64`);let t=new TextEncoder().encode(e),n=``;for(let e of t)n+=String.fromCharCode(e);return btoa(n)}function ke(e){if(X)return X.from(e,`base64`).toString(`utf8`);let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return new TextDecoder().decode(n)}function Z(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function Ae(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function je(e){return Z(Oe(JSON.stringify(e)))}function Me(e){if(!e)return null;try{let t=ke(Ae(e)),n=JSON.parse(t);return!n||n.v!==1||typeof n.symbol!=`string`?null:{v:1,symbol:n.symbol,timeframe:n.timeframe,chartType:n.chartType,scaleMode:n.scaleMode??`regular`,indicators:Array.isArray(n.indicators)?n.indicators:[],drawings:Array.isArray(n.drawings)?n.drawings:[]}}catch{return null}}var Q=`tcw`;function Ne(e){let t=e.startsWith(`#`)?e.slice(1):e;for(let e of t.split(`&`)){let t=e.indexOf(`=`);if(t>0&&e.slice(0,t)===Q)return decodeURIComponent(e.slice(t+1))}return null}function Pe(e,t){let[n]=e.split(`#`);return`${n}#${Q}=${t}`}var $=[`#f7931a`,`#627eea`,`#26a17b`,`#e84142`,`#8247e5`,`#f3ba2f`],Fe=class{chart;state;toolbar=null;sidebar=null;settings=null;statusBar=null;commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;drawingStyle=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;favoritesStore=new be;watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;watchlistInterval=null;replayOriginalData=null;replayPollInterval=null;replaySpeed=5;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;destroyed=!1;options;symbols;settingsState;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;compares=[];constructor(t,n={}){if(this.options=n,this.symbols=n.symbols??l,this.settingsState={...u},n.persistLayouts){let e=n.persistLayouts===!0?{}:n.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let r=this.resolveIsDark(n.theme),d=this.resolveTheme(n.theme);this.state={symbol:n.symbol??this.symbols[0]??`BTCUSDT`,timeframe:n.timeframe??`5m`,chartType:n.chartOptions?.chartType??`candlestick`,isDark:r,activeIndicators:new Map,activeTool:null,magnetEnabled:!0,connectionState:`connecting`,connectionMessage:`Connecting...`},m(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=r?`dark`:`light`,t.appendChild(this.root),n.toolbar!==!1&&(this.toolbar=new y(this.root,{symbols:this.symbols,timeframes:n.timeframes?i.filter(e=>n.timeframes.includes(e.value)):i,chartTypes:n.chartTypes?a.filter(e=>n.chartTypes.includes(e.value)):a,indicators:s,popularIndicatorIds:c},{onSymbolClick:()=>this.handleSymbolClick(),onTimeframe:e=>this.handleTimeframe(e),onChartType:e=>this.handleChartType(e),onAddIndicator:e=>this.handleAddIndicator(e),onRemoveIndicator:e=>this.handleRemoveIndicator(e),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:n.alerts===!1?void 0:()=>this.toggleAlerts(),onToggleObjects:n.objectTree===!1?void 0:()=>this.toggleObjects(),onBracket:n.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:n.trading!==!1&&n.depthLadder?()=>this.depthLadder?.toggle():void 0}));let f=document.createElement(`div`);if(f.className=`tcw-body`,n.drawingTools!==!1&&(n.drawingFavorites&&this.favoritesStore.seedDefaults(n.drawingFavorites),this.sidebar=new ie(f,{drawingToolGroups:o,favorites:this.favoritesStore.list()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:()=>this.handleToggleMagnet(),onToggleFavorite:e=>this.handleToggleFavorite(e),onUndo:()=>this.chart.undo(),onRedo:()=>this.chart.redo(),onClearDrawings:()=>{this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI()},onToggleStyle:()=>this.drawingStyle?.toggle()})),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,f.appendChild(this.chartContainer),n.watchlist&&(this.watchlist=new L(f,this.symbols,{onSelect:e=>{this.setSymbol(e)}}),this.watchlist.setActive(this.state.symbol)),this.root.appendChild(f),this.chart=new e.r(this.chartContainer,{chartType:this.state.chartType,theme:d,autoScale:!0,crosshair:{mode:`magnet`},features:{drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:n.trading!==!1,tradingContextMenu:n.trading!==!1,volume:!0,legend:!0,crosshair:!0,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0},...n.chartOptions}),n.dragDropImport!==!1&&(this.dragDrop=new e.t(this.chartContainer,{onData:(e,t,n)=>{this.setData(e),this.toast(`Loaded ${t.data.length} bars from ${n.name}`+(t.skipped>0?` (${t.skipped} skipped)`:``))},onError:(e,t)=>{this.toast(`${t.name}: ${e.message}`,`error`)}}),this.dragDrop.attach()),n.statusBar!==!1&&(this.statusBar=new b(this.root)),n.settings!==!1&&(this.settings=new oe({onChange:e=>this.applySettings(e),onReset:()=>this.resetSettings(),onClose:()=>{}})),this.symbolSearch=new S({onPick:e=>{this.setSymbol(e)},onClose:()=>{}}),this.hotkeySheet=new k({onClose:()=>{}}),this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;typeof t==`number`&&(this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(t),this.replayBar.setState(`paused`))}),this.dataWindow=new Te(this.root,{formatPrice:e=>this.formatAlertPrice(e)}),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.lastHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.dataWindow?.isOpen()&&this.dataWindow.render(this.buildDataWindowModel())}),n.drawingTools!==!1&&(this.drawingStyle=new ve(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},new me)),n.trading!==!1&&(this.bracketBar=new xe(this.root,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}}),this.chart.on(`bracketPlace`,e=>{let t=e.payload;this.bracketBar?.hide(),this.toast(`${t.side===`buy`?`Long`:`Short`} bracket placed · ${t.riskReward.toFixed(2)}R`)}),n.depthLadder&&(this.depthLadder=new we(this.root,{onTrade:(e,t)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:t}),this.toast(`${e===`buy`?`Buy`:`Sell`} limit @ ${this.formatAlertPrice(t)}`)},formatPrice:e=>this.formatAlertPrice(e)})),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),n.alerts!==!1&&(this.alertsPanel=new G(this.root,{onAdd:(e,t,n,r,i)=>{this.chart.addAlert(e,t,n,r,i)},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)}),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),n.alertNotifications&&(this.alertNotifier=new Se(n.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let t=e.payload,n=`Price ${this.formatAlertPrice(t.price)}${t.message?` — ${t.message}`:``}`;this.toast(`🔔 Alert: ${n}`,`info`),this.alertNotifier?.notify(n),this.refreshAlerts()})),n.objectTree!==!1){this.indicatorSettings=new ue(this.root,{onApply:(e,t)=>this.chart.updateIndicator(e,t),onClose:()=>{}}),this.objectTree=new K(this.root,{onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects()},onRemoveDrawing:e=>{this.chart.removeDrawing(e),this.refreshObjects()},onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onAddCompare:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)});let e=()=>{this.objectTree?.isOpen()&&this.refreshObjects()};this.chart.on(`drawingCreate`,e),this.chart.on(`drawingRemove`,e),this.chart.on(`indicatorAdd`,e),this.chart.on(`indicatorRemove`,e)}if(this.commandPalette=new x({onIndicator:e=>this.handleAddIndicator(e),onChartType:e=>this.handleChartType(e),onDrawingTool:e=>this.handleDrawingTool(e),onTimeframe:e=>this.handleTimeframe(e),onAction:e=>this.handleAction(e),onClose:()=>{}}),this.boundGlobalKeydown=e=>{if((e.ctrlKey||e.metaKey)&&e.key===`k`)e.preventDefault(),this.toggleCommandPalette();else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`))e.preventDefault(),this.symbolSearch?.open(this.symbols,this.state.symbol);else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){let t=document.activeElement;if(t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.isContentEditable))return;e.preventDefault(),this.hotkeySheet?.open()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),n.adapter&&(this.adapter=n.adapter,this.connectStream()),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.updateUI(),n.onReady?.(this.chart),n.shareUrl&&typeof location<`u`){let e=Ne(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e,this.watchlist?.setSymbols(e)}async setSymbol(e){this.flushActiveLayout(),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.watchlist?.setActive(e),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist)return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1];this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let n=this.watchlistSparkBuffer.get(this.state.symbol)??[];n.push(t.close),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(this.state.symbol,n),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:this.sessionRefPrice,sparkline:n.slice()})}async setTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.adapter){await this.connectStream();return}this.options.resampleTimeframes!==!1&&this.applyTimeframeData()}setTheme(e){let t=this.resolveIsDark(e),n=this.resolveTheme(e);this.state={...this.state,isDark:t},this.root.dataset.tcwTheme=t?`dark`:`light`,this.chart.setTheme(n),this.updateUI()}getChart(){return this.chart}destroy(){this.destroyed||(this.destroyed=!0,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.drawingStyle?.destroy(),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.chart.destroy(),this.root.remove(),h())}handleSymbolClick(){this.symbolSearch?.open(this.symbols,this.state.symbol)}handleTimeframe(e){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.adapter){this.connectStream();return}if(this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=r(e))}this.applyTimeframeData()}}setData(e){this.baseSeries=e,this.baseTimeframeMs=r(e),this.applyTimeframeData()}applyTimeframeData(){if(!this.baseSeries)return;let e=(0,t.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&e>this.baseTimeframeMs){let e=this.options.weekStartsOn??1;this.chart.setData(n(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries)}toggleAlerts(){this.alertsPanel&&(this.alertsPanel.toggle(),this.alertsPanel.isOpen()&&this.refreshAlerts())}handleToggleFavorite(e){let t=this.favoritesStore.toggle(e);this.sidebar?.setFavorites(this.favoritesStore.list()),this.toast(t?`Pinned to favorites`:`Unpinned`)}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params}));return je({v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,chartType:this.state.chartType,scaleMode:this.chart.getScaleMode(),indicators:e,drawings:this.chart.getDrawings()})}async importState(e){let t=Me(e);if(!t)return!1;t.symbol&&t.symbol!==this.state.symbol&&await this.setSymbol(t.symbol),t.timeframe&&t.timeframe!==this.state.timeframe&&await this.setTimeframe(t.timeframe),t.chartType&&this.handleChartType(t.chartType),this.chart.setScaleMode(t.scaleMode);for(let[,e]of this.state.activeIndicators)this.chart.removeIndicator(e);let n=new Map;for(let e of t.indicators){let t=this.chart.addIndicator(e.id,e.params);t&&n.set(e.id,t)}return this.state={...this.state,activeIndicators:n},this.chart.setDrawings(t.drawings),this.updateUI(),!0}async copyChartImage(){let e=await this.chart.copyScreenshot();this.toast(e?`Chart image copied`:`Copy failed — image clipboard unavailable`,e?`info`:`error`)}async copyShareLink(){let e=Pe(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.toast(`Share link copied`)}catch{this.toast(`Copy failed — clipboard unavailable`,`error`)}}setDepth(e){this.chart.setDepthData(e),this.depthLadder?.setData(e),e&&this.chart.pushDepthSnapshot(e)}startBracket(e){this.chart.startBracket(e)&&this.bracketBar?.show(e)}buildDataWindowModel(){let e=this.chart.getData(),t=this.lastHoverIndex;if(t===null||t<0||t>=e.length)return{ohlc:null,change:0,changePct:0,indicators:[]};let n=e[t],r=t>0?e[t-1].close:n.open,i=n.close-r,a=r===0?0:i/r*100,o=this.chart.getActiveIndicators().map(e=>{let n=this.chart.getIndicatorOutput(e.instanceId)?.series?.[t]??null,r=n?Object.entries(n).filter(([,e])=>typeof e==`number`&&Number.isFinite(e)).map(([e,t])=>({key:e,value:t})):[];return{name:e.descriptor.name,values:r}}).filter(e=>e.values.length>0);return{ohlc:{open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume},change:i,changePct:a,indicators:o}}toggleDataWindow(){this.dataWindow&&(this.dataWindow.toggle(),this.dataWindow.isOpen()&&this.dataWindow.render(this.buildDataWindowModel()))}toggleObjects(){this.objectTree&&(this.objectTree.toggle(),this.objectTree.isOpen()&&this.refreshObjects())}openIndicatorSettings(e){if(!this.indicatorSettings)return;let t=this.chart.getActiveIndicators().find(t=>t.instanceId===e);t&&this.indicatorSettings.open({instanceId:e,name:t.descriptor.name,defaults:t.descriptor.defaultConfig,params:t.params})}refreshObjects(){if(!this.objectTree)return;let e=this.chart.getActiveIndicators().map(e=>({instanceId:e.instanceId,name:e.descriptor.name,visible:e.visible})),t=this.chart.getDrawings().map(e=>({id:e.id,label:se(e.type),visible:e.visible,locked:e.locked})),n=this.compares.map(e=>({id:e.id,label:e.symbol,color:e.color}));this.objectTree.setObjects(e,t,n)}async handleAddCompare(){if(!this.adapter){this.toast(`Comparison needs a live data adapter`,`error`);return}let e=new Set([this.state.symbol,...this.compares.map(e=>e.symbol)]),t=this.symbols.filter(t=>!e.has(t));this.symbolSearch?.open(t.length?t:this.symbols,this.state.symbol,e=>{this.addCompareSymbol(e)})}async addCompareSymbol(e){if(!this.adapter||this.compares.some(t=>t.symbol===e))return;let t=$[this.compares.length%$.length],n=`cmp_${e}`;try{let r=await this.adapter.fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(n,e,r,t),this.compares=[...this.compares,{id:n,symbol:e,color:t}],this.refreshObjects(),this.toast(`Comparing ${e}`)}catch(t){this.toast(`${e}: ${t instanceof Error?t.message:`failed to load`}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}async refetchCompares(){if(!this.adapter||this.compares.length===0)return;let e=this.compares.filter(e=>e.symbol===this.state.symbol);for(let t of e)this.handleRemoveCompare(t.id);for(let e of this.compares)try{let t=await this.adapter.fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}refreshAlerts(){this.alertsPanel&&(this.alertsPanel.setSources(this.buildAlertSources()),this.alertsPanel.setAlerts(this.chart.getAlerts().map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label}))))}buildAlertSources(){let e=[{channel:`price`,label:`Price`}];for(let t of this.chart.getActiveIndicators()){let n=this.chart.getIndicatorOutput(t.instanceId)?.series,r=n&&n.length>0?n[n.length-1]:null,i=r?Object.keys(r).filter(e=>typeof r[e]==`number`):[];for(let n of i){let r=i.length>1?`${t.descriptor.name} ${n}`:t.descriptor.name;e.push({channel:`${t.instanceId}:${n}`,label:r})}}return e}getAlertChannelValue(e){let t=this.chart.getData();if(e===`price`)return t.length>0?t[t.length-1].close:null;let n=e.indexOf(`:`);if(n<0||t.length===0)return null;let r=e.slice(0,n),i=e.slice(n+1),a=this.chart.getIndicatorOutput(r)?.series?.[t.length-1]?.[i];return typeof a==`number`&&Number.isFinite(a)?a:null}formatAlertPrice(e){let t=Math.abs(e),n=t>=1e3?2:t>=1?4:6,r=this.settingsState.numberLocale||void 0;return e.toLocaleString(r,{minimumFractionDigits:2,maximumFractionDigits:n})}handleChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.updateUI()}handleAddIndicator(e){if(this.state.activeIndicators.has(e)){let t=this.state.activeIndicators.get(e);this.chart.removeIndicator(t);let n=new Map(this.state.activeIndicators);n.delete(e),this.state={...this.state,activeIndicators:n}}else{let t=this.chart.addIndicator(e);if(t){let n=new Map(this.state.activeIndicators);n.set(e,t),this.state={...this.state,activeIndicators:n}}}this.updateUI()}handleRemoveIndicator(e){this.chart.removeIndicator(e);let t=new Map(this.state.activeIndicators);for(let[n,r]of t.entries())if(r===e){t.delete(n);break}this.state={...this.state,activeIndicators:t},this.updateUI()}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of s)e.push({id:t.id,label:t.name,category:`indicator`,active:this.state.activeIndicators.has(t.id)});for(let t of a)e.push({id:t.value,label:t.label,category:`chartType`,active:this.state.chartType===t.value});for(let t of o)for(let n of t.tools)e.push({id:n.value,label:n.label,category:`drawing`,active:this.state.activeTool===n.value});for(let t of i)e.push({id:t.value,label:t.label,category:`timeframe`,active:this.state.timeframe===t.value});return e.push({id:`screenshot`,label:`Screenshot`,category:`action`,shortcut:``},{id:`copyImage`,label:`Copy Chart Image`,category:`action`},{id:`toggleTheme`,label:`Toggle Theme`,category:`action`},{id:`settings`,label:`Settings`,category:`action`},{id:`shareView`,label:`Share View (copy link)`,category:`action`},{id:`autoFib`,label:`Auto Fibonacci (visible swing)`,category:`action`},{id:`dataWindow`,label:`Toggle Data Window`,category:`action`},{id:`clearDrawings`,label:`Clear All Drawings`,category:`action`}),e}handleAction(e){switch(e){case`screenshot`:this.chart.screenshot();break;case`toggleTheme`:this.handleToggleTheme();break;case`settings`:this.openSettings();break;case`copyImage`:this.copyChartImage();break;case`shareView`:this.copyShareLink();break;case`autoFib`:{let e=this.chart.autoFib();this.toast(e?`Auto Fibonacci added`:`No clear swing in view`);break}case`dataWindow`:this.toggleDataWindow();break;case`clearDrawings`:this.chart.clearDrawings(),this.state={...this.state,activeTool:null},this.updateUI();break}}handleDrawingTool(e){this.state={...this.state,activeTool:e},this.chart.setDrawingTool(e),this.updateUI()}handleCancelDrawing(){this.state={...this.state,activeTool:null},this.chart.setDrawingTool(null),this.updateUI()}handleToggleMagnet(){let e=!this.state.magnetEnabled;this.state={...this.state,magnetEnabled:e},this.chart.setDrawingMagnet(e),this.updateUI()}handleToggleTheme(){let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.chart.setTheme(e?t.DARK_THEME:t.LIGHT_THEME),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:e?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.updateUI()}openSettings(){this.settings?.open(this.settingsState)}toast(e,t=`info`){let n=document.createElement(`div`);n.className=`tcw-toast ${t===`error`?`tcw-toast-error`:``}`,n.textContent=e,this.root.appendChild(n),requestAnimationFrame(()=>n.classList.add(`tcw-toast-in`)),setTimeout(()=>{n.classList.remove(`tcw-toast-in`),n.addEventListener(`transitionend`,()=>n.remove(),{once:!0}),setTimeout(()=>n.remove(),400)},3500)}clearSavedLayout(e){if(!this.layoutKeyPrefix)return;let t=e??this.state.symbol;try{localStorage.removeItem(this.layoutKeyPrefix+t)}catch{}}applySymbolLayout(e){if(!this.layoutKeyPrefix)return;let t=this.layoutKeyPrefix+e;this.activeLayoutKey=t;try{this.chart.loadStateFromStorage(t)&&this.rebuildActiveIndicatorsMapFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}rebuildActiveIndicatorsMapFromChart(){let e=new Map;for(let t of this.chart.getActiveIndicators())e.set(t.id,t.instanceId);this.state={...this.state,activeIndicators:e},this.updateUI()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.enterReplay()}enterReplay(){let e=this.chart.getData();e.length<2||(this.replayOriginalData=e.slice(),this.replayBar=new j({onPlay:()=>{this.chart.getReplayState()===`paused`?this.chart.replayResume():this.chart.replayStart({speed:this.replaySpeed,interval:200}),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStop:()=>{this.chart.replayStop(),this.replayBar?.setState(`paused`)},onStepBack:()=>{let e=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,e.current-1)),this.replayBar?.setState(`paused`)},onStepForward:()=>{let e=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.min(e.total-1,e.current+1)),this.replayBar?.setState(`paused`)},onSeek:e=>{this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(e),this.replayBar?.setState(`paused`)},onSpeedChange:e=>{this.replaySpeed=e,this.chart.setReplaySpeed(e)},onClose:()=>this.exitReplay()}),this.replayBar.mount(this.chartContainer,{total:e.length,speed:this.replaySpeed}),this.chart.replayStart({speed:this.replaySpeed,interval:200,startIndex:1}),this.chart.replayPause(),this.replayBar.setState(`paused`),this.replayPollInterval=setInterval(()=>{if(!this.replayBar?.isMounted())return;let e=this.chart.getReplayProgress();this.replayBar.setProgress(e.current,e.total);let t=this.chart.getReplayState();t===`stopped`?this.replayBar.setState(`paused`):this.replayBar.setState(t)},150))}exitReplay(){this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.chart.replayStop(),this.replayBar?.unmount(),this.replayBar=null,this.replayOriginalData&&=(this.chart.setData(this.replayOriginalData),null)}applySettings(e){this.settingsState={...this.settingsState,...e},e.gridVisible!==void 0&&this.chart.setGridVisible(e.gridVisible),e.volumeVisible!==void 0&&this.chart.setVolumeVisible(e.volumeVisible),e.volumeProfileVisible!==void 0&&this.chart.setVolumeProfileVisible(e.volumeProfileVisible),e.marketProfileVisible!==void 0&&this.chart.setMarketProfileVisible(e.marketProfileVisible),e.marketProfileSplit!==void 0&&this.chart.setMarketProfileConfig({splitBySession:e.marketProfileSplit}),e.marketProfileLetters!==void 0&&this.chart.setMarketProfileConfig({letters:e.marketProfileLetters}),e.marketProfileBuckets!==void 0&&this.chart.setMarketProfileConfig({buckets:e.marketProfileBuckets}),e.marketProfileOpacity!==void 0&&this.chart.setMarketProfileConfig({opacity:e.marketProfileOpacity}),e.depthHeatmapVisible!==void 0&&this.chart.setDepthHeatmapVisible(e.depthHeatmapVisible),e.depthHeatmapOpacity!==void 0&&this.chart.setDepthHeatmapConfig({opacity:e.depthHeatmapOpacity}),e.sessionShadingVisible!==void 0&&this.chart.setSessionShadingVisible(e.sessionShadingVisible),e.pivotMarkersVisible!==void 0&&this.chart.setPivotMarkersVisible(e.pivotMarkersVisible),e.pivotStrength!==void 0&&this.chart.setPivotMarkersConfig({left:e.pivotStrength,right:e.pivotStrength}),e.pivotStructureLabels!==void 0&&this.chart.setPivotMarkersConfig({structureLabels:e.pivotStructureLabels}),e.periodLevelsVisible!==void 0&&this.chart.setPeriodLevelsVisible(e.periodLevelsVisible),e.periodLevelsPeriod!==void 0&&this.chart.setPeriodLevelsPeriod(e.periodLevelsPeriod),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.scaleMode===void 0?e.logScale!==void 0&&(this.chart.setLogScale(e.logScale),this.settingsState={...this.settingsState,scaleMode:e.logScale?`logarithmic`:`regular`}):(this.chart.setScaleMode(e.scaleMode),this.settingsState={...this.settingsState,logScale:e.scaleMode===`logarithmic`}),e.numberLocale!==void 0&&this.chart.setNumberLocale(e.numberLocale),e.timezone!==void 0&&this.chart.setTimezoneOffset(e.timezone===`local`?null:Number(e.timezone));let t={...this.chart.getTheme()},n=!1;e.candleUpColor!==void 0&&(t.candleUp=e.candleUpColor,n=!0),e.candleDownColor!==void 0&&(t.candleDown=e.candleDownColor,n=!0),e.candleUpWick!==void 0&&(t.candleUpWick=e.candleUpWick,n=!0),e.candleDownWick!==void 0&&(t.candleDownWick=e.candleDownWick,n=!0),e.backgroundColor!==void 0&&(t.background=e.backgroundColor,n=!0),e.gridColor!==void 0&&(t.grid=e.gridColor,n=!0),n&&this.chart.setTheme(t)}resetSettings(){this.settingsState={...u},this.applySettings(this.settingsState)}async connectStream(){if(this.adapter){this.state={...this.state,connectionState:`connecting`,connectionMessage:`Connecting...`},this.updateUI();try{this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500}),this.chart.setWatermark(this.state.symbol.replace(`USDT`,` / USDT`),{fontSize:48,color:this.state.isDark?`rgba(255,255,255,0.03)`:`rgba(0,0,0,0.03)`}),this.applySymbolLayout(this.state.symbol),this.state={...this.state,connectionState:`connected`,connectionMessage:`Live`},this.refetchCompares()}catch(e){this.state={...this.state,connectionState:`error`,connectionMessage:e instanceof Error?e.message:`Connection failed`}}this.updateUI()}}updateUI(){this.toolbar?.update(this.state),this.sidebar?.update(this.state),this.statusBar?.update({connectionState:this.state.connectionState,message:this.state.connectionMessage,symbol:this.state.symbol,timeframe:this.state.timeframe})}resolveIsDark(e){return e===void 0||e===`dark`?!0:e===`light`?!1:typeof e==`object`&&e.background?this.isColorDark(e.background):!0}resolveTheme(e){return e===void 0||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:typeof e==`object`?e:t.DARK_THEME}isColorDark(e){if(e.startsWith(`#`)&&e.length>=7){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),r=parseInt(e.slice(5,7),16);return t+n+r<384}return!0}};exports.ChartWidget=Fe;
2373
2388
  //# sourceMappingURL=index.cjs.map