@tradecanvas/chart 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +16 -14
- package/dist/Chart.d.ts +11 -3
- package/dist/Chart.d.ts.map +1 -1
- package/dist/LayoutSession-1uhJw0L7.cjs +2 -0
- package/dist/LayoutSession-1uhJw0L7.cjs.map +1 -0
- package/dist/{LayoutSession-BF1iuUrs.js → LayoutSession-2yRujs2S.js} +295 -281
- package/dist/LayoutSession-2yRujs2S.js.map +1 -0
- package/dist/charts/ChartTypeStrategy.d.ts +2 -0
- package/dist/charts/ChartTypeStrategy.d.ts.map +1 -1
- package/dist/{i18n-CiQ8EDVs.js → i18n-BU-BoBDZ.js} +6 -2
- package/dist/i18n-BU-BoBDZ.js.map +1 -0
- package/dist/{i18n-WsLA9SmD.cjs → i18n-DkzAxytR.cjs} +2 -2
- package/dist/i18n-DkzAxytR.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +22 -22
- package/dist/index.js.map +1 -1
- package/dist/widget/ChartWidget.d.ts +5 -3
- package/dist/widget/ChartWidget.d.ts.map +1 -1
- package/dist/widget/i18n.d.ts.map +1 -1
- package/dist/widget/index.cjs +2 -2
- package/dist/widget/index.cjs.map +1 -1
- package/dist/widget/index.js +97 -3
- package/dist/widget/index.js.map +1 -1
- package/dist/widget/locales/ar.d.ts.map +1 -1
- package/dist/widget/locales/cs.d.ts +4 -0
- package/dist/widget/locales/cs.d.ts.map +1 -0
- package/dist/widget/locales/da.d.ts +4 -0
- package/dist/widget/locales/da.d.ts.map +1 -0
- package/dist/widget/locales/de.d.ts.map +1 -1
- package/dist/widget/locales/el.d.ts +4 -0
- package/dist/widget/locales/el.d.ts.map +1 -0
- package/dist/widget/locales/en.d.ts +2 -0
- package/dist/widget/locales/en.d.ts.map +1 -1
- package/dist/widget/locales/es.d.ts.map +1 -1
- package/dist/widget/locales/et.d.ts +4 -0
- package/dist/widget/locales/et.d.ts.map +1 -0
- package/dist/widget/locales/fa.d.ts +4 -0
- package/dist/widget/locales/fa.d.ts.map +1 -0
- package/dist/widget/locales/fr.d.ts.map +1 -1
- package/dist/widget/locales/he.d.ts.map +1 -1
- package/dist/widget/locales/hu.d.ts +4 -0
- package/dist/widget/locales/hu.d.ts.map +1 -0
- package/dist/widget/locales/id.d.ts.map +1 -1
- package/dist/widget/locales/index.cjs +1 -1
- package/dist/widget/locales/index.cjs.map +1 -1
- package/dist/widget/locales/index.d.ts +15 -1
- package/dist/widget/locales/index.d.ts.map +1 -1
- package/dist/widget/locales/index.js +10127 -5
- package/dist/widget/locales/index.js.map +1 -1
- package/dist/widget/locales/it.d.ts +4 -0
- package/dist/widget/locales/it.d.ts.map +1 -0
- package/dist/widget/locales/ja.d.ts.map +1 -1
- package/dist/widget/locales/ko.d.ts.map +1 -1
- package/dist/widget/locales/ms.d.ts +4 -0
- package/dist/widget/locales/ms.d.ts.map +1 -0
- package/dist/widget/locales/nb.d.ts +4 -0
- package/dist/widget/locales/nb.d.ts.map +1 -0
- package/dist/widget/locales/nl.d.ts +4 -0
- package/dist/widget/locales/nl.d.ts.map +1 -0
- package/dist/widget/locales/pl.d.ts +4 -0
- package/dist/widget/locales/pl.d.ts.map +1 -0
- package/dist/widget/locales/pt.d.ts.map +1 -1
- package/dist/widget/locales/ro.d.ts +4 -0
- package/dist/widget/locales/ro.d.ts.map +1 -0
- package/dist/widget/locales/ru.d.ts.map +1 -1
- package/dist/widget/locales/sk.d.ts +4 -0
- package/dist/widget/locales/sk.d.ts.map +1 -0
- package/dist/widget/locales/sv.d.ts +4 -0
- package/dist/widget/locales/sv.d.ts.map +1 -0
- package/dist/widget/locales/th.d.ts.map +1 -1
- package/dist/widget/locales/tr.d.ts.map +1 -1
- package/dist/widget/locales/vi.d.ts.map +1 -1
- package/dist/widget/locales/zh.d.ts.map +1 -1
- package/dist/widget/locales/zhHant.d.ts.map +1 -1
- package/dist/widget/widgetConfig.d.ts.map +1 -1
- package/package.json +3 -3
- package/dist/LayoutSession-BF1iuUrs.js.map +0 -1
- package/dist/LayoutSession-BRw64EVI.cjs +0 -2
- package/dist/LayoutSession-BRw64EVI.cjs.map +0 -1
- package/dist/i18n-CiQ8EDVs.js.map +0 -1
- package/dist/i18n-WsLA9SmD.cjs.map +0 -1
package/dist/widget/index.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-BRw64EVI.cjs`),t=require(`../i18n-WsLA9SmD.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,n.timeframeBucketStart)(r.time,t,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 a(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 o=[{zone:`Pacific/Honolulu`,city:`Honolulu`},{zone:`America/Los_Angeles`,city:`Los Angeles`},{zone:`America/Denver`,city:`Denver`},{zone:`America/Chicago`,city:`Chicago`},{zone:`America/New_York`,city:`New York`},{zone:`America/Toronto`,city:`Toronto`},{zone:`America/Sao_Paulo`,city:`São Paulo`},{zone:`UTC`,city:`UTC`},{zone:`Europe/London`,city:`London`},{zone:`Europe/Berlin`,city:`Frankfurt`},{zone:`Europe/Paris`,city:`Paris`},{zone:`Europe/Zurich`,city:`Zurich`},{zone:`Africa/Johannesburg`,city:`Johannesburg`},{zone:`Europe/Istanbul`,city:`Istanbul`},{zone:`Europe/Moscow`,city:`Moscow`},{zone:`Asia/Dubai`,city:`Dubai`},{zone:`Asia/Kolkata`,city:`Mumbai`},{zone:`Asia/Bangkok`,city:`Bangkok`},{zone:`Asia/Ho_Chi_Minh`,city:`Ho Chi Minh City`},{zone:`Asia/Jakarta`,city:`Jakarta`},{zone:`Asia/Singapore`,city:`Singapore`},{zone:`Asia/Hong_Kong`,city:`Hong Kong`},{zone:`Asia/Shanghai`,city:`Shanghai`},{zone:`Asia/Taipei`,city:`Taipei`},{zone:`Asia/Seoul`,city:`Seoul`},{zone:`Asia/Tokyo`,city:`Tokyo`},{zone:`Australia/Sydney`,city:`Sydney`},{zone:`Pacific/Auckland`,city:`Auckland`}];function s(e){return!e||e===`local`?null:e===`exchange`?`exchange`:/^-?\d+$/.test(e)?Number(e):(0,n.isValidTimeZone)(e)?e:null}function c(e){return e===null?`local`:String(e)}function l(e,t,r,i){let a=(0,n.offsetAt)(null,t),c=o.filter(({zone:e})=>(0,n.isValidTimeZone)(e)).map(({zone:e,city:r})=>{let i=(0,n.offsetAt)(e,t);return{value:e,label:e===`UTC`?`UTC`:`(${(0,n.tzLabel)(i)}) ${r}`,offset:i}}),l=s(e);typeof l==`number`&&c.push({value:e,label:(0,n.tzLabel)(l),offset:l}),c.sort((e,t)=>e.offset-t.offset);let u=[{value:`local`,label:`${r} (${(0,n.tzLabel)(a)})`,offset:a}];if(i){let e=(0,n.offsetAt)(i.zone&&(0,n.isValidTimeZone)(i.zone)?i.zone:`UTC`,t);u.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...u,...c]}var u=[{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`},{label:`High-Low`,value:`hiLo`},{label:`Renko`,value:`renko`},{label:`Line Break`,value:`lineBreak`},{label:`Kagi`,value:`kagi`},{label:`Point & Figure`,value:`pointAndFigure`},{label:`Range Bars`,value:`rangeBars`}],d=[{label:`Lines`,section:`lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`},{label:`Info Line`,value:`infoLine`},{label:`Trend Angle`,value:`trendAngle`}]},{label:`Horizontal/Vertical`,section:`lines`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Horizontal Ray`,value:`horizontalRay`},{label:`Vertical Line`,value:`verticalLine`},{label:`Cross Line`,value:`crossLine`}]},{label:`Channels`,section:`lines`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,section:`fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`},{label:`Fib Channel`,value:`fibChannel`},{label:`Fib Time Zones`,value:`fibTimeZones`},{label:`Fib Speed Resistance Fan`,value:`fibSpeedResistanceFan`},{label:`Fib Speed Resistance Arcs`,value:`fibArcs`},{label:`Fib Circles`,value:`fibCircles`},{label:`Fib Spiral`,value:`fibSpiral`},{label:`Fib Wedge`,value:`fibWedge`}]},{label:`Gann & Pitchforks`,section:`fibonacci`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Schiff Pitchfork`,value:`schiffPitchfork`},{label:`Modified Schiff Pitchfork`,value:`modifiedSchiffPitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Gann Square`,value:`gannSquare`},{label:`Pitchfan`,value:`pitchfan`}]},{label:`Cycles`,section:`fibonacci`,tools:[{label:`Cyclic Lines`,value:`cyclicLines`},{label:`Time Cycles`,value:`timeCycles`},{label:`Sine Line`,value:`sineLine`}]},{label:`Patterns`,section:`patterns`,tools:[{label:`XABCD Pattern`,value:`xabcdPattern`},{label:`ABCD Pattern`,value:`abcdPattern`},{label:`Head and Shoulders`,value:`headAndShoulders`},{label:`Cypher Pattern`,value:`cypherPattern`},{label:`Three Drives Pattern`,value:`threeDrives`}]},{label:`Elliott Waves`,section:`patterns`,tools:[{label:`Elliott Wave`,value:`elliottWave`},{label:`Elliott Impulse Wave`,value:`elliottImpulse`},{label:`Elliott Correction Wave`,value:`elliottCorrection`},{label:`Elliott Triangle Wave`,value:`elliottTriangle`},{label:`Elliott Double Combo Wave`,value:`elliottDoubleCombo`},{label:`Elliott Triple Combo Wave`,value:`elliottTripleCombo`}]},{label:`Forecasting`,section:`forecasting`,tools:[{label:`Long/Short Position`,value:`riskReward`},{label:`Anchored VWAP`,value:`anchoredVWAP`},{label:`Fixed Range Volume Profile`,value:`volumeProfileRange`},{label:`Forecast`,value:`forecast`},{label:`Projection`,value:`projection`},{label:`Bars Pattern`,value:`barsPattern`}]},{label:`Measure`,section:`forecasting`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Date and Price Range`,value:`dateAndPriceRange`},{label:`Measure`,value:`measure`}]},{label:`Shapes`,section:`annotation`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Circle`,value:`circle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`},{label:`Polyline`,value:`polyline`},{label:`Curve`,value:`curve`},{label:`Arc`,value:`arc`}]},{label:`Brushes`,section:`annotation`,tools:[{label:`Brush`,value:`brush`},{label:`Highlighter`,value:`highlighter`},{label:`Path`,value:`path`}]},{label:`Annotation`,section:`annotation`,tools:[{label:`Text`,value:`text`},{label:`Price Label`,value:`priceLabel`},{label:`Arrow`,value:`arrow`},{label:`Note`,value:`note`},{label:`Callout`,value:`callout`},{label:`Flag Mark`,value:`flag`},{label:`Arrow Mark`,value:`arrowMark`},{label:`Icon`,value:`icon`}]}],ee=[{id:`sma`,name:`SMA`,type:`overlay`},{id:`ema`,name:`EMA`,type:`overlay`},{id:`tema`,name:`Triple EMA`,type:`overlay`},{id:`vwma`,name:`VWMA`,type:`overlay`},{id:`wma`,name:`Weighted MA`,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:`envelope`,name:`Envelope`,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:`overlay`},{id:`dema`,name:`Double EMA`,type:`overlay`},{id:`smma`,name:`Smoothed MA`,type:`overlay`},{id:`alma`,name:`Arnaud Legoux MA`,type:`overlay`},{id:`kama`,name:`Kaufman Adaptive MA`,type:`overlay`},{id:`lsma`,name:`Least Squares MA`,type:`overlay`},{id:`mcginley`,name:`McGinley Dynamic`,type:`overlay`},{id:`macross`,name:`MA Cross`,type:`overlay`},{id:`fractals`,name:`Williams Fractals`,type:`overlay`},{id:`cks`,name:`Chande Kroll Stop`,type:`overlay`},{id:`bbpb`,name:`Bollinger %B`,type:`panel`},{id:`bbw`,name:`Bollinger BandWidth`,type:`panel`},{id:`mom`,name:`Momentum`,type:`panel`},{id:`hv`,name:`Historical Volatility`,type:`panel`},{id:`vo`,name:`Volume Oscillator`,type:`panel`},{id:`ulcer`,name:`Ulcer Index`,type:`panel`},{id:`seb`,name:`Standard Error Bands`,type:`overlay`},{id:`gmma`,name:`Guppy Multiple MA`,type:`overlay`},{id:`maribbon`,name:`Moving Average Ribbon`,type:`overlay`},{id:`smi`,name:`Stochastic Momentum Index`,type:`panel`},{id:`rvix`,name:`Relative Volatility Index`,type:`panel`},{id:`trendstrength`,name:`Trend Strength Index`,type:`panel`},{id:`lrslope`,name:`Linear Regression Slope`,type:`panel`},{id:`stderror`,name:`Standard Error`,type:`panel`},{id:`adr`,name:`Average Day Range`,type:`panel`},{id:`netvolume`,name:`Net Volume`,type:`panel`}],f=[`sma`,`ema`,`bb`,`rsi`,`macd`,`stochastic`,`vwap`,`atr`,`obv`,`ichimoku`],te=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],ne={candleUpColor:n.DARK_THEME.candleUp,candleDownColor:n.DARK_THEME.candleDown,candleUpWick:n.DARK_THEME.candleUpWick,candleDownWick:n.DARK_THEME.candleDownWick,backgroundColor:n.DARK_THEME.background,gridColor:n.DARK_THEME.grid,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,indicatorValueLabels:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},p=`/* === TradeCanvas Widget — Premium Styles === */
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`../LayoutSession-1uhJw0L7.cjs`),t=require(`../i18n-DkzAxytR.cjs`);let n=require(`@tradecanvas/commons`),r=require(`@tradecanvas/core`);function i(e,t,r={}){if(e.length===0)return[];let i=r.weekStartsOn??1,a=[],o=null,s=NaN;for(let r of e){let e=(0,n.timeframeBucketStart)(r.time,t,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 a(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 o=[{zone:`Pacific/Honolulu`,city:`Honolulu`},{zone:`America/Los_Angeles`,city:`Los Angeles`},{zone:`America/Denver`,city:`Denver`},{zone:`America/Chicago`,city:`Chicago`},{zone:`America/New_York`,city:`New York`},{zone:`America/Toronto`,city:`Toronto`},{zone:`America/Sao_Paulo`,city:`São Paulo`},{zone:`UTC`,city:`UTC`},{zone:`Europe/London`,city:`London`},{zone:`Europe/Berlin`,city:`Frankfurt`},{zone:`Europe/Paris`,city:`Paris`},{zone:`Europe/Zurich`,city:`Zurich`},{zone:`Africa/Johannesburg`,city:`Johannesburg`},{zone:`Europe/Istanbul`,city:`Istanbul`},{zone:`Europe/Moscow`,city:`Moscow`},{zone:`Asia/Dubai`,city:`Dubai`},{zone:`Asia/Kolkata`,city:`Mumbai`},{zone:`Asia/Bangkok`,city:`Bangkok`},{zone:`Asia/Ho_Chi_Minh`,city:`Ho Chi Minh City`},{zone:`Asia/Jakarta`,city:`Jakarta`},{zone:`Asia/Singapore`,city:`Singapore`},{zone:`Asia/Hong_Kong`,city:`Hong Kong`},{zone:`Asia/Shanghai`,city:`Shanghai`},{zone:`Asia/Taipei`,city:`Taipei`},{zone:`Asia/Seoul`,city:`Seoul`},{zone:`Asia/Tokyo`,city:`Tokyo`},{zone:`Australia/Sydney`,city:`Sydney`},{zone:`Pacific/Auckland`,city:`Auckland`}];function s(e){return!e||e===`local`?null:e===`exchange`?`exchange`:/^-?\d+$/.test(e)?Number(e):(0,n.isValidTimeZone)(e)?e:null}function c(e){return e===null?`local`:String(e)}function l(e,t,r,i){let a=(0,n.offsetAt)(null,t),c=o.filter(({zone:e})=>(0,n.isValidTimeZone)(e)).map(({zone:e,city:r})=>{let i=(0,n.offsetAt)(e,t);return{value:e,label:e===`UTC`?`UTC`:`(${(0,n.tzLabel)(i)}) ${r}`,offset:i}}),l=s(e);typeof l==`number`&&c.push({value:e,label:(0,n.tzLabel)(l),offset:l}),c.sort((e,t)=>e.offset-t.offset);let u=[{value:`local`,label:`${r} (${(0,n.tzLabel)(a)})`,offset:a}];if(i){let e=(0,n.offsetAt)(i.zone&&(0,n.isValidTimeZone)(i.zone)?i.zone:`UTC`,t);u.push({value:`exchange`,label:`${i.label} (${(0,n.tzLabel)(e)})`,offset:e})}return[...u,...c]}var u=[{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`},{label:`High-Low`,value:`hiLo`},{label:`Renko`,value:`renko`},{label:`Line Break`,value:`lineBreak`},{label:`Kagi`,value:`kagi`},{label:`Point & Figure`,value:`pointAndFigure`},{label:`Range Bars`,value:`rangeBars`}],d=[{label:`Lines`,section:`lines`,tools:[{label:`Trend Line`,value:`trendLine`},{label:`Ray`,value:`ray`},{label:`Extended Line`,value:`extendedLine`},{label:`Info Line`,value:`infoLine`},{label:`Trend Angle`,value:`trendAngle`}]},{label:`Horizontal/Vertical`,section:`lines`,tools:[{label:`Horizontal Line`,value:`horizontalLine`},{label:`Horizontal Ray`,value:`horizontalRay`},{label:`Vertical Line`,value:`verticalLine`},{label:`Cross Line`,value:`crossLine`}]},{label:`Channels`,section:`lines`,tools:[{label:`Parallel Channel`,value:`parallelChannel`},{label:`Regression Channel`,value:`regressionChannel`}]},{label:`Fibonacci`,section:`fibonacci`,tools:[{label:`Fib Retracement`,value:`fibRetracement`},{label:`Fib Extension`,value:`fibExtension`},{label:`Fib Channel`,value:`fibChannel`},{label:`Fib Time Zones`,value:`fibTimeZones`},{label:`Fib Speed Resistance Fan`,value:`fibSpeedResistanceFan`},{label:`Fib Speed Resistance Arcs`,value:`fibArcs`},{label:`Fib Circles`,value:`fibCircles`},{label:`Fib Spiral`,value:`fibSpiral`},{label:`Fib Wedge`,value:`fibWedge`}]},{label:`Gann & Pitchforks`,section:`fibonacci`,tools:[{label:`Pitchfork`,value:`pitchfork`},{label:`Schiff Pitchfork`,value:`schiffPitchfork`},{label:`Modified Schiff Pitchfork`,value:`modifiedSchiffPitchfork`},{label:`Gann Fan`,value:`gannFan`},{label:`Gann Box`,value:`gannBox`},{label:`Gann Square`,value:`gannSquare`},{label:`Pitchfan`,value:`pitchfan`}]},{label:`Cycles`,section:`fibonacci`,tools:[{label:`Cyclic Lines`,value:`cyclicLines`},{label:`Time Cycles`,value:`timeCycles`},{label:`Sine Line`,value:`sineLine`}]},{label:`Patterns`,section:`patterns`,tools:[{label:`XABCD Pattern`,value:`xabcdPattern`},{label:`ABCD Pattern`,value:`abcdPattern`},{label:`Head and Shoulders`,value:`headAndShoulders`},{label:`Cypher Pattern`,value:`cypherPattern`},{label:`Three Drives Pattern`,value:`threeDrives`}]},{label:`Elliott Waves`,section:`patterns`,tools:[{label:`Elliott Wave`,value:`elliottWave`},{label:`Elliott Impulse Wave`,value:`elliottImpulse`},{label:`Elliott Correction Wave`,value:`elliottCorrection`},{label:`Elliott Triangle Wave`,value:`elliottTriangle`},{label:`Elliott Double Combo Wave`,value:`elliottDoubleCombo`},{label:`Elliott Triple Combo Wave`,value:`elliottTripleCombo`}]},{label:`Forecasting`,section:`forecasting`,tools:[{label:`Long/Short Position`,value:`riskReward`},{label:`Anchored VWAP`,value:`anchoredVWAP`},{label:`Fixed Range Volume Profile`,value:`volumeProfileRange`},{label:`Forecast`,value:`forecast`},{label:`Projection`,value:`projection`},{label:`Bars Pattern`,value:`barsPattern`}]},{label:`Measure`,section:`forecasting`,tools:[{label:`Price Range`,value:`priceRange`},{label:`Date Range`,value:`dateRange`},{label:`Date and Price Range`,value:`dateAndPriceRange`},{label:`Measure`,value:`measure`}]},{label:`Shapes`,section:`annotation`,tools:[{label:`Rectangle`,value:`rectangle`},{label:`Circle`,value:`circle`},{label:`Ellipse`,value:`ellipse`},{label:`Triangle`,value:`triangle`},{label:`Polyline`,value:`polyline`},{label:`Curve`,value:`curve`},{label:`Arc`,value:`arc`}]},{label:`Brushes`,section:`annotation`,tools:[{label:`Brush`,value:`brush`},{label:`Highlighter`,value:`highlighter`},{label:`Path`,value:`path`}]},{label:`Annotation`,section:`annotation`,tools:[{label:`Text`,value:`text`},{label:`Price Label`,value:`priceLabel`},{label:`Arrow`,value:`arrow`},{label:`Note`,value:`note`},{label:`Callout`,value:`callout`},{label:`Flag Mark`,value:`flag`},{label:`Arrow Mark`,value:`arrowMark`},{label:`Icon`,value:`icon`}]}],ee=[{id:`sma`,name:`SMA`,type:`overlay`},{id:`ema`,name:`EMA`,type:`overlay`},{id:`tema`,name:`Triple EMA`,type:`overlay`},{id:`vwma`,name:`VWMA`,type:`overlay`},{id:`wma`,name:`Weighted MA`,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:`envelope`,name:`Envelope`,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:`overlay`},{id:`dema`,name:`Double EMA`,type:`overlay`},{id:`smma`,name:`Smoothed MA`,type:`overlay`},{id:`alma`,name:`Arnaud Legoux MA`,type:`overlay`},{id:`kama`,name:`Kaufman Adaptive MA`,type:`overlay`},{id:`lsma`,name:`Least Squares MA`,type:`overlay`},{id:`mcginley`,name:`McGinley Dynamic`,type:`overlay`},{id:`macross`,name:`MA Cross`,type:`overlay`},{id:`fractals`,name:`Williams Fractals`,type:`overlay`},{id:`cks`,name:`Chande Kroll Stop`,type:`overlay`},{id:`bbpb`,name:`Bollinger %B`,type:`panel`},{id:`bbw`,name:`Bollinger BandWidth`,type:`panel`},{id:`mom`,name:`Momentum`,type:`panel`},{id:`hv`,name:`Historical Volatility`,type:`panel`},{id:`vo`,name:`Volume Oscillator`,type:`panel`},{id:`ulcer`,name:`Ulcer Index`,type:`panel`},{id:`seb`,name:`Standard Error Bands`,type:`overlay`},{id:`gmma`,name:`Guppy Multiple MA`,type:`overlay`},{id:`maribbon`,name:`Moving Average Ribbon`,type:`overlay`},{id:`smi`,name:`Stochastic Momentum Index`,type:`panel`},{id:`rvix`,name:`Relative Volatility Index`,type:`panel`},{id:`trendstrength`,name:`Trend Strength Index`,type:`panel`},{id:`lrslope`,name:`Linear Regression Slope`,type:`panel`},{id:`stderror`,name:`Standard Error`,type:`panel`},{id:`adr`,name:`Average Day Range`,type:`panel`},{id:`netvolume`,name:`Net Volume`,type:`panel`},{id:`avgprice`,name:`Average Price`,type:`overlay`},{id:`medprice`,name:`Median Price`,type:`overlay`},{id:`typprice`,name:`Typical Price`,type:`overlay`},{id:`machannel`,name:`Moving Average Channel`,type:`overlay`},{id:`hamming`,name:`Moving Average Hamming`,type:`overlay`},{id:`madouble`,name:`Moving Average Double`,type:`overlay`},{id:`matriple`,name:`Moving Average Triple`,type:`overlay`},{id:`volindex`,name:`Volatility Index`,type:`overlay`},{id:`asi`,name:`Accumulative Swing Index`,type:`panel`},{id:`advdecline`,name:`Advance/Decline`,type:`panel`},{id:`majority`,name:`Majority Rule`,type:`panel`},{id:`chopzone`,name:`Chop Zone`,type:`panel`},{id:`smiergodic`,name:`SMI Ergodic`,type:`panel`},{id:`po`,name:`Price Oscillator`,type:`panel`},{id:`volohlc`,name:`Volatility O-H-L-C`,type:`panel`},{id:`volzt`,name:`Volatility Zero Trend`,type:`panel`}],f=[`sma`,`ema`,`bb`,`rsi`,`macd`,`stochastic`,`vwap`,`atr`,`obv`,`ichimoku`],te=[`BTCUSDT`,`ETHUSDT`,`SOLUSDT`,`BNBUSDT`],ne={candleUpColor:n.DARK_THEME.candleUp,candleDownColor:n.DARK_THEME.candleDown,candleUpWick:n.DARK_THEME.candleUpWick,candleDownWick:n.DARK_THEME.candleDownWick,backgroundColor:n.DARK_THEME.background,gridColor:n.DARK_THEME.grid,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,indicatorValueLabels:!0,logScale:!1,scaleMode:`regular`,autoScale:!0,invertScale:!1,leftPriceScale:!1,crosshairMode:`magnet`,numberLocale:`en-US`,timezone:`local`,highLowLines:!1,mainSeriesVisible:!0,extendedHours:!0,chartTypeOptions:{}},p=`/* === TradeCanvas Widget — Premium Styles === */
|
|
2
2
|
|
|
3
3
|
/*
|
|
4
4
|
* The HTML \`hidden\` attribute only sets \`display: none\` via the UA stylesheet,
|
|
@@ -4300,5 +4300,5 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
|
|
|
4300
4300
|
</span>
|
|
4301
4301
|
${this.steps.length>1?`<select class="tcw-replay-speed tcw-replay-step" data-act="step" aria-label="${w(e.step)}" title="${w(e.step)}">${this.steps.map(e=>`<option value="${w(e.value)}"${e.value===this.step?` selected`:``}>${w(e.label)}</option>`).join(``)}</select>`:``}
|
|
4302
4302
|
<button class="tcw-replay-text-btn tcw-replay-realtime" data-act="realtime">${w(e.realtime)}</button>
|
|
4303
|
-
`}wireEvents(){let e=this.root;e&&(this.scrubber=e.querySelector(`input[data-act="seek"]`),this.progressLabel=e.querySelector(`[data-tcw="progress"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.realtimeBtn?.addEventListener(`click`,()=>this.callbacks.onClose()),e.querySelector(`[data-act="random"]`)?.addEventListener(`click`,()=>this.callbacks.onRandomStart()),e.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),e.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`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.speed=t,this.callbacks.onSpeedChange(t)}),e.querySelector(`[data-act="step"]`)?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)}))}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))t.hidden=t.dataset.mode!==this.mode;if(e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=e?ze():Re(),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}};function Re(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7L8 5z"/></svg>`}function ze(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>`}function Be(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 6h2v12H6zM20 6L9 12l11 6V6z"/></svg>`}function Ve(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M4 6l11 6L4 18V6zM16 6h2v12h-2z"/></svg>`}function He(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 3v18M8 7l4-4 4 4M8 17l4 4 4-4"/></svg>`}var Ue=class{el;headerEl;nameBtn;menuEl;listEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n){this.callbacks=t,this.labels=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.textContent=`+`,r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,r,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),e.appendChild(this.el)}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}makeRow(e){let n=document.createElement(`div`);n.className=`tcw-watchlist-row`,n.setAttribute(`role`,`listitem`),n.dataset.symbol=e,n.tabIndex=0,n.draggable=!!this.callbacks.onMove;let r=document.createElement(`div`);r.className=`tcw-watchlist-symbol`,r.textContent=We(e);let i=document.createElement(`canvas`);i.className=`tcw-watchlist-spark`,i.width=64,i.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let s=document.createElement(`span`);if(s.className=`tcw-watchlist-change`,a.append(o,s),n.append(r,i,a),this.callbacks.onRemove){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.textContent=`×`,r.tabIndex=-1;let i=t.r(this.labels.remove,{symbol:e});r.title=i,r.setAttribute(`aria-label`,i),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),n.appendChild(r)}n.addEventListener(`click`,()=>this.callbacks.onSelect(e)),n.addEventListener(`keydown`,t=>this.onRowKey(t,e)),n.addEventListener(`dragstart`,t=>{this.dragging=e,t.dataTransfer?.setData(`text/plain`,e),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`),n.classList.add(`tcw-watchlist-dragging`)}),n.addEventListener(`dragend`,()=>{this.dragging=null,n.classList.remove(`tcw-watchlist-dragging`)}),n.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),n.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:n,priceEl:o,changeEl:s,sparkCanvas:i}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=Ge(n.lastPrice,this.locale)),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?`+`:`-`,a=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&Ke(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},n=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),r=document.createElement(`div`);if(r.className=`tcw-dropdown-divider`,n.push(r),this.callbacks.onCreateList){let t=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));t.dataset.action=`new`,n.push(t)}let i=this.shownList();if(i&&this.callbacks.onRenameList){let t=e(this.labels.rename,()=>this.editName(i.name,e=>this.callbacks.onRenameList?.(i.id,e)));t.dataset.action=`rename`,n.push(t)}if(i&&this.callbacks.onDeleteList&&this.lists.length>1){let r=!1,a=e(this.labels.deleteList,()=>{if(!r){r=!0,a.textContent=t.r(this.labels.confirmDelete,{name:i.name}),a.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(i.id)});a.dataset.action=`delete`,n.push(a)}this.menuEl.replaceChildren(...n)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function We(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 Ge(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function Ke(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?`#1fa874`:`#e8505b`;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 qe=50,Je=500,Ye=60,Xe=64,D=e=>typeof e==`string`&&e.trim().slice(0,Ye)||null,Ze=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=Xe?t:null};function Qe(e){let t=[];for(let n of e){let e=Ze(n);if(e&&!t.includes(e)&&t.push(e),t.length===Je)break}return t}function O(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===qe)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=Xe?t.id:null,i=D(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?Qe(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var $e=e=>({...e,symbols:[...e.symbols]}),et=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?O({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:D(e.defaultName)??`Watchlist`,symbols:Qe(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map($e)}getActive(){return $e(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=O({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=D(e);if(!t||this.lists.length>=qe)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),$e(r)}rename(e,t){let n=D(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=Ze(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=Je?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);return e?O(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},tt=class{el;bodyEl;newsEl;shown=!1;constructor(e,n=t.t,r={}){this.t=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,n(`symbolInfo.title`)),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-syminfo-header`;let a=document.createElement(`span`);a.textContent=n(`symbolInfo.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-syminfo-close`,o.setAttribute(`aria-label`,n(`common.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.append(a,o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(i,this.bodyEl,this.newsEl),e.appendChild(this.el)}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`,t.append(k(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(k(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(k(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(k(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=k(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=k(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(k(`dt`,``,t.label),k(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=k(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(k(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(k(`span`,``,t.title));t.meta&&e.append(k(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function k(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var nt=300,rt=80,it=class{el;holdTimer=null;repeatTimer=null;onMove=e=>{e.pointerType!==`touch`&&(this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`))};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,n,r=t.t){this.host=e,this.actions=n,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`nav.label`));let i=[[`zoomOut`,`minus`,r(`nav.zoomOut`)],[`zoomIn`,`plus`,r(`nav.zoomIn`)],[`scrollLeft`,`chevronLeft`,r(`nav.scrollLeft`)],[`scrollRight`,`chevronRight`,r(`nav.scrollRight`)],[`reset`,`reset`,r(`nav.reset`)]];for(let[e,t,r]of i){let i=document.createElement(`button`);if(i.type=`button`,i.className=`tcw-nav-btn`,i.dataset.nav=e,i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=S(t,16),e===`scrollLeft`||e===`scrollRight`){let t=e===`scrollRight`?1:-1;i.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{i.setPointerCapture(e.pointerId)}catch{}this.startHold(t)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])i.addEventListener(e,()=>this.stopHold());i.addEventListener(`click`,e=>{e.detail===0&&n.scroll(t)})}else i.addEventListener(`click`,()=>{e===`zoomIn`?n.zoomIn():e===`zoomOut`?n.zoomOut():n.reset()});this.el.appendChild(i)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`focusin`,()=>{this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||this.el.classList.remove(`tcw-nav-shown`)}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),rt)},nt)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function at(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=lt.get(e.condition),s=o?n(o):e.condition;if(st.includes(e.condition))return`${a} ${s} ${t.r(n(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${a} ${s} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?dt(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var ot=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],st=[`movesUp`,`movesDown`],ct={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},A=``,lt=new Map(ot.map(e=>[e.value,e.key]));function ut(e){return Math.round(e*1e6)/1e6}function dt(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var ft=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;constructor(e,n,i=t.t){this.t=i,this.callbacks=n,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-alerts-header`;let o=document.createElement(`span`);o.textContent=this.t(`alerts.title`);let s=document.createElement(`button`);s.className=`tcw-alerts-close`,s.type=`button`,s.setAttribute(`aria-label`,this.t(`alerts.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`form`);c.className=`tcw-alerts-form`,c.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of ot){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(r.MIN_ALERT_BARS),this.barsInput.max=String(r.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let l=document.createElement(`div`);l.className=`tcw-alerts-row-fields tcw-alerts-options`;let u=document.createElement(`label`);u.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,u.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}l.append(u,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let d=document.createElement(`button`);d.type=`submit`,d.className=`tcw-alerts-add`,d.innerHTML=`${S(`plus`,14)}<span>${w(this.t(`alerts.add`))}</span>`,c.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,l,this.messageInput,d),c.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(c),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=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),e.appendChild(this.el)}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=st.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==A}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=A,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:A,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.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`,this.renderTargets()}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(ut(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),a={},o=NaN;if(st.includes(e)){a.percent=Number(this.percentInput.value),a.bars=Number(this.barsInput.value);let e=Number.isInteger(a.bars)&&a.bars>=r.MIN_ALERT_BARS&&a.bars<=r.MAX_ALERT_BARS;if(!(a.percent>0)||!e){this.markInvalid(a.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==A)a.target=this.targetSelect.value;else if(o=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(o)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(a.onBarClose=!0);let s=ct[this.expirySelect.value];s&&(a.expiresAt=(this.callbacks.now??Date.now)()+s),this.callbacks.onAdd({price:o,condition:e,message:t,channel:n,label:i,options:a})!==!1&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return at(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let n=document.createElement(`div`);n.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let r=document.createElement(`div`);r.className=`tcw-alerts-info`;let i=document.createElement(`div`);i.className=`tcw-alerts-row-main`,i.textContent=this.describe(e),r.appendChild(i);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let n=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(t.r(this.t(`alerts.until`),{time:n}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),r.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,r.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),i.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=S(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}},pt=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,mt=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,ht={studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:48,menuItem:30},font:{family:`'Manrope', 'Inter', ${pt}`,mono:mt,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${pt}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},font:{family:`'Sora', 'Manrope', ${pt}`,mono:mt,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999}},gt={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:54,menuItem:34}};function _t(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var vt=Object.freeze(Object.fromEntries(Object.keys(ht).map(e=>[e,bt(yt(e))])));function yt(e){let t=ht[e];return{...t,preset:e,radius:{...t.radius},components:_t(t.radius,t.components),sizes:{...t.sizes},font:{...t.font},borders:{...t.borders},shadows:{...t.shadows}}}function bt(e){for(let t of Object.values(e))t&&typeof t==`object`&&bt(t);return Object.freeze(e)}var xt=e=>e===`studio`||e===`terminal`||e===`capsule`,j=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,St=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&Ct(e);function Ct(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var wt=(e,t)=>typeof e==`string`&&t.includes(e);function M(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function N(e){let t=typeof e==`string`?{preset:e}:e??{},n=xt(t.preset)?t.preset:`studio`,r=ht[n],i=M(r.radius,t.radius,(e,t)=>j(t,0,999)),a=M(t.density===`compact`||t.density===`spacious`?gt[t.density]:r.sizes,t.sizes,(e,t)=>e===`icon`?j(t,10,32):j(t,16,80)),o=M(r.font,t.font,(e,t)=>e===`family`||e===`mono`?St(t):e===`size`?j(t,11,20):e===`weight`||e===`strongWeight`?j(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:j(t,0,.5));return{preset:n,radius:i,components:M(_t(i,r.components),t.components,(e,t)=>j(t,0,999)),sizes:a,font:o,borders:M(r.borders,t.borders,(e,t)=>e===`width`?j(t,0,4):typeof t==`boolean`),shadows:M(r.shadows,t.shadows,(e,t)=>St(t)),blur:j(t.blur,0,40)?t.blur:r.blur,active:wt(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:wt(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:wt(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:wt(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:j(t.tagRadius,0,999)?t.tagRadius:r.tagRadius}}function Tt(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font;return{"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(a.size-1),"--tcw-font-size-xs":t(a.size-2),"--tcw-font-size-lg":t(a.size+2),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function P(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Tt(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`}var Et=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-tree-header`;let a=document.createElement(`span`);a.textContent=this.t(`objects.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-tree-close`,o.setAttribute(`aria-label`,this.t(`objects.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare&&(this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>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 e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=S(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}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(this.t(`objects.noIndicators`)));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?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator&&n.appendChild(this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId))),n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`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(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let i=n.some(e=>e.visible),a=n.every(e=>e.locked);i||r.classList.add(`tcw-tree-hidden`);let o=r.querySelector(`.tcw-tree-name`);o.innerHTML=S(`layers`,13),o.append(` ${t}`);let s=document.createElement(`div`);return s.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(o.addEventListener(`dblclick`,()=>this.renameGroup(o,e,t)),s.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(o,e,t)))),this.callbacks.onToggleGroupVisible&&s.appendChild(this.iconButton(i?`eye`:`eyeOff`,i?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!i))),this.callbacks.onToggleGroupLocked&&s.appendChild(this.iconButton(a?`lock`:`unlock`,a?this.t(`common.unlock`):this.t(`common.lock`),a?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!a))),this.callbacks.onUngroup&&s.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(s),r}renameGroup(e,t,n){if(!e.isConnected)return;let r=document.createElement(`input`);r.type=`text`,r.className=`tcw-tree-rename`,r.value=n,r.maxLength=80,r.setAttribute(`aria-label`,this.t(`objects.renameGroup`));let i=!1,a=a=>{if(i)return;i=!0;let o=r.value.trim();r.isConnected&&r.replaceWith(e),a&&o&&o!==n&&this.callbacks.onRenameGroup?.(t,o)};r.addEventListener(`keydown`,e=>{e.key===`Enter`?a(!0):e.key===`Escape`&&(e.stopPropagation(),a(!1))}),r.addEventListener(`blur`,()=>a(!0)),e.replaceWith(r),r.focus(),r.select()}drawingRow(e){let t=this.row(e.label);e.visible||t.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);return n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),n.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onConfigureDrawing&&n.appendChild(this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id))),n.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(n),t}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));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`,this.t(`objects.removeComparison`),`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=S(e,14),i.addEventListener(`click`,r),i}},Dt={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,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`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`};function Ot(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Dt[e]??e}var kt=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function F(e,t){if(e.key!==`Tab`)return;let n=[...t.querySelectorAll(kt)].filter(e=>e.getClientRects().length>0||e===document.activeElement);if(n.length===0)return;let r=n[0],i=n[n.length-1],a=document.activeElement;e.shiftKey&&(a===r||!t.contains(a))?(e.preventDefault(),i.focus()):!e.shiftKey&&(a===i||!t.contains(a))&&(e.preventDefault(),r.focus())}var At=1,jt=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Mt=[1,1.5,2,3,4];function Nt(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}var Pt=class{backdrop;modal;bodyEl;titleEl;tabsEl;resetBtn;callbacks;target=null;draft={};colors=[];levels=[];tab=`inputs`;tabButtons=[];returnFocus=null;uid=At++;t;constructor(e,n,r){this.callbacks=n,this.t=r??(e=>t.c[e]),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`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-indi-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let i=document.createElement(`div`);i.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-indi-title-${this.uid}`,this.titleEl.textContent=`Indicator`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-modal-close`,a.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),a.innerHTML=S(`x`,16),a.addEventListener(`click`,()=>this.close()),i.append(this.titleEl,a),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-indi-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`);let o=document.createElement(`div`);o.className=`tcw-modal-footer`,this.resetBtn=document.createElement(`button`),this.resetBtn.type=`button`,this.resetBtn.className=`tcw-reset-link`,this.resetBtn.textContent=this.t(`settings.resetToDefaults`),this.resetBtn.addEventListener(`click`,()=>this.resetTab());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-done-btn`,s.textContent=this.t(`settings.done`),s.addEventListener(`click`,()=>this.close()),o.append(this.resetBtn,s),this.modal.append(i,this.tabsEl,this.bodyEl,o),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.backdrop.hidden&&(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.target=e,this.titleEl.textContent=this.t(`indicatorSettings.title`).replace(`{name}`,e.name),this.draft={},this.colors=[...e.colors??[]],this.levels=[...e.levels??[]],this.tab=`inputs`,this.renderTabs(),this.renderBody(),this.backdrop.hidden=!1;let t=this.tabsEl.hidden?null:this.tabButtons[0]??null;(this.bodyEl.querySelector(`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)??t??this.modal).focus()}close(){let e=document.activeElement;(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&this.modal.contains(e)&&e.dispatchEvent(new Event(`change`)),this.backdrop.hidden=!0,this.target=null,this.callbacks.onClose(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return!this.backdrop.hidden}destroy(){this.backdrop.remove()}tabs(){let e=this.target;if(!e)return[];let t=[`inputs`];return e.plots?.length&&e.colors&&this.callbacks.onStyle&&t.push(`style`),e.levels&&this.callbacks.onLevels&&t.push(`levels`),t}renderTabs(){let e=this.tabs();this.tabsEl.hidden=e.length<2,this.tabButtons=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-indi-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`indicatorSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||t.length===0||(e.preventDefault(),this.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close();return}F(e,this.modal)}renderBody(){if(this.bodyEl.replaceChildren(),!this.target)return;let e=document.createElement(`div`);e.className=`tcw-settings-section`,this.tab===`style`?this.renderStyle(e):this.tab===`levels`?this.renderLevels(e):this.renderInputs(e),this.resetBtn.hidden=this.tab===`style`,this.bodyEl.appendChild(e)}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}))}renderInputs(e){let t=Object.keys(this.target.defaults);if(t.length===0){e.appendChild(this.note(this.t(`indicatorSettings.noInputs`)));return}for(let n of t)e.appendChild(this.fieldRow(n))}fieldRow(e){let t=this.target?.inputs?.[e],n=this.currentValue(e),r=typeof(this.target?.defaults[e]??n),i;return i=t?.source?this.sourceControl(e,String(n??`close`)):t?.options?this.choiceControl(e,t.options,n):r===`boolean`?this.toggleControl(e,!!n):r===`number`?this.numberControl(e,Number(n),t):typeof n==`string`&&jt.test(n)?this.colorInput(n,t=>this.setValue(e,t)):this.textControl(e,String(n??``)),this.row(t?.label??Nt(e),i)}sourceControl(e,t){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;let i=document.createElement(`optgroup`);i.label=this.t(`indicatorSettings.source.prices`);for(let e of n.PRICE_SOURCES)i.appendChild(this.option(e,e));r.appendChild(i);let a=this.target?.lineSources??[];if(a.length){let e=document.createElement(`optgroup`);e.label=this.t(`indicatorSettings.source.indicators`);for(let t of a)e.appendChild(this.option(t.value,t.label));r.appendChild(e)}return r.value=t,r.value!==t&&(r.value=`close`),r.addEventListener(`change`,()=>this.setValue(e,r.value)),r}choiceControl(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let e of t)r.appendChild(this.option(String(e),String(e)));return r.value=String(n),r.addEventListener(`change`,()=>{let n=t.find(e=>String(e)===r.value);n!==void 0&&this.setValue(e,n)}),r}toggleControl(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${t?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(t)),n.addEventListener(`click`,()=>{let t=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,t),n.setAttribute(`aria-checked`,String(t)),this.setValue(e,t)}),n}numberControl(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(t),r.step=String(n?.step??(Number.isInteger(t)?1:.1)),n?.min!==void 0&&(r.min=String(n.min)),n?.max!==void 0&&(r.max=String(n.max)),r.addEventListener(`change`,()=>{let t=Number(r.value);Number.isFinite(t)&&(n?.min!==void 0&&(t=Math.max(n.min,t)),n?.max!==void 0&&(t=Math.min(n.max,t)),r.value=String(t),this.setValue(e,t))}),r}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}renderStyle(e){let t=this.target,n=new Map,r=(e,t)=>{let r=n.get(e)??[];r.includes(t)||r.push(t),n.set(e,r)};for(let e of t.plots??[]){let t=e.tone!==void 0&&e.downColor!==void 0;r(e.color,t?`${e.title} ${this.t(`indicatorSettings.up`)}`:e.title),t&&r(e.downColor,`${e.title} ${this.t(`indicatorSettings.down`)}`)}for(let[r,i]of[...n].sort((e,t)=>e[0]-t[0])){let n=this.colors[r]??this.colors[0]??`#4c8dff`;e.appendChild(this.row(i.join(` · `),this.colorInput(n,e=>{let n=[...this.colors];for(;n.length<=r;)n.push(n[0]??e);n[r]=e,this.colors=n,this.callbacks.onStyle?.(t.instanceId,{colors:[...n]})})))}let i=document.createElement(`select`);i.className=`tcw-indi-input tcw-indi-select`;for(let e of Mt)i.appendChild(this.option(String(e),`${e} px`));if(i.value=String(t.lineWidth??1.5),i.addEventListener(`change`,()=>this.callbacks.onStyle?.(t.instanceId,{lineWidths:[Number(i.value)]})),e.appendChild(this.row(this.t(`indicatorSettings.lineWidth`),i)),t.scale&&this.callbacks.onScale){let n=document.createElement(`select`);n.className=`tcw-indi-input tcw-indi-select`,n.appendChild(this.option(`right`,this.t(`indicatorSettings.scale.right`))),n.appendChild(this.option(`left`,this.t(`indicatorSettings.scale.left`))),n.value=t.scale,n.addEventListener(`change`,()=>{let e=n.value===`left`?`left`:`right`;this.target={...t,scale:e},this.callbacks.onScale?.(t.instanceId,e)}),e.appendChild(this.row(this.t(`indicatorSettings.scale`),n))}}renderLevels(e){this.levels.length===0&&e.appendChild(this.note(this.t(`indicatorSettings.noLevels`))),this.levels.forEach((t,n)=>{let r=document.createElement(`input`);r.type=`number`,r.className=`tcw-indi-input`,r.id=`tcw-indi-level-${this.uid}-${n}`,r.value=String(t),r.step=`any`,r.addEventListener(`change`,()=>{let e=Number(r.value);!Number.isFinite(e)||r.value.trim()===``||(this.levels=this.levels.map((t,r)=>r===n?e:t),this.applyLevels())});let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-indi-remove`,i.innerHTML=S(`x`,12);let a=this.t(`indicatorSettings.removeLevel`);i.title=a,i.setAttribute(`aria-label`,`${a} ${n+1}`),i.addEventListener(`click`,()=>{this.levels=this.levels.filter((e,t)=>t!==n),this.applyLevels(),this.renderBody(),(this.bodyEl.querySelectorAll(`.tcw-indi-remove`)[n]??this.bodyEl.querySelector(`.tcw-indi-add`))?.focus()});let o=document.createElement(`span`);o.className=`tcw-indi-level`,o.append(r,i);let s=document.createElement(`div`);s.className=`tcw-settings-row`;let c=document.createElement(`label`);c.className=`tcw-settings-label`,c.htmlFor=r.id,c.textContent=`${this.t(`indicatorSettings.level`)} ${n+1}`,s.append(c,o),e.appendChild(s)});let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-reset-link tcw-indi-add`,t.textContent=`+ ${this.t(`indicatorSettings.addLevel`)}`,t.addEventListener(`click`,()=>{let e=this.levels[this.levels.length-1];this.levels=[...this.levels,e===void 0?0:e+10],this.applyLevels(),this.renderBody();let t=this.bodyEl.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),e.appendChild(t)}applyLevels(){this.target&&this.callbacks.onLevels?.(this.target.instanceId,[...this.levels])}resetTab(){let e=this.target;if(e){if(this.tab===`levels`)this.levels=[...e.defaultLevels??[]],this.callbacks.onLevels?.(e.instanceId,null);else{let t={};for(let[n,r]of Object.entries(e.defaults))t[n]=r;this.draft=t,this.callbacks.onApply(e.instanceId,{...t})}this.renderBody()}}row(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}note(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}option(e,t){let n=document.createElement(`option`);return n.value=e,n.textContent=t,n}colorInput(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Ft(e),n.addEventListener(`input`,()=>t(n.value)),n}};function Ft(e){let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);return n?`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`:`#000000`}function It(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Lt=80;function Rt(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function zt(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var Bt=class{templates=[];constructor(e=`tcw:draw-templates`,t=It()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(zt)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?zt(n):null}save(e,t,n){let r=e.trim().slice(0,Lt);if(!r)return;let i={name:r,style:Rt(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===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`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,Lt),style:Rt(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},Vt=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=It()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},Ht=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Ut=[1,2,3,4],Wt=[`solid`,`dashed`,`dotted`],Gt=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,n,r,i=t.t){this.t=i,this.callbacks=n,this.store=r,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-style-header`;let o=document.createElement(`span`);o.textContent=this.t(`drawingStyle.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let c=document.createElement(`div`);c.className=`tcw-style-subhead`,c.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-style-savebtn`,u.innerHTML=`${S(`plus`,13)}<span>${w(this.t(`common.save`))}</span>`,u.addEventListener(`click`,()=>this.saveTemplate()),l.appendChild(this.nameInput),l.appendChild(u),this.el.appendChild(l),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 Ht){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 Ut){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 Wt){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=this.t(`drawingStyle.noTemplates`),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`,this.t(`drawingStyle.deleteTemplate`)),a.innerHTML=S(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}};function I(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}function Kt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${e?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(e)),n.addEventListener(`click`,()=>{let e=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,e),n.setAttribute(`aria-checked`,String(e)),t(e)}),n}function L(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(e),r.step=String(t.step??(Number.isInteger(e)?1:.001)),t.min!==void 0&&(r.min=String(t.min)),t.max!==void 0&&(r.max=String(t.max)),r.addEventListener(`change`,()=>{if(r.value.trim()===``)return;let e=Number(r.value);Number.isFinite(e)&&(t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),r.value=String(e),n(e))}),r}function qt(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Jt(e),n.addEventListener(`input`,()=>t(n.value)),n}function R(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let t of e){let e=document.createElement(`option`);e.value=t.value,e.textContent=t.label,r.appendChild(e)}return r.value=t,r.addEventListener(`change`,()=>n(r.value)),r}function Jt(e){if(typeof e!=`string`)return`#000000`;let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);return n?`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`:`#000000`}function Yt(e){if(typeof e!=`string`)return 1;let t=/^rgba\([^)]*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return t?Math.max(0,Math.min(1,Number(t[1]))):1}function Xt(e,t){let n=Jt(e),[r,i,a]=[1,3,5].map(e=>parseInt(n.slice(e,e+2),16));return`rgba(${r}, ${i}, ${a}, ${Math.round(t*100)/100})`}var Zt=12,Qt=[1,2,3,4],$t=[`solid`,`dashed`,`dotted`],en=[10,11,12,14,16,18,20,24,28,32],tn=48,nn=1,rn=class{backdrop;modal;titleEl;tabsEl;bodyEl;footerLeft;tabButtons=[];target=null;style;options={};anchors=[];tab=`style`;returnFocus=null;uid=nn++;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(!0),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-drawing-settings`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-draw-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-draw-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,16),o.addEventListener(`click`,()=>this.close(!0)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-draw-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`);let s=document.createElement(`div`);s.className=`tcw-modal-footer`,this.footerLeft=document.createElement(`div`),this.footerLeft.className=`tcw-drawing-settings-tools`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-reset-link`,c.textContent=this.t(`common.cancel`),c.addEventListener(`click`,()=>this.close(!0));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-done-btn`,l.textContent=this.t(`drawingSettings.ok`),l.addEventListener(`click`,()=>this.close(!1)),s.append(this.footerLeft,c,l),this.modal.append(a,this.tabsEl,this.bodyEl,s),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.target&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.target=e,this.style={...e.style},this.options=structuredClone(e.options),this.anchors=e.anchors.map(e=>({...e})),this.titleEl.textContent=e.name,this.tab=`style`,this.callbacks.onBegin(e.id);try{this.renderTabs(),this.renderBody()}catch(t){throw this.target=null,this.callbacks.onEnd(e.id,!0),t}this.backdrop.hidden=!1,(this.tabButtons[0]??this.modal).focus()}close(e){let t=this.target;if(!t)return;let n=document.activeElement;!e&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&this.modal.contains(n)&&n.dispatchEvent(new Event(`change`)),this.target=null,this.backdrop.hidden=!0,this.callbacks.onEnd(t.id,e),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return this.target!==null}editing(){return this.target?.id??null}destroy(){this.close(!0),this.backdrop.remove()}tabs(){let e=[`style`];return this.target&&Object.keys(this.target.defs).length>0&&e.push(`options`),this.target&&this.target.anchors.length<=Zt&&e.push(`coordinates`),e}renderTabs(){this.tabButtons=this.tabs().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-draw-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`drawingSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close(!0);return}F(e,this.modal)}renderBody(){if(this.bodyEl.replaceChildren(),this.footerLeft.replaceChildren(),!this.target)return;if(this.target.alertable&&this.callbacks.onAddAlert){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link tcw-drawing-alert`,e.innerHTML=`${S(`bell`,13)}<span></span>`,e.querySelector(`span`).textContent=this.t(`drawingSettings.addAlert`),e.addEventListener(`click`,()=>this.callbacks.onAddAlert?.(this.target.id)),this.footerLeft.appendChild(e)}let e=document.createElement(`div`);e.className=`tcw-settings-section`,this.tab===`options`?this.renderOptions(e):this.tab===`coordinates`?this.renderCoordinates(e):this.renderStyle(e),this.bodyEl.appendChild(e)}change(e){this.target&&this.callbacks.onChange(this.target.id,e)}setStyle(e){this.style={...this.style,...e},this.change({style:e})}setOptions(e){this.options={...this.options,...structuredClone(e)},this.change({options:e})}renderStyle(e){let t=this.target;e.appendChild(I(this.t(`drawingSettings.color`),qt(this.style.color,e=>this.setStyle({color:e})))),e.appendChild(I(this.t(`drawingSettings.lineWidth`),R(Qt.map(e=>({value:String(e),label:`${e} px`})),String(this.style.lineWidth),e=>this.setStyle({lineWidth:Number(e)})))),e.appendChild(I(this.t(`drawingSettings.lineStyle`),R($t.map(e=>({value:e,label:this.t(`drawingSettings.lineStyle.${e}`)})),this.style.lineStyle,e=>this.setStyle({lineStyle:e})))),t.fill&&this.renderFill(e),t.text&&this.renderText(e),this.callbacks.templates&&this.renderTemplates(e)}renderFill(e){let t=this.style.fillColor??Xt(this.style.color,.1),n=Jt(t),r=Yt(t),i=()=>this.setStyle({fillColor:Xt(n,r),fillOpacity:r});e.appendChild(I(this.t(`drawingSettings.fill`),qt(n,e=>{n=e,i()}))),e.appendChild(I(this.t(`drawingSettings.opacity`),L(Math.round(r*100),{min:0,max:100,step:5},e=>{r=e/100,i()})))}renderText(e){let t=document.createElement(`textarea`);t.className=`tcw-indi-input tcw-drawing-text`,t.rows=3,t.value=this.style.text??``,t.addEventListener(`input`,()=>this.setStyle({text:t.value})),e.appendChild(I(this.t(`drawingSettings.text`),t)),e.appendChild(I(this.t(`drawingSettings.fontSize`),R(en.map(e=>({value:String(e),label:`${e} px`})),String(this.style.fontSize??12),e=>this.setStyle({fontSize:Number(e)}))))}renderTemplates(e){let t=this.callbacks.templates,r=this.target,i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=this.t(`drawingStyle.templates`),e.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-drawing-templates`;let o=t.list(r.type);if(o.length===0){let e=document.createElement(`div`);e.className=`tcw-settings-label`,e.textContent=this.t(`drawingStyle.noTemplates`),a.appendChild(e)}for(let e of o){let i=document.createElement(`div`);i.className=`tcw-style-tmpl`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-style-tmpl-apply`,o.textContent=e.name,o.addEventListener(`click`,()=>{this.setStyle(e.style),e.options&&this.setOptions((0,n.sanitizeDrawingOptions)(r.defs,e.options)),this.renderBody()});let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-tmpl-del`,s.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),s.innerHTML=S(`x`,12),s.addEventListener(`click`,()=>{t.remove(e.name,e.type),this.renderBody()}),i.append(o,s),a.appendChild(i)}e.appendChild(a);let s=document.createElement(`div`);s.className=`tcw-style-save`;let c=document.createElement(`input`);c.type=`text`,c.className=`tcw-style-name`,c.placeholder=this.t(`drawingStyle.templateName`),c.setAttribute(`aria-label`,this.t(`drawingStyle.templateName`));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-style-savebtn`,l.textContent=this.t(`common.save`),l.addEventListener(`click`,()=>{c.value.trim()&&(t.save(c.value,this.style,{type:r.type,options:this.options}),this.renderBody())}),s.append(c,l),e.appendChild(s)}label(e,t){let n=`drawingOption.${e}`,r=this.t(n);return r===n?t:r}renderOptions(e){let t=this.target;for(let[n,r]of Object.entries(t.defs))r.kind===`levels`?e.appendChild(this.levelsEditor(n,r)):e.appendChild(I(this.label(n,r.label),this.optionControl(n,r)));let n=document.createElement(`button`);if(n.type=`button`,n.className=`tcw-reset-link`,n.textContent=this.t(`settings.resetToDefaults`),n.addEventListener(`click`,()=>{let e={};for(let[n,r]of Object.entries(t.defs))e[n]=structuredClone(r.default);this.setOptions(e),this.renderBody()}),this.footerLeft.appendChild(n),this.callbacks.onSaveDefault){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link`,e.textContent=this.t(`drawingSettings.saveDefault`),e.addEventListener(`click`,()=>this.callbacks.onSaveDefault?.(t.type,structuredClone(this.options))),this.footerLeft.appendChild(e)}}optionControl(e,t){let n=this.options[e];switch(t.kind){case`boolean`:return Kt(!!n,t=>this.setOptions({[e]:t}));case`number`:return L(Number(n),{min:t.min,max:t.max,step:t.step},t=>this.setOptions({[e]:t}));case`choice`:return R(t.choices.map(t=>({value:t.value,label:this.label(`${e}.${t.value}`,t.label)})),String(n),t=>this.setOptions({[e]:t}));case`text`:{let t=document.createElement(`input`);return t.type=`text`,t.className=`tcw-indi-input`,t.value=String(n??``),t.addEventListener(`change`,()=>this.setOptions({[e]:t.value})),t}}}levelsEditor(e,t){let n=document.createElement(`div`);n.className=`tcw-levels-editor`;let r=document.createElement(`div`);r.className=`tcw-style-subhead`,r.textContent=this.label(e,t.label),n.appendChild(r);let i=()=>{let t=this.options[e];return Array.isArray(t)?t:[]},a=t=>this.setOptions({[e]:t}),o=document.createElement(`div`);o.className=`tcw-levels-grid`,i().forEach((e,t)=>{let n=document.createElement(`div`);n.className=`tcw-level-row`;let r=document.createElement(`input`);r.type=`checkbox`,r.checked=e.visible;let s=` ${t+1}`;r.setAttribute(`aria-label`,this.t(`drawingSettings.levelVisible`)+s),r.addEventListener(`change`,()=>a(i().map((e,n)=>n===t?{...e,visible:r.checked}:e)));let c=L(e.value,{step:.001},e=>a(i().map((n,r)=>r===t?{...n,value:e}:n)));c.setAttribute(`aria-label`,this.t(`drawingSettings.levelValue`)+s);let l=qt(e.color??this.style.color,e=>a(i().map((n,r)=>r===t?{...n,color:e}:n)));l.setAttribute(`aria-label`,this.t(`drawingSettings.levelColor`)+s);let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-level-remove`,u.setAttribute(`aria-label`,this.t(`drawingSettings.removeLevel`)+s),u.innerHTML=S(`x`,12),u.addEventListener(`click`,()=>{a(i().filter((e,n)=>n!==t)),this.renderBody()}),n.append(r,c,l,u),o.appendChild(n)}),n.appendChild(o);let s=document.createElement(`button`);return s.type=`button`,s.className=`tcw-reset-link tcw-level-add`,s.textContent=this.t(`drawingSettings.addLevel`),s.disabled=i().length>=tn,s.addEventListener(`click`,()=>{let e=i().at(-1)?.value??0;a([...i(),{value:Math.round((e+.5)*1e3)/1e3,visible:!0}]),this.renderBody()}),n.appendChild(s),n}renderCoordinates(e){this.anchors.forEach((n,r)=>{let i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=t.r(this.t(`drawingSettings.point`),{n:r+1}),e.appendChild(i);let a=this.callbacks.toWallTime(n.time),o=document.createElement(`input`);o.type=`date`,o.className=`tcw-indi-input`,o.value=a.date;let s=document.createElement(`input`);s.type=`time`,s.className=`tcw-indi-input`,s.value=a.time;let c=()=>{let e=this.callbacks.fromWallTime(o.value,s.value);e!==null&&this.setAnchor(r,{time:e})};o.addEventListener(`change`,c),s.addEventListener(`change`,c),e.appendChild(I(this.t(`drawingSettings.date`),o)),e.appendChild(I(this.t(`drawingSettings.time`),s)),e.appendChild(I(this.t(`drawingSettings.price`),L(n.price,{step:`any`},e=>this.setAnchor(r,{price:e}))))})}setAnchor(e,t){this.anchors=this.anchors.map((n,r)=>r===e?{...n,...t}:n),this.change({anchors:this.anchors.map(e=>({...e}))})}},an=4;function on(e,t,n){let r=e+t>n?e-t:e;return Math.max(0,Math.min(r,n-t))}var z=class{el;onPick=null;returnFocus=null;anchor=null;onDocPointer=e=>{let t=e.target;this.el.contains(t)||this.anchor?.contains(t)||this.close()};onAway=()=>this.close();constructor(e,t){this.host=e,this.el=document.createElement(`div`),this.el.className=`tcw-context-menu`,this.el.setAttribute(`role`,`menu`),this.el.setAttribute(`aria-label`,t),this.el.hidden=!0,this.el.addEventListener(`keydown`,e=>this.onKeyDown(e)),e.appendChild(this.el)}open(e,t,n,r,i){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.onPick=r,this.anchor=i??null,this.el.replaceChildren(...e.map(e=>this.entry(e))),this.el.hidden=!1;let a=this.host.getBoundingClientRect(),o=Math.min(this.host.clientWidth,window.innerWidth-a.left)-an,s=Math.min(this.host.clientHeight,window.innerHeight-a.top)-an;this.el.style.left=`${on(t,this.el.offsetWidth,o)}px`,this.el.style.top=`${on(n,this.el.offsetHeight,s)}px`,document.addEventListener(`pointerdown`,this.onDocPointer,!0),document.addEventListener(`wheel`,this.onAway,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.onAway),window.addEventListener(`blur`,this.onAway),this.items()[0]?.focus({preventScroll:!0})}close(){this.el.hidden||(this.el.hidden=!0,this.onPick=null,this.anchor=null,document.removeEventListener(`pointerdown`,this.onDocPointer,!0),document.removeEventListener(`wheel`,this.onAway,{capture:!0}),window.removeEventListener(`resize`,this.onAway),window.removeEventListener(`blur`,this.onAway),this.returnFocus?.isConnected&&this.returnFocus.focus({preventScroll:!0}),this.returnFocus=null)}isOpen(){return!this.el.hidden}destroy(){this.close(),this.el.remove()}entry(e){if(e===`separator`){let e=document.createElement(`div`);return e.className=`tcw-context-sep`,e.setAttribute(`role`,`separator`),e}let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-context-item${e.danger?` tcw-context-danger`:``}`,t.setAttribute(`role`,e.checked===void 0?`menuitem`:`menuitemcheckbox`),e.checked!==void 0&&t.setAttribute(`aria-checked`,String(e.checked)),t.tabIndex=-1,t.dataset.id=e.id;let n=e.checked===void 0?e.icon??``:e.checked?`check`:``;t.innerHTML=n?S(n,14):`<span class="tcw-context-icon"></span>`;let r=document.createElement(`span`);return r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,()=>this.pick(e.id)),t}pick(e){let t=this.onPick;this.close(),t?.(e)}items(){return[...this.el.querySelectorAll(`[role=menuitem], [role=menuitemcheckbox]`)]}onKeyDown(e){let t=this.items(),n=t.indexOf(document.activeElement),r=-1;if(e.key===`ArrowDown`)r=(n+1)%t.length;else if(e.key===`ArrowUp`)r=(n-1+t.length)%t.length;else if(e.key===`Home`)r=0;else if(e.key===`End`)r=t.length-1;else if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.close();return}else return;e.preventDefault(),t[r]?.focus({preventScroll:!0})}};function sn(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}function cn(e,n){if(e.price===void 0||!Number.isFinite(e.price))return[];let r=e.formatPrice(e.price),i=[];if(e.canAlert&&i.push({id:`alert`,label:t.r(n(`chartMenu.addAlert`),{price:r}),icon:`bell`}),e.canTrade){let a=e.lastPrice===null||e.price<=e.lastPrice;i.push(a?{id:`buyLimit`,label:t.r(n(`chartMenu.buyLimit`),{price:r}),icon:`trendingUp`}:{id:`buyStop`,label:t.r(n(`chartMenu.buyStop`),{price:r}),icon:`trendingUp`},a?{id:`sellStop`,label:t.r(n(`chartMenu.sellStop`),{price:r}),icon:`trendingDown`}:{id:`sellLimit`,label:t.r(n(`chartMenu.sellLimit`),{price:r}),icon:`trendingDown`}),e.canOrderTicket&&i.push({id:`orderTicket`,label:n(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&i.push({id:`horizontalLine`,label:t.r(n(`chartMenu.horizontalLine`),{price:r}),icon:`minus`}),i}function ln(e,t,n){let r=e=>{let r=cn(t,n);return r.length>0?[...r,`separator`,...e]:e},i={id:`settings`,label:n(`chartMenu.settings`),icon:`settings`};switch(e){case`priceAxis`:{let e=cn({...t,canTrade:!1,canDraw:!1},n);return[{id:`autoScale`,label:n(`settings.autoScale`),checked:t.autoScale},{id:`logScale`,label:n(`settings.scale.logarithmic`),checked:t.scaleMode===`logarithmic`},{id:`percentScale`,label:n(`settings.scale.percentage`),checked:t.scaleMode===`percentage`},{id:`invertScale`,label:n(`chartMenu.invertScale`),checked:t.inverted},...e.length>0?[`separator`,...e]:[]]}case`timeAxis`:return[{id:`resetView`,label:n(`chartMenu.resetTimeScale`)},...t.canGoToDate?[{id:`goToDate`,label:n(`chartMenu.goToDate`),icon:`calendar`}]:[]];case`pane`:return[{id:`resetView`,label:n(`chartMenu.resetView`)},...t.pane?[`separator`,{id:`paneLog`,label:n(`chartMenu.paneLog`),checked:t.pane.log},{id:`paneInvert`,label:n(`chartMenu.paneInvert`),checked:t.pane.invert},{id:`panePercent`,label:n(`chartMenu.panePercent`),checked:t.pane.percent}]:[],`separator`,i];default:{let e=t.hasDrawings?[t.drawingsHidden?{id:`showDrawings`,label:n(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:n(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:n(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}]:[],a=t.canExport?[{id:`exportData`,label:n(`chartMenu.exportData`),icon:`save`}]:[];return r([{id:`resetView`,label:n(`chartMenu.resetView`)},...e,...a,`separator`,i])}}}var B=[`positions`,`orders`,`history`],un=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],dn=[`market`,`limit`,`stop`],fn=[`gtc`,`day`];function pn(e,t,n){return e.includes(t??``)?t:n}function mn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hn(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function V(e,t=2){return`${e>0?`+`:``}${e.toFixed(t)}`}var gn=class{el;tabButtons=new Map;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let i=document.createElement(`div`);i.className=`tcw-account-head`;let a=document.createElement(`div`);a.className=`tcw-account-tabs`,a.setAttribute(`role`,`tablist`),a.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of B){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`,t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),a.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,o.innerHTML=S(`plus`,13),o.append(this.t(`account.newOrder`)),o.addEventListener(`click`,()=>this.callbacks.onNewOrder());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-tree-close`,s.setAttribute(`aria-label`,this.t(`account.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,o,s),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(i,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,mn(t.positions,e.positions)&&mn(t.orders,e.orders)&&mn(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){this.open&&this.tab===`positions`&&t.price!==e.price&&this.patchPrices();return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=B.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=B[(n+B.length)%B.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;n.textContent=`${this.t(`account.${t}`)} (${e[t]})`,n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?`—`:this.callbacks.formatPrice(e),this.writePnl(t.pnl,hn(t.position,e))}writePnl(e,t){e.className=t===null?``:t.pnl>=0?`tcw-account-up`:`tcw-account-down`,e.textContent=t===null?`—`:`${V(t.pnl)} (${V(t.pct)}%)`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e);return}let r=document.createElement(`table`);r.className=`tcw-account-table`;let i=r.createTHead().insertRow();for(let t of e){let e=document.createElement(`th`);e.scope=`col`,e.textContent=t?this.t(t):``,i.appendChild(e)}r.createTBody().append(...t),this.content.replaceChildren(r)}row(e,t=``){let n=document.createElement(`tr`);t&&(n.className=t);for(let t of e){let e=n.insertCell();typeof t==`string`?e.textContent=t:e.appendChild(t)}return n}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=S(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=this.snapshot.positions.map(n=>{let r=n.quantity-(n.closedQuantity??0),i=document.createElement(`span`);this.writePnl(i,hn(n,t));let a=`${this.sideText(n.side,`position`)} ${r} @ ${e(n.entryPrice)}`,o=this.row([this.sideCell(n.side),String(r),e(n.entryPrice),t===null?`—`:e(t),i,n.stopLoss===void 0?`—`:e(n.stopLoss),n.takeProfit===void 0?`—`:e(n.takeProfit),this.actions({icon:`repeat`,label:`${this.t(`account.reverse`)}: ${a}`,key:`reverse:${n.id}`,run:()=>this.callbacks.onReversePosition(n.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${a}`,key:`close:${n.id}`,run:()=>this.callbacks.onClosePosition(n.id),danger:!0})]);return this.live.push({position:n,price:o.cells[3],pnl:i}),o});this.table([`account.side`,`account.quantity`,`account.entry`,`account.price`,`account.pnl`,`account.stopLoss`,`account.takeProfit`,`account.actions`],n,`account.noPositions`)}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=pn(dn,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return this.row([this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),t.stopLoss===void 0?`—`:e(t.stopLoss),t.takeProfit===void 0?`—`:e(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${pn(fn,t.timeInForce,`gtc`)}`):`—`,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})])});this.table([`account.side`,`ticket.type`,`account.quantity`,`account.price`,`account.stopLoss`,`account.takeProfit`,`ticket.timeInForce`,`account.actions`],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:n}=this.callbacks,r=[...this.snapshot.fills].reverse().map(t=>{let r=document.createElement(`span`);return t.pnl===void 0?r.textContent=`—`:(r.className=t.pnl>=0?`tcw-account-up`:`tcw-account-down`,r.textContent=V(t.pnl)),this.row([n(t.time),this.sideCell(t.side,`trade`),String(t.quantity),e(t.price),this.t(`account.reason.${pn(un,t.reason,`order`)}`),r])});this.table([`account.time`,`account.side`,`account.quantity`,`account.price`,`account.reason`,`account.pnl`],r,`account.noFills`);let i=this.snapshot.realisedPnl??this.snapshot.fills.reduce((e,t)=>e+(t.pnl??0),0);if(r.length>0){let e=document.createElement(`p`);e.className=`tcw-account-summary`,e.textContent=t.r(this.t(`account.realised`),{pnl:V(i)}),this.content.appendChild(e)}}};function _n(e,t){return e.type===`market`?t:e.price}function vn(e,t){let n=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&n.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&n.push(`price`),e.type===`market`&&!((t??e.price)>0)&&n.push(`market`);let r=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let i=e.price<t;e.type===`limit`&&i!==r&&e.price!==t&&n.push(`limitSide`),e.type===`stop`&&i===r&&e.price!==t&&n.push(`stopSide`)}let i=e=>e===null||Number.isFinite(e)&&e>0;i(e.stopLoss)||n.push(`stopLoss`),i(e.takeProfit)||n.push(`takeProfit`);let a=_n(e,t);return a!==null&&a>0&&(e.stopLoss!==null&&i(e.stopLoss)&&(r?e.stopLoss>=a:e.stopLoss<=a)&&n.push(`stopLossSide`),e.takeProfit!==null&&i(e.takeProfit)&&(r?e.takeProfit<=a:e.takeProfit>=a)&&n.push(`takeProfitSide`)),n}function yn(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),n}function bn(e,t){let n=_n(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}var xn=0,Sn=class{backdrop;modal;body;problemsEl;submit;draft=null;lastPrice=null;returnFocus=null;uid=++xn;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}F(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`h3`);o.id=`tcw-ticket-title-${this.uid}`,o.textContent=this.t(`ticket.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-modal-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,16),s.addEventListener(`click`,()=>this.close()),a.append(o,s),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let c=document.createElement(`div`);c.className=`tcw-modal-footer`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-reset-link`,l.textContent=this.t(`common.cancel`),l.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-done-btn`,this.submit.addEventListener(`click`,()=>this.place()),c.append(l,this.submit),this.modal.append(a,this.body,this.problemsEl,c),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice;let t=e.price??e.lastPrice??0,n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&e.price!==e.lastPrice&&(r=e.price<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:1,price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button, input, select`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){!this.draft||e===this.lastPrice||(this.lastPrice=e,this.check())}destroy(){this.close(),this.backdrop.remove()}place(){let e=this.draft;!e||vn(e,this.lastPrice).length>0||(this.callbacks.onSubmit(yn(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&this.body.contains(t)?t.dataset.ticketField:void 0;this.body.replaceChildren(this.sideToggle(e.side),I(this.t(`ticket.type`),H(`type`,R([`market`,`limit`,`stop`].map(e=>({value:e,label:this.t(`ticket.type.${e}`)})),e.type,e=>this.set({type:e},!0)))),I(this.t(`ticket.quantity`),H(`quantity`,this.number(e.quantity,e=>this.set({quantity:e}))))),e.type!==`market`&&this.body.append(I(this.t(`ticket.price`),H(`price`,this.number(e.price,e=>this.set({price:e})))),I(this.t(`ticket.timeInForce`),H(`timeInForce`,R([`gtc`,`day`].map(e=>({value:e,label:this.t(`ticket.tif.${e}`)})),e.timeInForce,e=>this.set({timeInForce:e})))));let r=e.type===`market`?this.lastPrice??e.price:e.price,i=t=>Cn(r*(1+(e.side===`buy`?t:-t)/100),r);this.body.append(this.optionalPrice(`ticket.stopLoss`,e.stopLoss,i(-1),t=>this.set({stopLoss:t},t===null||e.stopLoss===null)),this.optionalPrice(`ticket.takeProfit`,e.takeProfit,i(2),t=>this.set({takeProfit:t},t===null||e.takeProfit===null))),n&&this.body.querySelector(`[data-ticket-field="${n}"]`)?.focus(),this.check()}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>this.set({side:n},!0)),t.appendChild(r)}return t}number(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.step=`any`,n.min=`0`,n.value=String(e),n.addEventListener(`input`,()=>t(n.value.trim()===``?NaN:Number(n.value))),n}optionalPrice(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-settings-row tcw-ticket-optional`;let a=document.createElement(`span`);a.textContent=this.t(e);let o=Kt(t!==null,e=>r(e?n:null));if(o.setAttribute(`aria-label`,this.t(e)),o.dataset.ticketField=`${e}-switch`,i.append(a,o),t!==null){let n=this.number(t,e=>r(Number.isFinite(e)?e:NaN));n.setAttribute(`aria-label`,this.t(e)),n.dataset.ticketField=e,i.appendChild(n)}return i}check(){let e=this.draft;if(!e)return;let n=vn(e,this.lastPrice),r=n.map(e=>this.t(`ticket.problem.${e}`)),i=bn(e,this.lastPrice);n.length===0&&i!==null&&r.push(t.r(this.t(`ticket.riskReward`),{rr:i.toFixed(2)})),this.problemsEl.replaceChildren(...r.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t})),this.problemsEl.classList.toggle(`tcw-ticket-bad`,n.length>0),this.submit.disabled=n.length>0,this.submit.classList.toggle(`tcw-ticket-sell`,e.side===`sell`),this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}};function H(e,t){return t.dataset.ticketField=e,t}function Cn(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var wn=0,Tn=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++wn;constructor(e,n=t.t){this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let i=document.createElement(`form`);i.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,i.noValidate=!0,i.setAttribute(`role`,`dialog`),i.setAttribute(`aria-modal`,`true`),i.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),i.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}F(e,i)}),i.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`label`);c.className=`tcw-name-field`;let l=document.createElement(`span`);l.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),c.append(l,this.input),s.appendChild(c);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-reset-link`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,u.append(d,this.submit),i.append(a,s,u),this.backdrop.appendChild(i),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},En=0,Dn=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++En;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-modal-narrow tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){F(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let s=document.createElement(`h3`);s.id=`tcw-layouts-title-${this.uid}`,s.textContent=this.t(`layouts.dialogTitle`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=S(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-indi-input tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.addEventListener(`input`,()=>this.render()),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let l=document.createElement(`div`);l.className=`tcw-modal-body tcw-layouts-body`,l.append(this.search,this.listEl),a.append(o,l),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,n){let r=document.createElement(`div`);r.className=`tcw-layouts-row`,r.setAttribute(`role`,`listitem`),r.dataset.id=e.id;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-layouts-open`,n&&i.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol,e.timeframe].filter(Boolean).join(` · `),t.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),i.append(a,o),n){let e=document.createElement(`span`);e.className=`tcw-tag`,e.textContent=this.t(`layouts.current`),a.appendChild(e)}i.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let s=document.createElement(`div`);if(s.className=`tcw-account-actions`,this.confirming===e.id){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-layouts-confirm`,n.textContent=this.t(`layouts.deleteConfirm`),n.setAttribute(`aria-label`,t.r(this.t(`layouts.deleteNamed`),{name:e.name})),n.addEventListener(`click`,()=>void this.remove(e.id));let r=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));s.append(n,r)}else s.append(this.iconButton(`penLine`,t.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,t.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return r.append(i,s),r}iconButton(e,t,n,r=!1){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=S(e,14),i.addEventListener(`click`,n),i}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},On=5,kn=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new z(n,r(`toolbar.layouts`)),this.prompt=new Tn(n,r),this.dialog=new Dn(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:n}=this.host;try{let r=await this.session.save();r&&n(t.r(e(`layouts.saved`),{name:r.name}))}catch{n(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:n}=this.host,r=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:r?t.r(e(`layouts.copyName`),{name:r.name}):``,submitLabel:e(`common.save`),onSubmit:async r=>{try{let i=await this.session.saveAs(r);n(t.r(e(`layouts.saved`),{name:i.name}))}catch(t){throw n(e(`layouts.saveFailed`),`error`),t}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n,root:r}=this.host,i=[];try{i=(await t.list()).slice(0,On)}catch{}if(this.destroyed)return;let a=t.current(),o=[{id:`save`,label:n(`layouts.save`),icon:`save`},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];a&&o.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),o.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),i.length>0&&o.push(`separator`,...i.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===a?.id}))),o.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`});let s=e.getBoundingClientRect(),c=r.getBoundingClientRect();this.menu.open(o,s.left-c.left,s.bottom-c.top+2,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))},e)}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},An=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],jn=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],Mn=6;function Nn(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var Pn=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,Fn=(e,t)=>{let r=(0,n.tickBarCount)(e),i=(0,n.tickBarCount)(t);return r!==null||i!==null?r===null?1:i===null?-1:r-i:(0,n.timeframeToMs)(e)-(0,n.timeframeToMs)(t)};function In(e,t){let n=t?.length?t:null,r=e?.length?e:n??An;return[...new Set(r)].filter(e=>Pn(e)&&(!n||n.includes(e))).sort(Fn)}function Ln(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>jn.includes(e));return r.length>0?r:e.slice(0,Mn)}var Rn=9999,zn={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},Bn={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function Vn(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=Rn&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=zn[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=Bn[i];e&&r%e[1]===0;e=Bn[i])r/=e[1],i=e[0];if(r>Rn)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function Hn(e,t,n){let r=n?.length?n:null,i=t.filter(e=>Pn(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(Fn)}var Un=0,Wn=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Un}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=Vn(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=Vn(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Gn=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:i}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(i))continue;let a=r.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:i})).indicators;a.length>0&&t.push({name:e.slice(0,60),indicators:a})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},U=[],W=null;function Kn(e){let t=()=>{W=e};return e.addEventListener(`pointerdown`,t,!0),U.push(e),()=>{e.removeEventListener(`pointerdown`,t,!0);let n=U.indexOf(e);n>=0&&U.splice(n,1),W===e&&(W=null)}}function G(e,t=!1){let n=W?.isConnected?W:null;if(!n){let e=document.activeElement;n=e?U.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=U.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function K(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var qn=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Jn=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Yn(e){let{theme:t,timestamp:n,...r}=e;return r}function Xn(e){return!Jn(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,n.isTimeFrame)(e.timeframe)||(0,n.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:qn.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Jn(e.chart)?Yn(e.chart):null}}function Zn(e){try{return JSON.parse(e)}catch{return null}}function Qn(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var $n=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=Qn()){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{}}},er=/^(\d{4})-(\d{2})-(\d{2})$/,tr=/^(\d{2}):(\d{2})$/;function nr(e,t,r){let i=er.exec(e),a=t?tr.exec(t):[``,`00`,`00`];if(!i||!a)return null;let[o,s,c,l,u]=[+i[1],+i[2],+i[3],+a[1],+a[2]];if(s<1||s>12||c<1||c>31||l>23||u>59)return null;let d=Date.UTC(o,s-1,c,l,u);return new Date(d).getUTCDate()===c?(0,n.wallToUtc)(d,r):null}function q(e,t){let r=e=>String(e).padStart(2,`0`),i=(0,n.timeParts)(e,t);return{date:`${i.year}-${r(i.month)}-${r(i.day)}`,time:`${r(i.hours)}:${r(i.minutes)}`}}var rr=class{form=null;returnFocus=null;opener=null;onOutside=e=>{let t=e.target;this.form&&!this.form.contains(t)&&!this.opener?.contains(t)&&this.close()};constructor(e,t,n){this.host=e,this.labels=t,this.onSubmit=n}isOpen(){return this.form!==null}open(e,t=null){this.close(),this.opener=t,this.returnFocus=document.activeElement;let n=document.createElement(`form`);n.className=`tcw-goto`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-label`,this.labels.title);let r=document.createElement(`div`);r.className=`tcw-goto-title`,r.textContent=this.labels.title;let i=this.field(n,this.labels.date,`date`,e.date);i.required=!0;let a=this.field(n,this.labels.time,`time`,e.time),o=document.createElement(`div`);o.className=`tcw-goto-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-btn`,s.textContent=this.labels.cancel,s.addEventListener(`click`,()=>this.close());let c=document.createElement(`button`);c.type=`submit`,c.className=`tcw-btn tcw-goto-submit`,c.textContent=this.labels.submit,o.append(s,c),n.prepend(r),n.append(o),n.addEventListener(`submit`,e=>{if(e.preventDefault(),!i.value)return;let t={date:i.value,time:a.value};this.close(),this.onSubmit(t)}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&this.close()}),this.host.appendChild(n),this.form=n,document.addEventListener(`mousedown`,this.onOutside),i.focus()}close(){if(!this.form)return;document.removeEventListener(`mousedown`,this.onOutside),this.form.remove(),this.form=null;let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}destroy(){this.close()}field(e,t,n,r){let i=document.createElement(`label`);i.className=`tcw-goto-field`;let a=document.createElement(`span`);a.textContent=t;let o=document.createElement(`input`);return o.type=n,o.value=r,o.className=`tcw-goto-input`,i.append(a,o),e.appendChild(i),o}},J=8,Y=4,X=3,ir=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,ar=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&or(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(or(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Z(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(or(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Z(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Z(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!lr(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Z(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(ir);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Z(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!cr(e)){this.hide();return}this.el.textContent=sr(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(cr(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=ur(e);s===`bottom`&&o+n.height+J+i>t.height?s=`top`:s===`top`&&o-J-i<0?s=`bottom`:s===`right`&&a+n.width+J+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+J:o-J-i):(c=s===`right`?a+n.width+J:a-J-r,l=o+n.height/2-i/2),c=Math.max(Y,Math.min(t.width-r-Y,c)),l=Math.max(Y,Math.min(t.height-i-Y,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,X],bottom:[0,-X],left:[X,0],right:[-X,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function or(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Z(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function sr(e){return e.dataset.tip??e.getAttribute(`title`)??``}function cr(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function lr(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function ur(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var dr=2,fr=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack)}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set,a=!1;for(let t of e){i.add(t.instanceId);let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId);this.fill(e,t),t.pane?e.el.parentElement!==this.host&&this.host.appendChild(e.el):e.el.parentElement!==this.stack&&(this.stack.insertBefore(e.el,this.toggle),a=!0),this.place(e,t.pane)}for(let[e,t]of this.rows)i.has(e)||(t.el.remove(),this.rows.delete(e));a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let i=this.labels,a=(t,r,i,a)=>{let o=e.buttons.get(t);!r&&document.activeElement===o&&e.buttons.get(`max`).focus(),o.hidden=!r,o.innerHTML=S(i,12),Q(o,a??t,n.label)};a(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,i.paneUp),a(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,i.paneDown),a(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?i.paneExpand:i.paneCollapse),a(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?i.paneRestore:i.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,t.dataset.instance=e;let n=new Map,r=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`;for(let i of[`up`,`down`,`fold`,`max`]){let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-pane-btn`,a.dataset.act=i,a.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,r(i))),n.set(i,a),t.appendChild(a)}this.host.appendChild(t);let i={el:t,buttons:n,key:``};return this.panes.set(e,i),i}createRow(e){let t=document.createElement(`div`);t.className=`tcw-ind-legend-row`,t.dataset.instance=e;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ind-legend-name`,n.addEventListener(`click`,()=>this.callbacks.onSettings(e));let r=document.createElement(`span`);r.className=`tcw-ind-legend-values`;let i=document.createElement(`span`);i.className=`tcw-ind-legend-actions`;let a=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`tcw-ind-legend-act`,r.dataset.act=e,r.innerHTML=S(t,13),r.addEventListener(`click`,n),i.appendChild(r),r},o=a(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!u.visible)}),s=a(`settings`,`settings`,()=>this.callbacks.onSettings(e)),c=this.callbacks.onMore?a(`more`,`more`,()=>this.callbacks.onMore?.(e,c)):null,l=a(`remove`,`x`,()=>this.callbacks.onRemove(e));t.append(n,r,i);let u={el:t,name:n,values:r,eye:o,settings:s,more:c,remove:l,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,u),u}fill(e,t){let n=`${t.label}|${t.visible}`;n!==e.state&&(e.state=n,e.visible=t.visible,e.name.textContent=t.label,e.name.title=this.labels.settings,e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible),e.eye.innerHTML=S(t.visible?`eye`:`eyeOff`,13),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(e.remove,this.labels.remove,t.label));let r=t.values.map(e=>`${e.text}${e.color??``}`).join(``);r!==e.valuesKey&&(e.valuesKey=r,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=dr;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;Q(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=S(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function pr(e,t,n){if(!t)return[];let i=e.plots;if(!i){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let a={colors:[...n],lineWidths:[],opacity:1},o=[];for(let e of i){let i=t[e.key];typeof i!=`number`||!Number.isFinite(i)||o.push({value:i,color:n.length?(0,r.plotColor)(e,a,t):null})}return o}var mr=new Map;function hr(e){let t=mr.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),mr.set(e,t)),t}function gr(e,t=`en-US`){return Math.abs(e)>=1e6?hr(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var _r=class{el;labelEl;callbacks;visible=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,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 i=document.createElement(`span`);i.className=`tcw-bracket-hint`,i.textContent=this.t(`bracket.hint`),this.el.appendChild(i);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-bracket-cancel`,a.innerHTML=`${S(`x`,14)}<span>${w(this.t(`common.cancel`))}</span>`,a.addEventListener(`click`,()=>this.callbacks.onCancel());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-confirm`,o.innerHTML=`${S(`check`,14)}<span>${w(this.t(`bracket.place`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(a),this.el.appendChild(o),e.appendChild(this.el)}show(e){this.visible=!0,this.labelEl.textContent=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`),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()}},vr=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 yr(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 br=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`span`);o.textContent=this.t(`ladder.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`div`);c.className=`tcw-ladder-cols`,c.innerHTML=[this.t(`ladder.bid`),this.t(`ladder.price`),this.t(`ladder.ask`)].map(e=>`<span>${w(e)}</span>`).join(``),this.el.appendChild(c),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(yr(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let n=e.maxVolume>0?1/e.maxVolume:0;for(let r of e.rows){let e=r.askVolume>0,i=document.createElement(`div`);i.className=`tcw-ladder-row`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-cell tcw-ladder-bid`,r.bidVolume>0?(a.textContent=xr(r.bidVolume),a.style.setProperty(`--w`,`${(r.bidVolume*n*100).toFixed(1)}%`),a.title=t.r(this.t(`ladder.sellAt`),{price:this.callbacks.formatPrice(r.price)}),a.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,r.price))):a.disabled=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,o.textContent=this.callbacks.formatPrice(r.price);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-cell tcw-ladder-ask`,r.askVolume>0?(s.textContent=xr(r.askVolume),s.style.setProperty(`--w`,`${(r.askVolume*n*100).toFixed(1)}%`),s.title=t.r(this.t(`ladder.buyAt`),{price:this.callbacks.formatPrice(r.price)}),s.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,r.price))):s.disabled=!0,i.appendChild(a),i.appendChild(o),i.appendChild(s),this.bodyEl.appendChild(i)}}};function xr(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var Sr=class{el;bodyEl;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-datawin-header`;let a=document.createElement(`span`);a.textContent=this.t(`dataWindow.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-datawin-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),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=this.t(`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``;this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),wr(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,Cr(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 Cr(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 wr(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 Tr=globalThis.Buffer;function Er(e){if(Tr)return Tr.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 Dr(e){if(Tr)return Tr.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 Or(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function kr(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Ar(e){return Or(Er(JSON.stringify(e)))}function jr(e){if(!e)return null;try{let t=Dr(kr(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 Mr=`tcw`;function Nr(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)===Mr)return decodeURIComponent(e.slice(t+1))}return null}function Pr(e,t){let[n]=e.split(`#`);return`${n}#${Mr}=${t}`}var Fr=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],Ir=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-card`;let r=document.createElement(`div`);r.className=`tcw-loading-candles`,r.setAttribute(`aria-hidden`,`true`),Fr.forEach(([e,t,n,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${n}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),r.appendChild(s)}),n.appendChild(r);let i=document.createElement(`div`);i.className=`tcw-loading-track`,i.setAttribute(`aria-hidden`,`true`),i.appendChild(document.createElement(`span`)),n.appendChild(i),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,n.appendChild(this.label),this.el.appendChild(n),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},Lr=4e3,Rr=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),Lr)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},zr=48,Br=5e4,Vr=100;function Hr(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,Vr);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Ur=[`#4c8dff`,`#a57cff`,`#1398a8`,`#e25592`,`#8a93a3`,`#62c895`],Wr=4,Gr=7,Kr=17,qr=3,Jr=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`],Yr=5e3,Xr=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},Zr={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`},Qr=e=>(e[e.length-1]?.time??0)>0xe8d4a51000?1:1e3,$r=class{chart;state;toolbar=null;sidebar=null;settings=null;statusBar=null;goToDate=null;tooltip;indicatorLegend=null;legendFrame=0;portal=document.createElement(`div`);overlayHost=()=>{let e=document.fullscreenElement===this.root?this.root:document.body;return this.portal.parentElement!==e&&e.appendChild(this.portal),this.portal};unregisterKeys=()=>{};onFullscreenChange=()=>{this.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;legendMenu=null;templates=new Gn;templatePrompt=null;intervalInput=null;markerTip=null;accountPanel=null;orderTicket=null;accountFrame=0;layoutSession=null;layoutsUI=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;legendHoverIndex=null;favoritesStore=new $n;timeframeFavorites=new $n(`tcw:tf-favorites`);customTimeframes=new $n(`tcw:tf-custom`);timeframes=[];watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;symbolInfoPanel=null;newsRequest=0;newsCache=new Map;marketTimer=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=5;replayStep=`bar`;replayStartSeq=0;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;settingsState;settingsDefaults;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;compares=[];constructor(i,a={}){this.options=a,this.symbols=a.symbols??te;let o=a.chartOptions;if(this.settingsState={...ne,...o?.numberLocale?{numberLocale:o.numberLocale}:{},...o?.timeZone==null?{}:{timezone:c(o.timeZone)},...o?.leftPriceScale===void 0?{}:{leftPriceScale:o.leftPriceScale},...o?.highLowLines===void 0?{}:{highLowLines:o.highLowLines},...o?.extendedHours===void 0?{}:{extendedHours:o.extendedHours},...o?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(o.chartTypeOptions)}:{}},this.t=t.n(t.o(a.locale,a.messages)),a.persistLayouts){let e=a.persistLayouts===!0?{}:a.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let s=this.resolveIsDark(a.theme),l=this.resolveTheme(a.theme),p={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:a.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:a.alerts!==!1||a.trading!==!1||a.drawingTools!==!1,volume:!0,legend:!0,crosshair:!0,crosshairTooltip:!1,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0,...a.chartOptions?.features};if(this.canExport=p.dataExport!==!1,this.settingsDefaults={...this.settingsState,legendVisible:p.legend!==!1,barCountdown:p.barCountdown!==!1,indicatorValueLabels:p.indicatorValueLabels!==!1},this.settingsState={...this.settingsDefaults},this.timeframes=Hn(In(a.timeframes,p.timeframes),this.customTimeframes.list(),p.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=Ln(this.timeframes,p.defaultTimeframeFavorites,!!a.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let m=a.timeframe??`5m`,h=!p.timeframes?.length||p.timeframes.includes(m)?m:this.timeframes[0]??m;this.state={symbol:a.symbol??this.symbols[0]??`BTCUSDT`,timeframe:h,chartType:a.chartOptions?.chartType??`candlestick`,isDark:s,activeIndicators:new Map,activeTool:null,magnetEnabled:p.drawingMagnet!==!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:a.adapter?`connecting`:`disconnected`,connectionMessage:a.adapter?this.t(`status.connecting`):``},g(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=s?`dark`:`light`;let _=a.dir===`ltr`||a.dir===`rtl`?a.dir:li(a.locale)?`rtl`:`ltr`;this.root.dir=_,this.portal.dir=_,i.appendChild(this.root),this.tooltip=new ar(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.ui=N(a.ui);let v=a.ui!==void 0;P(this.root,this.ui,{variables:v}),P(this.portal,this.ui,{variables:v}),a.toolbar!==!1&&(this.toolbar=new ve(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:a.chartTypes?u.filter(e=>a.chartTypes.includes(e.value)):u,indicators:ee,popularIndicatorIds:f},{onSymbolClick:()=>this.handleSymbolClick(),onSymbolInfo:a.symbolInfo===!1?void 0:()=>this.toggleSymbolInfo(),onTimeframe:e=>this.handleTimeframe(e),onToggleTimeframeFavorite:e=>this.handleToggleTimeframeFavorite(e),onAddTimeframe:a.customTimeframes===!1?void 0:e=>this.handleAddTimeframe(e),onRemoveTimeframe:e=>this.handleRemoveTimeframe(e),onChartType:e=>this.handleChartType(e),onAddIndicator:e=>this.handleAddIndicator(e),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:a.alerts===!1?void 0:()=>this.toggleAlerts(),onToggleObjects:a.objectTree===!1?void 0:()=>this.toggleObjects(),onToggleAccount:a.trading!==!1&&a.accountPanel!==!1?()=>this.accountPanel?.toggle():void 0,onLayouts:a.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),...a.indicatorTemplates===!1?{}:{onApplyIndicatorTemplate:e=>this.applyIndicatorTemplate(e),onSaveIndicatorTemplate:()=>this.promptSaveIndicatorTemplate(),onDeleteIndicatorTemplate:e=>{this.templates.remove(e),this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name),!0)}},onBracket:a.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:a.trading!==!1&&a.depthLadder?()=>this.depthLadder?.toggle():void 0,onToggleFullscreen:a.fullscreen!==!1&&typeof document<`u`&&document.fullscreenEnabled?()=>this.toggleFullscreen():void 0},this.t));let y=document.createElement(`div`);y.className=`tcw-body`,a.drawingTools!==!1&&(a.drawingFavorites&&this.favoritesStore.seedDefaults(a.drawingFavorites),this.sidebar=new Se(y,{drawingToolGroups:he(d,this.t),favorites:this.favoritesStore.list()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:p.drawingMagnet===!1?void 0:()=>this.handleToggleMagnet(),onToggleEraser:()=>this.chart.setEraserMode(!this.chart.isEraserMode()),onToggleZoomArea:()=>this.chart.setZoomAreaMode(!this.chart.isZoomAreaMode()),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(),onToggleStayInDrawing:()=>this.handleToggleStayInDrawing()},this.t)),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,y.appendChild(this.chartContainer),this.loading=new Ir(this.chartContainer,this.t(`status.loading`)),this.historyPill=new Rr(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),a.watchlist&&this.createWatchlist(y,a.watchlist===!0?{}:a.watchlist),this.root.appendChild(y);let b=document.createElement(`div`);if(b.className=`tcw-account-dock`,this.root.appendChild(b),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:l,autoScale:!0,crosshair:{mode:`magnet`},a11y:{labels:{role:this.t(`a11y.role`),summary:this.t(`a11y.summary`),empty:this.t(`a11y.empty`),view:this.t(`a11y.view`),bar:this.t(`a11y.bar`),keys:this.t(`a11y.keys`),typeName:e=>{let t=`chartType.${e}`,n=this.t(t);return n===t?e:n}}},...a.chartOptions,features:p}),a.chartOptions?.shapes||this.applyChartShapes(),this.chart.on(`visibleRangeChange`,e=>{let{from:t,to:n}=e.payload;Number.isFinite(t)&&Number.isFinite(n)&&(this.visibleBarCount=Math.max(1,n-t))}),a.navigation!==!1&&(this.chartNav=new it(this.chartContainer,{zoomIn:()=>this.chart.zoomIn(),zoomOut:()=>this.chart.zoomOut(),scroll:e=>this.chart.scrollBars(e*Math.max(1,Math.round(this.visibleBarCount/10))),reset:()=>{this.chart.fitContent(),this.changeSettings({autoScale:!0})},plotRect:()=>this.chart.getPlotRect()},this.t)),this.chart.on(`dataUpdate`,e=>this.handleDataUpdate(e.payload)),this.chart.on(`historyLoad`,e=>this.historyPill.update(e.payload)),this.chart.on(`symbolInfoChange`,e=>{let t=e.payload.info,n=t?[t.description,t.exchange].filter(Boolean).join(` · `):``;this.toolbar?.setSymbolDescription(n||null),this.refreshMarket()}),a.symbolInfo!==!1&&(this.symbolInfoPanel=new tt(this.root,this.t,{onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}})),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),a.dragDropImport!==!1&&(this.dragDrop=new e.o(this.chartContainer,{onData:(e,n,r)=>{this.setData(e);let i=t.r(this.t(`toast.fileLoaded`),{count:n.data.length,file:r.name});this.toast(n.skipped>0?`${i} (${t.r(this.t(`toast.fileSkipped`),{count:n.skipped})})`:i)},onError:(e,t)=>{this.toast(`${t.name}: ${e.message}`,`error`)}}),this.dragDrop.attach()),a.statusBar!==!1){let e=a.rangeBar!==!1;this.statusBar=new Ee(this.root,e?{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),onPreset:e=>this.chart.setVisibleRangePreset(e),onGoTo:()=>this.toggleGoToDate()}:void 0),e&&(this.goToDate=new rr(this.root,{title:this.t(`range.goTo`),date:this.t(`range.date`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`)},({date:e,time:t})=>this.goToWallTime(e,t)))}if(a.settings!==!1&&(this.settings=new we({onChange:e=>this.changeSettings(e),onReset:()=>this.resetSettings(),onClose:()=>{}},this.t,{barCountdown:p.barCountdown,logScale:p.logScale,exchangeZone:this.adapter?.resolveSymbol?()=>this.chart.getSymbolInfo()?.timezone??null:void 0},this.overlayHost)),this.symbolSearch=new Oe({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new Pe({onClose:()=>{}},this.t,this.overlayHost),this.chart.on(`drawingToolChange`,e=>{let t=e.payload.tool;t!==this.state.activeTool&&(this.state={...this.state,activeTool:t},this.updateUI())}),this.chart.on(`toolModeChange`,e=>{let{eraser:t,zoomArea:n}=e.payload;this.state={...this.state,eraser:t??this.state.eraser,zoomArea:n??this.state.zoomArea},this.updateUI()}),this.chart.on(`indicatorAdd`,()=>this.syncIndicatorsFromChart()),this.chart.on(`indicatorRemove`,()=>this.syncIndicatorsFromChart()),a.indicatorLegend!==!1){this.chart.setPaneTitlesVisible(!1),this.indicatorLegend=new fr(this.chartContainer,{onToggleVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.scheduleLegend(),this.objectTree?.isOpen()&&this.refreshObjects()},onSettings:e=>this.openIndicatorSettings(e),onRemove:e=>this.handleRemoveIndicator(e),onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t)},{show:this.t(`legend.show`),hide:this.t(`legend.hide`),settings:this.t(`legend.settings`),remove:this.t(`legend.remove`),collapse:this.t(`legend.collapse`),expand:this.t(`legend.expand`),more:this.t(`legend.more`),paneUp:this.t(`pane.moveUp`),paneDown:this.t(`pane.moveDown`),paneCollapse:this.t(`pane.collapse`),paneExpand:this.t(`pane.expand`),paneMaximize:this.t(`pane.maximize`),paneRestore:this.t(`pane.restore`)}),this.legendMenu=new z(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.legendHoverIndex=null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`])this.chart.on(e,()=>this.scheduleLegend())}if(this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;if(typeof t==`number`){if(this.replayBar.getMode()===`select`){this.startReplayAt(t);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(t?.x??null)}),this.dataWindow=new Sr(this.root,{formatPrice:e=>this.formatAlertPrice(e)},this.t),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())}),a.drawingTools!==!1){let e=new Bt,n=new Vt;for(let[e,t]of Object.entries(n.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new rn(this.root,{onBegin:e=>this.chart.beginDrawingEdit(e),onChange:(e,t)=>this.chart.updateDrawing(e,t),onEnd:(e,t)=>{this.chart.endDrawingEdit(e,{cancel:t}),this.refreshObjects()},toWallTime:e=>q(e*Qr(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=nr(e,t,this.displayTimezone());return n===null?null:n/Qr(this.chart.getData())},onAddAlert:e=>this.addDrawingAlert(e),onSaveDefault:(e,r)=>{this.chart.setDrawingToolDefaults(e,r),n.set(e,this.chart.getDrawingToolDefaults(e)),this.toast(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:e},this.t),this.chart.on(`drawingDoubleClick`,e=>this.openDrawingSettings(e.payload.id)),this.drawingStyle=new Gt(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},e,this.t)}if(this.drawingMenu=new z(this.root,this.t(`drawingMenu.label`)),this.chart.on(`drawingContextMenu`,e=>{let{id:t,x:n,y:r}=e.payload;this.openDrawingMenu(t,n,r)}),this.chartMenu=new z(this.root,this.t(`chartMenu.label`)),this.chart.on(`symbolSeriesRequest`,e=>void this.loadSymbolSeries(e.payload.symbol)),this.chart.on(`chartContextMenu`,e=>{let{area:t,x:n,y:r,price:i,time:a,pane:o}=e.payload,s=i===void 0?void 0:this.chart.roundPrice(i),c={...this.chartMenuContext(s),...o?{pane:this.chart.getPaneScale(o)}:{}};this.menuPane=o??null,this.openChartMenu(ln(t,c,this.t),n,r,{area:t,price:s,time:a})}),this.chart.on(`priceAxisAdd`,e=>{let{price:t,x:n,y:r}=e.payload,i=this.chart.roundPrice(t);this.openChartMenu(cn(this.chartMenuContext(i),this.t),n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),a.intervalTyping!==!1&&(this.intervalInput=new Wn(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e))),a.indicatorTemplates!==!1&&this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name)),a.layouts!==!1&&this.setupLayouts(a.layouts===!0||a.layouts===void 0?{}:a.layouts),a.trading!==!1&&a.accountPanel!==!1){this.orderTicket=new Sn(this.root,{onSubmit:e=>{this.chart.placeOrderIntent(e),this.toast(t.r(this.t(`ticket.sent`),{side:this.t(e.side===`buy`?`ticket.buy`:`ticket.sell`),quantity:e.quantity??1,price:this.formatAlertPrice(e.price)}))},formatPrice:e=>this.formatAlertPrice(e)},this.t),this.accountPanel=new gn(b,{onClosePosition:e=>this.chart.closePositionIntent(e),onReversePosition:e=>this.chart.reversePositionIntent(e),onCancelOrder:e=>this.chart.cancelOrderIntent(e),onNewOrder:()=>this.openOrderTicket(),formatPrice:e=>this.formatAlertPrice(e),formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`},onToggle:e=>{this.toolbar?.setActive(`account`,e),this.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.refreshAccountSoon())}if(a.trading!==!1&&(this.bracketBar=new _r(this.root,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}},this.t),this.chart.on(`bracketPlace`,e=>{let n=e.payload;this.bracketBar?.hide(),this.toast(t.r(this.t(n.side===`buy`?`bracket.longPlaced`:`bracket.shortPlaced`),{rr:n.riskReward.toFixed(2)}))}),a.depthLadder&&(this.depthLadder=new br(this.root,{onTrade:(e,n)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:n}),this.toast(t.r(this.t(e===`buy`?`order.buyLimit`:`order.sellLimit`),{price:this.formatAlertPrice(n)}))},formatPrice:e=>this.formatAlertPrice(e)},void 0,this.t)),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),a.alerts!==!1&&(this.alertsPanel=new ft(this.root,{onAdd:({price:e,condition:t,message:n,channel:r,label:i,options:a})=>{try{return this.chart.addAlert(e,t,n,r,i,a),!0}catch{return this.toast(this.t(`alerts.invalid`),`error`),!1}},formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),this.chart.on(`alertExpired`,e=>{let n=e.payload;this.toast(t.r(this.t(`alerts.expiredToast`),{text:n.message??this.alertText(n)})),this.refreshAlerts()}),a.alertNotifications&&(this.alertNotifier=new vr(a.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let n=e.payload,r=`${this.alertText(n)}${n.message?` — ${n.message}`:``}`;this.toast(`🔔 ${t.r(this.t(`alerts.fired`),{text:r})}`,`info`),this.alertNotifier?.notify(r),this.refreshAlerts()})),a.objectTree!==!1){this.indicatorSettings=new Pt(this.root,{onApply:(e,t)=>{this.chart.updateIndicator(e,t),this.syncIndicatorsFromChart()},onStyle:(e,t)=>this.chart.updateIndicatorStyle(e,t),onLevels:(e,t)=>this.chart.setIndicatorLevels(e,t),onScale:(e,t)=>this.chart.setIndicatorScale(e,t),onClose:()=>{}},this.t),this.objectTree=new Et(this.root,{onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects(),this.scheduleLegend()},onRemoveDrawing:e=>{this.drawingSettings?.editing()===e&&this.drawingSettings.close(!0),this.chart.removeDrawing(e),this.refreshObjects()},onConfigureDrawing:this.drawingSettings?e=>this.openDrawingSettings(e):void 0,onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onToggleGroupVisible:(e,t)=>{this.chart.setDrawingGroupVisible(e,t),this.refreshObjects()},onToggleGroupLocked:(e,t)=>{this.chart.setDrawingGroupLocked(e,t),this.refreshObjects()},onUngroup:e=>{this.chart.ungroupDrawings(e),this.refreshObjects()},onRenameGroup:(e,t)=>{this.chart.renameDrawingGroup(e,t),this.refreshObjects()},onAddCompare:p.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)},this.t);let e=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},t=0;this.chart.on(`drawingCreate`,e),this.chart.on(`drawingRemove`,e),this.chart.on(`drawingUpdate`,()=>{t||!this.objectTree?.isOpen()||(t=requestAnimationFrame(()=>{t=0,this.destroyed||e()}))}),this.chart.on(`indicatorAdd`,e),this.chart.on(`indicatorRemove`,e),this.chart.on(`indicatorChange`,e)}if(this.commandPalette=new De({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.overlayHost,this.t),this.boundGlobalKeydown=e=>{if(this.replayBar?.isMounted()&&this.handleReplayKey(e))return;let t=G(this.root);if((e.ctrlKey||e.metaKey)&&e.key===`k`){if(!t)return;e.preventDefault(),this.toggleCommandPalette()}else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`)){if(!t)return;e.preventDefault(),this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}else if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`s`||e.key===`S`)){if(!this.layoutSession||K()||!G(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&Zr[e.code]){if(e.defaultPrevented||K()||!t||Xr()||this.options.drawingTools===!1)return;e.preventDefault(),this.handleDrawingTool(Zr[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||K()||Xr()||!G(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.intervalInput.open(e.key)}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`)){if(K()||!t)return;e.code===`KeyI`?(e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale})):this.goToDate&&(e.preventDefault(),this.toggleGoToDate())}else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(K()||!t)return;e.preventDefault(),this.hotkeySheet?.open()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Kn(this.root),a.adapter&&(this.adapter=a.adapter,this.connectStream()),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.refreshMarket(),this.updateUI(),a.onReady?.(this.chart),a.shareUrl&&typeof location<`u`){let e=Nr(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e;let t=this.watchlistStore;t&&this.watchlistFromSymbols&&t.replace(t.getLists().map(t=>t.id===`default`?{...t,symbols:e}:t))}getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}toggleSymbolInfo(e){let t=this.symbolInfoPanel;t&&(e===void 0?t.toggle():e?t.open():t.close())}refreshMarket(){let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now());this.statusBar?.setMarket(e.state,this.t(e.state===`open`?`symbolInfo.open`:`symbolInfo.closed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.chart.getSymbolInfo(),r=this.state.symbol,i=this.quotes.get(r),a=ai(this.chart.getData(),e?.timezone),o=e=>this.formatAlertPrice(e),s=this.textLocale(),c=i?.last??a?.close,l=i?.prevClose??a?.prevClose,u=i?.change??(c!==void 0&&l!==void 0?c-l:void 0),d=c!==void 0&&u!==void 0?c-u:void 0,ee=i?.changePercent??(u!==void 0&&d?u/d*100:void 0),f=(0,n.marketStatus)(e,Date.now()),te=this.t(f.state===`open`?`symbolInfo.open`:f.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(f.state!==`always`&&f.next!==null){let e=oi(f.next-Date.now(),s);te+=` · ${t.r(this.t(f.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:e})}`}let ne=[],p=(e,t)=>{t&&ne.push({label:e,value:t})},m=e=>e===void 0?void 0:o(e);p(this.t(`dataWindow.open`),m(i?.open??a?.open)),p(this.t(`dataWindow.high`),m(i?.high??a?.high)),p(this.t(`dataWindow.low`),m(i?.low??a?.low)),p(this.t(`symbolInfo.prevClose`),m(l));let h=i?.volume??a?.volume;p(this.t(`dataWindow.volume`),h===void 0?void 0:si(h,this.intlLocale())),p(this.t(`symbolInfo.bid`),m(i?.bid)),p(this.t(`symbolInfo.ask`),m(i?.ask)),p(this.t(`symbolInfo.tick`),e?.minTick===void 0?void 0:String(e.minTick)),p(this.t(`symbolInfo.currency`),e?.currency),p(this.t(`symbolInfo.timezone`),e?.timezone),p(this.t(`symbolInfo.hours`),ci(e,s));let g=(u??0)>=0?`+`:`-`;return{symbol:r,description:e?.description,meta:[e?.exchange,e?.type].filter(Boolean).join(` · `)||void 0,price:c===void 0?void 0:o(c),change:u===void 0?void 0:{text:`${g}${o(Math.abs(u))}${ee===void 0?``:` (${g}${Math.abs(ee).toFixed(2)}%)`}`,up:u>=0},status:{state:f.state,text:te},stats:ne}}loadNews(){let e=this.symbolInfoPanel;if(!e?.isOpen())return;let t=this.options.adapter,r=this.options.news??(t?.fetchNews?t.fetchNews.bind(t):null);if(!r){e.renderNews({kind:`none`});return}let i=this.state.symbol,a=++this.newsRequest,o=t=>{let n=this.textLocale();e.renderNews({kind:`items`,items:t.map(e=>({title:e.title,url:e.url,meta:[e.source,oi(e.time-Date.now(),n)].filter(Boolean).join(` · `)}))})},s=this.newsCache.get(i);if(s&&Date.now()-s.at<ri){o(s.items);return}e.renderNews({kind:`loading`}),Promise.resolve().then(()=>r(i,ni)).then(e=>{if(a!==this.newsRequest||this.destroyed)return;let t=(0,n.readNews)(e,ni);this.newsCache.set(i,{at:Date.now(),items:t}),o(t)}).catch(()=>{a===this.newsRequest&&!this.destroyed&&e.renderNews({kind:`failed`})})}intlLocale(){return this.settingsState.numberLocale||this.options.locale||`en`}textLocale(){return this.options.locale||`en`}createWatchlist(e,t){let n=t.persist?ti():null,r=new et({lists:t.lists,activeList:t.activeList,symbols:this.symbols,defaultName:this.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.options.adapter?.subscribeQuotes?this.options.adapter:null);let i=e=>this.t(e);this.watchlist=new Ue(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open(this.symbols,this.state.symbol,e=>r.add(e),this.symbolSearchFn()),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e)},{title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`)}),this.watchlist.setActive(this.state.symbol),this.watchlist.setLocale(this.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.destroyed||!Array.isArray(e))return;let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.state.symbol)&&this.refreshSymbolInfo()}async setSymbol(e){this.flushActiveLayout(),e!==this.state.symbol&&this.chart.clearFills(),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.watchlist?.setActive(e),this.refreshMarket(),this.loadNews(),this.layoutSession?.changed(),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.state.symbol))return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.state.symbol);n===void 0&&this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.state.symbol,r),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:n??this.sessionRefPrice??e[0].open,sparkline:r.slice()})}async setTimeframe(e){if(this.chart.isTimeframeAllowed(e)){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.layoutSession?.changed(),this.adapter){await this.connectStream();return}if(this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=a(e))}await this.switchLocalTimeframe()}}}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.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.chart.setTheme(n),this.updateUI()}getChart(){return this.chart}setUI(e){this.ui=N(e),P(this.root,this.ui),P(this.portal,this.ui),this.applyChartShapes()}getUI(){return N({...this.ui})}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){this.destroyed||(this.destroyed=!0,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legendFrame&&cancelAnimationFrame(this.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.drawingStyle?.destroy(),this.drawingSettings?.destroy(),this.drawingMenu?.destroy(),this.chartMenu?.destroy(),this.legendMenu?.destroy(),this.templatePrompt?.destroy(),this.intervalInput?.destroy(),this.markerTip?.remove(),this.layoutSession?.destroy(),this.layoutsUI?.destroy(),this.accountPanel?.destroy(),this.orderTicket?.destroy(),this.accountFrame&&cancelAnimationFrame(this.accountFrame),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.stopQuotes?.(),this.stopQuotes=null,this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.goToDate?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),_())}handleSymbolClick(){this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}symbolSearchFn(){if(this.options.searchSymbols)return this.options.searchSymbols;let e=this.adapter;if(e?.searchSymbols)return(t,n)=>e.searchSymbols(t,{signal:n,limit:50})}handleTimeframe(e){this.setTimeframe(e)}toggleFullscreen(){if(document.fullscreenElement===this.root){document.exitFullscreen().catch(()=>{});return}this.root.requestFullscreen().catch(e=>{this.toast(e instanceof Error?e.message:this.t(`toast.fullscreenUnavailable`),`error`)})}drawingToolName(e){let t=`tool.${e}`,n=this.t(t);return n===t?this.chart.getDrawingToolDescriptor(e)?.name??e:n}openDrawingSettings(e){let t=this.chart.getDrawings().find(t=>t.id===e),n=t?this.chart.getDrawingToolDescriptor(t.type):null;!t||!n||!this.drawingSettings||this.drawingSettings.open({id:e,type:t.type,name:this.drawingToolName(t.type),style:{...t.style},options:this.chart.getDrawingOptions(e),defs:n.options??{},anchors:t.anchors.map(e=>({...e})),fill:n.fill===!0,text:n.text===!0,alertable:this.chart.canAddDrawingAlert(e)})}addDrawingAlert(e){let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.drawingToolName(n.type):``;this.chart.addDrawingAlert(e,{label:r})&&this.toast(t.r(this.t(`drawingSettings.alertAdded`),{name:r}))}openDrawingMenu(e,t,n){if(!this.drawingMenu)return;let r=new Map(this.chart.getDrawings().map(e=>[e.id,e])),i=this.chart.getSelectedDrawingIds().flatMap(e=>{let t=r.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(i.length===0)return;let a=sn({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect(),c=i.map(e=>e.id);this.drawingMenu.open(a,o.left-s.left+t,o.top-s.top+n,t=>this.runDrawingMenuAction(e,c,t))}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.openDrawingSettings(e);return;case`alert`:this.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.chart.moveDrawing(e,n);break;case`group`:this.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.chart.duplicateDrawing(e);break;case`delete`:{let e=this.drawingSettings?.editing();e&&t.includes(e)&&this.drawingSettings?.close(!0),this.chart.removeDrawings(t);break}}this.objectTree?.isOpen()&&this.refreshObjects()}chartMenuContext(e){let t=this.chart.getDrawings(),n=this.chart.getData();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.formatAlertPrice(e),canAlert:this.alertsPanel!==null,canTrade:this.options.trading!==!1,canOrderTicket:this.orderTicket!==null,canDraw:this.options.drawingTools!==!1,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canGoToDate:this.goToDate!==null,canExport:this.canExport,autoScale:this.chart.isAutoScale(),scaleMode:this.settingsState.scaleMode,inverted:this.chart.isInvertScale()}}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.options.chartMenuItems?.(r)??[],a=[...e,...e.length>0&&i.length>0?[`separator`]:[],...i.map((e,t)=>({id:`host:${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))];if(a.length===0)return;let o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{e.startsWith(`host:`)?i[Number(e.slice(5))]?.onSelect():this.runChartMenuAction(e,r.price)})}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar.addHostButton(e),n=()=>{let e=t.querySelector(`.tcw-host-btn-text`);if(e)return e;let n=document.createElement(`span`);return n.className=`tcw-host-btn-text`,t.appendChild(n),n};return{element:t,setActive:n=>{t.classList.toggle(`tcw-active`,n),e.toggle&&t.setAttribute(`aria-pressed`,String(n))},setText:r=>{n().textContent=r,_e(t,e.label)},remove:()=>t.remove()}}runChartMenuAction(e,n){let r=n??NaN;switch(e){case`alert`:this.chart.addAlert(r,`crossing`),this.toast(t.r(this.t(`chartMenu.alertAdded`),{price:this.formatAlertPrice(r)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.placeOrderAt(e,r);break;case`orderTicket`:this.openOrderTicket(n);break;case`exportData`:this.chart.exportAllData(`csv`,`${this.state.symbol}-${this.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.chart.getPaneScale(t);this.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.chart.getData();e.length>0&&this.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:r}]});break}case`resetView`:this.chart.fitContent(),this.changeSettings({autoScale:!0});break;case`hideDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.chart.removeDrawings(this.chart.getDrawings().map(e=>e.id));break;case`settings`:this.openSettings();break;case`autoScale`:this.changeSettings({autoScale:!this.chart.isAutoScale()});break;case`logScale`:this.changeSettings({scaleMode:this.settingsState.scaleMode===`logarithmic`?`regular`:`logarithmic`});break;case`percentScale`:this.changeSettings({scaleMode:this.settingsState.scaleMode===`percentage`?`regular`:`percentage`});break;case`invertScale`:this.changeSettings({invertScale:!this.chart.isInvertScale()});break;case`goToDate`:this.toggleGoToDate();break}this.objectTree?.isOpen()&&this.refreshObjects()}toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||t.toggle()}openOrderTicket(e){let t=this.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null})}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.chart.getPositions(),orders:this.chart.getOrders(),fills:this.chart.getFills(),price:t,realisedPnl:this.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,n){let r=e.startsWith(`buy`)?`buy`:`sell`,i=e.endsWith(`Stop`);this.chart.placeOrderIntent(i?{side:r,type:`stop`,price:n,stopPrice:n,quantity:1}:{side:r,type:`limit`,price:n,quantity:1}),this.toast(t.r(this.t(`order.${e}`),{price:this.formatAlertPrice(n)}))}displayTimezone(){let e=s(this.settingsState.timezone);return e===`exchange`?this.chart.getEffectiveTimezone():e}toggleGoToDate(){if(!this.goToDate)return;if(this.goToDate.isOpen()){this.goToDate.close();return}let e=this.chart.getData();e.length!==0&&this.goToDate.open(q(e[e.length-1].time*Qr(e),this.displayTimezone()),this.root.querySelector(`[data-role="goto"]`))}goToWallTime(e,t){let n=nr(e,t,this.displayTimezone()),r=this.chart.getData();if(n===null||r.length===0)return;let i=n/Qr(r);this.chart.goToTime(i),i<r[0].time&&this.toast(this.t(`range.beforeData`))}pinnedTimeframes(){let e=this.timeframeFavorites.list();return this.timeframes.filter(t=>e.includes(t))}timeframeMenu(){return this.timeframes.map(e=>({value:e,label:Nn(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){let t=Vn(e);return!t||!this.chart.isTimeframeAllowed(t)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,t)||!this.adapter&&(0,n.tickBarCount)(t)!==null?!1:(this.timeframes.includes(t)||(this.customTimeframes.add(t),this.timeframeFavorites.add(t),this.timeframes=Hn(this.timeframes,[t]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(t),!0)}showMarkerTip(e){let{marker:n}=e;if(!n){this.markerTip&&(this.markerTip.hidden=!0);return}this.markerTip||(this.markerTip=document.createElement(`div`),this.markerTip.className=`tcw-marker-tip`,this.markerTip.setAttribute(`role`,`tooltip`),this.chartContainer.appendChild(this.markerTip));let r=n.direction===`long`?this.t(`account.long`):n.direction===`short`?this.t(`account.short`):this.t(`markers.neutral`),i=document.createElement(`strong`);i.textContent=n.label?`${n.label} · ${n.source}`:n.source;let a=document.createElement(`div`);a.textContent=`${r} · ${this.formatAlertPrice(n.price)} · ${t.r(this.t(`markers.confidence`),{pct:Math.round(n.confidence*100)})}`;let o=document.createElement(`div`),{date:s,time:c}=q(n.time,this.displayTimezone());o.textContent=`${s} ${c}`,this.markerTip.replaceChildren(i,a,o),this.markerTip.hidden=!1;let l=this.chartContainer.getBoundingClientRect(),u=Math.min(e.x+12,Math.max(0,l.width-this.markerTip.offsetWidth-4)),d=Math.max(0,e.y-this.markerTip.offsetHeight-10);this.markerTip.style.left=`${u}px`,this.markerTip.style.top=`${d}px`}selectTypedTimeframe(e){return!this.chart.isTimeframeAllowed(e)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,e)?!1:(this.timeframes.includes(e)||(this.customTimeframes.add(e),this.timeframes=Hn(this.timeframes,[e]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(e),!0)}applyIndicatorTemplate(e){let n=this.templates.get(e);n&&(this.chart.applyIndicatorSetup(n.indicators),this.syncIndicatorsFromChart(),this.updateUI(),this.toast(t.r(this.t(`templates.applied`),{name:n.name})))}promptSaveIndicatorTemplate(){if(this.chart.getActiveIndicators().length===0){this.toast(this.t(`templates.nothing`),`error`);return}this.templatePrompt??=new Tn(this.root,this.t),this.templatePrompt.open({title:this.t(`templates.saveTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`templates.namePlaceholder`),onSubmit:e=>{try{this.templates.save(e,this.chart.getIndicatorSetup())}catch(e){throw this.toast(this.t(`templates.saveFailed`),`error`),e}this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name)),this.toast(t.r(this.t(`templates.saved`),{name:e}))}})}handleRemoveTimeframe(e){this.customTimeframes.has(e)&&(this.customTimeframes.remove(e),this.timeframeFavorites.remove(e),this.timeframes=this.timeframes.filter(t=>t!==e),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes()),this.updateUI())}handleToggleTimeframeFavorite(e){this.timeframeFavorites.toggle(e),this.toolbar?.setTimeframeFavorites(this.pinnedTimeframes()),this.updateUI()}setData(e){this.localSeq++,this.baseSeries=e,this.baseTimeframeMs=a(e),this.applyTimeframeData(),this.adapter||this.loading.end()}async switchLocalTimeframe(){if(!this.baseSeries)return;let e=++this.localSeq,t=this.lastLocalSwitchMs>=zr||this.baseSeries.length>=Br;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Hr(),e!==this.localSeq||this.destroyed))return;this.applyTimeframeData()}finally{e===this.localSeq&&this.loading.end()}}applyTimeframeData(){if(!this.baseSeries)return;let e=performance.now(),t=(0,n.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&t>this.baseTimeframeMs){let e=this.options.weekStartsOn??1;this.chart.setData(i(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries);this.lastLocalSwitchMs=performance.now()-e}handleDataUpdate(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.length==`number`){t.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(t.error!==void 0){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,t.error||this.t(`status.connectionFailed`)));return}switch(t.connection?.state){case`connected`:this.loading.hasFailed()&&this.loading.end(),!this.loading.isActive()&&this.state.connectionState!==`connected`&&this.setConnectionState(`connected`,this.t(`status.live`));break;case`reconnecting`:this.loading.isActive()||this.setConnectionState(`connecting`,this.t(`status.connecting`));break;case`error`:this.loading.isActive()||this.setConnectionState(`error`,this.t(`status.connectionFailed`));break}}setConnectionState(e,t){this.state={...this.state,connectionState:e,connectionMessage:t},this.updateUI()}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?this.t(`toast.pinned`):this.t(`toast.unpinned`))}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params}));return Ar({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=jr(e);return t?(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.applyChartType(t.chartType),this.chart.setScaleMode(t.scaleMode),this.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.chart.setDrawings(t.drawings),this.updateUI(),!0):!1}async copyChartImage(){let e=await this.chart.copyScreenshot();this.toast(e?this.t(`toast.imageCopied`):this.t(`toast.imageCopyFailed`),e?`info`:`error`)}async copyShareLink(){let e=Pr(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.toast(this.t(`toast.linkCopied`))}catch{this.toast(this.t(`toast.copyFailed`),`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=e.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),i=n?r.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>({key:t,value:n[e]})):[];return{name:e.descriptor.name,values:i}}).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(),n=t.find(t=>t.instanceId===e);if(!n)return;let r=this.chart.getIndicatorStyle(e),i=n.descriptor.placement===`panel`||!!n.pane;this.indicatorSettings.open({instanceId:e,name:n.descriptor.name,defaults:n.descriptor.defaultConfig,params:n.params,inputs:n.descriptor.inputs,lineSources:ei(e,t),plots:n.descriptor.plots,colors:r?.colors,lineWidth:r?.lineWidths[0],levels:i?this.chart.getIndicatorLevels(e):void 0,defaultLevels:n.descriptor.levels,scale:i?void 0:this.chart.getIndicatorScale(e)})}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:Ot(e.type,this.t),visible:e.visible,locked:e.locked,group:e.group})),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(this.t(`toast.compareNeedsAdapter`),`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.pickCompareWay(e)},this.symbolSearchFn())}pickCompareWay(e){let n=this.state.symbol,r=[{id:`percent`,label:this.t(`compare.percent`)},{id:`scale`,label:this.t(`compare.ownScale`)},{id:`pane`,label:this.t(`compare.ownPane`)},{id:`spread`,label:t.r(this.t(`compare.spread`),{main:n,other:e})},{id:`ratio`,label:t.r(this.t(`compare.ratio`),{main:n,other:e})}],i=this.chart.getPlotRect();this.chartMenu?.open(r,i.x+24,i.y+24,t=>void this.addCompareSymbol(e,t))}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.toast(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){let t=n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:e},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbol`,{symbol:e}):this.chart.addIndicator(`spread`,{symbol:e,mode:n});t&&n===`pane`&&this.chart.moveIndicatorToPane(t,`new`);return}if(this.compares.some(t=>t.symbol===e))return;let i=Ur[this.compares.length%Ur.length],a=`cmp_${e}`;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(a,e,n,i),this.compares=[...this.compares,{id:a,symbol:e,color:i}],this.refreshObjects(),this.toast(t.r(this.t(`toast.comparing`),{symbol:e}))}catch(t){this.toast(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}async loadSymbolSeries(e){if(!this.adapter){this.toast(this.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.state.timeframe,n=(this.symbolLoads.get(e)??0)+1;this.symbolLoads.set(e,n);let i=()=>this.destroyed||t!==this.state.timeframe||this.symbolLoads.get(e)!==n;try{let n=Math.max(this.chart.getData().length,this.options.historyLimit??500),a=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,n);if(i())return;this.chart.setSymbolSeries(e,a)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.toast(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}async refetchCompares(){for(let e of this.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);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(0,r.withResampling)(this.adapter).fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.chart.getAlerts().map(t=>this.alertListItem(t,e)))}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return at(this.alertListItem(e,this.buildAlertSources()),this.t,e=>this.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.t(`alerts.source.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=this.chart.getPriceFormatter?.();if(t)return t(e);let n=Math.abs(e),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}handleChartType(e){let t=this.state.chartType;e!==t&&(this.applyChartType(e),this.chart.recordUndo({subject:`chartType`,undo:()=>this.applyChartType(t),redo:()=>this.applyChartType(e)}))}applyChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.updateUI()}handleAddIndicator(e){this.chart.addIndicator(e)}handleRemoveIndicator(e){this.chart.removeIndicator(e)}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of ee)e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let t of u)e.push({id:t.value,label:me(t,this.t),category:`chartType`,active:this.state.chartType===t.value});for(let t of he(d,this.t))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 this.timeframes)e.push({id:t,label:Nn(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`screenshot`,label:this.t(`action.screenshot`),category:`action`,shortcut:``},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},...this.symbolInfoPanel?[{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`}]:[],{id:`clearDrawings`,label:this.t(`action.clearDrawings`),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?this.t(`toast.autoFibAdded`):this.t(`toast.noSwing`));break}case`dataWindow`:this.toggleDataWindow();break;case`symbolInfo`:this.toggleSymbolInfo();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.chart.setEraserMode(!1),this.chart.setZoomAreaMode(!1),this.updateUI()}handleToggleStayInDrawing(){let e=!this.state.stayInDrawing;this.state={...this.state,stayInDrawing:e},this.chart.setStayInDrawingMode(e),this.updateUI()}handleToggleMagnet(){let e=this.state.magnetEnabled?this.state.magnetStrong?`off`:`strong`:`weak`;this.state={...this.state,magnetEnabled:e!==`off`,magnetStrong:e===`strong`},this.chart.setDrawingMagnetMode(e),this.updateUI()}handleToggleTheme(){let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.chart.setTheme(e?n.DARK_THEME:n.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.settingsState={...this.settingsState,chartTypeOptions:this.chart.getChartTypeOptions?.()??{}},this.settings?.open(this.settingsState,this.state.chartType)}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)}getLayoutSession(){return this.layoutSession}getSymbol(){return this.state.symbol}getTimeframe(){return this.state.timeframe}captureLayout(){let e=this.chart.saveState(),t=e?Zn(e):null,n=t&&typeof t==`object`?Yn(t):null;return{v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,scaleMode:this.settingsState.scaleMode,invertScale:this.settingsState.invertScale,chart:n}}async restoreLayout(e){if(e.symbol!==this.state.symbol&&await this.setSymbol(e.symbol),e.timeframe!==this.state.timeframe&&await this.setTimeframe(e.timeframe),!this.destroyed){if(e.chart){this.chart.loadState(JSON.stringify(Yn(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}this.applySettings({scaleMode:e.scaleMode,invertScale:e.invertScale}),this.syncIndicatorsFromChart(),this.updateUI()}}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Xn(Zn(e));return t?(await this.restoreLayout(t),!0):!1}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.state.symbol,timeframe:this.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new kn(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`}}),this.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}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.syncIndicatorsFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}syncIndicatorsFromChart(){let t=new Map;for(let n of this.chart.getActiveIndicators())t.set(n.instanceId,{id:n.id,label:e.C(n.id,n.params,n.descriptor.defaultConfig,n.descriptor.shortName)});this.state={...this.state,activeIndicators:t},this.updateUI()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new Le({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),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)},onRandomStart:()=>{let e=this.replayTotal(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)))},onClose:()=>this.exitReplay(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),random:e(`replay.random`),realtime:e(`replay.realtime`),barsPerSecond:e(`replay.barsPerSecond`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`)});let t=[{value:`bar`,label:e(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];t.some(e=>e.value===this.replayStep)||(this.replayStep=`bar`),this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),speed:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep}),this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade)}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t)}startReplayAt(e,t=!1){let n=this.replayBar;if(!n)return;let r=this.replayTotal(),i=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,r-1));this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),n.setMode(`replay`);let a=++this.replayStartSeq,o=e=>{this.destroyed||this.replayBar!==n||!n.isMounted()||a!==this.replayStartSeq||(this.chart.replayStart({speed:this.replaySpeed,interval:1e3,startIndex:i,paused:!0,...e?{steps:e}:{}}),t&&this.chart.replayResume(),n.setState(t?`playing`:`paused`),this.syncReplayBar(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),150))};if(this.replayStep===`bar`){o(null);return}this.replayStepsFor(this.replayStep).then(e=>{a===this.replayStartSeq&&(e||this.toast(this.t(`replay.stepsFailed`),`error`),o(e))})}replayStepOptions(){let e=(0,n.timeframeToMs)(this.state.timeframe);return Jr.filter(t=>{let i=(0,n.timeframeToMs)(t);return!(i<e)||e%i!==0?!1:this.adapter?(0,r.servesTimeframe)(this.adapter,t):this.baseSeries!==null&&this.baseTimeframeMs>0&&i>=this.baseTimeframeMs&&i%this.baseTimeframeMs===0})}async replayStepsFor(e){let t=`${this.state.symbol}|${this.state.timeframe}|${e}`;if(this.replayStepsCache?.key===t)return this.replayStepsCache.steps;let a=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e))),i=Math.min(Yr,Math.max(this.chart.getData().length,100)*t);try{a=await(0,r.withResampling)(this.adapter).fetchHistory(this.state.symbol,e,i)}catch{a=null}}else this.baseSeries&&(a=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e));return!a||a.length===0?null:(this.replayStepsCache={key:t,steps:a},a)}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||e.getMode()!==`replay`)return;if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,Math.min(t.total-1,t.current+e))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented)return!1;let t=document.activeElement;return t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable)?!1:e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&this.replayBar?.getMode()===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===`Escape`&&this.replayBar?.getMode()===`select`?(this.exitReplay(),!0):!1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),this.replayBar?.unmount(),this.replayBar=null}applySettings(e){this.settingsState={...this.settingsState,...e},(e.scaleMode!==void 0||e.logScale!==void 0||e.invertScale!==void 0)&&this.layoutSession?.changed(),this.scheduleLegend(),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.legendVisible!==void 0&&this.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&this.chart.setLeftPriceScaleVisible(e.leftPriceScale),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),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimezone(s(e.timezone)),e.highLowLines!==void 0&&this.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.chart.setChartTypeOptions({renko:{},lineBreak:{},kagi:{},pointAndFigure:{},rangeBars:{},...e.chartTypeOptions});let t={...this.chart.getTheme()},r=!1;e.candleUpColor!==void 0&&(t.candleUp=e.candleUpColor,t.volumeUp=(0,n.volumeColor)(e.candleUpColor),r=!0),e.candleDownColor!==void 0&&(t.candleDown=e.candleDownColor,t.volumeDown=(0,n.volumeColor)(e.candleDownColor),r=!0),e.candleUpWick!==void 0&&(t.candleUpWick=e.candleUpWick,r=!0),e.candleDownWick!==void 0&&(t.candleDownWick=e.candleDownWick,r=!0),e.backgroundColor!==void 0&&(t.background=e.backgroundColor,r=!0),e.gridColor!==void 0&&(t.grid=e.gridColor,r=!0),r&&this.chart.setTheme(t)}resetSettings(){let e={...this.settingsState};this.settingsState={...this.settingsDefaults},this.applySettings(this.settingsState);let t={...this.settingsState};JSON.stringify(e)!==JSON.stringify(t)&&this.chart.recordUndo({undo:()=>this.restoreSettings(e),redo:()=>this.restoreSettings(t)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]])),r=n();this.applySettings(e);let i=n();JSON.stringify(r)!==JSON.stringify(i)&&this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r),redo:()=>this.restoreSettings(i)})}restoreSettings(e){this.applySettings(e),this.settings?.refresh(this.settingsState)}async connectStream(){if(!this.adapter)return;let e=++this.connectSeq;this.state={...this.state,connectionState:`connecting`,connectionMessage:this.t(`status.connecting`)},this.updateUI(),this.loading.begin(this.chart.getData().length>0);try{if(this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500,historyPageSize:this.options.historyPageSize}),e!==this.connectSeq||this.destroyed)return;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.loading.hasFailed()?this.state={...this.state,connectionState:`error`}:(this.loading.end(),this.state={...this.state,connectionState:`connected`,connectionMessage:this.t(`status.live`)}),this.refetchCompares()}catch(t){if(e!==this.connectSeq||this.destroyed)return;this.loading.fail(this.t(`status.connectionFailed`)),this.state={...this.state,connectionState:`error`,connectionMessage:t instanceof Error?t.message:this.t(`status.connectionFailed`)}}this.updateUI()}scheduleLegend(){!this.indicatorLegend||this.legendFrame||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.indicatorLegend||this.destroyed)return;let t=this.chart.getData().length-1,n=this.chart.isTimeAligned()?this.legendHoverIndex:null,r=n===null?t:Math.min(Math.max(n,0),t),i=new Map;for(let e of this.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.settingsState.numberLocale||`en-US`,o=this.chart.getActiveIndicators().map(t=>{let n=i.get(t.instanceId)??null,o=r>=0?this.chart.getIndicatorOutput(t.instanceId)?.series?.[r]:null,s=this.chart.getIndicatorStyle(t.instanceId)?.colors??[],c=pr(t.descriptor,o,s);return{instanceId:t.instanceId,label:e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName),visible:t.visible,values:c.map(e=>({text:n?gr(e.value,a):this.chart.formatPrice(e.value),color:e.color})),pane:n?{x:n.x+Wr,y:n.y+Math.min(Gr+n.row*Kr,Math.max(Gr,n.height-Kr)),width:n.width-2*Wr}:null}}),s=this.chart.getPlotRect(),c=this.chart.getMaximizedPane(),l=e=>o.find(t=>t.instanceId===e)?.label??``,u=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-Wr,y:e.rect.y+qr,label:l(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:c===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(o,{left:s.x+Wr,top:this.chart.getLegendBottom()+1},u)}runPaneAction(e,t){t===`up`||t===`down`?this.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.chart.setPaneCollapsed(e,t===`collapse`):this.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.t(`legend.movePrice`),icon:`trendingUp`}),c.length>0&&c.push(`separator`),c.push({id:`settings`,label:this.t(`legend.settings`),icon:`settings`},{id:`remove`,label:this.t(`legend.remove`),icon:`trash`,danger:!0});let l=t.getBoundingClientRect(),u=this.root.getBoundingClientRect();n.open(c,l.left-u.left,l.bottom-u.top+2,t=>{t===`settings`?this.openIndicatorSettings(e):t===`remove`?this.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend()},t)}updateUI(){this.scheduleLegend(),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`?n.DARK_THEME:e===`light`?n.LIGHT_THEME:typeof e==`object`?e:n.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}};function ei(t,i){let a=e=>{let t=(0,r.sourceParam)(e.descriptor);return t&&(0,n.parseIndicatorSource)(e.params[t])?.instanceId||null},o=new Set([t]);for(let e=!0;e;){e=!1;for(let t of i){let n=a(t);n&&o.has(n)&&!o.has(t.instanceId)&&(o.add(t.instanceId),e=!0)}}let s=[];for(let t of i){if(o.has(t.instanceId))continue;let r=e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName);for(let e of t.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(t.instanceId,e.key),label:`${r}: ${e.title}`})}return s}function ti(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ni=10,ri=5*6e4,ii=864e5;function ai(e,t){if(e.length===0)return null;let r=t&&(0,n.isValidTimeZone)(t)?t:null,i=e=>{let t=e<1e11?e*1e3:e;return Math.floor((t+(r?(0,n.zoneOffsetMinutes)(r,t)*6e4:0))/ii)},a=e[e.length-1],o=i(a.time),s=e.length-1;for(;s>0&&i(e[s-1].time)===o;)s--;let c=-1/0,l=1/0,u=0;for(let t=s;t<e.length;t++)c=Math.max(c,e[t].high),l=Math.min(l,e[t].low),u+=e[t].volume??0;return{open:e[s].open,high:c,low:l,close:a.close,volume:u,prevClose:s>0?e[s-1].close:void 0}}function oi(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function si(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function ci(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}function li(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var ui={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},di=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function fi(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function pi(e){return JSON.parse(JSON.stringify(e))}function mi(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function hi(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!fi(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(Xn);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...ui};for(let e of di)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var gi=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;syncButtons=new Map;layoutsButton=null;session=null;layoutsUI=null;t;destroyed=!1;unregisterKeys=()=>{};onKeyDown=e=>{!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!==`s`&&e.key!==`S`||!this.layoutsUI||K()||!G(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=fi(n.layout)?n.layout:`1x2`,this.sync={...ui,...n.sync},this.t=t.n(t.o(n.widget?.locale,n.widget?.messages)),g(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=n.widget?.theme===`light`?`light`:`dark`,P(this.root,N(n.widget?.ui),{variables:n.widget?.ui!==void 0}),n.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.appendChild(this.root),this.applyShape();for(let e=0;e<this.shapeCount();e++)this.cells.push(this.createCell(e));this.markActive();let r=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;r&&(this.root.dataset.tcwTheme=r),n.layouts!==!1&&this.setupLayouts(n.layouts===!0||n.layouts===void 0?{}:n.layouts),this.unregisterKeys=Kn(this.root),document.addEventListener(`keydown`,this.onKeyDown)}get relaying(){return this.relayDepth>0}quietly(e){this.relayDepth++;try{return e()}finally{this.relayDepth--}}getWidget(e){return this.cells[e]?.widget??null}getWidgets(){return this.cells.map(e=>e.widget)}getActiveIndex(){return this.active}getActiveWidget(){return this.cells[this.active].widget}setActive(e){e<0||e>=this.cells.length||e===this.active||(this.active=e,this.markActive(),this.options.onActiveChange?.(e,this.cells[e].widget),this.session?.changed())}getLayout(){return this.layout}setLayout(e){if(e===this.layout||!fi(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){let e=this.cells.length-1,t=this.cells.pop();this.parked.set(e,t.widget.captureLayout()),this.destroyCell(t)}this.applyShape();for(let e=this.cells.length;e<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(this.active=0,this.options.onActiveChange?.(0,this.cells[0].widget)),this.markActive(),this.renderBar(),this.session?.changed()}getSync(){return{...this.sync}}setUI(e){let t=N(e);P(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return N(this.uiTheme??this.options.widget?.ui)}setSync(e){let t=this.sync;if(this.sync={...this.sync,...e},t.crosshair&&!this.sync.crosshair)for(let e of this.cells)e.widget.getChart().setCrosshairTime(null);let n=this.cells[this.active];if(n&&!this.relaying){let e=n.widget.getSymbol(),r=n.widget.getTimeframe();!t.symbol&&this.sync.symbol&&this.relay(n,t=>void t.setSymbol(e)),!t.interval&&this.sync.interval&&this.relay(n,e=>void e.setTimeframe(r)),!t.drawings&&this.sync.drawings&&this.mergeDrawings()}this.renderBar(),this.session?.changed()}setTheme(e){for(let t of this.cells)t.widget.setTheme(e);this.followTheme()}getLayoutSession(){return this.session}captureLayout(){let e=[...this.parked.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{v:1,kind:`grid`,layout:this.layout,sync:{...this.sync},active:this.active,cells:[...this.cells.map(e=>e.widget.captureLayout()),...e]}}async restoreLayout(e){this.relayDepth++;let t;try{this.parked.clear(),this.setLayout(e.layout),this.sync={...e.sync},this.renderBar();let n=this.cells.length;e.cells.slice(n).forEach((e,t)=>this.parked.set(n+t,e)),t=await Promise.allSettled(this.cells.map((t,n)=>e.cells[n]?t.widget.restoreLayout(e.cells[n]):Promise.resolve()))}finally{this.relayDepth--}if(this.destroyed)return;this.setActive(Math.min(Math.max(0,e.active),this.cells.length-1));let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=hi(Zn(e));return t?(await this.restoreLayout(t),!0):!1}destroy(){if(!this.destroyed){this.destroyed=!0,document.removeEventListener(`keydown`,this.onKeyDown),this.unregisterKeys(),this.drawingFrame&&cancelAnimationFrame(this.drawingFrame),this.session?.destroy(),this.layoutsUI?.destroy();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),_()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let n=document.createElement(`div`);n.className=`tcw-grid-cell`,n.setAttribute(`role`,`region`),n.setAttribute(`aria-label`,t.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(n);let r=this.options.widget??{},i=this.options.cells?.[e]??{},a=this.cells[this.active]?.widget,o={},s=new $r(n,{...r,...i,...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,onSymbolChange:e=>{i.onSymbolChange?.(e),r.onSymbolChange?.(e),this.sync.symbol&&this.relay(o,t=>void t.setSymbol(e)),this.session?.changed()},onTimeframeChange:e=>{i.onTimeframeChange?.(e),r.onTimeframeChange?.(e),this.sync.interval&&this.relay(o,t=>void t.setTimeframe(e)),this.session?.changed()}});return o.el=n,o.widget=s,this.wireCell(o),n.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(o)),!0),n.addEventListener(`pointerenter`,()=>{this.hovered=o}),n.addEventListener(`pointerleave`,()=>{this.hovered===o&&(this.hovered=null)}),this.options.onChartAdd?.(s,e),o}wireCell(e){let t=e.widget.getChart(),n=()=>this.cells.filter(t=>t!==e);t.on(`crosshairMove`,e=>{let t=e.payload.bar?.time;if(!(!this.sync.crosshair||t===void 0))for(let e of n())e.widget.getChart().setCrosshairTime(t)}),t.on(`crosshairLeave`,()=>{if(this.sync.crosshair)for(let e of n())e.widget.getChart().setCrosshairTime(null)}),t.on(`visibleRangeChange`,n=>{if(!this.sync.time||this.relaying||(this.hovered??this.cells[this.active])!==e)return;let{from:r,to:i}=n.payload,a=t.getData(),o=a[r]?.time,s=a[i]?.time;o===void 0||s===void 0||this.relay(e,e=>e.getChart().setVisibleRange(o,s))});for(let n of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])t.on(n,()=>{this.sync.drawings&&!this.relaying&&this.copyDrawingsSoon(e)});t.on(`replayStep`,t=>{if(!this.sync.replay||this.relaying)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=_i(t.getData(),n);r>=0&&t.replayStart({startIndex:r,paused:!0})})}),t.on(`replayState`,t=>{!this.sync.replay||this.relaying||t.payload.state!==`stopped`||this.relay(e,e=>{e.getChart().isReplayActive()&&e.getChart().replayStop()})}),t.on(`stateChange`,()=>this.session?.changed()),t.on(`themeChange`,()=>{this.relaying||this.followTheme(e)})}destroyCell(e){this.hovered===e&&(this.hovered=null),this.drawingSource===e&&(this.drawingSource=null),this.quietly(()=>e.widget.destroy()),e.el.remove()}relay(e,t){this.relaying||this.quietly(()=>{for(let n of this.cells)n!==e&&t(n.widget)})}unpark(e,t){let n=this.parked.get(e);if(!n)return;this.parked.delete(e);let r=this.cells[this.active]?.widget,i={...n,...r&&this.sync.symbol?{symbol:r.getSymbol()}:{},...r&&this.sync.interval?{timeframe:r.getTimeframe()}:{}};this.relayDepth++,t.widget.restoreLayout(i).catch(()=>t.widget.toast(this.t(`layouts.openFailed`),`error`)).finally(()=>{this.relayDepth--})}copyDrawingsSoon(e){this.drawingSource=e,!this.drawingFrame&&(this.drawingFrame=requestAnimationFrame(()=>{this.drawingFrame=0;let e=this.drawingSource;this.drawingSource=null,e&&!this.destroyed&&!this.relaying&&this.copyDrawings(e)}))}copyDrawings(e){let t=e.widget.getSymbol(),n=e.widget.getChart().getDrawings();this.quietly(()=>{for(let r of this.cells)r!==e&&r.widget.getSymbol()===t&&r.widget.getChart().setDrawings(pi(n))})}mergeDrawings(){let e=new Map;for(let t of this.cells)e.set(t.widget.getSymbol(),[...e.get(t.widget.getSymbol())??[],t]);this.quietly(()=>{for(let t of e.values()){if(t.length<2)continue;let e=new Map;for(let n of t)for(let t of n.widget.getChart().getDrawings())e.has(t.id)||e.set(t.id,t);let n=[...e.values()];for(let e of t)e.widget.getChart().setDrawings(pi(n))}})}followTheme(e=this.cells[this.active]){let t=e?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;t&&(this.root.dataset.tcwTheme=t,this.quietly(()=>{for(let n of this.cells)n!==e&&n.el.querySelector(`.tcw-root`)?.dataset.tcwTheme!==t&&n.widget.setTheme(t)}))}markActive(){this.cells.forEach((e,t)=>e.el.classList.toggle(`tcw-grid-cell-active`,t===this.active&&this.cells.length>1))}buildBar(){let e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.setAttribute(`aria-label`,this.t(`grid.bar`));let n=document.createElement(`div`);n.className=`tcw-grid-group`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,this.t(`grid.layout`));let r=this.options.layoutChoices?.filter(fi)??Object.keys($);for(let e of r){let{cols:r,rows:i}=$[e],a=r*i===1?this.t(`grid.single`):t.r(this.t(`grid.layoutOption`),{count:r*i,cols:r,rows:i}),o=document.createElement(`button`);o.type=`button`,o.className=`tcw-btn-icon`,o.title=a,o.setAttribute(`aria-label`,a),o.innerHTML=mi(r,i),o.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,o),n.appendChild(o)}let i=document.createElement(`div`);i.className=`tcw-grid-group`,i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,this.t(`grid.sync`));let a=document.createElement(`span`);a.className=`tcw-grid-label`,a.innerHTML=`${S(`link`,13)}<span>${w(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of di){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-btn tcw-grid-sync`,t.textContent=this.t(`grid.sync.${e}`),t.title=this.t(`grid.sync.${e}.hint`),t.addEventListener(`click`,()=>this.setSync({[e]:!this.sync[e]})),this.syncButtons.set(e,t),i.appendChild(t)}let o=document.createElement(`span`);return o.className=`tcw-toolbar-spacer`,e.append(n,this.sep(),i,o),this.options.layouts!==!1&&(this.layoutsButton=document.createElement(`button`),this.layoutsButton.type=`button`,this.layoutsButton.className=`tcw-dropdown-trigger tcw-layouts-btn`,this.layoutsButton.setAttribute(`aria-haspopup`,`menu`),this.layoutsButton.addEventListener(`click`,()=>{this.layoutsButton&&this.layoutsUI?.openMenu(this.layoutsButton)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}for(let[e,t]of this.syncButtons)t.classList.toggle(`tcw-active`,this.sync[e]),t.setAttribute(`aria-pressed`,String(this.sync[e]));this.renderLayoutsButton()}renderLayoutsButton(){let e=this.layoutsButton;if(!e)return;let t=this.session?.current()?.name??this.t(`layouts.unnamed`),n=this.session?.isDirty()??!1,r=`${this.t(`toolbar.layouts`)}: ${t}${n?` (${this.t(`layouts.unsavedChanges`)})`:``}`;e.innerHTML=`${S(`save`,14)}<span class="tcw-layouts-label">${w(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+S(`chevronDown`,12),e.title=r,e.setAttribute(`aria-label`,r)}setupLayouts(t){let n=new e.t(t.storage??e.i(`tcw:grid-layouts:`),{capture:()=>{let e=this.cells[this.active].widget;return{content:this.getLayoutContent(),symbol:e.getSymbol(),timeframe:e.getTimeframe()}},apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a grid layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,kind:`grid`,onChange:()=>this.renderLayoutsButton(),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.session=n,this.layoutsUI=new kn(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(e,null);return`${t} ${n}`}}),this.renderLayoutsButton(),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.layoutsUI?.open(e.id):void 0,()=>void 0)}toast(e,t=`info`){this.cells[this.active]?.widget.toast(e,t)}};function _i(e,t){let n=-1;for(let r=0;r<e.length&&e[r].time<t;r++)n=r;return n}exports.CHART_TYPE_ICONS=b,exports.ChartWidget=$r,exports.ChartWidgetGrid=gi,exports.DEFAULT_GRID_SYNC=ui,exports.DRAWING_TOOL_ICONS=y,exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=$,exports.LayoutSession=e.t,exports.MAX_LAYOUT_NAME=e.n,exports.UI_ICONS=v,exports.VI_MESSAGES=t.s,exports.WIDGET_UI_PRESETS=vt,exports.applyWidgetUI=P,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=ce,exports.createIcon=S,exports.createToolIcon=C,exports.findWidgetLocale=t.i,exports.iconSvg=x,exports.localStorageLayouts=e.i,exports.memoryLayouts=e.a,exports.readGridLayout=hi,exports.readWatchlists=O,exports.readWidgetLayout=Xn,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=N,exports.widgetUIVariables=Tt;
|
|
4303
|
+
`}wireEvents(){let e=this.root;e&&(this.scrubber=e.querySelector(`input[data-act="seek"]`),this.progressLabel=e.querySelector(`[data-tcw="progress"]`),this.playBtn=e.querySelector(`button[data-act="play"]`),this.realtimeBtn=e.querySelector(`button[data-act="realtime"]`),this.realtimeBtn?.addEventListener(`click`,()=>this.callbacks.onClose()),e.querySelector(`[data-act="random"]`)?.addEventListener(`click`,()=>this.callbacks.onRandomStart()),e.querySelector(`[data-act="stepBack"]`)?.addEventListener(`click`,()=>this.callbacks.onStepBack()),e.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`,()=>this.callbacks.onSeek(Number(this.scrubber.value))),e.querySelector(`[data-act="speed"]`)?.addEventListener(`change`,e=>{let t=Number(e.target.value);this.speed=t,this.callbacks.onSpeedChange(t)}),e.querySelector(`[data-act="step"]`)?.addEventListener(`change`,e=>{this.step=e.target.value,this.callbacks.onStepChange?.(this.step)}))}syncUi(){let e=this.root;if(e){for(let t of e.querySelectorAll(`.tcw-replay-group`))t.hidden=t.dataset.mode!==this.mode;if(e.classList.toggle(`tcw-replay-bar--ended`,this.ended),this.playBtn){let e=this.state===`playing`;this.playBtn.innerHTML=e?ze():Re(),this.playBtn.title=e?this.labels.pause:this.labels.play,this.playBtn.setAttribute(`aria-label`,this.playBtn.title);let t=this.ended&&!e;t&&document.activeElement===this.playBtn&&this.realtimeBtn?.focus(),this.playBtn.disabled=t}}}};function Re(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M8 5v14l11-7L8 5z"/></svg>`}function ze(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>`}function Be(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M6 6h2v12H6zM20 6L9 12l11 6V6z"/></svg>`}function Ve(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true"><path d="M4 6l11 6L4 18V6zM16 6h2v12h-2z"/></svg>`}function He(){return`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><path d="M12 3v18M8 7l4-4 4 4M8 17l4 4 4-4"/></svg>`}var Ue=class{el;headerEl;nameBtn;menuEl;listEl;rowMap=new Map;entries=new Map;lists=[];activeList=``;active=null;locale;dragging=null;onOutside=e=>{this.headerEl.contains(e.target)||this.closeMenu()};constructor(e,t,n){this.callbacks=t,this.labels=n,this.el=document.createElement(`div`),this.el.className=`tcw-watchlist`,this.el.setAttribute(`aria-label`,n.title),this.headerEl=document.createElement(`div`),this.headerEl.className=`tcw-watchlist-header`,this.nameBtn=document.createElement(`button`),this.nameBtn.type=`button`,this.nameBtn.className=`tcw-watchlist-name`,this.nameBtn.setAttribute(`aria-haspopup`,`menu`),this.nameBtn.setAttribute(`aria-expanded`,`false`),this.nameBtn.title=n.lists,this.nameBtn.addEventListener(`click`,()=>this.menuEl.hidden?this.openMenu():this.closeMenu());let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-add`,r.textContent=`+`,r.title=n.add,r.setAttribute(`aria-label`,n.add),r.hidden=!t.onAdd,r.addEventListener(`click`,()=>t.onAdd?.()),this.menuEl=document.createElement(`div`),this.menuEl.className=`tcw-dropdown tcw-watchlist-menu`,this.menuEl.setAttribute(`role`,`menu`),this.menuEl.hidden=!0,this.headerEl.append(this.nameBtn,r,this.menuEl),this.el.appendChild(this.headerEl),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-watchlist-list`,this.listEl.setAttribute(`role`,`list`),this.el.appendChild(this.listEl),e.appendChild(this.el)}setLists(e,t){this.lists=e.map(e=>({...e,symbols:[...e.symbols]})),this.activeList=e.some(e=>e.id===t)?t:e[0]?.id??``;let n=this.shownList();this.nameBtn.textContent=n?.name??this.labels.title,this.renderRows(n?.symbols??[]),this.menuEl.hidden||this.renderMenu()}setLocale(e){this.locale=e;for(let e of this.rowMap.keys())this.renderRow(e)}setActive(e){this.active=e;for(let[t,n]of this.rowMap){let r=t===e;n.row.classList.toggle(`tcw-watchlist-active`,r),r?n.row.setAttribute(`aria-current`,`true`):n.row.removeAttribute(`aria-current`)}}setEntry(e,t){let n=this.entries.get(e)??{symbol:e};this.entries.set(e,{...n,...t,symbol:e}),this.renderRow(e)}destroy(){this.closeMenu(),this.el.remove(),this.rowMap.clear(),this.entries.clear()}shownList(){return this.lists.find(e=>e.id===this.activeList)}renderRows(e){for(let t of[...this.rowMap.keys()])e.includes(t)||(this.rowMap.get(t).row.remove(),this.rowMap.delete(t));for(let t of e)this.rowMap.has(t)||this.makeRow(t);if(this.listEl.replaceChildren(...e.map(e=>this.rowMap.get(e).row)),e.length===0){let e=document.createElement(`div`);e.className=`tcw-watchlist-empty`,e.textContent=this.labels.empty,this.listEl.appendChild(e)}this.active&&this.setActive(this.active)}makeRow(e){let n=document.createElement(`div`);n.className=`tcw-watchlist-row`,n.setAttribute(`role`,`listitem`),n.dataset.symbol=e,n.tabIndex=0,n.draggable=!!this.callbacks.onMove;let r=document.createElement(`div`);r.className=`tcw-watchlist-symbol`,r.textContent=We(e);let i=document.createElement(`canvas`);i.className=`tcw-watchlist-spark`,i.width=64,i.height=22;let a=document.createElement(`div`);a.className=`tcw-watchlist-stats`;let o=document.createElement(`span`);o.className=`tcw-watchlist-price`,o.textContent=`—`;let s=document.createElement(`span`);if(s.className=`tcw-watchlist-change`,a.append(o,s),n.append(r,i,a),this.callbacks.onRemove){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-watchlist-remove`,r.textContent=`×`,r.tabIndex=-1;let i=t.r(this.labels.remove,{symbol:e});r.title=i,r.setAttribute(`aria-label`,i),r.addEventListener(`click`,t=>{t.stopPropagation(),this.callbacks.onRemove?.(e)}),n.appendChild(r)}n.addEventListener(`click`,()=>this.callbacks.onSelect(e)),n.addEventListener(`keydown`,t=>this.onRowKey(t,e)),n.addEventListener(`dragstart`,t=>{this.dragging=e,t.dataTransfer?.setData(`text/plain`,e),t.dataTransfer&&(t.dataTransfer.effectAllowed=`move`),n.classList.add(`tcw-watchlist-dragging`)}),n.addEventListener(`dragend`,()=>{this.dragging=null,n.classList.remove(`tcw-watchlist-dragging`)}),n.addEventListener(`dragover`,t=>{this.dragging&&this.dragging!==e&&t.preventDefault()}),n.addEventListener(`drop`,t=>{t.preventDefault();let n=this.dragging;if(this.dragging=null,!n||n===e)return;let r=this.shownList()?.symbols??[];this.callbacks.onMove?.(n,r.indexOf(e))}),this.rowMap.set(e,{row:n,priceEl:o,changeEl:s,sparkCanvas:i}),this.renderRow(e)}onRowKey(e,t){let n=this.shownList()?.symbols??[],r=n.indexOf(t);if([`Enter`,` `,`Delete`,`Backspace`,`ArrowDown`,`ArrowUp`].includes(e.key)&&e.stopPropagation(),e.key===`Enter`||e.key===` `)e.preventDefault(),this.callbacks.onSelect(t);else if((e.key===`Delete`||e.key===`Backspace`)&&this.callbacks.onRemove){e.preventDefault();let i=n[r+1]??n[r-1];this.callbacks.onRemove(t),i&&this.rowMap.get(i)?.row.focus()}else if(e.key===`ArrowDown`||e.key===`ArrowUp`){e.preventDefault();let i=r+(e.key===`ArrowDown`?1:-1);if(i<0||i>=n.length)return;e.altKey?(this.callbacks.onMove?.(t,i),this.rowMap.get(t)?.row.focus()):this.rowMap.get(n[i])?.row.focus()}}renderRow(e){let t=this.rowMap.get(e),n=this.entries.get(e);if(!(!t||!n)){if(n.lastPrice!==void 0&&(t.priceEl.textContent=Ge(n.lastPrice,this.locale)),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?`+`:`-`,a=Math.abs(r).toLocaleString(this.locale,{minimumFractionDigits:2,maximumFractionDigits:2});t.changeEl.textContent=`${i}${a}%`,t.changeEl.className=`tcw-watchlist-change ${e>=0?`tcw-up`:`tcw-down`}`}else t.changeEl.textContent=``;n.sparkline&&n.sparkline.length>=2&&Ke(t.sparkCanvas,n.sparkline,n.refPrice??n.sparkline[0])}}openMenu(){this.renderMenu(),this.menuEl.hidden=!1,this.nameBtn.setAttribute(`aria-expanded`,`true`),document.addEventListener(`mousedown`,this.onOutside)}closeMenu(){this.menuEl.hidden=!0,this.nameBtn.setAttribute(`aria-expanded`,`false`),document.removeEventListener(`mousedown`,this.onOutside)}renderMenu(){let e=(e,t)=>{let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-dropdown-item`,n.setAttribute(`role`,`menuitem`),n.textContent=e,n.addEventListener(`click`,t),n},n=this.lists.map(t=>{let n=e(``,()=>{this.closeMenu(),this.callbacks.onPickList?.(t.id)});n.dataset.list=t.id,n.classList.toggle(`tcw-active`,t.id===this.activeList);let r=document.createElement(`span`);r.textContent=t.name;let i=document.createElement(`span`);return i.className=`tcw-watchlist-count`,i.textContent=String(t.symbols.length),n.append(r,i),n}),r=document.createElement(`div`);if(r.className=`tcw-dropdown-divider`,n.push(r),this.callbacks.onCreateList){let t=e(this.labels.newList,()=>this.editName(``,e=>this.callbacks.onCreateList?.(e)));t.dataset.action=`new`,n.push(t)}let i=this.shownList();if(i&&this.callbacks.onRenameList){let t=e(this.labels.rename,()=>this.editName(i.name,e=>this.callbacks.onRenameList?.(i.id,e)));t.dataset.action=`rename`,n.push(t)}if(i&&this.callbacks.onDeleteList&&this.lists.length>1){let r=!1,a=e(this.labels.deleteList,()=>{if(!r){r=!0,a.textContent=t.r(this.labels.confirmDelete,{name:i.name}),a.classList.add(`tcw-danger`);return}this.closeMenu(),this.callbacks.onDeleteList?.(i.id)});a.dataset.action=`delete`,n.push(a)}this.menuEl.replaceChildren(...n)}editName(e,t){this.closeMenu();let n=document.createElement(`input`);n.className=`tcw-watchlist-input`,n.type=`text`,n.maxLength=60,n.value=e,n.placeholder=this.labels.listName,n.setAttribute(`aria-label`,this.labels.listName),this.nameBtn.hidden=!0,this.headerEl.insertBefore(n,this.nameBtn);let r=!1,i=i=>{if(r)return;r=!0;let a=n.value.trim();n.remove(),this.nameBtn.hidden=!1,i&&a&&a!==e&&t(a),this.nameBtn.focus()};n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Enter`?(e.preventDefault(),i(!0)):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),i(!1))}),n.addEventListener(`blur`,()=>i(!1)),n.focus()}};function We(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 Ge(e,t){if(e===0)return`0`;let n=Math.abs(e);return n>=1e3?e.toLocaleString(t,{minimumFractionDigits:2,maximumFractionDigits:2}):n>=1?e.toLocaleString(t,{minimumFractionDigits:4,maximumFractionDigits:4}):Number(e.toPrecision(4)).toLocaleString(t,{maximumFractionDigits:10})}function Ke(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?`#1fa874`:`#e8505b`;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 qe=50,Je=500,Ye=60,Xe=64,D=e=>typeof e==`string`&&e.trim().slice(0,Ye)||null,Ze=e=>{if(typeof e!=`string`)return null;let t=e.trim();return t&&t.length<=Xe?t:null};function Qe(e){let t=[];for(let n of e){let e=Ze(n);if(e&&!t.includes(e)&&t.push(e),t.length===Je)break}return t}function O(e){if(!e||typeof e!=`object`)return null;let t=e;if(!Array.isArray(t.lists))return null;let n=[];for(let e of t.lists){if(n.length===qe)break;if(!e||typeof e!=`object`)continue;let t=e,r=typeof t.id==`string`&&t.id&&t.id.length<=Xe?t.id:null,i=D(t.name);!r||!i||n.some(e=>e.id===r)||n.push({id:r,name:i,symbols:Array.isArray(t.symbols)?Qe(t.symbols):[]})}return n.length===0?null:{lists:n,active:typeof t.active==`string`&&n.some(e=>e.id===t.active)?t.active:n[0].id}}var $e=e=>({...e,symbols:[...e.symbols]}),et=class{lists;active;listeners=new Set;storage;storageKey;constructor(e){this.storage=e.storage??null,this.storageKey=e.storageKey??`tcw:watchlists`;let t=this.load(),n=e.lists?O({lists:e.lists,active:e.activeList}):null,r=t??n??{lists:[{id:`default`,name:D(e.defaultName)??`Watchlist`,symbols:Qe(e.symbols??[])}],active:`default`};this.lists=r.lists,this.active=r.active}getLists(){return this.lists.map($e)}getActive(){return $e(this.activeList())}setActive(e){e===this.active||!this.lists.some(t=>t.id===e)||(this.active=e,this.changed())}replace(e,t){let n=O({lists:e,active:t??this.active});n&&(this.lists=n.lists,this.active=n.active,this.changed())}create(e){let t=D(e);if(!t||this.lists.length>=qe)return null;let n=this.lists.length+1;for(;this.lists.some(e=>e.id===`list-${n}`);)n++;let r={id:`list-${n}`,name:t,symbols:[]};return this.lists=[...this.lists,r],this.active=r.id,this.changed(),$e(r)}rename(e,t){let n=D(t);n&&this.update(e,e=>({...e,name:n}))}remove(e){this.lists.length<=1||!this.lists.some(t=>t.id===e)||(this.lists=this.lists.filter(t=>t.id!==e),this.active===e&&(this.active=this.lists[0].id),this.changed())}add(e,t=this.active){let n=Ze(e),r=this.lists.find(e=>e.id===t);return!n||!r||r.symbols.includes(n)||r.symbols.length>=Je?!1:(this.update(t,e=>({...e,symbols:[...e.symbols,n]})),!0)}removeSymbol(e,t=this.active){this.lists.find(e=>e.id===t)?.symbols.includes(e)&&this.update(t,t=>({...t,symbols:t.symbols.filter(t=>t!==e)}))}move(e,t,n=this.active){let r=this.lists.find(e=>e.id===n);if(!r)return;let i=r.symbols.indexOf(e);if(i<0)return;let a=r.symbols.filter(t=>t!==e),o=Math.max(0,Math.min(Math.round(t),a.length));o!==i&&this.update(n,t=>({...t,symbols:[...a.slice(0,o),e,...a.slice(o)]}))}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}activeList(){return this.lists.find(e=>e.id===this.active)??this.lists[0]}update(e,t){this.lists=this.lists.map(n=>n.id===e?t(n):n),this.changed()}changed(){this.save();for(let e of this.listeners)e()}load(){if(!this.storage)return null;try{let e=this.storage.getItem(this.storageKey);return e?O(JSON.parse(e)):null}catch{return null}}save(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify({lists:this.lists,active:this.active}))}catch{}}},tt=class{el;bodyEl;newsEl;shown=!1;constructor(e,n=t.t,r={}){this.t=n,this.callbacks=r,this.el=document.createElement(`div`),this.el.className=`tcw-syminfo`,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,n(`symbolInfo.title`)),this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-syminfo-header`;let a=document.createElement(`span`);a.textContent=n(`symbolInfo.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-syminfo-close`,o.setAttribute(`aria-label`,n(`common.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.append(a,o),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-syminfo-body`,this.newsEl=document.createElement(`div`),this.newsEl.className=`tcw-syminfo-news`,this.newsEl.hidden=!0,this.el.append(i,this.bodyEl,this.newsEl),e.appendChild(this.el)}isOpen(){return this.shown}toggle(){this.shown?this.close():this.open()}open(){this.shown||(this.shown=!0,this.el.hidden=!1,this.callbacks.onToggle?.(!0))}close(){this.shown&&(this.shown=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}render(e){let t=document.createElement(`div`);t.className=`tcw-syminfo-head`,t.append(k(`div`,`tcw-syminfo-symbol`,e.symbol)),e.description&&t.append(k(`div`,`tcw-syminfo-desc`,e.description)),e.meta&&t.append(k(`div`,`tcw-syminfo-meta`,e.meta));let n=document.createElement(`div`);if(n.className=`tcw-syminfo-quote`,e.price&&n.append(k(`span`,`tcw-syminfo-price`,e.price)),e.change){let t=k(`span`,`tcw-syminfo-change`,e.change.text);t.classList.add(e.change.up?`tcw-up`:`tcw-down`),n.append(t)}let r=k(`div`,`tcw-syminfo-status`,e.status.text);r.dataset.state=e.status.state;let i=document.createElement(`dl`);i.className=`tcw-syminfo-stats`;for(let t of e.stats){let e=document.createElement(`div`);e.className=`tcw-syminfo-stat`,e.append(k(`dt`,``,t.label),k(`dd`,``,t.value)),i.append(e)}this.bodyEl.replaceChildren(t,n,r,i)}renderNews(e){if(this.newsEl.hidden=e.kind===`none`,e.kind===`none`){this.newsEl.replaceChildren();return}let t=k(`div`,`tcw-syminfo-news-title`,this.t(`symbolInfo.news`));if(e.kind===`loading`||e.kind===`failed`||e.items.length===0){let t=e.kind===`loading`?`symbolInfo.loading`:e.kind===`failed`?`symbolInfo.newsFailed`:`symbolInfo.noNews`;this.newsEl.replaceChildren(k(`div`,`tcw-syminfo-news-note`,this.t(t)));return}let n=document.createElement(`ul`);n.className=`tcw-syminfo-news-list`;for(let t of e.items){let e=document.createElement(`li`);if(e.className=`tcw-syminfo-news-item`,t.url){let n=document.createElement(`a`);n.href=t.url,n.target=`_blank`,n.rel=`noopener noreferrer`,n.textContent=t.title,e.append(n)}else e.append(k(`span`,``,t.title));t.meta&&e.append(k(`div`,`tcw-syminfo-news-meta`,t.meta)),n.append(e)}this.newsEl.replaceChildren(t,n)}destroy(){this.el.remove()}};function k(e,t,n){let r=document.createElement(e);return t&&(r.className=t),r.textContent=n,r}var nt=300,rt=80,it=class{el;holdTimer=null;repeatTimer=null;onMove=e=>{e.pointerType!==`touch`&&(this.el.classList.contains(`tcw-nav-shown`)||this.place(),this.el.classList.add(`tcw-nav-shown`))};onLeave=()=>{this.el.classList.remove(`tcw-nav-shown`),this.stopHold()};constructor(e,n,r=t.t){this.host=e,this.actions=n,this.el=document.createElement(`div`),this.el.className=`tcw-nav`,this.el.setAttribute(`role`,`toolbar`),this.el.setAttribute(`aria-label`,r(`nav.label`));let i=[[`zoomOut`,`minus`,r(`nav.zoomOut`)],[`zoomIn`,`plus`,r(`nav.zoomIn`)],[`scrollLeft`,`chevronLeft`,r(`nav.scrollLeft`)],[`scrollRight`,`chevronRight`,r(`nav.scrollRight`)],[`reset`,`reset`,r(`nav.reset`)]];for(let[e,t,r]of i){let i=document.createElement(`button`);if(i.type=`button`,i.className=`tcw-nav-btn`,i.dataset.nav=e,i.title=r,i.setAttribute(`aria-label`,r),i.innerHTML=S(t,16),e===`scrollLeft`||e===`scrollRight`){let t=e===`scrollRight`?1:-1;i.addEventListener(`pointerdown`,e=>{if(e.button===0){e.preventDefault();try{i.setPointerCapture(e.pointerId)}catch{}this.startHold(t)}});for(let e of[`pointerup`,`pointercancel`,`pointerleave`])i.addEventListener(e,()=>this.stopHold());i.addEventListener(`click`,e=>{e.detail===0&&n.scroll(t)})}else i.addEventListener(`click`,()=>{e===`zoomIn`?n.zoomIn():e===`zoomOut`?n.zoomOut():n.reset()});this.el.appendChild(i)}for(let e of[`dblclick`,`contextmenu`,`pointerdown`,`mousedown`])this.el.addEventListener(e,e=>e.stopPropagation());this.el.addEventListener(`focusin`,()=>{this.place(),this.el.classList.add(`tcw-nav-shown`)}),this.el.addEventListener(`focusout`,e=>{this.el.contains(e.relatedTarget)||this.el.classList.remove(`tcw-nav-shown`)}),e.appendChild(this.el),e.addEventListener(`pointermove`,this.onMove),e.addEventListener(`pointerleave`,this.onLeave)}destroy(){this.stopHold(),this.host.removeEventListener(`pointermove`,this.onMove),this.host.removeEventListener(`pointerleave`,this.onLeave),this.el.remove()}place(){let e=this.actions.plotRect();this.el.style.left=`${Math.round(e.x+e.width/2)}px`,this.el.style.top=`${Math.round(e.y+e.height)}px`}startHold(e){this.stopHold(),this.actions.scroll(e),this.holdTimer=setTimeout(()=>{this.repeatTimer=setInterval(()=>this.actions.scroll(e),rt)},nt)}stopHold(){this.holdTimer&&clearTimeout(this.holdTimer),this.repeatTimer&&clearInterval(this.repeatTimer),this.holdTimer=null,this.repeatTimer=null}};function at(e,n,r,i=!1){let a=e.label??n(`alerts.source.price`),o=lt.get(e.condition),s=o?n(o):e.condition;if(st.includes(e.condition))return`${a} ${s} ${t.r(n(`alerts.moveSummary`),{percent:e.percent??0,bars:e.bars??0})}`;if(e.target)return`${a} ${s} ${e.targetLabel??e.target}`;let c=e.channel&&e.channel!==`price`,l=Number.isFinite(e.price)?c?dt(e.price):r(e.price):`—`;return`${(c||e.drawingId)&&e.label?`${e.label} `:i?`${a} `:``}${s} ${l}`}var ot=[{value:`crossing`,key:`alerts.condition.crossing`},{value:`crossingUp`,key:`alerts.condition.crossingUp`},{value:`crossingDown`,key:`alerts.condition.crossingDown`},{value:`greaterThan`,key:`alerts.condition.greaterThan`},{value:`lessThan`,key:`alerts.condition.lessThan`},{value:`movesUp`,key:`alerts.condition.movesUp`},{value:`movesDown`,key:`alerts.condition.movesDown`}],st=[`movesUp`,`movesDown`],ct={hour:36e5,day:864e5,week:7*864e5,month:30*864e5},A=``,lt=new Map(ot.map(e=>[e.value,e.key]));function ut(e){return Math.round(e*1e6)/1e6}function dt(e){let t=Math.abs(e);return t>=1e3||t>=1?e.toFixed(2):e.toPrecision(4)}var ft=class{el;listEl;priceInput;conditionSelect;sourceSelect;targetSelect;percentInput;barsInput;levelRow;moveRow;closeCheck;expirySelect;messageInput;emptyEl;callbacks;open=!1;alerts=[];sources;constructor(e,n,i=t.t){this.t=i,this.callbacks=n,this.sources=[{channel:`price`,label:this.t(`alerts.source.price`)}],this.el=document.createElement(`div`),this.el.className=`tcw-alerts-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-alerts-header`;let o=document.createElement(`span`);o.textContent=this.t(`alerts.title`);let s=document.createElement(`button`);s.className=`tcw-alerts-close`,s.type=`button`,s.setAttribute(`aria-label`,this.t(`alerts.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`form`);c.className=`tcw-alerts-form`,c.noValidate=!0,this.sourceSelect=document.createElement(`select`),this.sourceSelect.className=`tcw-alerts-source`,this.sourceSelect.setAttribute(`aria-label`,this.t(`alerts.source`)),this.sourceSelect.addEventListener(`change`,()=>{this.renderTargets(),this.prefillPrice()}),this.conditionSelect=document.createElement(`select`),this.conditionSelect.className=`tcw-alerts-condition`,this.conditionSelect.setAttribute(`aria-label`,this.t(`alerts.conditionLabel`));for(let e of ot){let t=document.createElement(`option`);t.value=e.value,t.textContent=this.t(e.key),this.conditionSelect.appendChild(t)}this.conditionSelect.addEventListener(`change`,()=>this.showFields()),this.levelRow=document.createElement(`div`),this.levelRow.className=`tcw-alerts-row-fields`,this.targetSelect=document.createElement(`select`),this.targetSelect.className=`tcw-alerts-target`,this.targetSelect.setAttribute(`aria-label`,this.t(`alerts.compareWith`)),this.targetSelect.addEventListener(`change`,()=>this.showFields()),this.priceInput=document.createElement(`input`),this.priceInput.type=`number`,this.priceInput.step=`any`,this.priceInput.placeholder=this.t(`alerts.value`),this.priceInput.setAttribute(`aria-label`,this.t(`alerts.value`)),this.priceInput.className=`tcw-alerts-price`,this.levelRow.append(this.targetSelect,this.priceInput),this.moveRow=document.createElement(`div`),this.moveRow.className=`tcw-alerts-row-fields`,this.percentInput=this.numberField(`tcw-alerts-percent`,this.t(`alerts.percent`),`1`,`0.01`),this.barsInput=this.numberField(`tcw-alerts-bars`,this.t(`alerts.bars`),`10`,`1`),this.barsInput.min=String(r.MIN_ALERT_BARS),this.barsInput.max=String(r.MAX_ALERT_BARS),this.moveRow.append(this.percentInput,this.barsInput);let l=document.createElement(`div`);l.className=`tcw-alerts-row-fields tcw-alerts-options`;let u=document.createElement(`label`);u.className=`tcw-alerts-check`,this.closeCheck=document.createElement(`input`),this.closeCheck.type=`checkbox`,u.append(this.closeCheck,document.createTextNode(this.t(`alerts.onBarClose`))),this.expirySelect=document.createElement(`select`),this.expirySelect.className=`tcw-alerts-expiry`,this.expirySelect.setAttribute(`aria-label`,this.t(`alerts.expires`));for(let e of[`never`,`hour`,`day`,`week`,`month`]){let t=document.createElement(`option`);t.value=e,t.textContent=this.t(`alerts.expires.${e}`),this.expirySelect.appendChild(t)}l.append(u,this.expirySelect),this.messageInput=document.createElement(`input`),this.messageInput.type=`text`,this.messageInput.placeholder=this.t(`alerts.note`),this.messageInput.setAttribute(`aria-label`,this.t(`alerts.note`)),this.messageInput.className=`tcw-alerts-message`;let d=document.createElement(`button`);d.type=`submit`,d.className=`tcw-alerts-add`,d.innerHTML=`${S(`plus`,14)}<span>${w(this.t(`alerts.add`))}</span>`,c.append(this.sourceSelect,this.conditionSelect,this.levelRow,this.moveRow,l,this.messageInput,d),c.addEventListener(`submit`,e=>{e.preventDefault(),this.submitForm()}),this.el.appendChild(c),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=this.t(`alerts.empty`),this.listEl.appendChild(this.emptyEl),this.renderSources(),this.showFields(),e.appendChild(this.el)}numberField(e,t,n,r){let i=document.createElement(`input`);return i.type=`number`,i.step=r,i.min=`0`,i.value=n,i.className=e,i.placeholder=t,i.setAttribute(`aria-label`,t),i}showFields(){let e=st.includes(this.conditionSelect.value);this.moveRow.hidden=!e,this.levelRow.hidden=e,this.priceInput.hidden=this.targetSelect.value!==A}renderTargets(){let e=this.targetSelect.value,t=this.sourceSelect.value||`price`;this.targetSelect.replaceChildren();let n=document.createElement(`option`);n.value=A,n.textContent=this.t(`alerts.compare.value`),this.targetSelect.appendChild(n);for(let e of this.sources){if(e.channel===t)continue;let n=document.createElement(`option`);n.value=e.channel,n.textContent=e.label,this.targetSelect.appendChild(n)}this.targetSelect.value=[...this.targetSelect.options].some(t=>t.value===e)?e:A,this.showFields()}setSources(e){this.sources=e.length>0?e:[{channel:`price`,label:this.t(`alerts.source.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`,this.renderTargets()}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(ut(e))}close(){this.open=!1,this.el.hidden=!0}setAlerts(e){this.alerts=e,this.renderList()}destroy(){this.el.remove()}submitForm(){let e=this.conditionSelect.value,t=this.messageInput.value.trim()||void 0,n=this.sourceSelect.value||`price`,i=this.sources.find(e=>e.channel===n)?.label??this.t(`alerts.source.price`),a={},o=NaN;if(st.includes(e)){a.percent=Number(this.percentInput.value),a.bars=Number(this.barsInput.value);let e=Number.isInteger(a.bars)&&a.bars>=r.MIN_ALERT_BARS&&a.bars<=r.MAX_ALERT_BARS;if(!(a.percent>0)||!e){this.markInvalid(a.percent>0?this.barsInput:this.percentInput);return}}else if(this.targetSelect.value!==A)a.target=this.targetSelect.value;else if(o=Number(this.priceInput.value),this.priceInput.value.trim()===``||!Number.isFinite(o)){this.markInvalid(this.priceInput);return}this.closeCheck.checked&&(a.onBarClose=!0);let s=ct[this.expirySelect.value];s&&(a.expiresAt=(this.callbacks.now??Date.now)()+s),this.callbacks.onAdd({price:o,condition:e,message:t,channel:n,label:i,options:a})!==!1&&(this.messageInput.value=``,this.prefillPrice())}markInvalid(e){e.setAttribute(`aria-invalid`,`true`),e.focus(),e.addEventListener(`input`,()=>e.removeAttribute(`aria-invalid`),{once:!0})}describe(e){return at(e,this.t,this.callbacks.formatPrice)}renderList(){if(this.listEl.replaceChildren(),this.alerts.length===0){this.listEl.appendChild(this.emptyEl);return}for(let e of[...this.alerts].reverse()){let n=document.createElement(`div`);n.className=`tcw-alerts-row`+(e.triggered?` tcw-alerts-triggered`:``)+(e.expired?` tcw-alerts-expired`:``);let r=document.createElement(`div`);r.className=`tcw-alerts-info`;let i=document.createElement(`div`);i.className=`tcw-alerts-row-main`,i.textContent=this.describe(e),r.appendChild(i);let a=[];if(e.onBarClose&&a.push(this.t(`alerts.onClose`)),e.expiresAt!==void 0&&!e.expired){let n=this.callbacks.formatTime?.(e.expiresAt)??new Date(e.expiresAt).toISOString();a.push(t.r(this.t(`alerts.until`),{time:n}))}if(a.length>0){let e=document.createElement(`div`);e.className=`tcw-alerts-row-meta`,e.textContent=a.join(` · `),r.appendChild(e)}if(e.message){let t=document.createElement(`div`);t.className=`tcw-alerts-row-note`,t.textContent=e.message,r.appendChild(t)}if(e.triggered||e.expired){let t=document.createElement(`span`);t.className=`tcw-alerts-badge`,t.textContent=this.t(e.expired?`alerts.expired`:`alerts.triggered`),i.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-alerts-del`,o.setAttribute(`aria-label`,this.t(`alerts.delete`)),o.innerHTML=S(`trash`,14),o.addEventListener(`click`,()=>this.callbacks.onRemove(e.id)),n.appendChild(r),n.appendChild(o),this.listEl.appendChild(n)}}},pt=`system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif`,mt=`'JetBrains Mono', 'SF Mono', 'Cascadia Code', 'Fira Code', 'Consolas', ui-monospace, monospace`,ht={studio:{radius:{xs:3,sm:5,md:7,lg:11,xl:16},components:{toolbar:0,sidebar:0},sizes:{toolbar:46,control:30,controlSmall:24,icon:18,sidebar:48,menuItem:30},font:{family:`'Manrope', 'Inter', ${pt}`,mono:mt,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`var(--tcw-shadow-lg)`,dialog:`var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-md)`},blur:0,active:`tint`,toolbar:`docked`,sidebar:`docked`,intervals:`segmented`,tagRadius:4},terminal:{radius:{xs:1,sm:2,md:2,lg:2,xl:3},components:{tag:0,toolbar:0,sidebar:0},sizes:{toolbar:36,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},font:{family:`'IBM Plex Sans Condensed', 'Roboto Condensed', 'Arial Narrow', ${pt}`,mono:`'IBM Plex Mono', ui-monospace, monospace`,size:12,weight:500,strongWeight:600,labelCase:`uppercase`,labelTracking:.08},borders:{width:1,separators:!0},shadows:{menu:`0 0 0 1px var(--tcw-border-strong)`,dialog:`0 0 0 1px var(--tcw-border-strong), var(--tcw-shadow-lg)`,tooltip:`none`},blur:0,active:`underline`,toolbar:`docked`,sidebar:`docked`,intervals:`plain`,tagRadius:0},capsule:{radius:{xs:6,sm:10,md:999,lg:18,xl:24},components:{tooltip:10,toolbar:999,sidebar:999,toast:999,tag:999},sizes:{toolbar:44,control:32,controlSmall:26,icon:18,sidebar:48,menuItem:34},font:{family:`'Sora', 'Manrope', ${pt}`,mono:mt,size:13,weight:500,strongWeight:600,labelCase:`none`,labelTracking:0},borders:{width:1,separators:!1},shadows:{menu:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,dialog:`0 0 0 1px var(--tcw-divider), var(--tcw-shadow-xl)`,tooltip:`var(--tcw-shadow-lg)`},blur:16,active:`solid`,toolbar:`floating`,sidebar:`floating`,intervals:`segmented`,tagRadius:999}},gt={compact:{toolbar:38,control:26,controlSmall:20,icon:16,sidebar:40,menuItem:26},spacious:{toolbar:52,control:34,controlSmall:28,icon:20,sidebar:54,menuItem:34}};function _t(e,t){return{control:e.md,input:e.md,menu:e.lg,dialog:e.xl,panel:e.lg,tooltip:e.sm,tag:e.sm,toast:e.lg,toolbar:0,sidebar:0,...t}}var vt=Object.freeze(Object.fromEntries(Object.keys(ht).map(e=>[e,bt(yt(e))])));function yt(e){let t=ht[e];return{...t,preset:e,radius:{...t.radius},components:_t(t.radius,t.components),sizes:{...t.sizes},font:{...t.font},borders:{...t.borders},shadows:{...t.shadows}}}function bt(e){for(let t of Object.values(e))t&&typeof t==`object`&&bt(t);return Object.freeze(e)}var xt=e=>e===`studio`||e===`terminal`||e===`capsule`,j=(e,t,n)=>typeof e==`number`&&Number.isFinite(e)&&e>=t&&e<=n,St=e=>typeof e==`string`&&e.trim().length>0&&e.length<=300&&!/[;{}<>\\]|url\s*\(|expression\s*\(|\/\*/i.test(e)&&Ct(e);function Ct(e){let t=0,n=``;for(let r of e)if(n)r===n&&(n=``);else if(r===`"`||r===`'`)n=r;else if(r===`(`)t++;else if(r===`)`&&--t<0)return!1;return t===0&&!n}var wt=(e,t)=>typeof e==`string`&&t.includes(e);function M(e,t,n){let r={...e};if(!t||typeof t!=`object`)return r;for(let i of Object.keys(e)){let e=t[i];e!==void 0&&n(i,e)&&(r[i]=e)}return r}function N(e){let t=typeof e==`string`?{preset:e}:e??{},n=xt(t.preset)?t.preset:`studio`,r=ht[n],i=M(r.radius,t.radius,(e,t)=>j(t,0,999)),a=M(t.density===`compact`||t.density===`spacious`?gt[t.density]:r.sizes,t.sizes,(e,t)=>e===`icon`?j(t,10,32):j(t,16,80)),o=M(r.font,t.font,(e,t)=>e===`family`||e===`mono`?St(t):e===`size`?j(t,11,20):e===`weight`||e===`strongWeight`?j(t,100,900):e===`labelCase`?t===`none`||t===`uppercase`:j(t,0,.5));return{preset:n,radius:i,components:M(_t(i,r.components),t.components,(e,t)=>j(t,0,999)),sizes:a,font:o,borders:M(r.borders,t.borders,(e,t)=>e===`width`?j(t,0,4):typeof t==`boolean`),shadows:M(r.shadows,t.shadows,(e,t)=>St(t)),blur:j(t.blur,0,40)?t.blur:r.blur,active:wt(t.active,[`tint`,`solid`,`underline`])?t.active:r.active,toolbar:wt(t.toolbar,[`docked`,`floating`])?t.toolbar:r.toolbar,sidebar:wt(t.sidebar,[`docked`,`floating`])?t.sidebar:r.sidebar,intervals:wt(t.intervals,[`plain`,`segmented`])?t.intervals:r.intervals,tagRadius:j(t.tagRadius,0,999)?t.tagRadius:r.tagRadius}}function Tt(e){let t=e=>`${e}px`,n=e.radius,r=e.components,i=e.sizes,a=e.font;return{"--tcw-radius-xs":t(n.xs),"--tcw-radius-sm":t(n.sm),"--tcw-radius":t(n.md),"--tcw-radius-lg":t(n.lg),"--tcw-radius-xl":t(n.xl),"--tcw-control-radius":t(r.control),"--tcw-input-radius":t(r.input),"--tcw-menu-radius":t(r.menu),"--tcw-dialog-radius":t(r.dialog),"--tcw-panel-radius":t(r.panel),"--tcw-tooltip-radius":t(r.tooltip),"--tcw-tag-radius":t(r.tag),"--tcw-toast-radius":t(r.toast),"--tcw-toolbar-radius":t(r.toolbar),"--tcw-sidebar-radius":t(r.sidebar),"--tcw-toolbar-h":t(i.toolbar),"--tcw-control-h":t(i.control),"--tcw-control-h-sm":t(i.controlSmall),"--tcw-icon":t(i.icon),"--tcw-sidebar-w":t(i.sidebar),"--tcw-menu-item-h":t(i.menuItem),"--tcw-font":a.family,"--tcw-font-mono":a.mono,"--tcw-font-size":t(a.size),"--tcw-font-size-sm":t(a.size-1),"--tcw-font-size-xs":t(a.size-2),"--tcw-font-size-lg":t(a.size+2),"--tcw-weight":String(a.weight),"--tcw-weight-strong":String(a.strongWeight),"--tcw-label-case":a.labelCase,"--tcw-label-tracking":`${a.labelTracking}em`,"--tcw-border-w":t(e.borders.width),"--tcw-sep-w":e.borders.separators?t(Math.max(1,e.borders.width)):`0px`,"--tcw-menu-shadow":e.shadows.menu,"--tcw-dialog-shadow":e.shadows.dialog,"--tcw-tooltip-shadow":e.shadows.tooltip,"--tcw-blur":t(e.blur),"--tcw-surface-opacity":e.blur>0?`82%`:`100%`}}function P(e,t,n={}){let r=n.variables!==!1;for(let[n,i]of Object.entries(Tt(t)))r?e.style.setProperty(n,i):e.style.removeProperty(n);e.dataset.tcwUi=t.preset,e.dataset.tcwActive=t.active,e.dataset.tcwToolbar=t.toolbar,e.dataset.tcwSidebar=t.sidebar,e.dataset.tcwIntervals=t.intervals,e.dataset.tcwSeparators=t.borders.separators?`on`:`off`}var Et=class{el;indicatorsEl;drawingsEl;compareEl=null;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-tree-panel`,this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-tree-header`;let a=document.createElement(`span`);a.textContent=this.t(`objects.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-tree-close`,o.setAttribute(`aria-label`,this.t(`objects.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),this.indicatorsEl=this.makeSection(this.t(`objects.indicators`)),this.drawingsEl=this.makeSection(this.t(`objects.drawings`)),this.callbacks.onAddCompare&&(this.compareEl=this.makeSection(this.t(`objects.compare`),{label:this.t(`objects.addCompare`),run:()=>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 e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-add`,e.setAttribute(`aria-label`,t.label),e.title=t.label,e.innerHTML=S(`plus`,13),e.addEventListener(`click`,t.run),r.appendChild(e)}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(this.t(`objects.noIndicators`)));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?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleIndicatorVisible?.(t.instanceId,!t.visible))),this.callbacks.onConfigureIndicator&&n.appendChild(this.iconButton(`settings`,this.t(`objects.indicatorSettings`),``,()=>this.callbacks.onConfigureIndicator?.(t.instanceId))),n.appendChild(this.iconButton(`trash`,this.t(`objects.removeIndicator`),`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(this.t(`objects.noDrawings`)));return}let t=new Set;for(let n of e){if(!n.group){this.drawingsEl.appendChild(this.drawingRow(n));continue}if(t.has(n.group.id))continue;t.add(n.group.id);let r=n.group.id,i=e.filter(e=>e.group?.id===r);this.drawingsEl.appendChild(this.groupRow(r,n.group.name,i));for(let e of i){let t=this.drawingRow(e);t.classList.add(`tcw-tree-member`),this.drawingsEl.appendChild(t)}}}groupRow(e,t,n){let r=this.row(t);r.classList.add(`tcw-tree-group`);let i=n.some(e=>e.visible),a=n.every(e=>e.locked);i||r.classList.add(`tcw-tree-hidden`);let o=r.querySelector(`.tcw-tree-name`);o.innerHTML=S(`layers`,13),o.append(` ${t}`);let s=document.createElement(`div`);return s.className=`tcw-tree-actions`,this.callbacks.onRenameGroup&&(o.addEventListener(`dblclick`,()=>this.renameGroup(o,e,t)),s.appendChild(this.iconButton(`penLine`,this.t(`objects.renameGroup`),``,()=>this.renameGroup(o,e,t)))),this.callbacks.onToggleGroupVisible&&s.appendChild(this.iconButton(i?`eye`:`eyeOff`,i?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleGroupVisible?.(e,!i))),this.callbacks.onToggleGroupLocked&&s.appendChild(this.iconButton(a?`lock`:`unlock`,a?this.t(`common.unlock`):this.t(`common.lock`),a?`tcw-tree-on`:``,()=>this.callbacks.onToggleGroupLocked?.(e,!a))),this.callbacks.onUngroup&&s.appendChild(this.iconButton(`x`,this.t(`drawingMenu.ungroup`),``,()=>this.callbacks.onUngroup?.(e))),r.appendChild(s),r}renameGroup(e,t,n){if(!e.isConnected)return;let r=document.createElement(`input`);r.type=`text`,r.className=`tcw-tree-rename`,r.value=n,r.maxLength=80,r.setAttribute(`aria-label`,this.t(`objects.renameGroup`));let i=!1,a=a=>{if(i)return;i=!0;let o=r.value.trim();r.isConnected&&r.replaceWith(e),a&&o&&o!==n&&this.callbacks.onRenameGroup?.(t,o)};r.addEventListener(`keydown`,e=>{e.key===`Enter`?a(!0):e.key===`Escape`&&(e.stopPropagation(),a(!1))}),r.addEventListener(`blur`,()=>a(!0)),e.replaceWith(r),r.focus(),r.select()}drawingRow(e){let t=this.row(e.label);e.visible||t.classList.add(`tcw-tree-hidden`);let n=document.createElement(`div`);return n.className=`tcw-tree-actions`,n.appendChild(this.iconButton(e.visible?`eye`:`eyeOff`,e.visible?this.t(`common.hide`):this.t(`common.show`),``,()=>this.callbacks.onToggleDrawingVisible(e.id,!e.visible))),n.appendChild(this.iconButton(e.locked?`lock`:`unlock`,e.locked?this.t(`common.unlock`):this.t(`common.lock`),e.locked?`tcw-tree-on`:``,()=>this.callbacks.onToggleDrawingLocked(e.id,!e.locked))),this.callbacks.onConfigureDrawing&&n.appendChild(this.iconButton(`settings`,this.t(`objects.drawingSettings`),``,()=>this.callbacks.onConfigureDrawing?.(e.id))),n.appendChild(this.iconButton(`trash`,this.t(`objects.removeDrawing`),`tcw-tree-del`,()=>this.callbacks.onRemoveDrawing(e.id))),t.appendChild(n),t}renderCompares(e){if(this.compareEl){if(this.compareEl.replaceChildren(),e.length===0){this.compareEl.appendChild(this.emptyRow(this.t(`objects.noComparisons`)));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`,this.t(`objects.removeComparison`),`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=S(e,14),i.addEventListener(`click`,r),i}},Dt={trendLine:`Trend Line`,ray:`Ray`,extendedLine:`Extended Line`,horizontalLine:`Horizontal Line`,horizontalRay:`Horizontal Ray`,crossLine:`Cross Line`,infoLine:`Info Line`,trendAngle:`Trend Angle`,circle:`Circle`,fibChannel:`Fib Channel`,fibSpeedResistanceFan:`Fib Speed Resistance Fan`,schiffPitchfork:`Schiff Pitchfork`,modifiedSchiffPitchfork:`Modified Schiff Pitchfork`,xabcdPattern:`XABCD Pattern`,abcdPattern:`ABCD Pattern`,headAndShoulders:`Head and Shoulders`,dateAndPriceRange:`Date and Price Range`,cyclicLines:`Cyclic Lines`,priceLabel:`Price Label`,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`,text:`Text`,textAnnotation:`Text`,anchoredVWAP:`Anchored VWAP`,volumeProfileRange:`Volume Profile`,riskReward:`Long/Short Position`};function Ot(e,t){let n=`tool.${e}`,r=t?.(n);return r&&r!==n?r:Dt[e]??e}var kt=`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`;function F(e,t){if(e.key!==`Tab`)return;let n=[...t.querySelectorAll(kt)].filter(e=>e.getClientRects().length>0||e===document.activeElement);if(n.length===0)return;let r=n[0],i=n[n.length-1],a=document.activeElement;e.shiftKey&&(a===r||!t.contains(a))?(e.preventDefault(),i.focus()):!e.shiftKey&&(a===i||!t.contains(a))&&(e.preventDefault(),r.focus())}var At=1,jt=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/,Mt=[1,1.5,2,3,4];function Nt(e){return e.replace(/_/g,` `).replace(/([a-z0-9])([A-Z])/g,`$1 $2`).replace(/^./,e=>e.toUpperCase())}var Pt=class{backdrop;modal;bodyEl;titleEl;tabsEl;resetBtn;callbacks;target=null;draft={};colors=[];levels=[];tab=`inputs`;tabButtons=[];returnFocus=null;uid=At++;t;constructor(e,n,r){this.callbacks=n,this.t=r??(e=>t.c[e]),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`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-indi-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let i=document.createElement(`div`);i.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-indi-title-${this.uid}`,this.titleEl.textContent=`Indicator`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-modal-close`,a.setAttribute(`aria-label`,this.t(`indicatorSettings.close`)),a.innerHTML=S(`x`,16),a.addEventListener(`click`,()=>this.close()),i.append(this.titleEl,a),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-indi-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`);let o=document.createElement(`div`);o.className=`tcw-modal-footer`,this.resetBtn=document.createElement(`button`),this.resetBtn.type=`button`,this.resetBtn.className=`tcw-reset-link`,this.resetBtn.textContent=this.t(`settings.resetToDefaults`),this.resetBtn.addEventListener(`click`,()=>this.resetTab());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-done-btn`,s.textContent=this.t(`settings.done`),s.addEventListener(`click`,()=>this.close()),o.append(this.resetBtn,s),this.modal.append(i,this.tabsEl,this.bodyEl,o),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.backdrop.hidden&&(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.target=e,this.titleEl.textContent=this.t(`indicatorSettings.title`).replace(`{name}`,e.name),this.draft={},this.colors=[...e.colors??[]],this.levels=[...e.levels??[]],this.tab=`inputs`,this.renderTabs(),this.renderBody(),this.backdrop.hidden=!1;let t=this.tabsEl.hidden?null:this.tabButtons[0]??null;(this.bodyEl.querySelector(`button:not([disabled]), input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])`)??t??this.modal).focus()}close(){let e=document.activeElement;(e instanceof HTMLInputElement||e instanceof HTMLSelectElement)&&this.modal.contains(e)&&e.dispatchEvent(new Event(`change`)),this.backdrop.hidden=!0,this.target=null,this.callbacks.onClose(),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return!this.backdrop.hidden}destroy(){this.backdrop.remove()}tabs(){let e=this.target;if(!e)return[];let t=[`inputs`];return e.plots?.length&&e.colors&&this.callbacks.onStyle&&t.push(`style`),e.levels&&this.callbacks.onLevels&&t.push(`levels`),t}renderTabs(){let e=this.tabs();this.tabsEl.hidden=e.length<2,this.tabButtons=e.map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-indi-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`indicatorSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||t.length===0||(e.preventDefault(),this.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close();return}F(e,this.modal)}renderBody(){if(this.bodyEl.replaceChildren(),!this.target)return;let e=document.createElement(`div`);e.className=`tcw-settings-section`,this.tab===`style`?this.renderStyle(e):this.tab===`levels`?this.renderLevels(e):this.renderInputs(e),this.resetBtn.hidden=this.tab===`style`,this.bodyEl.appendChild(e)}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}))}renderInputs(e){let t=Object.keys(this.target.defaults);if(t.length===0){e.appendChild(this.note(this.t(`indicatorSettings.noInputs`)));return}for(let n of t)e.appendChild(this.fieldRow(n))}fieldRow(e){let t=this.target?.inputs?.[e],n=this.currentValue(e),r=typeof(this.target?.defaults[e]??n),i;return i=t?.source?this.sourceControl(e,String(n??`close`)):t?.options?this.choiceControl(e,t.options,n):r===`boolean`?this.toggleControl(e,!!n):r===`number`?this.numberControl(e,Number(n),t):typeof n==`string`&&jt.test(n)?this.colorInput(n,t=>this.setValue(e,t)):this.textControl(e,String(n??``)),this.row(t?.label??Nt(e),i)}sourceControl(e,t){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;let i=document.createElement(`optgroup`);i.label=this.t(`indicatorSettings.source.prices`);for(let e of n.PRICE_SOURCES)i.appendChild(this.option(e,e));r.appendChild(i);let a=this.target?.lineSources??[];if(a.length){let e=document.createElement(`optgroup`);e.label=this.t(`indicatorSettings.source.indicators`);for(let t of a)e.appendChild(this.option(t.value,t.label));r.appendChild(e)}return r.value=t,r.value!==t&&(r.value=`close`),r.addEventListener(`change`,()=>this.setValue(e,r.value)),r}choiceControl(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let e of t)r.appendChild(this.option(String(e),String(e)));return r.value=String(n),r.addEventListener(`change`,()=>{let n=t.find(e=>String(e)===r.value);n!==void 0&&this.setValue(e,n)}),r}toggleControl(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${t?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(t)),n.addEventListener(`click`,()=>{let t=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,t),n.setAttribute(`aria-checked`,String(t)),this.setValue(e,t)}),n}numberControl(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(t),r.step=String(n?.step??(Number.isInteger(t)?1:.1)),n?.min!==void 0&&(r.min=String(n.min)),n?.max!==void 0&&(r.max=String(n.max)),r.addEventListener(`change`,()=>{let t=Number(r.value);Number.isFinite(t)&&(n?.min!==void 0&&(t=Math.max(n.min,t)),n?.max!==void 0&&(t=Math.min(n.max,t)),r.value=String(t),this.setValue(e,t))}),r}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}renderStyle(e){let t=this.target,n=new Map,r=(e,t)=>{let r=n.get(e)??[];r.includes(t)||r.push(t),n.set(e,r)};for(let e of t.plots??[]){let t=e.tone!==void 0&&e.downColor!==void 0;r(e.color,t?`${e.title} ${this.t(`indicatorSettings.up`)}`:e.title),t&&r(e.downColor,`${e.title} ${this.t(`indicatorSettings.down`)}`)}for(let[r,i]of[...n].sort((e,t)=>e[0]-t[0])){let n=this.colors[r]??this.colors[0]??`#4c8dff`;e.appendChild(this.row(i.join(` · `),this.colorInput(n,e=>{let n=[...this.colors];for(;n.length<=r;)n.push(n[0]??e);n[r]=e,this.colors=n,this.callbacks.onStyle?.(t.instanceId,{colors:[...n]})})))}let i=document.createElement(`select`);i.className=`tcw-indi-input tcw-indi-select`;for(let e of Mt)i.appendChild(this.option(String(e),`${e} px`));if(i.value=String(t.lineWidth??1.5),i.addEventListener(`change`,()=>this.callbacks.onStyle?.(t.instanceId,{lineWidths:[Number(i.value)]})),e.appendChild(this.row(this.t(`indicatorSettings.lineWidth`),i)),t.scale&&this.callbacks.onScale){let n=document.createElement(`select`);n.className=`tcw-indi-input tcw-indi-select`,n.appendChild(this.option(`right`,this.t(`indicatorSettings.scale.right`))),n.appendChild(this.option(`left`,this.t(`indicatorSettings.scale.left`))),n.value=t.scale,n.addEventListener(`change`,()=>{let e=n.value===`left`?`left`:`right`;this.target={...t,scale:e},this.callbacks.onScale?.(t.instanceId,e)}),e.appendChild(this.row(this.t(`indicatorSettings.scale`),n))}}renderLevels(e){this.levels.length===0&&e.appendChild(this.note(this.t(`indicatorSettings.noLevels`))),this.levels.forEach((t,n)=>{let r=document.createElement(`input`);r.type=`number`,r.className=`tcw-indi-input`,r.id=`tcw-indi-level-${this.uid}-${n}`,r.value=String(t),r.step=`any`,r.addEventListener(`change`,()=>{let e=Number(r.value);!Number.isFinite(e)||r.value.trim()===``||(this.levels=this.levels.map((t,r)=>r===n?e:t),this.applyLevels())});let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-indi-remove`,i.innerHTML=S(`x`,12);let a=this.t(`indicatorSettings.removeLevel`);i.title=a,i.setAttribute(`aria-label`,`${a} ${n+1}`),i.addEventListener(`click`,()=>{this.levels=this.levels.filter((e,t)=>t!==n),this.applyLevels(),this.renderBody(),(this.bodyEl.querySelectorAll(`.tcw-indi-remove`)[n]??this.bodyEl.querySelector(`.tcw-indi-add`))?.focus()});let o=document.createElement(`span`);o.className=`tcw-indi-level`,o.append(r,i);let s=document.createElement(`div`);s.className=`tcw-settings-row`;let c=document.createElement(`label`);c.className=`tcw-settings-label`,c.htmlFor=r.id,c.textContent=`${this.t(`indicatorSettings.level`)} ${n+1}`,s.append(c,o),e.appendChild(s)});let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-reset-link tcw-indi-add`,t.textContent=`+ ${this.t(`indicatorSettings.addLevel`)}`,t.addEventListener(`click`,()=>{let e=this.levels[this.levels.length-1];this.levels=[...this.levels,e===void 0?0:e+10],this.applyLevels(),this.renderBody();let t=this.bodyEl.querySelectorAll(`.tcw-indi-level input`);t[t.length-1]?.focus()}),e.appendChild(t)}applyLevels(){this.target&&this.callbacks.onLevels?.(this.target.instanceId,[...this.levels])}resetTab(){let e=this.target;if(e){if(this.tab===`levels`)this.levels=[...e.defaultLevels??[]],this.callbacks.onLevels?.(e.instanceId,null);else{let t={};for(let[n,r]of Object.entries(e.defaults))t[n]=r;this.draft=t,this.callbacks.onApply(e.instanceId,{...t})}this.renderBody()}}row(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}note(e){let t=document.createElement(`div`);return t.className=`tcw-settings-label`,t.textContent=e,t}option(e,t){let n=document.createElement(`option`);return n.value=e,n.textContent=t,n}colorInput(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Ft(e),n.addEventListener(`input`,()=>t(n.value)),n}};function Ft(e){let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);return n?`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`:`#000000`}function It(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var Lt=80;function Rt(e){let{text:t,...r}=(0,n.sanitizeDrawingStyle)(e);return r}function zt(e){let t={name:e.name,style:{...e.style}};return e.type&&(t.type=e.type),e.options&&(t.options=structuredClone(e.options)),t}var Bt=class{templates=[];constructor(e=`tcw:draw-templates`,t=It()){this.storageKey=e,this.storage=t,this.load()}list(e){return this.templates.filter(t=>!t.type||t.type===e).map(zt)}get(e,t){let n=this.templates.find(n=>n.name===e&&n.type===t);return n?zt(n):null}save(e,t,n){let r=e.trim().slice(0,Lt);if(!r)return;let i={name:r,style:Rt(t)};n&&(i.type=n.type,i.options=structuredClone(n.options)),this.templates=this.templates.filter(e=>!(e.name===r&&e.type===i.type)),this.templates.push(i),this.persist()}remove(e,t){this.templates=this.templates.filter(n=>!(n.name===e&&n.type===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`&&e.name.trim()!==``).map(e=>{let t={name:e.name.trim().slice(0,Lt),style:Rt(e.style)};return typeof e.type==`string`&&(t.type=e.type),e.options&&typeof e.options==`object`&&!Array.isArray(e.options)&&(t.options=e.options),t})}catch{}}persist(){if(this.storage)try{this.storage.setItem(this.storageKey,JSON.stringify(this.templates))}catch{}}},Vt=class{defaults={};constructor(e=`tcw:drawing-defaults`,t=It()){this.storageKey=e,this.storage=t;try{let e=this.storage?.getItem(this.storageKey),t=e?JSON.parse(e):null;if(t&&typeof t==`object`&&!Array.isArray(t))for(let[e,n]of Object.entries(t))n&&typeof n==`object`&&!Array.isArray(n)&&(this.defaults[e]=n)}catch{}}all(){return structuredClone(this.defaults)}set(e,t){t&&Object.keys(t).length>0?this.defaults[e]=structuredClone(t):delete this.defaults[e];try{this.storage?.setItem(this.storageKey,JSON.stringify(this.defaults))}catch{}}},Ht=[`#4c8dff`,`#1fa874`,`#e8505b`,`#f2a93b`,`#a57cff`,`#1398a8`,`#ffffff`,`#7d8696`],Ut=[1,2,3,4],Wt=[`solid`,`dashed`,`dotted`],Gt=class{el;templatesEl;nameInput;callbacks;store;open=!1;constructor(e,n,r,i=t.t){this.t=i,this.callbacks=n,this.store=r,this.el=document.createElement(`div`),this.el.className=`tcw-style-panel`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-style-header`;let o=document.createElement(`span`);o.textContent=this.t(`drawingStyle.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a),this.el.appendChild(this.colorRow()),this.el.appendChild(this.widthRow()),this.el.appendChild(this.lineStyleRow());let c=document.createElement(`div`);c.className=`tcw-style-subhead`,c.textContent=this.t(`drawingStyle.templates`),this.el.appendChild(c);let l=document.createElement(`div`);l.className=`tcw-style-save`,this.nameInput=document.createElement(`input`),this.nameInput.type=`text`,this.nameInput.placeholder=this.t(`drawingStyle.templateName`),this.nameInput.className=`tcw-style-name`;let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-style-savebtn`,u.innerHTML=`${S(`plus`,13)}<span>${w(this.t(`common.save`))}</span>`,u.addEventListener(`click`,()=>this.saveTemplate()),l.appendChild(this.nameInput),l.appendChild(u),this.el.appendChild(l),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 Ht){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 Ut){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 Wt){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=this.t(`drawingStyle.noTemplates`),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`,this.t(`drawingStyle.deleteTemplate`)),a.innerHTML=S(`trash`,13),a.addEventListener(`click`,()=>{this.store.remove(t.name),this.renderTemplates()}),e.appendChild(n),e.appendChild(a),this.templatesEl.appendChild(e)}}};function I(e,t){let n=document.createElement(`label`);n.className=`tcw-settings-row`;let r=document.createElement(`span`);return r.className=`tcw-settings-label`,r.textContent=e,n.append(r,t),n}function Kt(e,t){let n=document.createElement(`button`);return n.type=`button`,n.className=`tcw-toggle${e?` tcw-on`:``}`,n.setAttribute(`role`,`switch`),n.setAttribute(`aria-checked`,String(e)),n.addEventListener(`click`,()=>{let e=!n.classList.contains(`tcw-on`);n.classList.toggle(`tcw-on`,e),n.setAttribute(`aria-checked`,String(e)),t(e)}),n}function L(e,t,n){let r=document.createElement(`input`);return r.type=`number`,r.className=`tcw-indi-input`,r.value=String(e),r.step=String(t.step??(Number.isInteger(e)?1:.001)),t.min!==void 0&&(r.min=String(t.min)),t.max!==void 0&&(r.max=String(t.max)),r.addEventListener(`change`,()=>{if(r.value.trim()===``)return;let e=Number(r.value);Number.isFinite(e)&&(t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),r.value=String(e),n(e))}),r}function qt(e,t){let n=document.createElement(`input`);return n.type=`color`,n.className=`tcw-indi-color`,n.value=Jt(e),n.addEventListener(`input`,()=>t(n.value)),n}function R(e,t,n){let r=document.createElement(`select`);r.className=`tcw-indi-input tcw-indi-select`;for(let t of e){let e=document.createElement(`option`);e.value=t.value,e.textContent=t.label,r.appendChild(e)}return r.value=t,r.addEventListener(`change`,()=>n(r.value)),r}function Jt(e){if(typeof e!=`string`)return`#000000`;let t=e.trim();if(/^#[0-9a-f]{6}$/i.test(t))return t.toLowerCase();if(/^#[0-9a-f]{3}$/i.test(t))return`#${t[1]}${t[1]}${t[2]}${t[2]}${t[3]}${t[3]}`.toLowerCase();let n=/^rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i.exec(t);return n?`#${[n[1],n[2],n[3]].map(e=>Math.min(255,Number(e)).toString(16).padStart(2,`0`)).join(``)}`:`#000000`}function Yt(e){if(typeof e!=`string`)return 1;let t=/^rgba\([^)]*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return t?Math.max(0,Math.min(1,Number(t[1]))):1}function Xt(e,t){let n=Jt(e),[r,i,a]=[1,3,5].map(e=>parseInt(n.slice(e,e+2),16));return`rgba(${r}, ${i}, ${a}, ${Math.round(t*100)/100})`}var Zt=12,Qt=[1,2,3,4],$t=[`solid`,`dashed`,`dotted`],en=[10,11,12,14,16,18,20,24,28,32],tn=48,nn=1,rn=class{backdrop;modal;titleEl;tabsEl;bodyEl;footerLeft;tabButtons=[];target=null;style;options={};anchors=[];tab=`style`;returnFocus=null;uid=nn++;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(!0),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-drawing-settings`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-draw-title-${this.uid}`),this.modal.tabIndex=-1,this.modal.addEventListener(`keydown`,e=>this.onKeyDown(e));let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-draw-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,16),o.addEventListener(`click`,()=>this.close(!0)),a.append(this.titleEl,o),this.tabsEl=document.createElement(`div`),this.tabsEl.className=`tcw-modal-tabs`,this.tabsEl.setAttribute(`role`,`tablist`),this.tabsEl.addEventListener(`keydown`,e=>this.onTabKey(e)),this.bodyEl=document.createElement(`div`),this.bodyEl.className=`tcw-modal-body`,this.bodyEl.id=`tcw-draw-panel-${this.uid}`,this.bodyEl.setAttribute(`role`,`tabpanel`);let s=document.createElement(`div`);s.className=`tcw-modal-footer`,this.footerLeft=document.createElement(`div`),this.footerLeft.className=`tcw-drawing-settings-tools`;let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-reset-link`,c.textContent=this.t(`common.cancel`),c.addEventListener(`click`,()=>this.close(!0));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-done-btn`,l.textContent=this.t(`drawingSettings.ok`),l.addEventListener(`click`,()=>this.close(!1)),s.append(this.footerLeft,c,l),this.modal.append(a,this.tabsEl,this.bodyEl,s),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.target&&this.close(!1),this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.target=e,this.style={...e.style},this.options=structuredClone(e.options),this.anchors=e.anchors.map(e=>({...e})),this.titleEl.textContent=e.name,this.tab=`style`,this.callbacks.onBegin(e.id);try{this.renderTabs(),this.renderBody()}catch(t){throw this.target=null,this.callbacks.onEnd(e.id,!0),t}this.backdrop.hidden=!1,(this.tabButtons[0]??this.modal).focus()}close(e){let t=this.target;if(!t)return;let n=document.activeElement;!e&&(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&this.modal.contains(n)&&n.dispatchEvent(new Event(`change`)),this.target=null,this.backdrop.hidden=!0,this.callbacks.onEnd(t.id,e),this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null}isOpen(){return this.target!==null}editing(){return this.target?.id??null}destroy(){this.close(!0),this.backdrop.remove()}tabs(){let e=[`style`];return this.target&&Object.keys(this.target.defs).length>0&&e.push(`options`),this.target&&this.target.anchors.length<=Zt&&e.push(`coordinates`),e}renderTabs(){this.tabButtons=this.tabs().map(e=>{let t=document.createElement(`button`);return t.type=`button`,t.className=`tcw-modal-tab`,t.id=`tcw-draw-tab-${this.uid}-${e}`,t.setAttribute(`role`,`tab`),t.setAttribute(`aria-controls`,this.bodyEl.id),t.dataset.tab=e,t.textContent=this.t(`drawingSettings.tab.${e}`),t.addEventListener(`click`,()=>this.selectTab(e)),t}),this.tabsEl.replaceChildren(...this.tabButtons),this.markTabs()}markTabs(){for(let e of this.tabButtons){let t=e.dataset.tab===this.tab;e.classList.toggle(`tcw-active`,t),e.setAttribute(`aria-selected`,String(t)),e.tabIndex=t?0:-1,t&&this.bodyEl.setAttribute(`aria-labelledby`,e.id)}}selectTab(e,t=!1){this.tab=e,this.markTabs(),this.renderBody(),t&&this.tabButtons.find(t=>t.dataset.tab===e)?.focus()}onTabKey(e){let t=this.tabButtons.map(e=>e.dataset.tab),n=t.indexOf(this.tab),r=e.key===`ArrowRight`?(n+1)%t.length:e.key===`ArrowLeft`?(n-1+t.length)%t.length:e.key===`Home`?0:e.key===`End`?t.length-1:-1;r<0||(e.preventDefault(),this.selectTab(t[r],!0))}onKeyDown(e){if(e.key===`Escape`){e.preventDefault(),e.stopPropagation(),this.close(!0);return}F(e,this.modal)}renderBody(){if(this.bodyEl.replaceChildren(),this.footerLeft.replaceChildren(),!this.target)return;if(this.target.alertable&&this.callbacks.onAddAlert){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link tcw-drawing-alert`,e.innerHTML=`${S(`bell`,13)}<span></span>`,e.querySelector(`span`).textContent=this.t(`drawingSettings.addAlert`),e.addEventListener(`click`,()=>this.callbacks.onAddAlert?.(this.target.id)),this.footerLeft.appendChild(e)}let e=document.createElement(`div`);e.className=`tcw-settings-section`,this.tab===`options`?this.renderOptions(e):this.tab===`coordinates`?this.renderCoordinates(e):this.renderStyle(e),this.bodyEl.appendChild(e)}change(e){this.target&&this.callbacks.onChange(this.target.id,e)}setStyle(e){this.style={...this.style,...e},this.change({style:e})}setOptions(e){this.options={...this.options,...structuredClone(e)},this.change({options:e})}renderStyle(e){let t=this.target;e.appendChild(I(this.t(`drawingSettings.color`),qt(this.style.color,e=>this.setStyle({color:e})))),e.appendChild(I(this.t(`drawingSettings.lineWidth`),R(Qt.map(e=>({value:String(e),label:`${e} px`})),String(this.style.lineWidth),e=>this.setStyle({lineWidth:Number(e)})))),e.appendChild(I(this.t(`drawingSettings.lineStyle`),R($t.map(e=>({value:e,label:this.t(`drawingSettings.lineStyle.${e}`)})),this.style.lineStyle,e=>this.setStyle({lineStyle:e})))),t.fill&&this.renderFill(e),t.text&&this.renderText(e),this.callbacks.templates&&this.renderTemplates(e)}renderFill(e){let t=this.style.fillColor??Xt(this.style.color,.1),n=Jt(t),r=Yt(t),i=()=>this.setStyle({fillColor:Xt(n,r),fillOpacity:r});e.appendChild(I(this.t(`drawingSettings.fill`),qt(n,e=>{n=e,i()}))),e.appendChild(I(this.t(`drawingSettings.opacity`),L(Math.round(r*100),{min:0,max:100,step:5},e=>{r=e/100,i()})))}renderText(e){let t=document.createElement(`textarea`);t.className=`tcw-indi-input tcw-drawing-text`,t.rows=3,t.value=this.style.text??``,t.addEventListener(`input`,()=>this.setStyle({text:t.value})),e.appendChild(I(this.t(`drawingSettings.text`),t)),e.appendChild(I(this.t(`drawingSettings.fontSize`),R(en.map(e=>({value:String(e),label:`${e} px`})),String(this.style.fontSize??12),e=>this.setStyle({fontSize:Number(e)}))))}renderTemplates(e){let t=this.callbacks.templates,r=this.target,i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=this.t(`drawingStyle.templates`),e.appendChild(i);let a=document.createElement(`div`);a.className=`tcw-drawing-templates`;let o=t.list(r.type);if(o.length===0){let e=document.createElement(`div`);e.className=`tcw-settings-label`,e.textContent=this.t(`drawingStyle.noTemplates`),a.appendChild(e)}for(let e of o){let i=document.createElement(`div`);i.className=`tcw-style-tmpl`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-style-tmpl-apply`,o.textContent=e.name,o.addEventListener(`click`,()=>{this.setStyle(e.style),e.options&&this.setOptions((0,n.sanitizeDrawingOptions)(r.defs,e.options)),this.renderBody()});let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-style-tmpl-del`,s.setAttribute(`aria-label`,this.t(`drawingStyle.deleteTemplate`)),s.innerHTML=S(`x`,12),s.addEventListener(`click`,()=>{t.remove(e.name,e.type),this.renderBody()}),i.append(o,s),a.appendChild(i)}e.appendChild(a);let s=document.createElement(`div`);s.className=`tcw-style-save`;let c=document.createElement(`input`);c.type=`text`,c.className=`tcw-style-name`,c.placeholder=this.t(`drawingStyle.templateName`),c.setAttribute(`aria-label`,this.t(`drawingStyle.templateName`));let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-style-savebtn`,l.textContent=this.t(`common.save`),l.addEventListener(`click`,()=>{c.value.trim()&&(t.save(c.value,this.style,{type:r.type,options:this.options}),this.renderBody())}),s.append(c,l),e.appendChild(s)}label(e,t){let n=`drawingOption.${e}`,r=this.t(n);return r===n?t:r}renderOptions(e){let t=this.target;for(let[n,r]of Object.entries(t.defs))r.kind===`levels`?e.appendChild(this.levelsEditor(n,r)):e.appendChild(I(this.label(n,r.label),this.optionControl(n,r)));let n=document.createElement(`button`);if(n.type=`button`,n.className=`tcw-reset-link`,n.textContent=this.t(`settings.resetToDefaults`),n.addEventListener(`click`,()=>{let e={};for(let[n,r]of Object.entries(t.defs))e[n]=structuredClone(r.default);this.setOptions(e),this.renderBody()}),this.footerLeft.appendChild(n),this.callbacks.onSaveDefault){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-reset-link`,e.textContent=this.t(`drawingSettings.saveDefault`),e.addEventListener(`click`,()=>this.callbacks.onSaveDefault?.(t.type,structuredClone(this.options))),this.footerLeft.appendChild(e)}}optionControl(e,t){let n=this.options[e];switch(t.kind){case`boolean`:return Kt(!!n,t=>this.setOptions({[e]:t}));case`number`:return L(Number(n),{min:t.min,max:t.max,step:t.step},t=>this.setOptions({[e]:t}));case`choice`:return R(t.choices.map(t=>({value:t.value,label:this.label(`${e}.${t.value}`,t.label)})),String(n),t=>this.setOptions({[e]:t}));case`text`:{let t=document.createElement(`input`);return t.type=`text`,t.className=`tcw-indi-input`,t.value=String(n??``),t.addEventListener(`change`,()=>this.setOptions({[e]:t.value})),t}}}levelsEditor(e,t){let n=document.createElement(`div`);n.className=`tcw-levels-editor`;let r=document.createElement(`div`);r.className=`tcw-style-subhead`,r.textContent=this.label(e,t.label),n.appendChild(r);let i=()=>{let t=this.options[e];return Array.isArray(t)?t:[]},a=t=>this.setOptions({[e]:t}),o=document.createElement(`div`);o.className=`tcw-levels-grid`,i().forEach((e,t)=>{let n=document.createElement(`div`);n.className=`tcw-level-row`;let r=document.createElement(`input`);r.type=`checkbox`,r.checked=e.visible;let s=` ${t+1}`;r.setAttribute(`aria-label`,this.t(`drawingSettings.levelVisible`)+s),r.addEventListener(`change`,()=>a(i().map((e,n)=>n===t?{...e,visible:r.checked}:e)));let c=L(e.value,{step:.001},e=>a(i().map((n,r)=>r===t?{...n,value:e}:n)));c.setAttribute(`aria-label`,this.t(`drawingSettings.levelValue`)+s);let l=qt(e.color??this.style.color,e=>a(i().map((n,r)=>r===t?{...n,color:e}:n)));l.setAttribute(`aria-label`,this.t(`drawingSettings.levelColor`)+s);let u=document.createElement(`button`);u.type=`button`,u.className=`tcw-level-remove`,u.setAttribute(`aria-label`,this.t(`drawingSettings.removeLevel`)+s),u.innerHTML=S(`x`,12),u.addEventListener(`click`,()=>{a(i().filter((e,n)=>n!==t)),this.renderBody()}),n.append(r,c,l,u),o.appendChild(n)}),n.appendChild(o);let s=document.createElement(`button`);return s.type=`button`,s.className=`tcw-reset-link tcw-level-add`,s.textContent=this.t(`drawingSettings.addLevel`),s.disabled=i().length>=tn,s.addEventListener(`click`,()=>{let e=i().at(-1)?.value??0;a([...i(),{value:Math.round((e+.5)*1e3)/1e3,visible:!0}]),this.renderBody()}),n.appendChild(s),n}renderCoordinates(e){this.anchors.forEach((n,r)=>{let i=document.createElement(`div`);i.className=`tcw-style-subhead`,i.textContent=t.r(this.t(`drawingSettings.point`),{n:r+1}),e.appendChild(i);let a=this.callbacks.toWallTime(n.time),o=document.createElement(`input`);o.type=`date`,o.className=`tcw-indi-input`,o.value=a.date;let s=document.createElement(`input`);s.type=`time`,s.className=`tcw-indi-input`,s.value=a.time;let c=()=>{let e=this.callbacks.fromWallTime(o.value,s.value);e!==null&&this.setAnchor(r,{time:e})};o.addEventListener(`change`,c),s.addEventListener(`change`,c),e.appendChild(I(this.t(`drawingSettings.date`),o)),e.appendChild(I(this.t(`drawingSettings.time`),s)),e.appendChild(I(this.t(`drawingSettings.price`),L(n.price,{step:`any`},e=>this.setAnchor(r,{price:e}))))})}setAnchor(e,t){this.anchors=this.anchors.map((n,r)=>r===e?{...n,...t}:n),this.change({anchors:this.anchors.map(e=>({...e}))})}},an=4;function on(e,t,n){let r=e+t>n?e-t:e;return Math.max(0,Math.min(r,n-t))}var z=class{el;onPick=null;returnFocus=null;anchor=null;onDocPointer=e=>{let t=e.target;this.el.contains(t)||this.anchor?.contains(t)||this.close()};onAway=()=>this.close();constructor(e,t){this.host=e,this.el=document.createElement(`div`),this.el.className=`tcw-context-menu`,this.el.setAttribute(`role`,`menu`),this.el.setAttribute(`aria-label`,t),this.el.hidden=!0,this.el.addEventListener(`keydown`,e=>this.onKeyDown(e)),e.appendChild(this.el)}open(e,t,n,r,i){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.onPick=r,this.anchor=i??null,this.el.replaceChildren(...e.map(e=>this.entry(e))),this.el.hidden=!1;let a=this.host.getBoundingClientRect(),o=Math.min(this.host.clientWidth,window.innerWidth-a.left)-an,s=Math.min(this.host.clientHeight,window.innerHeight-a.top)-an;this.el.style.left=`${on(t,this.el.offsetWidth,o)}px`,this.el.style.top=`${on(n,this.el.offsetHeight,s)}px`,document.addEventListener(`pointerdown`,this.onDocPointer,!0),document.addEventListener(`wheel`,this.onAway,{capture:!0,passive:!0}),window.addEventListener(`resize`,this.onAway),window.addEventListener(`blur`,this.onAway),this.items()[0]?.focus({preventScroll:!0})}close(){this.el.hidden||(this.el.hidden=!0,this.onPick=null,this.anchor=null,document.removeEventListener(`pointerdown`,this.onDocPointer,!0),document.removeEventListener(`wheel`,this.onAway,{capture:!0}),window.removeEventListener(`resize`,this.onAway),window.removeEventListener(`blur`,this.onAway),this.returnFocus?.isConnected&&this.returnFocus.focus({preventScroll:!0}),this.returnFocus=null)}isOpen(){return!this.el.hidden}destroy(){this.close(),this.el.remove()}entry(e){if(e===`separator`){let e=document.createElement(`div`);return e.className=`tcw-context-sep`,e.setAttribute(`role`,`separator`),e}let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-context-item${e.danger?` tcw-context-danger`:``}`,t.setAttribute(`role`,e.checked===void 0?`menuitem`:`menuitemcheckbox`),e.checked!==void 0&&t.setAttribute(`aria-checked`,String(e.checked)),t.tabIndex=-1,t.dataset.id=e.id;let n=e.checked===void 0?e.icon??``:e.checked?`check`:``;t.innerHTML=n?S(n,14):`<span class="tcw-context-icon"></span>`;let r=document.createElement(`span`);return r.textContent=e.label,t.appendChild(r),t.addEventListener(`click`,()=>this.pick(e.id)),t}pick(e){let t=this.onPick;this.close(),t?.(e)}items(){return[...this.el.querySelectorAll(`[role=menuitem], [role=menuitemcheckbox]`)]}onKeyDown(e){let t=this.items(),n=t.indexOf(document.activeElement),r=-1;if(e.key===`ArrowDown`)r=(n+1)%t.length;else if(e.key===`ArrowUp`)r=(n-1+t.length)%t.length;else if(e.key===`Home`)r=0;else if(e.key===`End`)r=t.length-1;else if(e.key===`Escape`||e.key===`Tab`){e.preventDefault(),e.stopPropagation(),this.close();return}else return;e.preventDefault(),t[r]?.focus({preventScroll:!0})}};function sn(e,t){let{selected:n}=e,r=n.length===1,i=new Set(n.map(e=>e.groupId)),a=i.size===1&&!i.has(null),o=[];e.canConfigure&&r&&o.push({id:`settings`,label:t(`drawingMenu.settings`),icon:`settings`}),e.canAlert&&r&&o.push({id:`alert`,label:t(`drawingSettings.addAlert`),icon:`bell`}),o.length>0&&o.push(`separator`),r&&o.push({id:`front`,label:t(`drawingMenu.front`)},{id:`forward`,label:t(`drawingMenu.forward`)},{id:`backward`,label:t(`drawingMenu.backward`)},{id:`back`,label:t(`drawingMenu.back`)},`separator`),n.length>1&&!a&&o.push({id:`group`,label:t(`drawingMenu.group`),icon:`layers`}),n.some(e=>e.groupId)&&o.push({id:`ungroup`,label:t(`drawingMenu.ungroup`),icon:`layers`});let s=n.every(e=>e.locked);return o.push(s?{id:`unlock`,label:t(`common.unlock`),icon:`unlock`}:{id:`lock`,label:t(`common.lock`),icon:`lock`},{id:`hide`,label:t(`common.hide`),icon:`eyeOff`}),r&&o.push({id:`duplicate`,label:t(`drawingMenu.duplicate`),icon:`plus`}),s||o.push(`separator`,{id:`delete`,label:t(`drawingMenu.delete`),icon:`trash`,danger:!0}),o}function cn(e,n){if(e.price===void 0||!Number.isFinite(e.price))return[];let r=e.formatPrice(e.price),i=[];if(e.canAlert&&i.push({id:`alert`,label:t.r(n(`chartMenu.addAlert`),{price:r}),icon:`bell`}),e.canTrade){let a=e.lastPrice===null||e.price<=e.lastPrice;i.push(a?{id:`buyLimit`,label:t.r(n(`chartMenu.buyLimit`),{price:r}),icon:`trendingUp`}:{id:`buyStop`,label:t.r(n(`chartMenu.buyStop`),{price:r}),icon:`trendingUp`},a?{id:`sellStop`,label:t.r(n(`chartMenu.sellStop`),{price:r}),icon:`trendingDown`}:{id:`sellLimit`,label:t.r(n(`chartMenu.sellLimit`),{price:r}),icon:`trendingDown`}),e.canOrderTicket&&i.push({id:`orderTicket`,label:n(`chartMenu.orderTicket`),icon:`receipt`})}return e.canDraw&&i.push({id:`horizontalLine`,label:t.r(n(`chartMenu.horizontalLine`),{price:r}),icon:`minus`}),i}function ln(e,t,n){let r=e=>{let r=cn(t,n);return r.length>0?[...r,`separator`,...e]:e},i={id:`settings`,label:n(`chartMenu.settings`),icon:`settings`};switch(e){case`priceAxis`:{let e=cn({...t,canTrade:!1,canDraw:!1},n);return[{id:`autoScale`,label:n(`settings.autoScale`),checked:t.autoScale},{id:`logScale`,label:n(`settings.scale.logarithmic`),checked:t.scaleMode===`logarithmic`},{id:`percentScale`,label:n(`settings.scale.percentage`),checked:t.scaleMode===`percentage`},{id:`invertScale`,label:n(`chartMenu.invertScale`),checked:t.inverted},...e.length>0?[`separator`,...e]:[]]}case`timeAxis`:return[{id:`resetView`,label:n(`chartMenu.resetTimeScale`)},...t.canGoToDate?[{id:`goToDate`,label:n(`chartMenu.goToDate`),icon:`calendar`}]:[]];case`pane`:return[{id:`resetView`,label:n(`chartMenu.resetView`)},...t.pane?[`separator`,{id:`paneLog`,label:n(`chartMenu.paneLog`),checked:t.pane.log},{id:`paneInvert`,label:n(`chartMenu.paneInvert`),checked:t.pane.invert},{id:`panePercent`,label:n(`chartMenu.panePercent`),checked:t.pane.percent}]:[],`separator`,i];default:{let e=t.hasDrawings?[t.drawingsHidden?{id:`showDrawings`,label:n(`chartMenu.showDrawings`),icon:`eye`}:{id:`hideDrawings`,label:n(`chartMenu.hideDrawings`),icon:`eyeOff`},{id:`removeDrawings`,label:n(`chartMenu.removeDrawings`),icon:`trash`,danger:!0}]:[],a=t.canExport?[{id:`exportData`,label:n(`chartMenu.exportData`),icon:`save`}]:[];return r([{id:`resetView`,label:n(`chartMenu.resetView`)},...e,...a,`separator`,i])}}}var B=[`positions`,`orders`,`history`],un=[`order`,`close`,`reverse`,`stopLoss`,`takeProfit`],dn=[`market`,`limit`,`stop`],fn=[`gtc`,`day`];function pn(e,t,n){return e.includes(t??``)?t:n}function mn(e,t){return e.length===t.length&&e.every((e,n)=>e===t[n])}function hn(e,t){if(t===null)return null;let n=e.quantity-(e.closedQuantity??0),r=e.side===`buy`?1:-1;return{pnl:(t-e.entryPrice)*n*r,pct:e.entryPrice===0?0:(t-e.entryPrice)/e.entryPrice*100*r}}function V(e,t=2){return`${e>0?`+`:``}${e.toFixed(t)}`}var gn=class{el;tabButtons=new Map;content;tab=`positions`;snapshot={positions:[],orders:[],fills:[],price:null};open=!1;live=[];constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.el=document.createElement(`section`),this.el.className=`tcw-account`,this.el.hidden=!0,this.el.setAttribute(`aria-label`,this.t(`account.title`));let i=document.createElement(`div`);i.className=`tcw-account-head`;let a=document.createElement(`div`);a.className=`tcw-account-tabs`,a.setAttribute(`role`,`tablist`),a.addEventListener(`keydown`,e=>this.onTabKey(e));for(let e of B){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-account-tab`,t.setAttribute(`role`,`tab`),t.id=`tcw-account-tab-${e}`,t.addEventListener(`click`,()=>this.selectTab(e)),this.tabButtons.set(e,t),a.appendChild(t)}let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-account-new`,o.innerHTML=S(`plus`,13),o.append(this.t(`account.newOrder`)),o.addEventListener(`click`,()=>this.callbacks.onNewOrder());let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-tree-close`,s.setAttribute(`aria-label`,this.t(`account.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.closePanel()),i.append(a,o,s),this.content=document.createElement(`div`),this.content.className=`tcw-account-body`,this.content.setAttribute(`role`,`tabpanel`),this.el.append(i,this.content),e.appendChild(this.el),this.renderTabs()}isOpen(){return this.open}toggle(){this.open?this.closePanel():this.openPanel()}openPanel(){this.open=!0,this.el.hidden=!1,this.render(),this.callbacks.onToggle?.(!0)}closePanel(){this.open&&(this.open=!1,this.el.hidden=!0,this.callbacks.onToggle?.(!1))}update(e){let t=this.snapshot;if(this.snapshot=e,mn(t.positions,e.positions)&&mn(t.orders,e.orders)&&mn(t.fills,e.fills)&&t.realisedPnl===e.realisedPnl){this.open&&this.tab===`positions`&&t.price!==e.price&&this.patchPrices();return}this.renderTabs(),this.open&&this.render()}destroy(){this.el.remove()}selectTab(e){this.tab=e,this.renderTabs(),this.render()}onTabKey(e){let t=B.indexOf(this.tab),n=e.key===`ArrowRight`?t+1:e.key===`ArrowLeft`?t-1:-2;if(n===-2)return;e.preventDefault();let r=B[(n+B.length)%B.length];this.selectTab(r),this.tabButtons.get(r)?.focus()}renderTabs(){let e={positions:this.snapshot.positions.length,orders:this.snapshot.orders.length,history:this.snapshot.fills.length};for(let[t,n]of this.tabButtons){let r=t===this.tab;n.textContent=`${this.t(`account.${t}`)} (${e[t]})`,n.setAttribute(`aria-selected`,String(r)),n.tabIndex=r?0:-1,r&&this.content.setAttribute(`aria-labelledby`,n.id)}}render(){let e=document.activeElement,t=e instanceof HTMLElement&&this.content.contains(e)?e.dataset.focusKey:void 0;this.live=[],this.tab===`positions`?this.renderPositions():this.tab===`orders`?this.renderOrders():this.renderHistory(),t&&[...this.content.querySelectorAll(`[data-focus-key]`)].find(e=>e.dataset.focusKey===t)?.focus()}patchPrices(){let{price:e}=this.snapshot;for(let t of this.live)t.price.textContent=e===null?`—`:this.callbacks.formatPrice(e),this.writePnl(t.pnl,hn(t.position,e))}writePnl(e,t){e.className=t===null?``:t.pnl>=0?`tcw-account-up`:`tcw-account-down`,e.textContent=t===null?`—`:`${V(t.pnl)} (${V(t.pct)}%)`}table(e,t,n){if(t.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(n),this.content.replaceChildren(e);return}let r=document.createElement(`table`);r.className=`tcw-account-table`;let i=r.createTHead().insertRow();for(let t of e){let e=document.createElement(`th`);e.scope=`col`,e.textContent=t?this.t(t):``,i.appendChild(e)}r.createTBody().append(...t),this.content.replaceChildren(r)}row(e,t=``){let n=document.createElement(`tr`);t&&(n.className=t);for(let t of e){let e=n.insertCell();typeof t==`string`?e.textContent=t:e.appendChild(t)}return n}sideCell(e,t=`position`){let n=document.createElement(`span`);return n.className=`tcw-account-side tcw-account-${e}`,n.textContent=this.sideText(e,t),n}sideText(e,t){return t===`trade`?this.t(e===`buy`?`ticket.buy`:`ticket.sell`):this.t(e===`buy`?`account.long`:`account.short`)}actions(...e){let t=document.createElement(`div`);t.className=`tcw-account-actions`;for(let n of e){let e=document.createElement(`button`);e.type=`button`,e.className=`tcw-tree-btn${n.danger?` tcw-tree-del`:``}`,e.setAttribute(`aria-label`,n.label),e.title=n.label,e.dataset.focusKey=n.key,e.innerHTML=S(n.icon,14),e.addEventListener(`click`,n.run),t.appendChild(e)}return t}renderPositions(){let{formatPrice:e}=this.callbacks,{price:t}=this.snapshot,n=this.snapshot.positions.map(n=>{let r=n.quantity-(n.closedQuantity??0),i=document.createElement(`span`);this.writePnl(i,hn(n,t));let a=`${this.sideText(n.side,`position`)} ${r} @ ${e(n.entryPrice)}`,o=this.row([this.sideCell(n.side),String(r),e(n.entryPrice),t===null?`—`:e(t),i,n.stopLoss===void 0?`—`:e(n.stopLoss),n.takeProfit===void 0?`—`:e(n.takeProfit),this.actions({icon:`repeat`,label:`${this.t(`account.reverse`)}: ${a}`,key:`reverse:${n.id}`,run:()=>this.callbacks.onReversePosition(n.id)},{icon:`x`,label:`${this.t(`account.closePosition`)}: ${a}`,key:`close:${n.id}`,run:()=>this.callbacks.onClosePosition(n.id),danger:!0})]);return this.live.push({position:n,price:o.cells[3],pnl:i}),o});this.table([`account.side`,`account.quantity`,`account.entry`,`account.price`,`account.pnl`,`account.stopLoss`,`account.takeProfit`,`account.actions`],n,`account.noPositions`)}renderOrders(){let{formatPrice:e}=this.callbacks,t=this.snapshot.orders.map(t=>{let n=pn(dn,t.type===`stopLimit`?`stop`:t.type,`limit`),r=`${this.sideText(t.side,`trade`)} ${t.quantity} @ ${e(t.price)}`;return this.row([this.sideCell(t.side,`trade`),this.t(`ticket.type.${n}`),String(t.quantity),e(t.price),t.stopLoss===void 0?`—`:e(t.stopLoss),t.takeProfit===void 0?`—`:e(t.takeProfit),t.timeInForce?this.t(`ticket.tif.${pn(fn,t.timeInForce,`gtc`)}`):`—`,this.actions({icon:`x`,label:`${this.t(`account.cancelOrder`)}: ${r}`,key:`cancel:${t.id}`,run:()=>this.callbacks.onCancelOrder(t.id),danger:!0})])});this.table([`account.side`,`ticket.type`,`account.quantity`,`account.price`,`account.stopLoss`,`account.takeProfit`,`ticket.timeInForce`,`account.actions`],t,`account.noOrders`)}renderHistory(){let{formatPrice:e,formatTime:n}=this.callbacks,r=[...this.snapshot.fills].reverse().map(t=>{let r=document.createElement(`span`);return t.pnl===void 0?r.textContent=`—`:(r.className=t.pnl>=0?`tcw-account-up`:`tcw-account-down`,r.textContent=V(t.pnl)),this.row([n(t.time),this.sideCell(t.side,`trade`),String(t.quantity),e(t.price),this.t(`account.reason.${pn(un,t.reason,`order`)}`),r])});this.table([`account.time`,`account.side`,`account.quantity`,`account.price`,`account.reason`,`account.pnl`],r,`account.noFills`);let i=this.snapshot.realisedPnl??this.snapshot.fills.reduce((e,t)=>e+(t.pnl??0),0);if(r.length>0){let e=document.createElement(`p`);e.className=`tcw-account-summary`,e.textContent=t.r(this.t(`account.realised`),{pnl:V(i)}),this.content.appendChild(e)}}};function _n(e,t){return e.type===`market`?t:e.price}function vn(e,t){let n=[];(!(e.quantity>0)||!Number.isFinite(e.quantity))&&n.push(`quantity`),e.type!==`market`&&(!(e.price>0)||!Number.isFinite(e.price))&&n.push(`price`),e.type===`market`&&!((t??e.price)>0)&&n.push(`market`);let r=e.side===`buy`;if(t!==null&&e.type!==`market`&&e.price>0){let i=e.price<t;e.type===`limit`&&i!==r&&e.price!==t&&n.push(`limitSide`),e.type===`stop`&&i===r&&e.price!==t&&n.push(`stopSide`)}let i=e=>e===null||Number.isFinite(e)&&e>0;i(e.stopLoss)||n.push(`stopLoss`),i(e.takeProfit)||n.push(`takeProfit`);let a=_n(e,t);return a!==null&&a>0&&(e.stopLoss!==null&&i(e.stopLoss)&&(r?e.stopLoss>=a:e.stopLoss<=a)&&n.push(`stopLossSide`),e.takeProfit!==null&&i(e.takeProfit)&&(r?e.takeProfit<=a:e.takeProfit>=a)&&n.push(`takeProfitSide`)),n}function yn(e,t){let n={side:e.side,type:e.type,price:e.type===`market`?t??e.price:e.price,quantity:e.quantity};return e.type===`stop`&&(n.stopPrice=e.price),e.type!==`market`&&(n.timeInForce=e.timeInForce),e.stopLoss!==null&&(n.stopLoss=e.stopLoss),e.takeProfit!==null&&(n.takeProfit=e.takeProfit),n}function bn(e,t){let n=_n(e,t);if(n===null||e.stopLoss===null||e.takeProfit===null)return null;let r=Math.abs(n-e.stopLoss);return r>0?Math.abs(e.takeProfit-n)/r:null}var xn=0,Sn=class{backdrop;modal;body;problemsEl;submit;draft=null;lastPrice=null;returnFocus=null;uid=++xn;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1}),this.modal=document.createElement(`div`),this.modal.className=`tcw-modal tcw-modal-narrow tcw-order-ticket`,this.modal.setAttribute(`role`,`dialog`),this.modal.setAttribute(`aria-modal`,`true`),this.modal.setAttribute(`aria-labelledby`,`tcw-ticket-title-${this.uid}`),this.modal.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}F(e,this.modal)});let a=document.createElement(`div`);a.className=`tcw-modal-header`;let o=document.createElement(`h3`);o.id=`tcw-ticket-title-${this.uid}`,o.textContent=this.t(`ticket.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-modal-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,16),s.addEventListener(`click`,()=>this.close()),a.append(o,s),this.body=document.createElement(`div`),this.body.className=`tcw-modal-body`,this.problemsEl=document.createElement(`div`),this.problemsEl.className=`tcw-ticket-problems`,this.problemsEl.setAttribute(`aria-live`,`polite`);let c=document.createElement(`div`);c.className=`tcw-modal-footer`;let l=document.createElement(`button`);l.type=`button`,l.className=`tcw-reset-link`,l.textContent=this.t(`common.cancel`),l.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`button`,this.submit.className=`tcw-done-btn`,this.submit.addEventListener(`click`,()=>this.place()),c.append(l,this.submit),this.modal.append(a,this.body,this.problemsEl,c),this.backdrop.appendChild(this.modal),e.appendChild(this.backdrop)}open(e){this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null,this.lastPrice=e.lastPrice;let t=e.price??e.lastPrice??0,n=e.side??`buy`,r=`market`;e.price!==void 0&&e.lastPrice!==null&&e.price!==e.lastPrice&&(r=e.price<e.lastPrice==(n===`buy`)?`limit`:`stop`),this.draft={side:n,type:r,quantity:1,price:t,stopLoss:null,takeProfit:null,timeInForce:`gtc`},this.render(),this.backdrop.hidden=!1,this.body.querySelector(`button, input, select`)?.focus()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.draft=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}setLastPrice(e){!this.draft||e===this.lastPrice||(this.lastPrice=e,this.check())}destroy(){this.close(),this.backdrop.remove()}place(){let e=this.draft;!e||vn(e,this.lastPrice).length>0||(this.callbacks.onSubmit(yn(e,this.lastPrice)),this.close())}set(e,t=!1){this.draft&&(this.draft={...this.draft,...e},t?this.render():this.check())}render(){let e=this.draft;if(!e)return;let t=document.activeElement,n=t instanceof HTMLElement&&this.body.contains(t)?t.dataset.ticketField:void 0;this.body.replaceChildren(this.sideToggle(e.side),I(this.t(`ticket.type`),H(`type`,R([`market`,`limit`,`stop`].map(e=>({value:e,label:this.t(`ticket.type.${e}`)})),e.type,e=>this.set({type:e},!0)))),I(this.t(`ticket.quantity`),H(`quantity`,this.number(e.quantity,e=>this.set({quantity:e}))))),e.type!==`market`&&this.body.append(I(this.t(`ticket.price`),H(`price`,this.number(e.price,e=>this.set({price:e})))),I(this.t(`ticket.timeInForce`),H(`timeInForce`,R([`gtc`,`day`].map(e=>({value:e,label:this.t(`ticket.tif.${e}`)})),e.timeInForce,e=>this.set({timeInForce:e})))));let r=e.type===`market`?this.lastPrice??e.price:e.price,i=t=>Cn(r*(1+(e.side===`buy`?t:-t)/100),r);this.body.append(this.optionalPrice(`ticket.stopLoss`,e.stopLoss,i(-1),t=>this.set({stopLoss:t},t===null||e.stopLoss===null)),this.optionalPrice(`ticket.takeProfit`,e.takeProfit,i(2),t=>this.set({takeProfit:t},t===null||e.takeProfit===null))),n&&this.body.querySelector(`[data-ticket-field="${n}"]`)?.focus(),this.check()}sideToggle(e){let t=document.createElement(`div`);t.className=`tcw-ticket-side`,t.setAttribute(`role`,`group`);for(let n of[`buy`,`sell`]){let r=document.createElement(`button`);r.type=`button`,r.className=`tcw-ticket-side-btn tcw-ticket-${n}`,r.textContent=this.t(`ticket.${n}`),r.setAttribute(`aria-pressed`,String(e===n)),r.dataset.ticketField=`side-${n}`,r.addEventListener(`click`,()=>this.set({side:n},!0)),t.appendChild(r)}return t}number(e,t){let n=document.createElement(`input`);return n.type=`number`,n.className=`tcw-indi-input`,n.step=`any`,n.min=`0`,n.value=String(e),n.addEventListener(`input`,()=>t(n.value.trim()===``?NaN:Number(n.value))),n}optionalPrice(e,t,n,r){let i=document.createElement(`div`);i.className=`tcw-settings-row tcw-ticket-optional`;let a=document.createElement(`span`);a.textContent=this.t(e);let o=Kt(t!==null,e=>r(e?n:null));if(o.setAttribute(`aria-label`,this.t(e)),o.dataset.ticketField=`${e}-switch`,i.append(a,o),t!==null){let n=this.number(t,e=>r(Number.isFinite(e)?e:NaN));n.setAttribute(`aria-label`,this.t(e)),n.dataset.ticketField=e,i.appendChild(n)}return i}check(){let e=this.draft;if(!e)return;let n=vn(e,this.lastPrice),r=n.map(e=>this.t(`ticket.problem.${e}`)),i=bn(e,this.lastPrice);n.length===0&&i!==null&&r.push(t.r(this.t(`ticket.riskReward`),{rr:i.toFixed(2)})),this.problemsEl.replaceChildren(...r.map(e=>{let t=document.createElement(`p`);return t.textContent=e,t})),this.problemsEl.classList.toggle(`tcw-ticket-bad`,n.length>0),this.submit.disabled=n.length>0,this.submit.classList.toggle(`tcw-ticket-sell`,e.side===`sell`),this.submit.textContent=this.t(e.side===`buy`?`ticket.placeBuy`:`ticket.placeSell`)}};function H(e,t){return t.dataset.ticketField=e,t}function Cn(e,t){let n=Math.abs(t),r=n>=10||n===0?2:n>=1?4:Math.min(10,Math.ceil(-Math.log10(n))+3);return Number(e.toFixed(r))}var wn=0,Tn=class{backdrop;titleEl;input;submit;request=null;returnFocus=null;busy=!1;uid=++wn;constructor(e,n=t.t){this.t=n,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let r=!1;this.backdrop.addEventListener(`pointerdown`,e=>{r=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&r&&this.close(),r=!1});let i=document.createElement(`form`);i.className=`tcw-modal tcw-modal-narrow tcw-name-prompt`,i.noValidate=!0,i.setAttribute(`role`,`dialog`),i.setAttribute(`aria-modal`,`true`),i.setAttribute(`aria-labelledby`,`tcw-name-title-${this.uid}`),i.addEventListener(`keydown`,e=>{if(e.key===`Escape`){e.stopPropagation(),this.close();return}F(e,i)}),i.addEventListener(`submit`,e=>{e.preventDefault(),this.done()});let a=document.createElement(`div`);a.className=`tcw-modal-header`,this.titleEl=document.createElement(`h3`),this.titleEl.id=`tcw-name-title-${this.uid}`;let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-modal-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,16),o.addEventListener(`click`,()=>this.close()),a.append(this.titleEl,o);let s=document.createElement(`div`);s.className=`tcw-modal-body`;let c=document.createElement(`label`);c.className=`tcw-name-field`;let l=document.createElement(`span`);l.textContent=this.t(`layouts.name`),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-indi-input`,this.input.maxLength=80,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.placeholder=this.t(`layouts.namePlaceholder`),this.input.addEventListener(`input`,()=>this.check()),c.append(l,this.input),s.appendChild(c);let u=document.createElement(`div`);u.className=`tcw-modal-footer`;let d=document.createElement(`button`);d.type=`button`,d.className=`tcw-reset-link`,d.textContent=this.t(`common.cancel`),d.addEventListener(`click`,()=>this.close()),this.submit=document.createElement(`button`),this.submit.type=`submit`,this.submit.className=`tcw-done-btn`,u.append(d,this.submit),i.append(a,s,u),this.backdrop.appendChild(i),e.appendChild(this.backdrop)}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.request=e,this.busy=!1,this.titleEl.textContent=e.title,this.submit.textContent=e.submitLabel,this.input.value=e.value??``,this.input.placeholder=e.placeholder??this.t(`layouts.namePlaceholder`),this.check(),this.backdrop.hidden=!1,this.input.focus(),this.input.select()}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.request=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}check(){this.submit.disabled=this.busy||e.r(this.input.value)===null}async done(){let t=this.request,n=e.r(this.input.value);if(!(!t||n===null||this.busy)){this.busy=!0,this.check();try{await t.onSubmit(n),this.request===t&&this.close()}catch{}finally{this.busy=!1,this.check()}}}},En=0,Dn=class{backdrop;search;listEl;layouts=[];confirming=null;returnFocus=null;loadSeq=0;uid=++En;constructor(e,n,r=t.t){this.callbacks=n,this.t=r,this.backdrop=document.createElement(`div`),this.backdrop.className=`tcw-modal-backdrop`,this.backdrop.hidden=!0;let i=!1;this.backdrop.addEventListener(`pointerdown`,e=>{i=e.target===this.backdrop}),this.backdrop.addEventListener(`click`,e=>{e.target===this.backdrop&&i&&this.close(),i=!1});let a=document.createElement(`div`);a.className=`tcw-modal tcw-modal-narrow tcw-layouts-dialog`,a.setAttribute(`role`,`dialog`),a.setAttribute(`aria-modal`,`true`),a.setAttribute(`aria-labelledby`,`tcw-layouts-title-${this.uid}`),a.addEventListener(`keydown`,e=>{if(e.key!==`Escape`){F(e,a);return}e.stopPropagation(),this.confirming?this.setConfirming(null):this.close()});let o=document.createElement(`div`);o.className=`tcw-modal-header`;let s=document.createElement(`h3`);s.id=`tcw-layouts-title-${this.uid}`,s.textContent=this.t(`layouts.dialogTitle`);let c=document.createElement(`button`);c.type=`button`,c.className=`tcw-modal-close`,c.setAttribute(`aria-label`,this.t(`common.close`)),c.innerHTML=S(`x`,16),c.addEventListener(`click`,()=>this.close()),o.append(s,c),this.search=document.createElement(`input`),this.search.type=`search`,this.search.className=`tcw-indi-input tcw-layouts-search`,this.search.placeholder=this.t(`layouts.search`),this.search.setAttribute(`aria-label`,this.t(`layouts.search`)),this.search.addEventListener(`input`,()=>this.render()),this.listEl=document.createElement(`div`),this.listEl.className=`tcw-layouts-list`,this.listEl.setAttribute(`role`,`list`);let l=document.createElement(`div`);l.className=`tcw-modal-body tcw-layouts-body`,l.append(this.search,this.listEl),a.append(o,l),this.backdrop.appendChild(a),e.appendChild(this.backdrop)}async open(){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.search.value=``,this.confirming=null,this.backdrop.hidden=!1,this.search.focus(),await this.refresh()}async refresh(){let e=++this.loadSeq,t;try{t=await this.callbacks.list()}catch{t=[]}e===this.loadSeq&&(this.layouts=t,this.render())}close(){this.backdrop.hidden||(this.backdrop.hidden=!0,this.confirming=null,this.returnFocus?.isConnected&&this.returnFocus.focus(),this.returnFocus=null)}isOpen(){return!this.backdrop.hidden}destroy(){this.close(),this.backdrop.remove()}shown(){let e=this.search.value.trim().toLowerCase();return e?this.layouts.filter(t=>t.name.toLowerCase().includes(e)||(t.symbol??``).toLowerCase().includes(e)):this.layouts}render(){let e=this.shown();if(e.length===0){let e=document.createElement(`p`);e.className=`tcw-account-empty`,e.textContent=this.t(this.layouts.length===0?`layouts.empty`:`layouts.noMatch`),this.listEl.replaceChildren(e);return}let t=this.callbacks.currentId();this.listEl.replaceChildren(...e.map(e=>this.row(e,e.id===t)))}row(e,n){let r=document.createElement(`div`);r.className=`tcw-layouts-row`,r.setAttribute(`role`,`listitem`),r.dataset.id=e.id;let i=document.createElement(`button`);i.type=`button`,i.className=`tcw-layouts-open`,n&&i.setAttribute(`aria-current`,`true`);let a=document.createElement(`span`);a.className=`tcw-layouts-name`,a.textContent=e.name;let o=document.createElement(`span`);if(o.className=`tcw-layouts-meta`,o.textContent=[[e.symbol,e.timeframe].filter(Boolean).join(` · `),t.r(this.t(`layouts.updated`),{time:this.callbacks.formatTime(e.updatedAt)})].filter(Boolean).join(` — `),i.append(a,o),n){let e=document.createElement(`span`);e.className=`tcw-tag`,e.textContent=this.t(`layouts.current`),a.appendChild(e)}i.addEventListener(`click`,()=>{this.callbacks.onOpen(e.id),this.close()});let s=document.createElement(`div`);if(s.className=`tcw-account-actions`,this.confirming===e.id){let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-layouts-confirm`,n.textContent=this.t(`layouts.deleteConfirm`),n.setAttribute(`aria-label`,t.r(this.t(`layouts.deleteNamed`),{name:e.name})),n.addEventListener(`click`,()=>void this.remove(e.id));let r=this.iconButton(`x`,this.t(`common.cancel`),()=>this.setConfirming(null));s.append(n,r)}else s.append(this.iconButton(`penLine`,t.r(this.t(`layouts.renameNamed`),{name:e.name}),()=>this.callbacks.onRename(e)),this.iconButton(`trash`,t.r(this.t(`layouts.deleteNamed`),{name:e.name}),()=>this.setConfirming(e.id),!0));return r.append(i,s),r}iconButton(e,t,n,r=!1){let i=document.createElement(`button`);return i.type=`button`,i.className=`tcw-tree-btn${r?` tcw-tree-del`:``}`,i.setAttribute(`aria-label`,t),i.title=t,i.innerHTML=S(e,14),i.addEventListener(`click`,n),i}setConfirming(e){let t=this.confirming;this.confirming=e,this.render();let n=e??t;n&&[...this.listEl.querySelectorAll(`.tcw-layouts-row`)].find(e=>e.dataset.id===n)?.querySelector(e?`.tcw-layouts-confirm`:`.tcw-tree-del`)?.focus()}async remove(e){try{await this.callbacks.onDelete(e)}finally{this.confirming=null,await this.refresh(),this.isOpen()&&this.search.focus()}}},On=5,kn=class{menu;prompt;dialog;destroyed=!1;constructor(e,t){this.session=e,this.host=t;let{root:n,t:r}=t;this.menu=new z(n,r(`toolbar.layouts`)),this.prompt=new Tn(n,r),this.dialog=new Dn(n,{list:()=>e.list(),currentId:()=>e.current()?.id??null,onOpen:e=>void this.open(e),onRename:e=>this.promptRename(e),onDelete:async t=>{try{await e.remove(t)}catch{this.host.toast(r(`layouts.deleteFailed`),`error`)}},formatTime:t.formatTime},r)}async save(){if(this.prompt.isOpen())return;if(!this.session.current()){this.promptSaveAs();return}let{t:e,toast:n}=this.host;try{let r=await this.session.save();r&&n(t.r(e(`layouts.saved`),{name:r.name}))}catch{n(e(`layouts.saveFailed`),`error`)}}async open(e){try{if(await this.session.open(e))return!0}catch{}return this.destroyed||this.host.toast(this.host.t(`layouts.openFailed`),`error`),!1}promptSaveAs(){let{t:e,toast:n}=this.host,r=this.session.current();this.prompt.open({title:e(`layouts.saveAsTitle`),value:r?t.r(e(`layouts.copyName`),{name:r.name}):``,submitLabel:e(`common.save`),onSubmit:async r=>{try{let i=await this.session.saveAs(r);n(t.r(e(`layouts.saved`),{name:i.name}))}catch(t){throw n(e(`layouts.saveFailed`),`error`),t}}})}promptRename(e=this.session.current()){if(!e)return;let{t,toast:n}=this.host;this.prompt.open({title:t(`layouts.renameTitle`),value:e.name,submitLabel:t(`layouts.renameSubmit`),onSubmit:async r=>{try{await this.session.rename(e.id,r)}catch(e){throw n(t(`layouts.saveFailed`),`error`),e}this.dialog.isOpen()&&this.dialog.refresh()}})}openDialog(){return this.dialog.open()}async openMenu(e){if(this.menu.isOpen()){this.menu.close();return}let{session:t}=this,{t:n,root:r}=this.host,i=[];try{i=(await t.list()).slice(0,On)}catch{}if(this.destroyed)return;let a=t.current(),o=[{id:`save`,label:n(`layouts.save`),icon:`save`},{id:`saveAs`,label:n(`layouts.saveAs`),icon:`plus`}];a&&o.push({id:`rename`,label:n(`layouts.rename`),icon:`penLine`}),o.push({id:`autoSave`,label:n(`layouts.autoSave`),checked:t.isAutoSave()}),i.length>0&&o.push(`separator`,...i.map(e=>({id:`open:${e.id}`,label:e.name,checked:e.id===a?.id}))),o.push(`separator`,{id:`manage`,label:n(`layouts.open`),icon:`folder`});let s=e.getBoundingClientRect(),c=r.getBoundingClientRect();this.menu.open(o,s.left-c.left,s.bottom-c.top+2,e=>{e===`save`?this.save():e===`saveAs`?this.promptSaveAs():e===`rename`?this.promptRename():e===`autoSave`?t.setAutoSave(!t.isAutoSave()):e===`manage`?this.openDialog():e.startsWith(`open:`)&&this.open(e.slice(5))},e)}destroy(){this.destroyed=!0,this.menu.destroy(),this.prompt.destroy(),this.dialog.destroy()}},An=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`,`1w`,`1M`],jn=[`1m`,`5m`,`15m`,`1h`,`4h`,`1d`],Mn=6;function Nn(e){let t=e.slice(-1);return t===`h`||t===`d`||t===`w`?e.slice(0,-1)+t.toUpperCase():e}var Pn=e=>Number.isFinite((0,n.timeframeToMs)(e))||(0,n.tickBarCount)(e)!==null,Fn=(e,t)=>{let r=(0,n.tickBarCount)(e),i=(0,n.tickBarCount)(t);return r!==null||i!==null?r===null?1:i===null?-1:r-i:(0,n.timeframeToMs)(e)-(0,n.timeframeToMs)(t)};function In(e,t){let n=t?.length?t:null,r=e?.length?e:n??An;return[...new Set(r)].filter(e=>Pn(e)&&(!n||n.includes(e))).sort(Fn)}function Ln(e,t,n=!1){if(t?.length)return e.filter(e=>t.includes(e));if(n)return[...e];let r=e.filter(e=>jn.includes(e));return r.length>0?r:e.slice(0,Mn)}var Rn=9999,zn={"":`m`,s:`s`,S:`s`,m:`m`,h:`h`,H:`h`,d:`d`,D:`d`,w:`w`,W:`w`,M:`M`},Bn={s:[`m`,60],m:[`h`,60],h:[`d`,24]};function Vn(e){let t=/^(\d+)([a-zA-Z]?)$/.exec(e.trim());if(!t)return null;if(t[2]===`T`||t[2]===`t`){let e=`${Number(t[1])}T`;return Number(t[1])<=Rn&&(0,n.tickBarCount)(e)!==null?e:null}let r=Number(t[1]),i=zn[t[2]];if(!i||!Number.isSafeInteger(r)||r<1)return null;for(let e=Bn[i];e&&r%e[1]===0;e=Bn[i])r/=e[1],i=e[0];if(r>Rn)return null;let a=`${r}${i}`;return(0,n.isTimeFrame)(a)?a:null}function Hn(e,t,n){let r=n?.length?n:null,i=t.filter(e=>Pn(e)&&(!r||r.includes(e)));return[...new Set([...e,...i])].sort(Fn)}var Un=0,Wn=class{el;input;hint;returnFocus=null;constructor(e,t,n){this.labels=t,this.onApply=n,this.el=document.createElement(`div`),this.el.className=`tcw-interval-input`,this.el.hidden=!0,this.el.setAttribute(`role`,`dialog`),this.el.setAttribute(`aria-label`,t.title),this.input=document.createElement(`input`),this.input.type=`text`,this.input.className=`tcw-interval-field`,this.input.autocomplete=`off`,this.input.spellcheck=!1,this.input.maxLength=6,this.input.setAttribute(`aria-label`,t.title),this.hint=document.createElement(`div`),this.hint.className=`tcw-interval-hint`,this.hint.setAttribute(`role`,`status`),this.hint.id=`tcw-interval-hint-${++Un}`,this.input.setAttribute(`aria-describedby`,this.hint.id),this.el.append(this.input,this.hint),e.appendChild(this.el),this.input.addEventListener(`input`,()=>this.check()),this.input.addEventListener(`keydown`,e=>{e.key===`Enter`?(e.preventDefault(),e.stopPropagation(),this.apply()):e.key===`Escape`&&(e.preventDefault(),e.stopPropagation(),this.close())}),this.input.addEventListener(`blur`,()=>this.close(!1))}open(e){this.isOpen()||(this.returnFocus=document.activeElement instanceof HTMLElement?document.activeElement:null),this.el.hidden=!1,this.input.value=e,this.check(),this.input.focus(),this.input.setSelectionRange(e.length,e.length)}close(e=!0){if(this.el.hidden)return;this.el.hidden=!0;let t=this.returnFocus;this.returnFocus=null,e&&t?.isConnected&&t.focus({preventScroll:!0})}isOpen(){return!this.el.hidden}destroy(){this.el.remove()}check(){let e=Vn(this.input.value)!==null;!e&&this.input.value.trim()!==``?this.input.setAttribute(`aria-invalid`,`true`):this.input.removeAttribute(`aria-invalid`),this.hint.textContent=e||this.input.value.trim()===``?this.labels.hint:this.labels.invalid}apply(){let e=Vn(this.input.value);if(e&&this.onApply(e)){this.close();return}this.input.setAttribute(`aria-invalid`,`true`),this.hint.textContent=this.labels.invalid}},Gn=class{constructor(e=`tcw:indicator-templates`){this.key=e}list(){let e;try{e=JSON.parse(localStorage.getItem(this.key)??`[]`)}catch{return[]}if(!Array.isArray(e))return[];let t=[];for(let n of e){if(typeof n!=`object`||!n)continue;let{name:e,indicators:i}=n;if(typeof e!=`string`||!e.trim()||!Array.isArray(i))continue;let a=r.ChartStateManager.deserialize(JSON.stringify({version:2,indicators:i})).indicators;a.length>0&&t.push({name:e.slice(0,60),indicators:a})}return t.sort((e,t)=>e.name.localeCompare(t.name))}get(e){return this.list().find(t=>t.name===e)??null}save(e,t){let n=e.replace(/\s+/g,` `).trim().slice(0,60);if(!n)throw Error(`A template needs a name`);let r=[...this.list().filter(e=>e.name!==n),{name:n,indicators:[...t]}];localStorage.setItem(this.key,JSON.stringify(r))}remove(e){try{localStorage.setItem(this.key,JSON.stringify(this.list().filter(t=>t.name!==e)))}catch{}}},U=[],W=null;function Kn(e){let t=()=>{W=e};return e.addEventListener(`pointerdown`,t,!0),U.push(e),()=>{e.removeEventListener(`pointerdown`,t,!0);let n=U.indexOf(e);n>=0&&U.splice(n,1),W===e&&(W=null)}}function G(e,t=!1){let n=W?.isConnected?W:null;if(!n){let e=document.activeElement;n=e?U.find(t=>t.contains(e))??null:null}return!n&&!t&&(n=U.find(e=>e.isConnected)??null),n!==null&&e.contains(n)}function K(){let e=document.activeElement;return!!e&&(e.tagName===`INPUT`||e.tagName===`TEXTAREA`||e.tagName===`SELECT`||e.isContentEditable)}var qn=[`regular`,`logarithmic`,`percentage`,`indexedTo100`],Jn=e=>typeof e==`object`&&!!e&&!Array.isArray(e);function Yn(e){let{theme:t,timestamp:n,...r}=e;return r}function Xn(e){return!Jn(e)||e.v!==1||typeof e.symbol!=`string`||!e.symbol||typeof e.timeframe!=`string`||!((0,n.isTimeFrame)(e.timeframe)||(0,n.tickBarCount)(e.timeframe)!==null)?null:{v:1,symbol:e.symbol,timeframe:e.timeframe,scaleMode:qn.find(t=>t===e.scaleMode)??`regular`,invertScale:e.invertScale===!0,chart:Jn(e.chart)?Yn(e.chart):null}}function Zn(e){try{return JSON.parse(e)}catch{return null}}function Qn(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var $n=class{favorites=[];constructor(e=`tcw:draw-favorites`,t=Qn()){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{}}},er=/^(\d{4})-(\d{2})-(\d{2})$/,tr=/^(\d{2}):(\d{2})$/;function nr(e,t,r){let i=er.exec(e),a=t?tr.exec(t):[``,`00`,`00`];if(!i||!a)return null;let[o,s,c,l,u]=[+i[1],+i[2],+i[3],+a[1],+a[2]];if(s<1||s>12||c<1||c>31||l>23||u>59)return null;let d=Date.UTC(o,s-1,c,l,u);return new Date(d).getUTCDate()===c?(0,n.wallToUtc)(d,r):null}function q(e,t){let r=e=>String(e).padStart(2,`0`),i=(0,n.timeParts)(e,t);return{date:`${i.year}-${r(i.month)}-${r(i.day)}`,time:`${r(i.hours)}:${r(i.minutes)}`}}var rr=class{form=null;returnFocus=null;opener=null;onOutside=e=>{let t=e.target;this.form&&!this.form.contains(t)&&!this.opener?.contains(t)&&this.close()};constructor(e,t,n){this.host=e,this.labels=t,this.onSubmit=n}isOpen(){return this.form!==null}open(e,t=null){this.close(),this.opener=t,this.returnFocus=document.activeElement;let n=document.createElement(`form`);n.className=`tcw-goto`,n.setAttribute(`role`,`dialog`),n.setAttribute(`aria-label`,this.labels.title);let r=document.createElement(`div`);r.className=`tcw-goto-title`,r.textContent=this.labels.title;let i=this.field(n,this.labels.date,`date`,e.date);i.required=!0;let a=this.field(n,this.labels.time,`time`,e.time),o=document.createElement(`div`);o.className=`tcw-goto-actions`;let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-btn`,s.textContent=this.labels.cancel,s.addEventListener(`click`,()=>this.close());let c=document.createElement(`button`);c.type=`submit`,c.className=`tcw-btn tcw-goto-submit`,c.textContent=this.labels.submit,o.append(s,c),n.prepend(r),n.append(o),n.addEventListener(`submit`,e=>{if(e.preventDefault(),!i.value)return;let t={date:i.value,time:a.value};this.close(),this.onSubmit(t)}),n.addEventListener(`keydown`,e=>{e.stopPropagation(),e.key===`Escape`&&this.close()}),this.host.appendChild(n),this.form=n,document.addEventListener(`mousedown`,this.onOutside),i.focus()}close(){if(!this.form)return;document.removeEventListener(`mousedown`,this.onOutside),this.form.remove(),this.form=null;let e=this.returnFocus;this.returnFocus=null,e?.isConnected&&e.focus()}destroy(){this.close()}field(e,t,n,r){let i=document.createElement(`label`);i.className=`tcw-goto-field`;let a=document.createElement(`span`);a.textContent=t;let o=document.createElement(`input`);return o.type=n,o.value=r,o.className=`tcw-goto-input`,i.append(a,o),e.appendChild(i),o}},J=8,Y=4,X=3,ir=`[title]:not([title=""]), [data-tip]:not([data-tip=""])`,ar=class{el;target=null;source=null;pressed=null;showTimer=null;watchFrame=0;warmUntil=0;observer;constructor(e){this.root=e,this.el=document.createElement(`div`),this.el.className=`tcw-tooltip`,this.el.setAttribute(`aria-hidden`,`true`),e.appendChild(this.el),e.addEventListener(`pointerover`,this.onOver),e.addEventListener(`pointerout`,this.onOut),e.addEventListener(`pointerdown`,this.onPress,!0),e.addEventListener(`keydown`,this.onPress,!0),e.addEventListener(`focusin`,this.onFocus),e.addEventListener(`focusout`,this.onBlur),e.addEventListener(`wheel`,this.hide,{passive:!0}),this.observer=new MutationObserver(()=>{this.pressed?.hasAttribute(`title`)&&or(this.pressed);let e=this.target;!e||this.source!==`pointer`||!e.hasAttribute(`title`)||(or(e),this.isVisible()&&this.show(e))}),this.observer.observe(e,{subtree:!0,attributes:!0,attributeFilter:[`title`]})}destroy(){this.hide(),this.pressed&&Z(this.pressed),this.observer.disconnect(),this.root.removeEventListener(`pointerover`,this.onOver),this.root.removeEventListener(`pointerout`,this.onOut),this.root.removeEventListener(`pointerdown`,this.onPress,!0),this.root.removeEventListener(`keydown`,this.onPress,!0),this.root.removeEventListener(`focusin`,this.onFocus),this.root.removeEventListener(`focusout`,this.onBlur),this.root.removeEventListener(`wheel`,this.hide),this.el.remove()}onOver=e=>{if(e.pointerType===`touch`)return;let t=this.tipTarget(e.target);!t||t===this.pressed||t===this.target&&this.source===`pointer`||(or(t),this.schedule(t,`pointer`,Date.now()<this.warmUntil||this.isVisible()))};onOut=e=>{let t=e.relatedTarget,n=e=>!!e&&!!t&&e.contains(t);this.pressed&&!n(this.pressed)&&(Z(this.pressed),this.pressed=null),this.source===`pointer`&&!n(this.target)&&this.hide()};onPress=()=>{let e=this.target,t=this.source===`pointer`;this.warmUntil=0,this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.el.classList.remove(`tcw-tooltip--visible`),this.target=null,this.source=null,this.pressed&&this.pressed!==e&&Z(this.pressed),this.pressed=t?e:null};onFocus=e=>{let t=this.tipTarget(e.target);!t||!lr(t)||t===this.pressed||this.schedule(t,`focus`,!0)};onBlur=e=>{if(this.source!==`focus`)return;let t=e.relatedTarget;this.target&&t&&this.target.contains(t)||this.hide()};hide=()=>{this.clearTimer(),cancelAnimationFrame(this.watchFrame),this.isVisible()&&(this.warmUntil=Date.now()+500),this.el.classList.remove(`tcw-tooltip--visible`),this.target&&this.source===`pointer`&&Z(this.target),this.target=null,this.source=null};tipTarget(e){if(!(e instanceof Element))return null;let t=e.closest(ir);return t&&t!==this.el&&this.root.contains(t)?t:null}schedule(e,t,n){let r=this.target;if(this.clearTimer(),cancelAnimationFrame(this.watchFrame),r&&r!==e&&this.source===`pointer`&&Z(r),this.target=e,this.source=t,n){this.show(e);return}this.el.classList.remove(`tcw-tooltip--visible`),this.showTimer=setTimeout(()=>{this.showTimer=null,this.target===e&&this.show(e)},300)}show(e){if(!cr(e)){this.hide();return}this.el.textContent=sr(e),this.place(e),this.el.classList.add(`tcw-tooltip--visible`),this.watch(e)}watch(e){cancelAnimationFrame(this.watchFrame),this.watchFrame=requestAnimationFrame(()=>{this.target===e&&(cr(e)?this.watch(e):this.hide())})}place(e){let t=this.root.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.el.offsetWidth,i=this.el.offsetHeight,a=n.left-t.left,o=n.top-t.top,s=ur(e);s===`bottom`&&o+n.height+J+i>t.height?s=`top`:s===`top`&&o-J-i<0?s=`bottom`:s===`right`&&a+n.width+J+r>t.width&&(s=`left`);let c,l;s===`top`||s===`bottom`?(c=a+n.width/2-r/2,l=s===`bottom`?o+n.height+J:o-J-i):(c=s===`right`?a+n.width+J:a-J-r,l=o+n.height/2-i/2),c=Math.max(Y,Math.min(t.width-r-Y,c)),l=Math.max(Y,Math.min(t.height-i-Y,l)),this.el.style.left=`${Math.round(c)}px`,this.el.style.top=`${Math.round(l)}px`;let u={top:[0,X],bottom:[0,-X],left:[X,0],right:[-X,0]}[s];this.el.style.setProperty(`--tcw-tip-dx`,`${u[0]}px`),this.el.style.setProperty(`--tcw-tip-dy`,`${u[1]}px`),this.el.dataset.side=s}isVisible(){return this.el.classList.contains(`tcw-tooltip--visible`)}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}};function or(e){let t=e.getAttribute(`title`);t!==null&&(e.dataset.tip=t,e.removeAttribute(`title`))}function Z(e){e.dataset.tip!==void 0&&!e.hasAttribute(`title`)&&(e.setAttribute(`title`,e.dataset.tip),delete e.dataset.tip)}function sr(e){return e.dataset.tip??e.getAttribute(`title`)??``}function cr(e){return e.isConnected&&e.getClientRects().length>0&&!e.disabled}function lr(e){try{return e.matches(`:focus-visible`)}catch{return!1}}function ur(e){return e.dataset.tipSide||(e.closest(`.tcw-sidebar`)?`right`:e.closest(`.tcw-statusbar, .tcw-replay-bar`)?`top`:`bottom`)}var dr=2,fr=class{stack;toggle;rows=new Map;panes=new Map;collapsed=!1;toggleKey=``;stackKey=``;constructor(e,t,n){this.host=e,this.callbacks=t,this.labels=n,this.stack=document.createElement(`div`),this.stack.className=`tcw-ind-legend`,this.toggle=document.createElement(`button`),this.toggle.type=`button`,this.toggle.className=`tcw-ind-legend-toggle`,this.toggle.addEventListener(`click`,()=>{this.setCollapsed(!this.collapsed),this.renderToggle(this.overlayCount())}),this.stack.appendChild(this.toggle),e.appendChild(this.stack)}update(e,t,n=[]){this.updatePanes(n);let r=`${Math.round(t.left)},${Math.round(t.top)}`;r!==this.stackKey&&(this.stackKey=r,this.stack.style.left=`${Math.round(t.left)}px`,this.stack.style.top=`${Math.round(t.top)}px`);let i=new Set,a=!1;for(let t of e){i.add(t.instanceId);let e=this.rows.get(t.instanceId)??this.createRow(t.instanceId);this.fill(e,t),t.pane?e.el.parentElement!==this.host&&this.host.appendChild(e.el):e.el.parentElement!==this.stack&&(this.stack.insertBefore(e.el,this.toggle),a=!0),this.place(e,t.pane)}for(let[e,t]of this.rows)i.has(e)||(t.el.remove(),this.rows.delete(e));a&&this.collapsed&&this.setCollapsed(!1),this.renderToggle(e.filter(e=>!e.pane).length)}destroy(){for(let e of this.rows.values())e.el.remove();this.rows.clear();for(let e of this.panes.values())e.el.remove();this.panes.clear(),this.stack.remove()}updatePanes(e){if(!this.callbacks.onPaneAction)return;let t=new Set;for(let n of e){t.add(n.instanceId);let e=this.panes.get(n.instanceId)??this.createPane(n.instanceId),r=`${Math.round(n.x)},${Math.round(n.y)}|${n.label}|${n.collapsed}|${n.maximized}|${n.canMoveUp}|${n.canMoveDown}`;if(r===e.key)continue;e.key=r,e.el.style.left=`${Math.round(n.x)}px`,e.el.style.top=`${Math.round(n.y)}px`;let i=this.labels,a=(t,r,i,a)=>{let o=e.buttons.get(t);!r&&document.activeElement===o&&e.buttons.get(`max`).focus(),o.hidden=!r,o.innerHTML=S(i,12),Q(o,a??t,n.label)};a(`up`,n.canMoveUp&&!n.maximized,`arrowUp`,i.paneUp),a(`down`,n.canMoveDown&&!n.maximized,`arrowDown`,i.paneDown),a(`fold`,!n.maximized,n.collapsed?`chevronDown`:`chevronUp`,n.collapsed?i.paneExpand:i.paneCollapse),a(`max`,!0,n.maximized?`minimize`:`maximize`,n.maximized?i.paneRestore:i.paneMaximize),e.el.dataset.collapsed=String(n.collapsed),e.el.dataset.maximized=String(n.maximized)}for(let[e,n]of this.panes)t.has(e)||(n.el.remove(),this.panes.delete(e))}createPane(e){let t=document.createElement(`div`);t.className=`tcw-pane-controls`,t.dataset.instance=e;let n=new Map,r=e=>e===`up`||e===`down`?e:e===`fold`?t.dataset.collapsed===`true`?`expand`:`collapse`:t.dataset.maximized===`true`?`restore`:`maximize`;for(let i of[`up`,`down`,`fold`,`max`]){let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-pane-btn`,a.dataset.act=i,a.addEventListener(`click`,()=>this.callbacks.onPaneAction?.(e,r(i))),n.set(i,a),t.appendChild(a)}this.host.appendChild(t);let i={el:t,buttons:n,key:``};return this.panes.set(e,i),i}createRow(e){let t=document.createElement(`div`);t.className=`tcw-ind-legend-row`,t.dataset.instance=e;let n=document.createElement(`button`);n.type=`button`,n.className=`tcw-ind-legend-name`,n.addEventListener(`click`,()=>this.callbacks.onSettings(e));let r=document.createElement(`span`);r.className=`tcw-ind-legend-values`;let i=document.createElement(`span`);i.className=`tcw-ind-legend-actions`;let a=(e,t,n)=>{let r=document.createElement(`button`);return r.type=`button`,r.className=`tcw-ind-legend-act`,r.dataset.act=e,r.innerHTML=S(t,13),r.addEventListener(`click`,n),i.appendChild(r),r},o=a(`visible`,`eye`,()=>{this.callbacks.onToggleVisible(e,!u.visible)}),s=a(`settings`,`settings`,()=>this.callbacks.onSettings(e)),c=this.callbacks.onMore?a(`more`,`more`,()=>this.callbacks.onMore?.(e,c)):null,l=a(`remove`,`x`,()=>this.callbacks.onRemove(e));t.append(n,r,i);let u={el:t,name:n,values:r,eye:o,settings:s,more:c,remove:l,visible:!0,valuesKey:``,state:``,placeKey:``};return this.rows.set(e,u),u}fill(e,t){let n=`${t.label}|${t.visible}`;n!==e.state&&(e.state=n,e.visible=t.visible,e.name.textContent=t.label,e.name.title=this.labels.settings,e.el.classList.toggle(`tcw-ind-legend-row--hidden`,!t.visible),e.eye.innerHTML=S(t.visible?`eye`:`eyeOff`,13),Q(e.eye,t.visible?this.labels.hide:this.labels.show,t.label),Q(e.settings,this.labels.settings,t.label),e.more&&(Q(e.more,this.labels.more??`More`,t.label),e.more.setAttribute(`aria-haspopup`,`menu`)),Q(e.remove,this.labels.remove,t.label));let r=t.values.map(e=>`${e.text}${e.color??``}`).join(``);r!==e.valuesKey&&(e.valuesKey=r,e.values.replaceChildren(...t.values.map(e=>{let t=document.createElement(`span`);return t.textContent=e.text,e.color&&(t.style.color=e.color),t})))}place(e,t){let n=t?`${Math.round(t.x)},${Math.round(t.y)},${Math.round(t.width)}`:``;n!==e.placeKey&&(e.placeKey=n,e.el.classList.toggle(`tcw-ind-legend-row--pane`,t!==null),e.el.style.left=t?`${Math.round(t.x)}px`:``,e.el.style.top=t?`${Math.round(t.y)}px`:``,e.el.style.maxWidth=t?`${Math.max(0,Math.round(t.width))}px`:``)}setCollapsed(e){this.collapsed=e,this.stack.classList.toggle(`tcw-ind-legend--collapsed`,e)}overlayCount(){return this.stack.querySelectorAll(`:scope > .tcw-ind-legend-row`).length}renderToggle(e){let t=e>=dr;!t&&this.collapsed&&this.setCollapsed(!1);let n=`${t}|${this.collapsed}|${e}`;if(n===this.toggleKey||(this.toggleKey=n,this.toggle.hidden=!t,!t))return;let r=this.collapsed?this.labels.expand:this.labels.collapse;Q(this.toggle,r,this.collapsed?`(${e})`:void 0),this.toggle.setAttribute(`aria-expanded`,String(!this.collapsed));let i=S(this.collapsed?`chevronDown`:`chevronUp`,12);this.toggle.innerHTML=this.collapsed?`${i}<span>${e}</span>`:i}};function Q(e,t,n){e.title=t,e.setAttribute(`aria-label`,n?`${t} ${n}`:t)}function pr(e,t,n){if(!t)return[];let i=e.plots;if(!i){let e=[];for(let n in t){let r=t[n];typeof r==`number`&&Number.isFinite(r)&&e.push(r)}let r=e.length===1?n[0]??null:null;return e.map(e=>({value:e,color:r}))}let a={colors:[...n],lineWidths:[],opacity:1},o=[];for(let e of i){let i=t[e.key];typeof i!=`number`||!Number.isFinite(i)||o.push({value:i,color:n.length?(0,r.plotColor)(e,a,t):null})}return o}var mr=new Map;function hr(e){let t=mr.get(e);return t||(t=new Intl.NumberFormat(e,{notation:`compact`,maximumFractionDigits:2}),mr.set(e,t)),t}function gr(e,t=`en-US`){return Math.abs(e)>=1e6?hr(t).format(e):(0,n.formatPrice)(e,(0,r.indicatorValuePrecision)(e),t)}var _r=class{el;labelEl;callbacks;visible=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,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 i=document.createElement(`span`);i.className=`tcw-bracket-hint`,i.textContent=this.t(`bracket.hint`),this.el.appendChild(i);let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-bracket-cancel`,a.innerHTML=`${S(`x`,14)}<span>${w(this.t(`common.cancel`))}</span>`,a.addEventListener(`click`,()=>this.callbacks.onCancel());let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-bracket-confirm`,o.innerHTML=`${S(`check`,14)}<span>${w(this.t(`bracket.place`))}</span>`,o.addEventListener(`click`,()=>this.callbacks.onConfirm()),this.el.appendChild(a),this.el.appendChild(o),e.appendChild(this.el)}show(e){this.visible=!0,this.labelEl.textContent=e===`buy`?this.t(`toolbar.longBracket`):this.t(`toolbar.shortBracket`),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()}},vr=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 yr(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 br=class{el;bodyEl;callbacks;open=!1;levels;constructor(e,n,r=12,i=t.t){this.t=i,this.callbacks=n,this.levels=r,this.el=document.createElement(`div`),this.el.className=`tcw-ladder`,this.el.hidden=!0;let a=document.createElement(`div`);a.className=`tcw-ladder-header`;let o=document.createElement(`span`);o.textContent=this.t(`ladder.title`);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-close`,s.setAttribute(`aria-label`,this.t(`common.close`)),s.innerHTML=S(`x`,14),s.addEventListener(`click`,()=>this.close()),a.appendChild(o),a.appendChild(s),this.el.appendChild(a);let c=document.createElement(`div`);c.className=`tcw-ladder-cols`,c.innerHTML=[this.t(`ladder.bid`),this.t(`ladder.price`),this.t(`ladder.ask`)].map(e=>`<span>${w(e)}</span>`).join(``),this.el.appendChild(c),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(yr(e,this.levels))}destroy(){this.el.remove()}renderEmpty(){this.bodyEl.replaceChildren();let e=document.createElement(`div`);e.className=`tcw-ladder-empty`,e.textContent=this.t(`ladder.empty`),this.bodyEl.appendChild(e)}render(e){if(this.bodyEl.replaceChildren(),e.rows.length===0){this.renderEmpty();return}let n=e.maxVolume>0?1/e.maxVolume:0;for(let r of e.rows){let e=r.askVolume>0,i=document.createElement(`div`);i.className=`tcw-ladder-row`;let a=document.createElement(`button`);a.type=`button`,a.className=`tcw-ladder-cell tcw-ladder-bid`,r.bidVolume>0?(a.textContent=xr(r.bidVolume),a.style.setProperty(`--w`,`${(r.bidVolume*n*100).toFixed(1)}%`),a.title=t.r(this.t(`ladder.sellAt`),{price:this.callbacks.formatPrice(r.price)}),a.addEventListener(`click`,()=>this.callbacks.onTrade(`sell`,r.price))):a.disabled=!0;let o=document.createElement(`div`);o.className=`tcw-ladder-price ${e?`tcw-ask`:`tcw-bid`}`,o.textContent=this.callbacks.formatPrice(r.price);let s=document.createElement(`button`);s.type=`button`,s.className=`tcw-ladder-cell tcw-ladder-ask`,r.askVolume>0?(s.textContent=xr(r.askVolume),s.style.setProperty(`--w`,`${(r.askVolume*n*100).toFixed(1)}%`),s.title=t.r(this.t(`ladder.buyAt`),{price:this.callbacks.formatPrice(r.price)}),s.addEventListener(`click`,()=>this.callbacks.onTrade(`buy`,r.price))):s.disabled=!0,i.appendChild(a),i.appendChild(o),i.appendChild(s),this.bodyEl.appendChild(i)}}};function xr(e){return e>=1e3?(e/1e3).toFixed(1)+`k`:e>=1?e.toFixed(2).replace(/\.00$/,``):e.toPrecision(2)}var Sr=class{el;bodyEl;callbacks;open=!1;constructor(e,n,r=t.t){this.t=r,this.callbacks=n,this.el=document.createElement(`div`),this.el.className=`tcw-datawin`,this.el.hidden=!0;let i=document.createElement(`div`);i.className=`tcw-datawin-header`;let a=document.createElement(`span`);a.textContent=this.t(`dataWindow.title`);let o=document.createElement(`button`);o.type=`button`,o.className=`tcw-datawin-close`,o.setAttribute(`aria-label`,this.t(`common.close`)),o.innerHTML=S(`x`,14),o.addEventListener(`click`,()=>this.close()),i.appendChild(a),i.appendChild(o),this.el.appendChild(i),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=this.t(`dataWindow.hover`),this.bodyEl.appendChild(e);return}let t=this.callbacks.formatPrice,n=e.ohlc;this.bodyEl.appendChild(this.row(this.t(`dataWindow.open`),t(n.open))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.high`),t(n.high))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.low`),t(n.low))),this.bodyEl.appendChild(this.row(this.t(`dataWindow.close`),t(n.close)));let r=e.change>0?`up`:e.change<0?`down`:``,i=e.change>0?`+`:``;this.bodyEl.appendChild(this.row(this.t(`dataWindow.change`),`${i}${t(e.change)} (${i}${e.changePct.toFixed(2)}%)`,r)),this.bodyEl.appendChild(this.row(this.t(`dataWindow.volume`),wr(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,Cr(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 Cr(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 wr(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 Tr=globalThis.Buffer;function Er(e){if(Tr)return Tr.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 Dr(e){if(Tr)return Tr.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 Or(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function kr(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function Ar(e){return Or(Er(JSON.stringify(e)))}function jr(e){if(!e)return null;try{let t=Dr(kr(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 Mr=`tcw`;function Nr(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)===Mr)return decodeURIComponent(e.slice(t+1))}return null}function Pr(e,t){let[n]=e.split(`#`);return`${n}#${Mr}=${t}`}var Fr=[[34,16,28,26,!1],[30,14,24,26,!0],[26,18,20,30,!0],[30,10,24,22,!1],[20,16,14,28,!0],[14,18,8,30,!0],[18,10,12,20,!1],[8,18,2,30,!0]],Ir=class{el;label;showTimer=null;phase=`loading`;constructor(e,t){this.loadingText=t,this.el=document.createElement(`div`),this.el.className=`tcw-loading-overlay`,this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`div`);n.className=`tcw-loading-card`;let r=document.createElement(`div`);r.className=`tcw-loading-candles`,r.setAttribute(`aria-hidden`,`true`),Fr.forEach(([e,t,n,i,a],o)=>{let s=document.createElement(`span`);s.className=a?`tcw-loading-candle tcw-loading-candle--up`:`tcw-loading-candle`,s.style.setProperty(`--tcw-body-top`,`${e}px`),s.style.setProperty(`--tcw-body-h`,`${t}px`),s.style.setProperty(`--tcw-wick-top`,`${n}px`),s.style.setProperty(`--tcw-wick-h`,`${i}px`),s.style.setProperty(`--tcw-delay`,`${o*110}ms`),r.appendChild(s)}),n.appendChild(r);let i=document.createElement(`div`);i.className=`tcw-loading-track`,i.setAttribute(`aria-hidden`,`true`),i.appendChild(document.createElement(`span`)),n.appendChild(i),this.label=document.createElement(`div`),this.label.className=`tcw-loading-label`,this.label.textContent=t,n.appendChild(this.label),this.el.appendChild(n),e.appendChild(this.el)}begin(e,t=!1){if(this.phase=`loading`,this.clearTimer(),this.label.textContent=this.loadingText,this.el.classList.remove(`tcw-loading-overlay--error`),this.el.classList.toggle(`tcw-loading-overlay--veil`,e),!e||t||this.isShown()){this.el.classList.remove(`tcw-loading-overlay--hidden`);return}this.showTimer=setTimeout(()=>{this.showTimer=null,this.el.classList.remove(`tcw-loading-overlay--hidden`)},200)}end(){this.phase=`idle`,this.clearTimer(),this.el.classList.add(`tcw-loading-overlay--hidden`)}fail(e){this.phase!==`idle`&&(this.phase=`failed`,this.clearTimer(),this.label.textContent=e,this.el.classList.add(`tcw-loading-overlay--error`),this.el.classList.remove(`tcw-loading-overlay--hidden`))}isActive(){return this.phase!==`idle`}hasFailed(){return this.phase===`failed`}isShown(){return!this.el.classList.contains(`tcw-loading-overlay--hidden`)}destroy(){this.clearTimer(),this.el.remove()}clearTimer(){this.showTimer!==null&&(clearTimeout(this.showTimer),this.showTimer=null)}},Lr=4e3,Rr=class{el;text;hideTimer=null;constructor(e,t){this.texts=t,this.el=document.createElement(`div`),this.el.className=`tcw-history-pill tcw-history-pill--hidden`,this.el.setAttribute(`aria-hidden`,`true`),this.el.setAttribute(`role`,`status`),this.el.setAttribute(`aria-live`,`polite`);let n=document.createElement(`span`);n.className=`tcw-history-spinner`,n.setAttribute(`aria-hidden`,`true`),this.text=document.createElement(`span`),this.el.append(n,this.text),e.appendChild(this.el)}update(e){this.clearTimer(),e.state===`loading`?this.show(this.texts.loading,!1):e.state===`error`?(this.show(this.texts.failed,!0),this.hideTimer=setTimeout(()=>this.hide(),Lr)):this.hide()}destroy(){this.clearTimer(),this.el.remove()}show(e,t){this.text.textContent=e,this.el.classList.toggle(`tcw-history-pill--error`,t),this.el.classList.remove(`tcw-history-pill--hidden`),this.el.removeAttribute(`aria-hidden`)}hide(){this.hideTimer=null,this.el.classList.add(`tcw-history-pill--hidden`),this.el.setAttribute(`aria-hidden`,`true`),this.text.textContent=``}clearTimer(){this.hideTimer!==null&&clearTimeout(this.hideTimer),this.hideTimer=null}},zr=48,Br=5e4,Vr=100;function Hr(){return new Promise(e=>{if(typeof requestAnimationFrame!=`function`||document.hidden){setTimeout(e,0);return}let t=setTimeout(e,Vr);requestAnimationFrame(()=>setTimeout(()=>{clearTimeout(t),e()},0))})}var Ur=[`#4c8dff`,`#a57cff`,`#1398a8`,`#e25592`,`#8a93a3`,`#62c895`],Wr=4,Gr=7,Kr=17,qr=3,Jr=[`1m`,`3m`,`5m`,`15m`,`30m`,`1h`,`2h`,`4h`,`1d`],Yr=5e3,Xr=()=>{let e=document.activeElement;return e instanceof Element&&e.closest(`[role="dialog"], [aria-modal="true"], [role="menu"]`)!==null},Zr={KeyT:`trendLine`,KeyH:`horizontalLine`,KeyJ:`horizontalRay`,KeyV:`verticalLine`,KeyC:`crossLine`,KeyF:`fibRetracement`},Qr=e=>(e[e.length-1]?.time??0)>0xe8d4a51000?1:1e3,$r=class{chart;state;toolbar=null;sidebar=null;settings=null;statusBar=null;goToDate=null;tooltip;indicatorLegend=null;legendFrame=0;portal=document.createElement(`div`);overlayHost=()=>{let e=document.fullscreenElement===this.root?this.root:document.body;return this.portal.parentElement!==e&&e.appendChild(this.portal),this.portal};unregisterKeys=()=>{};onFullscreenChange=()=>{this.toolbar?.setFullscreen(document.fullscreenElement===this.root),this.portal.isConnected&&this.overlayHost()};commandPalette=null;symbolSearch=null;hotkeySheet=null;replayBar=null;dragDrop=null;alertsPanel=null;objectTree=null;indicatorSettings=null;drawingStyle=null;drawingSettings=null;drawingMenu=null;chartMenu=null;menuPane=null;canExport=!0;symbolLoads=new Map;ui;legendMenu=null;templates=new Gn;templatePrompt=null;intervalInput=null;markerTip=null;accountPanel=null;orderTicket=null;accountFrame=0;layoutSession=null;layoutsUI=null;bracketBar=null;alertNotifier=null;depthLadder=null;dataWindow=null;lastHoverIndex=null;legendHoverIndex=null;favoritesStore=new $n;timeframeFavorites=new $n(`tcw:tf-favorites`);customTimeframes=new $n(`tcw:tf-custom`);timeframes=[];watchlist=null;watchlistSparkBuffer=new Map;sessionRefPrice=null;hostWatchlistRefPrice=new Map;watchlistInterval=null;watchlistStore=null;watchlistFromSymbols=!1;quoteSource=null;stopQuotes=null;quotedKey=``;quotes=new Map;symbolInfoPanel=null;newsRequest=0;newsCache=new Map;marketTimer=null;chartNav=null;visibleBarCount=50;replayPollInterval=null;replaySpeed=5;replayStep=`bar`;replayStartSeq=0;replayStepsCache=null;replayShade=null;layoutKeyPrefix=null;layoutDebounceMs=1500;activeLayoutKey=null;root;chartContainer;loading;historyPill;connectSeq=0;localSeq=0;lastLocalSwitchMs=0;destroyed=!1;options;symbols;settingsState;settingsDefaults;t;adapter=null;boundGlobalKeydown=null;baseSeries=null;baseTimeframeMs=0;compares=[];constructor(i,a={}){this.options=a,this.symbols=a.symbols??te;let o=a.chartOptions;if(this.settingsState={...ne,...o?.numberLocale?{numberLocale:o.numberLocale}:{},...o?.timeZone==null?{}:{timezone:c(o.timeZone)},...o?.leftPriceScale===void 0?{}:{leftPriceScale:o.leftPriceScale},...o?.highLowLines===void 0?{}:{highLowLines:o.highLowLines},...o?.extendedHours===void 0?{}:{extendedHours:o.extendedHours},...o?.chartTypeOptions?{chartTypeOptions:(0,n.readChartTypeOptions)(o.chartTypeOptions)}:{}},this.t=t.n(t.o(a.locale,a.messages)),a.persistLayouts){let e=a.persistLayouts===!0?{}:a.persistLayouts;this.layoutKeyPrefix=e.keyPrefix??`tcw:layout:`,this.layoutDebounceMs=e.debounceMs??1500}let s=this.resolveIsDark(a.theme),l=this.resolveTheme(a.theme),p={drawings:!0,drawingMagnet:!0,drawingUndoRedo:!0,indicators:!0,trading:a.trading!==!1,tradingContextMenu:!1,priceAxisAddButton:a.alerts!==!1||a.trading!==!1||a.drawingTools!==!1,volume:!0,legend:!0,crosshair:!0,crosshairTooltip:!1,keyboard:!0,screenshot:!0,alerts:!0,barCountdown:!0,logScale:!0,watermark:!0,...a.chartOptions?.features};if(this.canExport=p.dataExport!==!1,this.settingsDefaults={...this.settingsState,legendVisible:p.legend!==!1,barCountdown:p.barCountdown!==!1,indicatorValueLabels:p.indicatorValueLabels!==!1},this.settingsState={...this.settingsDefaults},this.timeframes=Hn(In(a.timeframes,p.timeframes),this.customTimeframes.list(),p.timeframes),!this.timeframes.some(e=>this.timeframeFavorites.has(e))){let e=Ln(this.timeframes,p.defaultTimeframeFavorites,!!a.timeframes?.length);for(let t of e)this.timeframeFavorites.add(t)}let m=a.timeframe??`5m`,h=!p.timeframes?.length||p.timeframes.includes(m)?m:this.timeframes[0]??m;this.state={symbol:a.symbol??this.symbols[0]??`BTCUSDT`,timeframe:h,chartType:a.chartOptions?.chartType??`candlestick`,isDark:s,activeIndicators:new Map,activeTool:null,magnetEnabled:p.drawingMagnet!==!1,magnetStrong:!1,eraser:!1,zoomArea:!1,stayInDrawing:!1,connectionState:a.adapter?`connecting`:`disconnected`,connectionMessage:a.adapter?this.t(`status.connecting`):``},g(),this.root=document.createElement(`div`),this.root.className=`tcw-root`,this.root.dataset.tcwTheme=s?`dark`:`light`;let _=a.dir===`ltr`||a.dir===`rtl`?a.dir:li(a.locale)?`rtl`:`ltr`;this.root.dir=_,this.portal.dir=_,i.appendChild(this.root),this.tooltip=new ar(this.root),this.portal.className=`tcw-root tcw-portal`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.ui=N(a.ui);let v=a.ui!==void 0;P(this.root,this.ui,{variables:v}),P(this.portal,this.ui,{variables:v}),a.toolbar!==!1&&(this.toolbar=new ve(this.root,{symbols:this.symbols,timeframes:this.timeframeMenu(),timeframeFavorites:this.pinnedTimeframes(),chartTypes:a.chartTypes?u.filter(e=>a.chartTypes.includes(e.value)):u,indicators:ee,popularIndicatorIds:f},{onSymbolClick:()=>this.handleSymbolClick(),onSymbolInfo:a.symbolInfo===!1?void 0:()=>this.toggleSymbolInfo(),onTimeframe:e=>this.handleTimeframe(e),onToggleTimeframeFavorite:e=>this.handleToggleTimeframeFavorite(e),onAddTimeframe:a.customTimeframes===!1?void 0:e=>this.handleAddTimeframe(e),onRemoveTimeframe:e=>this.handleRemoveTimeframe(e),onChartType:e=>this.handleChartType(e),onAddIndicator:e=>this.handleAddIndicator(e),onScreenshot:()=>this.chart.screenshot(),onSettings:()=>this.openSettings(),onToggleTheme:()=>this.handleToggleTheme(),onToggleReplay:()=>this.toggleReplay(),onToggleAlerts:a.alerts===!1?void 0:()=>this.toggleAlerts(),onToggleObjects:a.objectTree===!1?void 0:()=>this.toggleObjects(),onToggleAccount:a.trading!==!1&&a.accountPanel!==!1?()=>this.accountPanel?.toggle():void 0,onLayouts:a.layouts===!1?void 0:e=>void this.layoutsUI?.openMenu(e),...a.indicatorTemplates===!1?{}:{onApplyIndicatorTemplate:e=>this.applyIndicatorTemplate(e),onSaveIndicatorTemplate:()=>this.promptSaveIndicatorTemplate(),onDeleteIndicatorTemplate:e=>{this.templates.remove(e),this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name),!0)}},onBracket:a.trading===!1?void 0:e=>this.startBracket(e),onToggleLadder:a.trading!==!1&&a.depthLadder?()=>this.depthLadder?.toggle():void 0,onToggleFullscreen:a.fullscreen!==!1&&typeof document<`u`&&document.fullscreenEnabled?()=>this.toggleFullscreen():void 0},this.t));let y=document.createElement(`div`);y.className=`tcw-body`,a.drawingTools!==!1&&(a.drawingFavorites&&this.favoritesStore.seedDefaults(a.drawingFavorites),this.sidebar=new Se(y,{drawingToolGroups:he(d,this.t),favorites:this.favoritesStore.list()},{onDrawingTool:e=>this.handleDrawingTool(e),onCancelDrawing:()=>this.handleCancelDrawing(),onToggleMagnet:p.drawingMagnet===!1?void 0:()=>this.handleToggleMagnet(),onToggleEraser:()=>this.chart.setEraserMode(!this.chart.isEraserMode()),onToggleZoomArea:()=>this.chart.setZoomAreaMode(!this.chart.isZoomAreaMode()),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(),onToggleStayInDrawing:()=>this.handleToggleStayInDrawing()},this.t)),this.chartContainer=document.createElement(`div`),this.chartContainer.className=`tcw-chart-container`,this.chartContainer.dir=`ltr`,y.appendChild(this.chartContainer),this.loading=new Ir(this.chartContainer,this.t(`status.loading`)),this.historyPill=new Rr(this.chartContainer,{loading:this.t(`history.loading`),failed:this.t(`history.failed`)}),a.watchlist&&this.createWatchlist(y,a.watchlist===!0?{}:a.watchlist),this.root.appendChild(y);let b=document.createElement(`div`);if(b.className=`tcw-account-dock`,this.root.appendChild(b),this.chart=new e.c(this.chartContainer,{chartType:this.state.chartType,theme:l,autoScale:!0,crosshair:{mode:`magnet`},a11y:{labels:{role:this.t(`a11y.role`),summary:this.t(`a11y.summary`),empty:this.t(`a11y.empty`),view:this.t(`a11y.view`),bar:this.t(`a11y.bar`),keys:this.t(`a11y.keys`),typeName:e=>{let t=`chartType.${e}`,n=this.t(t);return n===t?e:n}}},...a.chartOptions,features:p}),a.chartOptions?.shapes||this.applyChartShapes(),this.chart.on(`visibleRangeChange`,e=>{let{from:t,to:n}=e.payload;Number.isFinite(t)&&Number.isFinite(n)&&(this.visibleBarCount=Math.max(1,n-t))}),a.navigation!==!1&&(this.chartNav=new it(this.chartContainer,{zoomIn:()=>this.chart.zoomIn(),zoomOut:()=>this.chart.zoomOut(),scroll:e=>this.chart.scrollBars(e*Math.max(1,Math.round(this.visibleBarCount/10))),reset:()=>{this.chart.fitContent(),this.changeSettings({autoScale:!0})},plotRect:()=>this.chart.getPlotRect()},this.t)),this.chart.on(`dataUpdate`,e=>this.handleDataUpdate(e.payload)),this.chart.on(`historyLoad`,e=>this.historyPill.update(e.payload)),this.chart.on(`symbolInfoChange`,e=>{let t=e.payload.info,n=t?[t.description,t.exchange].filter(Boolean).join(` · `):``;this.toolbar?.setSymbolDescription(n||null),this.refreshMarket()}),a.symbolInfo!==!1&&(this.symbolInfoPanel=new tt(this.root,this.t,{onToggle:e=>{this.toolbar?.setActive(`symbolInfo`,e),e&&(this.refreshSymbolInfo(),this.loadNews())}})),this.marketTimer=setInterval(()=>this.refreshMarket(),3e4),a.dragDropImport!==!1&&(this.dragDrop=new e.o(this.chartContainer,{onData:(e,n,r)=>{this.setData(e);let i=t.r(this.t(`toast.fileLoaded`),{count:n.data.length,file:r.name});this.toast(n.skipped>0?`${i} (${t.r(this.t(`toast.fileSkipped`),{count:n.skipped})})`:i)},onError:(e,t)=>{this.toast(`${t.name}: ${e.message}`,`error`)}}),this.dragDrop.attach()),a.statusBar!==!1){let e=a.rangeBar!==!1;this.statusBar=new Ee(this.root,e?{presets:r.RANGE_PRESETS,presetLabels:{All:this.t(`range.all`)},groupLabel:this.t(`range.presets`),goToLabel:this.t(`range.goTo`),onPreset:e=>this.chart.setVisibleRangePreset(e),onGoTo:()=>this.toggleGoToDate()}:void 0),e&&(this.goToDate=new rr(this.root,{title:this.t(`range.goTo`),date:this.t(`range.date`),time:this.t(`range.time`),submit:this.t(`range.goToSubmit`),cancel:this.t(`range.cancel`)},({date:e,time:t})=>this.goToWallTime(e,t)))}if(a.settings!==!1&&(this.settings=new we({onChange:e=>this.changeSettings(e),onReset:()=>this.resetSettings(),onClose:()=>{}},this.t,{barCountdown:p.barCountdown,logScale:p.logScale,exchangeZone:this.adapter?.resolveSymbol?()=>this.chart.getSymbolInfo()?.timezone??null:void 0},this.overlayHost)),this.symbolSearch=new Oe({onPick:e=>{this.setSymbol(e)},onClose:()=>{}},this.overlayHost,this.t),this.hotkeySheet=new Pe({onClose:()=>{}},this.t,this.overlayHost),this.chart.on(`drawingToolChange`,e=>{let t=e.payload.tool;t!==this.state.activeTool&&(this.state={...this.state,activeTool:t},this.updateUI())}),this.chart.on(`toolModeChange`,e=>{let{eraser:t,zoomArea:n}=e.payload;this.state={...this.state,eraser:t??this.state.eraser,zoomArea:n??this.state.zoomArea},this.updateUI()}),this.chart.on(`indicatorAdd`,()=>this.syncIndicatorsFromChart()),this.chart.on(`indicatorRemove`,()=>this.syncIndicatorsFromChart()),a.indicatorLegend!==!1){this.chart.setPaneTitlesVisible(!1),this.indicatorLegend=new fr(this.chartContainer,{onToggleVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.scheduleLegend(),this.objectTree?.isOpen()&&this.refreshObjects()},onSettings:e=>this.openIndicatorSettings(e),onRemove:e=>this.handleRemoveIndicator(e),onMore:(e,t)=>this.openLegendMenu(e,t),onPaneAction:(e,t)=>this.runPaneAction(e,t)},{show:this.t(`legend.show`),hide:this.t(`legend.hide`),settings:this.t(`legend.settings`),remove:this.t(`legend.remove`),collapse:this.t(`legend.collapse`),expand:this.t(`legend.expand`),more:this.t(`legend.more`),paneUp:this.t(`pane.moveUp`),paneDown:this.t(`pane.moveDown`),paneCollapse:this.t(`pane.collapse`),paneExpand:this.t(`pane.expand`),paneMaximize:this.t(`pane.maximize`),paneRestore:this.t(`pane.restore`)}),this.legendMenu=new z(this.root,this.t(`legend.more`)),this.chart.on(`crosshairMove`,e=>{let t=e.payload;this.legendHoverIndex=typeof t.barIndex==`number`?t.barIndex:null,this.scheduleLegend()}),this.chart.on(`crosshairLeave`,()=>{this.legendHoverIndex=null,this.scheduleLegend()});for(let e of[`indicatorUpdate`,`indicatorChange`,`dataUpdate`,`resize`,`paneResize`,`paneChange`,`themeChange`])this.chart.on(e,()=>this.scheduleLegend())}if(this.chart.on(`barClick`,e=>{if(!this.replayBar?.isMounted())return;let t=e.payload.barIndex;if(typeof t==`number`){if(this.replayBar.getMode()===`select`){this.startReplayAt(t);return}this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeekToBar(t),this.replayBar.setState(`paused`)}}),this.chart.on(`crosshairMove`,e=>{if(this.replayBar?.getMode()!==`select`||!this.replayBar.isMounted())return;let t=e.payload.point;this.positionReplayShade(t?.x??null)}),this.dataWindow=new Sr(this.root,{formatPrice:e=>this.formatAlertPrice(e)},this.t),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())}),a.drawingTools!==!1){let e=new Bt,n=new Vt;for(let[e,t]of Object.entries(n.all()))this.chart.setDrawingToolDefaults(e,t??null);this.drawingSettings=new rn(this.root,{onBegin:e=>this.chart.beginDrawingEdit(e),onChange:(e,t)=>this.chart.updateDrawing(e,t),onEnd:(e,t)=>{this.chart.endDrawingEdit(e,{cancel:t}),this.refreshObjects()},toWallTime:e=>q(e*Qr(this.chart.getData()),this.displayTimezone()),fromWallTime:(e,t)=>{let n=nr(e,t,this.displayTimezone());return n===null?null:n/Qr(this.chart.getData())},onAddAlert:e=>this.addDrawingAlert(e),onSaveDefault:(e,r)=>{this.chart.setDrawingToolDefaults(e,r),n.set(e,this.chart.getDrawingToolDefaults(e)),this.toast(t.r(this.t(`drawingSettings.defaultSaved`),{name:this.drawingToolName(e)}))},templates:e},this.t),this.chart.on(`drawingDoubleClick`,e=>this.openDrawingSettings(e.payload.id)),this.drawingStyle=new Gt(this.root,{onStyleChange:e=>{this.chart.setDrawingStyle(e),this.chart.setSelectedDrawingStyle(e)},getStyle:()=>this.chart.getDrawingStyle()},e,this.t)}if(this.drawingMenu=new z(this.root,this.t(`drawingMenu.label`)),this.chart.on(`drawingContextMenu`,e=>{let{id:t,x:n,y:r}=e.payload;this.openDrawingMenu(t,n,r)}),this.chartMenu=new z(this.root,this.t(`chartMenu.label`)),this.chart.on(`symbolSeriesRequest`,e=>void this.loadSymbolSeries(e.payload.symbol)),this.chart.on(`chartContextMenu`,e=>{let{area:t,x:n,y:r,price:i,time:a,pane:o}=e.payload,s=i===void 0?void 0:this.chart.roundPrice(i),c={...this.chartMenuContext(s),...o?{pane:this.chart.getPaneScale(o)}:{}};this.menuPane=o??null,this.openChartMenu(ln(t,c,this.t),n,r,{area:t,price:s,time:a})}),this.chart.on(`priceAxisAdd`,e=>{let{price:t,x:n,y:r}=e.payload,i=this.chart.roundPrice(t);this.openChartMenu(cn(this.chartMenuContext(i),this.t),n,r,{area:`priceAxisAdd`,price:i})}),this.chart.on(`signalMarkerHover`,e=>this.showMarkerTip(e.payload)),a.intervalTyping!==!1&&(this.intervalInput=new Wn(this.chartContainer,{title:this.t(`interval.title`),hint:this.t(`interval.hint`),invalid:this.t(`interval.invalid`)},e=>this.selectTypedTimeframe(e))),a.indicatorTemplates!==!1&&this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name)),a.layouts!==!1&&this.setupLayouts(a.layouts===!0||a.layouts===void 0?{}:a.layouts),a.trading!==!1&&a.accountPanel!==!1){this.orderTicket=new Sn(this.root,{onSubmit:e=>{this.chart.placeOrderIntent(e),this.toast(t.r(this.t(`ticket.sent`),{side:this.t(e.side===`buy`?`ticket.buy`:`ticket.sell`),quantity:e.quantity??1,price:this.formatAlertPrice(e.price)}))},formatPrice:e=>this.formatAlertPrice(e)},this.t),this.accountPanel=new gn(b,{onClosePosition:e=>this.chart.closePositionIntent(e),onReversePosition:e=>this.chart.reversePositionIntent(e),onCancelOrder:e=>this.chart.cancelOrderIntent(e),onNewOrder:()=>this.openOrderTicket(),formatPrice:e=>this.formatAlertPrice(e),formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`},onToggle:e=>{this.toolbar?.setActive(`account`,e),this.refreshAccount()}},this.t);for(let e of[`ordersChange`,`positionsChange`,`executionFill`,`dataUpdate`,`indicatorUpdate`])this.chart.on(e,()=>this.refreshAccountSoon())}if(a.trading!==!1&&(this.bracketBar=new _r(this.root,{onConfirm:()=>this.chart.confirmBracket(),onCancel:()=>{this.chart.cancelBracket(),this.bracketBar?.hide()}},this.t),this.chart.on(`bracketPlace`,e=>{let n=e.payload;this.bracketBar?.hide(),this.toast(t.r(this.t(n.side===`buy`?`bracket.longPlaced`:`bracket.shortPlaced`),{rr:n.riskReward.toFixed(2)}))}),a.depthLadder&&(this.depthLadder=new br(this.root,{onTrade:(e,n)=>{this.chart.placeOrderIntent({side:e,type:`limit`,price:n}),this.toast(t.r(this.t(e===`buy`?`order.buyLimit`:`order.sellLimit`),{price:this.formatAlertPrice(n)}))},formatPrice:e=>this.formatAlertPrice(e)},void 0,this.t)),this.chart.on(`dataUpdate`,e=>{let t=e.payload;t&&t.bracket===`cancelled`&&this.bracketBar?.hide()})),a.alerts!==!1&&(this.alertsPanel=new ft(this.root,{onAdd:({price:e,condition:t,message:n,channel:r,label:i,options:a})=>{try{return this.chart.addAlert(e,t,n,r,i,a),!0}catch{return this.toast(this.t(`alerts.invalid`),`error`),!1}},formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`},onRemove:e=>this.chart.removeAlert(e),onClear:()=>this.chart.clearAlerts(),getChannelValue:e=>this.getAlertChannelValue(e),formatPrice:e=>this.formatAlertPrice(e)},this.t),this.chart.on(`alertAdd`,()=>this.refreshAlerts()),this.chart.on(`alertRemove`,()=>this.refreshAlerts()),this.chart.on(`alertUpdate`,()=>this.refreshAlerts()),this.chart.on(`alertExpired`,e=>{let n=e.payload;this.toast(t.r(this.t(`alerts.expiredToast`),{text:n.message??this.alertText(n)})),this.refreshAlerts()}),a.alertNotifications&&(this.alertNotifier=new vr(a.alertNotifications)),this.chart.on(`alertTriggered`,e=>{let n=e.payload,r=`${this.alertText(n)}${n.message?` — ${n.message}`:``}`;this.toast(`🔔 ${t.r(this.t(`alerts.fired`),{text:r})}`,`info`),this.alertNotifier?.notify(r),this.refreshAlerts()})),a.objectTree!==!1){this.indicatorSettings=new Pt(this.root,{onApply:(e,t)=>{this.chart.updateIndicator(e,t),this.syncIndicatorsFromChart()},onStyle:(e,t)=>this.chart.updateIndicatorStyle(e,t),onLevels:(e,t)=>this.chart.setIndicatorLevels(e,t),onScale:(e,t)=>this.chart.setIndicatorScale(e,t),onClose:()=>{}},this.t),this.objectTree=new Et(this.root,{onRemoveIndicator:e=>this.handleRemoveIndicator(e),onConfigureIndicator:e=>this.openIndicatorSettings(e),onToggleIndicatorVisible:(e,t)=>{this.chart.setIndicatorVisible(e,t),this.refreshObjects(),this.scheduleLegend()},onRemoveDrawing:e=>{this.drawingSettings?.editing()===e&&this.drawingSettings.close(!0),this.chart.removeDrawing(e),this.refreshObjects()},onConfigureDrawing:this.drawingSettings?e=>this.openDrawingSettings(e):void 0,onToggleDrawingVisible:(e,t)=>{this.chart.setDrawingVisible(e,t),this.refreshObjects()},onToggleDrawingLocked:(e,t)=>{this.chart.setDrawingLocked(e,t),this.refreshObjects()},onToggleGroupVisible:(e,t)=>{this.chart.setDrawingGroupVisible(e,t),this.refreshObjects()},onToggleGroupLocked:(e,t)=>{this.chart.setDrawingGroupLocked(e,t),this.refreshObjects()},onUngroup:e=>{this.chart.ungroupDrawings(e),this.refreshObjects()},onRenameGroup:(e,t)=>{this.chart.renameDrawingGroup(e,t),this.refreshObjects()},onAddCompare:p.compareSymbols===!1?void 0:()=>this.handleAddCompare(),onRemoveCompare:e=>this.handleRemoveCompare(e)},this.t);let e=()=>{this.objectTree?.isOpen()&&this.refreshObjects()},t=0;this.chart.on(`drawingCreate`,e),this.chart.on(`drawingRemove`,e),this.chart.on(`drawingUpdate`,()=>{t||!this.objectTree?.isOpen()||(t=requestAnimationFrame(()=>{t=0,this.destroyed||e()}))}),this.chart.on(`indicatorAdd`,e),this.chart.on(`indicatorRemove`,e),this.chart.on(`indicatorChange`,e)}if(this.commandPalette=new De({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.overlayHost,this.t),this.boundGlobalKeydown=e=>{if(this.replayBar?.isMounted()&&this.handleReplayKey(e))return;let t=G(this.root);if((e.ctrlKey||e.metaKey)&&e.key===`k`){if(!t)return;e.preventDefault(),this.toggleCommandPalette()}else if((e.ctrlKey||e.metaKey)&&(e.key===`p`||e.key===`P`)){if(!t)return;e.preventDefault(),this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}else if((e.ctrlKey||e.metaKey)&&!e.altKey&&!e.shiftKey&&(e.key===`s`||e.key===`S`)){if(!this.layoutSession||K()||!G(this.root,!0))return;e.preventDefault(),this.saveLayout()}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&!e.shiftKey&&Zr[e.code]){if(e.defaultPrevented||K()||!t||Xr()||this.options.drawingTools===!1)return;e.preventDefault(),this.handleDrawingTool(Zr[e.code])}else if(/^[0-9]$/.test(e.key)&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(e.defaultPrevented||!this.intervalInput||K()||Xr()||!G(this.root,!0))return;let t=document.activeElement;if(t&&t!==document.body&&!this.root.contains(t))return;e.preventDefault(),this.intervalInput.open(e.key)}else if(e.altKey&&!e.ctrlKey&&!e.metaKey&&(e.code===`KeyI`||e.code===`KeyG`)){if(K()||!t)return;e.code===`KeyI`?(e.preventDefault(),this.changeSettings({invertScale:!this.settingsState.invertScale})):this.goToDate&&(e.preventDefault(),this.toggleGoToDate())}else if(e.key===`?`&&!e.ctrlKey&&!e.metaKey&&!e.altKey){if(K()||!t)return;e.preventDefault(),this.hotkeySheet?.open()}},document.addEventListener(`keydown`,this.boundGlobalKeydown),document.addEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys=Kn(this.root),a.adapter&&(this.adapter=a.adapter,this.connectStream()),this.watchlist&&(this.watchlistInterval=setInterval(()=>this.tickWatchlist(),1e3)),this.refreshMarket(),this.updateUI(),a.onReady?.(this.chart),a.shareUrl&&typeof location<`u`){let e=Nr(location.hash);e&&this.importState(e)}}setSymbols(e){this.symbols=e;let t=this.watchlistStore;t&&this.watchlistFromSymbols&&t.replace(t.getLists().map(t=>t.id===`default`?{...t,symbols:e}:t))}getWatchlists(){return this.watchlistStore?.getLists()??[]}getActiveWatchlist(){return this.watchlistStore?.getActive().id??null}setWatchlists(e,t){this.watchlistFromSymbols=!1,this.watchlistStore?.replace(e,t)}setActiveWatchlist(e){this.watchlistStore?.setActive(e)}addToWatchlist(e,t){this.watchlistStore?.add(e,t)}removeFromWatchlist(e,t){this.watchlistStore?.removeSymbol(e,t)}setQuotes(e){let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)}getQuote(e){let t=this.quotes.get(e);return t?{...t}:null}toggleSymbolInfo(e){let t=this.symbolInfoPanel;t&&(e===void 0?t.toggle():e?t.open():t.close())}refreshMarket(){let e=(0,n.marketStatus)(this.chart.getSymbolInfo(),Date.now());this.statusBar?.setMarket(e.state,this.t(e.state===`open`?`symbolInfo.open`:`symbolInfo.closed`)),this.refreshSymbolInfo()}refreshSymbolInfo(){let e=this.symbolInfoPanel;!e?.isOpen()||this.destroyed||e.render(this.symbolInfoView())}symbolInfoView(){let e=this.chart.getSymbolInfo(),r=this.state.symbol,i=this.quotes.get(r),a=ai(this.chart.getData(),e?.timezone),o=e=>this.formatAlertPrice(e),s=this.textLocale(),c=i?.last??a?.close,l=i?.prevClose??a?.prevClose,u=i?.change??(c!==void 0&&l!==void 0?c-l:void 0),d=c!==void 0&&u!==void 0?c-u:void 0,ee=i?.changePercent??(u!==void 0&&d?u/d*100:void 0),f=(0,n.marketStatus)(e,Date.now()),te=this.t(f.state===`open`?`symbolInfo.open`:f.state===`closed`?`symbolInfo.closed`:`symbolInfo.always`);if(f.state!==`always`&&f.next!==null){let e=oi(f.next-Date.now(),s);te+=` · ${t.r(this.t(f.state===`open`?`symbolInfo.closesIn`:`symbolInfo.opensIn`),{when:e})}`}let ne=[],p=(e,t)=>{t&&ne.push({label:e,value:t})},m=e=>e===void 0?void 0:o(e);p(this.t(`dataWindow.open`),m(i?.open??a?.open)),p(this.t(`dataWindow.high`),m(i?.high??a?.high)),p(this.t(`dataWindow.low`),m(i?.low??a?.low)),p(this.t(`symbolInfo.prevClose`),m(l));let h=i?.volume??a?.volume;p(this.t(`dataWindow.volume`),h===void 0?void 0:si(h,this.intlLocale())),p(this.t(`symbolInfo.bid`),m(i?.bid)),p(this.t(`symbolInfo.ask`),m(i?.ask)),p(this.t(`symbolInfo.tick`),e?.minTick===void 0?void 0:String(e.minTick)),p(this.t(`symbolInfo.currency`),e?.currency),p(this.t(`symbolInfo.timezone`),e?.timezone),p(this.t(`symbolInfo.hours`),ci(e,s));let g=(u??0)>=0?`+`:`-`;return{symbol:r,description:e?.description,meta:[e?.exchange,e?.type].filter(Boolean).join(` · `)||void 0,price:c===void 0?void 0:o(c),change:u===void 0?void 0:{text:`${g}${o(Math.abs(u))}${ee===void 0?``:` (${g}${Math.abs(ee).toFixed(2)}%)`}`,up:u>=0},status:{state:f.state,text:te},stats:ne}}loadNews(){let e=this.symbolInfoPanel;if(!e?.isOpen())return;let t=this.options.adapter,r=this.options.news??(t?.fetchNews?t.fetchNews.bind(t):null);if(!r){e.renderNews({kind:`none`});return}let i=this.state.symbol,a=++this.newsRequest,o=t=>{let n=this.textLocale();e.renderNews({kind:`items`,items:t.map(e=>({title:e.title,url:e.url,meta:[e.source,oi(e.time-Date.now(),n)].filter(Boolean).join(` · `)}))})},s=this.newsCache.get(i);if(s&&Date.now()-s.at<ri){o(s.items);return}e.renderNews({kind:`loading`}),Promise.resolve().then(()=>r(i,ni)).then(e=>{if(a!==this.newsRequest||this.destroyed)return;let t=(0,n.readNews)(e,ni);this.newsCache.set(i,{at:Date.now(),items:t}),o(t)}).catch(()=>{a===this.newsRequest&&!this.destroyed&&e.renderNews({kind:`failed`})})}intlLocale(){return this.settingsState.numberLocale||this.options.locale||`en`}textLocale(){return this.options.locale||`en`}createWatchlist(e,t){let n=t.persist?ti():null,r=new et({lists:t.lists,activeList:t.activeList,symbols:this.symbols,defaultName:this.t(`watchlist.title`),storage:n,storageKey:t.storageKey});this.watchlistStore=r,this.watchlistFromSymbols=!t.lists&&!t.persist,this.quoteSource=t.quotes===!1?null:t.quotes??(this.options.adapter?.subscribeQuotes?this.options.adapter:null);let i=e=>this.t(e);this.watchlist=new Ue(e,{onSelect:e=>{this.setSymbol(e)},onAdd:()=>this.symbolSearch?.open(this.symbols,this.state.symbol,e=>r.add(e),this.symbolSearchFn()),onRemove:e=>r.removeSymbol(e),onMove:(e,t)=>r.move(e,t),onPickList:e=>r.setActive(e),onCreateList:e=>r.create(e),onRenameList:(e,t)=>r.rename(e,t),onDeleteList:e=>r.remove(e)},{title:i(`watchlist.title`),lists:i(`watchlist.lists`),newList:i(`watchlist.newList`),rename:i(`watchlist.rename`),deleteList:i(`watchlist.deleteList`),confirmDelete:i(`watchlist.confirmDelete`),add:i(`watchlist.add`),remove:i(`watchlist.remove`),empty:i(`watchlist.empty`),listName:i(`watchlist.listName`)}),this.watchlist.setActive(this.state.symbol),this.watchlist.setLocale(this.settingsState.numberLocale||void 0);let a=()=>{this.watchlist?.setLists(r.getLists(),r.getActive().id),this.followQuotes()};r.subscribe(()=>{a(),t.onChange?.(r.getLists(),r.getActive().id)}),a()}followQuotes(){if(!this.quoteSource||!this.watchlistStore||this.destroyed)return;let e=this.watchlistStore.getActive().symbols,t=[...e].sort().join(`\0`);if(t!==this.quotedKey&&(this.quotedKey=t,this.stopQuotes?.(),this.stopQuotes=null,e.length!==0))try{this.stopQuotes=this.quoteSource.subscribeQuotes(e,e=>{if(this.destroyed||!Array.isArray(e))return;let t=e.map(n.readQuote).filter(e=>e!==null);t.length>0&&this.takeQuotes(t)})}catch{this.stopQuotes=null}}takeQuotes(e){for(let t of e){let e={...this.quotes.get(t.symbol),...t};this.quotes.set(e.symbol,e);let n=this.watchlistSparkBuffer.get(e.symbol)??[];n.push(e.last),n.length>40&&n.shift(),this.watchlistSparkBuffer.set(e.symbol,n);let r=this.hostWatchlistRefPrice.get(e.symbol);this.watchlist?.setEntry(e.symbol,{lastPrice:e.last,refPrice:r??(e.change===void 0?void 0:e.last-e.change),sparkline:n.slice()})}e.some(e=>e.symbol===this.state.symbol)&&this.refreshSymbolInfo()}async setSymbol(e){this.flushActiveLayout(),e!==this.state.symbol&&this.chart.clearFills(),this.state={...this.state,symbol:e},this.sessionRefPrice=null,this.options.onSymbolChange?.(e),this.updateUI(),this.watchlist?.setActive(e),this.refreshMarket(),this.loadNews(),this.layoutSession?.changed(),this.adapter&&await this.connectStream()}setWatchlistEntry(e,t){t.refPrice!==void 0&&this.hostWatchlistRefPrice.set(e,t.refPrice),this.watchlist?.setEntry(e,t)}tickWatchlist(){if(!this.watchlist||this.quotes.has(this.state.symbol))return;let e=this.chart.getData();if(e.length===0)return;let t=e[e.length-1],n=this.hostWatchlistRefPrice.get(this.state.symbol);n===void 0&&this.sessionRefPrice===null&&(this.sessionRefPrice=e[0].open);let r=this.watchlistSparkBuffer.get(this.state.symbol)??[];r.push(t.close),r.length>40&&r.shift(),this.watchlistSparkBuffer.set(this.state.symbol,r),this.watchlist.setEntry(this.state.symbol,{lastPrice:t.close,refPrice:n??this.sessionRefPrice??e[0].open,sparkline:r.slice()})}async setTimeframe(e){if(this.chart.isTimeframeAllowed(e)){if(this.state={...this.state,timeframe:e},this.options.onTimeframeChange?.(e),this.updateUI(),this.layoutSession?.changed(),this.adapter){await this.connectStream();return}if(this.options.resampleTimeframes!==!1){if(!this.baseSeries){let e=this.chart.getData();e.length>0&&(this.baseSeries=e,this.baseTimeframeMs=a(e))}await this.switchLocalTimeframe()}}}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.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.chart.setTheme(n),this.updateUI()}getChart(){return this.chart}setUI(e){this.ui=N(e),P(this.root,this.ui),P(this.portal,this.ui),this.applyChartShapes()}getUI(){return N({...this.ui})}applyChartShapes(){this.chart.setShapes({tagRadius:this.ui.tagRadius})}destroy(){this.destroyed||(this.destroyed=!0,this.boundGlobalKeydown&&document.removeEventListener(`keydown`,this.boundGlobalKeydown),document.removeEventListener(`fullscreenchange`,this.onFullscreenChange),this.unregisterKeys(),this.tooltip.destroy(),this.legendFrame&&cancelAnimationFrame(this.legendFrame),this.indicatorLegend?.destroy(),this.portal.remove(),document.fullscreenElement===this.root&&document.exitFullscreen().catch(()=>{}),this.flushActiveLayout(),this.commandPalette?.destroy(),this.symbolSearch?.destroy(),this.hotkeySheet?.destroy(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayShade?.remove(),this.replayBar?.destroy(),this.dragDrop?.detach(),this.alertsPanel?.destroy(),this.objectTree?.destroy(),this.indicatorSettings?.destroy(),this.drawingStyle?.destroy(),this.drawingSettings?.destroy(),this.drawingMenu?.destroy(),this.chartMenu?.destroy(),this.legendMenu?.destroy(),this.templatePrompt?.destroy(),this.intervalInput?.destroy(),this.markerTip?.remove(),this.layoutSession?.destroy(),this.layoutsUI?.destroy(),this.accountPanel?.destroy(),this.orderTicket?.destroy(),this.accountFrame&&cancelAnimationFrame(this.accountFrame),this.bracketBar?.destroy(),this.alertNotifier?.destroy(),this.depthLadder?.destroy(),this.dataWindow?.destroy(),this.watchlistInterval&&clearInterval(this.watchlistInterval),this.marketTimer&&clearInterval(this.marketTimer),this.chartNav?.destroy(),this.symbolInfoPanel?.destroy(),this.stopQuotes?.(),this.stopQuotes=null,this.watchlist?.destroy(),this.toolbar?.destroy(),this.sidebar?.destroy(),this.settings?.destroy(),this.statusBar?.destroy(),this.goToDate?.destroy(),this.loading.destroy(),this.historyPill.destroy(),this.chart.destroy(),this.root.remove(),_())}handleSymbolClick(){this.symbolSearch?.open(this.symbols,this.state.symbol,void 0,this.symbolSearchFn())}symbolSearchFn(){if(this.options.searchSymbols)return this.options.searchSymbols;let e=this.adapter;if(e?.searchSymbols)return(t,n)=>e.searchSymbols(t,{signal:n,limit:50})}handleTimeframe(e){this.setTimeframe(e)}toggleFullscreen(){if(document.fullscreenElement===this.root){document.exitFullscreen().catch(()=>{});return}this.root.requestFullscreen().catch(e=>{this.toast(e instanceof Error?e.message:this.t(`toast.fullscreenUnavailable`),`error`)})}drawingToolName(e){let t=`tool.${e}`,n=this.t(t);return n===t?this.chart.getDrawingToolDescriptor(e)?.name??e:n}openDrawingSettings(e){let t=this.chart.getDrawings().find(t=>t.id===e),n=t?this.chart.getDrawingToolDescriptor(t.type):null;!t||!n||!this.drawingSettings||this.drawingSettings.open({id:e,type:t.type,name:this.drawingToolName(t.type),style:{...t.style},options:this.chart.getDrawingOptions(e),defs:n.options??{},anchors:t.anchors.map(e=>({...e})),fill:n.fill===!0,text:n.text===!0,alertable:this.chart.canAddDrawingAlert(e)})}addDrawingAlert(e){let n=this.chart.getDrawings().find(t=>t.id===e),r=n?this.drawingToolName(n.type):``;this.chart.addDrawingAlert(e,{label:r})&&this.toast(t.r(this.t(`drawingSettings.alertAdded`),{name:r}))}openDrawingMenu(e,t,n){if(!this.drawingMenu)return;let r=new Map(this.chart.getDrawings().map(e=>[e.id,e])),i=this.chart.getSelectedDrawingIds().flatMap(e=>{let t=r.get(e);return t?[{id:t.id,locked:t.locked,groupId:t.group?.id??null}]:[]});if(i.length===0)return;let a=sn({selected:i,canConfigure:this.drawingSettings!==null,canAlert:this.chart.canAddDrawingAlert(e)},this.t),o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect(),c=i.map(e=>e.id);this.drawingMenu.open(a,o.left-s.left+t,o.top-s.top+n,t=>this.runDrawingMenuAction(e,c,t))}runDrawingMenuAction(e,t,n){switch(n){case`settings`:this.openDrawingSettings(e);return;case`alert`:this.addDrawingAlert(e);return;case`front`:case`forward`:case`backward`:case`back`:this.chart.moveDrawing(e,n);break;case`group`:this.chart.groupDrawings(t);break;case`ungroup`:{let e=new Set(this.chart.getDrawings().filter(e=>t.includes(e.id)).map(e=>e.group?.id));for(let t of e)t&&this.chart.ungroupDrawings(t);break}case`lock`:case`unlock`:this.chart.setDrawingsLocked(t,n===`lock`);break;case`hide`:this.chart.setDrawingsVisible(t,!1);break;case`duplicate`:this.chart.duplicateDrawing(e);break;case`delete`:{let e=this.drawingSettings?.editing();e&&t.includes(e)&&this.drawingSettings?.close(!0),this.chart.removeDrawings(t);break}}this.objectTree?.isOpen()&&this.refreshObjects()}chartMenuContext(e){let t=this.chart.getDrawings(),n=this.chart.getData();return{price:e,lastPrice:n.length>0?n[n.length-1].close:null,formatPrice:e=>this.formatAlertPrice(e),canAlert:this.alertsPanel!==null,canTrade:this.options.trading!==!1,canOrderTicket:this.orderTicket!==null,canDraw:this.options.drawingTools!==!1,hasDrawings:t.length>0,drawingsHidden:t.length>0&&t.every(e=>!e.visible),canGoToDate:this.goToDate!==null,canExport:this.canExport,autoScale:this.chart.isAutoScale(),scaleMode:this.settingsState.scaleMode,inverted:this.chart.isInvertScale()}}openChartMenu(e,t,n,r){if(!this.chartMenu)return;let i=this.options.chartMenuItems?.(r)??[],a=[...e,...e.length>0&&i.length>0?[`separator`]:[],...i.map((e,t)=>({id:`host:${t}`,label:e.label,icon:e.icon,danger:e.danger,checked:e.checked}))];if(a.length===0)return;let o=this.chartContainer.getBoundingClientRect(),s=this.root.getBoundingClientRect();this.chartMenu.open(a,o.left-s.left+t,o.top-s.top+n,e=>{e.startsWith(`host:`)?i[Number(e.slice(5))]?.onSelect():this.runChartMenuAction(e,r.price)})}addToolbarButton(e){if(!this.toolbar)return null;let t=this.toolbar.addHostButton(e),n=()=>{let e=t.querySelector(`.tcw-host-btn-text`);if(e)return e;let n=document.createElement(`span`);return n.className=`tcw-host-btn-text`,t.appendChild(n),n};return{element:t,setActive:n=>{t.classList.toggle(`tcw-active`,n),e.toggle&&t.setAttribute(`aria-pressed`,String(n))},setText:r=>{n().textContent=r,_e(t,e.label)},remove:()=>t.remove()}}runChartMenuAction(e,n){let r=n??NaN;switch(e){case`alert`:this.chart.addAlert(r,`crossing`),this.toast(t.r(this.t(`chartMenu.alertAdded`),{price:this.formatAlertPrice(r)}));break;case`buyLimit`:case`sellLimit`:case`buyStop`:case`sellStop`:this.placeOrderAt(e,r);break;case`orderTicket`:this.openOrderTicket(n);break;case`exportData`:this.chart.exportAllData(`csv`,`${this.state.symbol}-${this.state.timeframe}.csv`.replace(/[^\w.-]+/g,`_`));break;case`paneLog`:case`paneInvert`:case`panePercent`:{let t=this.menuPane;if(!t)break;let n=this.chart.getPaneScale(t);this.chart.setPaneScale(t,e===`paneLog`?{log:!n.log}:e===`paneInvert`?{invert:!n.invert}:{percent:!n.percent});break}case`horizontalLine`:{let e=this.chart.getData();e.length>0&&this.chart.addDrawing({type:`horizontalLine`,anchors:[{time:e[e.length-1].time,price:r}]});break}case`resetView`:this.chart.fitContent(),this.changeSettings({autoScale:!0});break;case`hideDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!1);break;case`showDrawings`:this.chart.setDrawingsVisible(this.chart.getDrawings().map(e=>e.id),!0);break;case`removeDrawings`:this.chart.removeDrawings(this.chart.getDrawings().map(e=>e.id));break;case`settings`:this.openSettings();break;case`autoScale`:this.changeSettings({autoScale:!this.chart.isAutoScale()});break;case`logScale`:this.changeSettings({scaleMode:this.settingsState.scaleMode===`logarithmic`?`regular`:`logarithmic`});break;case`percentScale`:this.changeSettings({scaleMode:this.settingsState.scaleMode===`percentage`?`regular`:`percentage`});break;case`invertScale`:this.changeSettings({invertScale:!this.chart.isInvertScale()});break;case`goToDate`:this.toggleGoToDate();break}this.objectTree?.isOpen()&&this.refreshObjects()}toggleAccountPanel(e){let t=this.accountPanel;!t||e===t.isOpen()||t.toggle()}openOrderTicket(e){let t=this.chart.getData();this.orderTicket?.open({price:e,lastPrice:t.length>0?t[t.length-1].close:null})}refreshAccountSoon(){this.accountFrame||!this.accountPanel||(this.accountFrame=requestAnimationFrame(()=>{this.accountFrame=0,this.destroyed||this.refreshAccount()}))}refreshAccount(){if(!this.accountPanel)return;let e=this.chart.getData(),t=e.length>0?e[e.length-1].close:null;this.accountPanel.update({positions:this.chart.getPositions(),orders:this.chart.getOrders(),fills:this.chart.getFills(),price:t,realisedPnl:this.chart.getRealisedPnl()}),this.orderTicket?.setLastPrice(t)}placeOrderAt(e,n){let r=e.startsWith(`buy`)?`buy`:`sell`,i=e.endsWith(`Stop`);this.chart.placeOrderIntent(i?{side:r,type:`stop`,price:n,stopPrice:n,quantity:1}:{side:r,type:`limit`,price:n,quantity:1}),this.toast(t.r(this.t(`order.${e}`),{price:this.formatAlertPrice(n)}))}displayTimezone(){let e=s(this.settingsState.timezone);return e===`exchange`?this.chart.getEffectiveTimezone():e}toggleGoToDate(){if(!this.goToDate)return;if(this.goToDate.isOpen()){this.goToDate.close();return}let e=this.chart.getData();e.length!==0&&this.goToDate.open(q(e[e.length-1].time*Qr(e),this.displayTimezone()),this.root.querySelector(`[data-role="goto"]`))}goToWallTime(e,t){let n=nr(e,t,this.displayTimezone()),r=this.chart.getData();if(n===null||r.length===0)return;let i=n/Qr(r);this.chart.goToTime(i),i<r[0].time&&this.toast(this.t(`range.beforeData`))}pinnedTimeframes(){let e=this.timeframeFavorites.list();return this.timeframes.filter(t=>e.includes(t))}timeframeMenu(){return this.timeframes.map(e=>({value:e,label:Nn(e),custom:this.customTimeframes.has(e)}))}handleAddTimeframe(e){let t=Vn(e);return!t||!this.chart.isTimeframeAllowed(t)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,t)||!this.adapter&&(0,n.tickBarCount)(t)!==null?!1:(this.timeframes.includes(t)||(this.customTimeframes.add(t),this.timeframeFavorites.add(t),this.timeframes=Hn(this.timeframes,[t]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(t),!0)}showMarkerTip(e){let{marker:n}=e;if(!n){this.markerTip&&(this.markerTip.hidden=!0);return}this.markerTip||(this.markerTip=document.createElement(`div`),this.markerTip.className=`tcw-marker-tip`,this.markerTip.setAttribute(`role`,`tooltip`),this.chartContainer.appendChild(this.markerTip));let r=n.direction===`long`?this.t(`account.long`):n.direction===`short`?this.t(`account.short`):this.t(`markers.neutral`),i=document.createElement(`strong`);i.textContent=n.label?`${n.label} · ${n.source}`:n.source;let a=document.createElement(`div`);a.textContent=`${r} · ${this.formatAlertPrice(n.price)} · ${t.r(this.t(`markers.confidence`),{pct:Math.round(n.confidence*100)})}`;let o=document.createElement(`div`),{date:s,time:c}=q(n.time,this.displayTimezone());o.textContent=`${s} ${c}`,this.markerTip.replaceChildren(i,a,o),this.markerTip.hidden=!1;let l=this.chartContainer.getBoundingClientRect(),u=Math.min(e.x+12,Math.max(0,l.width-this.markerTip.offsetWidth-4)),d=Math.max(0,e.y-this.markerTip.offsetHeight-10);this.markerTip.style.left=`${u}px`,this.markerTip.style.top=`${d}px`}selectTypedTimeframe(e){return!this.chart.isTimeframeAllowed(e)||this.adapter&&!(0,r.servesTimeframe)(this.adapter,e)?!1:(this.timeframes.includes(e)||(this.customTimeframes.add(e),this.timeframes=Hn(this.timeframes,[e]),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes())),this.handleTimeframe(e),!0)}applyIndicatorTemplate(e){let n=this.templates.get(e);n&&(this.chart.applyIndicatorSetup(n.indicators),this.syncIndicatorsFromChart(),this.updateUI(),this.toast(t.r(this.t(`templates.applied`),{name:n.name})))}promptSaveIndicatorTemplate(){if(this.chart.getActiveIndicators().length===0){this.toast(this.t(`templates.nothing`),`error`);return}this.templatePrompt??=new Tn(this.root,this.t),this.templatePrompt.open({title:this.t(`templates.saveTitle`),submitLabel:this.t(`common.save`),placeholder:this.t(`templates.namePlaceholder`),onSubmit:e=>{try{this.templates.save(e,this.chart.getIndicatorSetup())}catch(e){throw this.toast(this.t(`templates.saveFailed`),`error`),e}this.toolbar?.setIndicatorTemplates(this.templates.list().map(e=>e.name)),this.toast(t.r(this.t(`templates.saved`),{name:e}))}})}handleRemoveTimeframe(e){this.customTimeframes.has(e)&&(this.customTimeframes.remove(e),this.timeframeFavorites.remove(e),this.timeframes=this.timeframes.filter(t=>t!==e),this.toolbar?.setTimeframes(this.timeframeMenu(),this.pinnedTimeframes()),this.updateUI())}handleToggleTimeframeFavorite(e){this.timeframeFavorites.toggle(e),this.toolbar?.setTimeframeFavorites(this.pinnedTimeframes()),this.updateUI()}setData(e){this.localSeq++,this.baseSeries=e,this.baseTimeframeMs=a(e),this.applyTimeframeData(),this.adapter||this.loading.end()}async switchLocalTimeframe(){if(!this.baseSeries)return;let e=++this.localSeq,t=this.lastLocalSwitchMs>=zr||this.baseSeries.length>=Br;try{if(t&&(this.loading.begin(this.chart.getData().length>0,!0),await Hr(),e!==this.localSeq||this.destroyed))return;this.applyTimeframeData()}finally{e===this.localSeq&&this.loading.end()}}applyTimeframeData(){if(!this.baseSeries)return;let e=performance.now(),t=(0,n.timeframeToMs)(this.state.timeframe);if(this.baseTimeframeMs>0&&t>this.baseTimeframeMs){let e=this.options.weekStartsOn??1;this.chart.setData(i(this.baseSeries,this.state.timeframe,{weekStartsOn:e}))}else this.chart.setData(this.baseSeries);this.lastLocalSwitchMs=performance.now()-e}handleDataUpdate(e){if(!e||typeof e!=`object`)return;let t=e;if(typeof t.length==`number`){t.length>0&&this.loading.isActive()&&(this.loading.end(),this.state.connectionState===`error`&&this.setConnectionState(`connected`,this.t(`status.live`)));return}if(t.error!==void 0){this.loading.isActive()&&(this.loading.fail(this.t(`status.connectionFailed`)),this.setConnectionState(`error`,t.error||this.t(`status.connectionFailed`)));return}switch(t.connection?.state){case`connected`:this.loading.hasFailed()&&this.loading.end(),!this.loading.isActive()&&this.state.connectionState!==`connected`&&this.setConnectionState(`connected`,this.t(`status.live`));break;case`reconnecting`:this.loading.isActive()||this.setConnectionState(`connecting`,this.t(`status.connecting`));break;case`error`:this.loading.isActive()||this.setConnectionState(`error`,this.t(`status.connectionFailed`));break}}setConnectionState(e,t){this.state={...this.state,connectionState:e,connectionMessage:t},this.updateUI()}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?this.t(`toast.pinned`):this.t(`toast.unpinned`))}exportState(){let e=this.chart.getActiveIndicators().map(e=>({id:e.id,params:e.params}));return Ar({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=jr(e);return t?(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.applyChartType(t.chartType),this.chart.setScaleMode(t.scaleMode),this.chart.applyIndicatorSetup(t.indicators.map((e,t)=>({id:e.id,instanceId:`shared_${t}`,params:e.params}))),this.chart.setDrawings(t.drawings),this.updateUI(),!0):!1}async copyChartImage(){let e=await this.chart.copyScreenshot();this.toast(e?this.t(`toast.imageCopied`):this.t(`toast.imageCopyFailed`),e?`info`:`error`)}async copyShareLink(){let e=Pr(typeof location<`u`?location.href:``,this.exportState());try{await navigator.clipboard.writeText(e),this.toast(this.t(`toast.linkCopied`))}catch{this.toast(this.t(`toast.copyFailed`),`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=e.descriptor.plots?.map(e=>[e.key,e.title])??Object.keys(n??{}).map(e=>[e,e]),i=n?r.filter(([e])=>typeof n[e]==`number`&&Number.isFinite(n[e])).map(([e,t])=>({key:t,value:n[e]})):[];return{name:e.descriptor.name,values:i}}).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(),n=t.find(t=>t.instanceId===e);if(!n)return;let r=this.chart.getIndicatorStyle(e),i=n.descriptor.placement===`panel`||!!n.pane;this.indicatorSettings.open({instanceId:e,name:n.descriptor.name,defaults:n.descriptor.defaultConfig,params:n.params,inputs:n.descriptor.inputs,lineSources:ei(e,t),plots:n.descriptor.plots,colors:r?.colors,lineWidth:r?.lineWidths[0],levels:i?this.chart.getIndicatorLevels(e):void 0,defaultLevels:n.descriptor.levels,scale:i?void 0:this.chart.getIndicatorScale(e)})}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:Ot(e.type,this.t),visible:e.visible,locked:e.locked,group:e.group})),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(this.t(`toast.compareNeedsAdapter`),`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.pickCompareWay(e)},this.symbolSearchFn())}pickCompareWay(e){let n=this.state.symbol,r=[{id:`percent`,label:this.t(`compare.percent`)},{id:`scale`,label:this.t(`compare.ownScale`)},{id:`pane`,label:this.t(`compare.ownPane`)},{id:`spread`,label:t.r(this.t(`compare.spread`),{main:n,other:e})},{id:`ratio`,label:t.r(this.t(`compare.ratio`),{main:n,other:e})},{id:`correlation`,label:t.r(this.t(`compare.correlation`),{main:n,other:e})},{id:`correlationLog`,label:t.r(this.t(`compare.correlationLog`),{main:n,other:e})}],i=this.chart.getPlotRect();this.chartMenu?.open(r,i.x+24,i.y+24,t=>void this.addCompareSymbol(e,t))}async addCompareSymbol(e,n=`percent`){if(!this.adapter){this.toast(this.t(`toast.compareNeedsAdapter`),`error`);return}if(n!==`percent`){let t=n===`scale`?this.chart.addIndicator(`compareSymbol`,{symbol:e},`bottom`,{scale:`left`}):n===`pane`?this.chart.addIndicator(`compareSymbol`,{symbol:e}):n===`correlation`?this.chart.addIndicator(`correlation`,{symbol:e}):n===`correlationLog`?this.chart.addIndicator(`correlationlog`,{symbol:e}):this.chart.addIndicator(`spread`,{symbol:e,mode:n});t&&n===`pane`&&this.chart.moveIndicatorToPane(t,`new`);return}if(this.compares.some(t=>t.symbol===e))return;let i=Ur[this.compares.length%Ur.length],a=`cmp_${e}`;try{let n=await(0,r.withResampling)(this.adapter).fetchHistory(e,this.state.timeframe,this.options.historyLimit??500);this.compares.length===0&&this.chart.setCompareMode(`percent`),this.chart.addCompareSymbol(a,e,n,i),this.compares=[...this.compares,{id:a,symbol:e,color:i}],this.refreshObjects(),this.toast(t.r(this.t(`toast.comparing`),{symbol:e}))}catch(t){this.toast(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}handleRemoveCompare(e){this.chart.removeCompareSymbol(e),this.compares=this.compares.filter(t=>t.id!==e),this.refreshObjects()}async loadSymbolSeries(e){if(!this.adapter){this.toast(this.t(`toast.compareNeedsAdapter`),`error`);return}let t=this.state.timeframe,n=(this.symbolLoads.get(e)??0)+1;this.symbolLoads.set(e,n);let i=()=>this.destroyed||t!==this.state.timeframe||this.symbolLoads.get(e)!==n;try{let n=Math.max(this.chart.getData().length,this.options.historyLimit??500),a=await(0,r.withResampling)(this.adapter).fetchHistory(e,t,n);if(i())return;this.chart.setSymbolSeries(e,a)}catch(t){if(i())return;this.chart.setSymbolSeries(e,this.chart.getSymbolSeries(e)),this.toast(`${e}: ${t instanceof Error?t.message:this.t(`toast.loadFailed`)}`,`error`)}}async refetchCompares(){for(let e of this.chart.getRequiredSymbols?.()??[])this.loadSymbolSeries(e);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(0,r.withResampling)(this.adapter).fetchHistory(e.symbol,this.state.timeframe,this.options.historyLimit??500);this.chart.updateCompareData(e.id,t)}catch{}}refreshAlerts(){if(!this.alertsPanel)return;let e=this.buildAlertSources();this.alertsPanel.setSources(e),this.alertsPanel.setAlerts(this.chart.getAlerts().map(t=>this.alertListItem(t,e)))}alertListItem(e,t){return{id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,targetLabel:e.target?t.find(t=>t.channel===e.target)?.label:void 0,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}}alertText(e){return at(this.alertListItem(e,this.buildAlertSources()),this.t,e=>this.formatAlertPrice(e),!0)}buildAlertSources(){let e=[{channel:`price`,label:this.t(`alerts.source.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=this.chart.getPriceFormatter?.();if(t)return t(e);let n=Math.abs(e),r=n>=1e3?2:n>=1?4:6,i=this.settingsState.numberLocale||void 0;return e.toLocaleString(i,{minimumFractionDigits:2,maximumFractionDigits:r})}handleChartType(e){let t=this.state.chartType;e!==t&&(this.applyChartType(e),this.chart.recordUndo({subject:`chartType`,undo:()=>this.applyChartType(t),redo:()=>this.applyChartType(e)}))}applyChartType(e){this.state={...this.state,chartType:e},this.chart.setChartType(e),this.updateUI()}handleAddIndicator(e){this.chart.addIndicator(e)}handleRemoveIndicator(e){this.chart.removeIndicator(e)}toggleCommandPalette(){if(this.commandPalette?.isOpen()){this.commandPalette.close();return}this.commandPalette?.open(this.buildCommandItems())}buildCommandItems(){let e=[];for(let t of ee)e.push({id:t.id,label:t.name,category:`indicator`,active:[...this.state.activeIndicators.values()].some(e=>e.id===t.id)});for(let t of u)e.push({id:t.value,label:me(t,this.t),category:`chartType`,active:this.state.chartType===t.value});for(let t of he(d,this.t))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 this.timeframes)e.push({id:t,label:Nn(t),category:`timeframe`,active:this.state.timeframe===t});return e.push({id:`screenshot`,label:this.t(`action.screenshot`),category:`action`,shortcut:``},{id:`copyImage`,label:this.t(`action.copyImage`),category:`action`},{id:`toggleTheme`,label:this.t(`action.toggleTheme`),category:`action`},{id:`settings`,label:this.t(`action.settings`),category:`action`},{id:`shareView`,label:this.t(`action.shareView`),category:`action`},{id:`autoFib`,label:this.t(`action.autoFib`),category:`action`},{id:`dataWindow`,label:this.t(`action.dataWindow`),category:`action`},...this.symbolInfoPanel?[{id:`symbolInfo`,label:this.t(`action.symbolInfo`),category:`action`}]:[],{id:`clearDrawings`,label:this.t(`action.clearDrawings`),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?this.t(`toast.autoFibAdded`):this.t(`toast.noSwing`));break}case`dataWindow`:this.toggleDataWindow();break;case`symbolInfo`:this.toggleSymbolInfo();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.chart.setEraserMode(!1),this.chart.setZoomAreaMode(!1),this.updateUI()}handleToggleStayInDrawing(){let e=!this.state.stayInDrawing;this.state={...this.state,stayInDrawing:e},this.chart.setStayInDrawingMode(e),this.updateUI()}handleToggleMagnet(){let e=this.state.magnetEnabled?this.state.magnetStrong?`off`:`strong`:`weak`;this.state={...this.state,magnetEnabled:e!==`off`,magnetStrong:e===`strong`},this.chart.setDrawingMagnetMode(e),this.updateUI()}handleToggleTheme(){let e=!this.state.isDark;this.state={...this.state,isDark:e},this.root.dataset.tcwTheme=e?`dark`:`light`,this.portal.dataset.tcwTheme=this.root.dataset.tcwTheme,this.chart.setTheme(e?n.DARK_THEME:n.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.settingsState={...this.settingsState,chartTypeOptions:this.chart.getChartTypeOptions?.()??{}},this.settings?.open(this.settingsState,this.state.chartType)}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)}getLayoutSession(){return this.layoutSession}getSymbol(){return this.state.symbol}getTimeframe(){return this.state.timeframe}captureLayout(){let e=this.chart.saveState(),t=e?Zn(e):null,n=t&&typeof t==`object`?Yn(t):null;return{v:1,symbol:this.state.symbol,timeframe:this.state.timeframe,scaleMode:this.settingsState.scaleMode,invertScale:this.settingsState.invertScale,chart:n}}async restoreLayout(e){if(e.symbol!==this.state.symbol&&await this.setSymbol(e.symbol),e.timeframe!==this.state.timeframe&&await this.setTimeframe(e.timeframe),!this.destroyed){if(e.chart){this.chart.loadState(JSON.stringify(Yn(e.chart)));let t=e.chart.chartType;typeof t==`string`&&(this.state={...this.state,chartType:t})}this.applySettings({scaleMode:e.scaleMode,invertScale:e.invertScale}),this.syncIndicatorsFromChart(),this.updateUI()}}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=Xn(Zn(e));return t?(await this.restoreLayout(t),!0):!1}setupLayouts(t){let n=new e.t(t.storage??e.i(),{capture:()=>({content:this.getLayoutContent(),symbol:this.state.symbol,timeframe:this.state.timeframe}),apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a widget layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,onChange:()=>this.toolbar?.setLayout(n.current()?.name??null,n.isDirty()),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.layoutSession=n,this.layoutsUI=new kn(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(e,this.displayTimezone());return`${t} ${n}`}}),this.chart.on(`stateChange`,()=>n.changed()),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.openLayout(e.id):void 0,()=>void 0)}async saveLayout(){await this.layoutsUI?.save()}async openLayout(e){return await this.layoutsUI?.open(e)??!1}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.syncIndicatorsFromChart()}catch{}this.chart.setAutoSave(t,this.layoutDebounceMs)}flushActiveLayout(){if(this.activeLayoutKey){try{this.chart.saveState(this.activeLayoutKey)}catch{}this.chart.disableAutoSave(),this.activeLayoutKey=null}}syncIndicatorsFromChart(){let t=new Map;for(let n of this.chart.getActiveIndicators())t.set(n.instanceId,{id:n.id,label:e.C(n.id,n.params,n.descriptor.defaultConfig,n.descriptor.shortName)});this.state={...this.state,activeIndicators:t},this.updateUI()}toggleReplay(){this.replayBar?.isMounted()?this.exitReplay():this.enterReplay()}enterReplay(){if(this.replayTotal()<2)return;let e=this.t;this.replayBar=new Le({onPlay:()=>{if(this.replayBar?.getMode()===`select`){this.startReplayAt(Math.max(1,this.replayTotal()-100),!0);return}this.chart.getReplayState()===`paused`&&this.chart.replayResume(),this.replayBar?.setState(`playing`)},onPause:()=>{this.chart.replayPause(),this.replayBar?.setState(`paused`)},onStepBack:()=>this.stepReplay(-1),onStepForward:()=>this.stepReplay(1),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)},onRandomStart:()=>{let e=this.replayTotal(),t=Math.max(1,Math.floor(e*.1)),n=Math.max(t,Math.floor(e*.9));this.startReplayAt(t+Math.floor(Math.random()*(n-t+1)))},onClose:()=>this.exitReplay(),onStepChange:e=>{if(this.replayStep=e,this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayState()===`playing`;this.startReplayAt(Math.max(0,this.chart.getReplayBarIndex()-1),t)}},{selectHint:e(`replay.selectHint`),random:e(`replay.random`),realtime:e(`replay.realtime`),barsPerSecond:e(`replay.barsPerSecond`),play:e(`replay.play`),pause:e(`replay.pause`),stepBack:e(`replay.stepBack`),stepForward:e(`replay.stepForward`),replay:e(`replay.label`),position:e(`replay.position`),speed:e(`replay.speed`),step:e(`replay.step`)});let t=[{value:`bar`,label:e(`replay.step.bar`)},...this.replayStepOptions().map(e=>({value:e,label:e}))];t.some(e=>e.value===this.replayStep)||(this.replayStep=`bar`),this.replayBar.mount(this.chartContainer,{total:this.replayTotal(),speed:this.replaySpeed,mode:`select`,steps:t,step:this.replayStep}),this.replayShade=document.createElement(`div`),this.replayShade.className=`tcw-replay-shade`,this.replayShade.hidden=!0,this.chartContainer.appendChild(this.replayShade),this.chartContainer.addEventListener(`mouseleave`,this.hideReplayShade)}hideReplayShade=()=>this.positionReplayShade(null);replayFrom(e,t=!1){this.replayBar?.isMounted()||this.enterReplay(),this.startReplayAt(e,t)}startReplayAt(e,t=!1){let n=this.replayBar;if(!n)return;let r=this.replayTotal(),i=Math.max(0,Math.min(Number.isFinite(e)?Math.floor(e):0,r-1));this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),n.setMode(`replay`);let a=++this.replayStartSeq,o=e=>{this.destroyed||this.replayBar!==n||!n.isMounted()||a!==this.replayStartSeq||(this.chart.replayStart({speed:this.replaySpeed,interval:1e3,startIndex:i,paused:!0,...e?{steps:e}:{}}),t&&this.chart.replayResume(),n.setState(t?`playing`:`paused`),this.syncReplayBar(),this.replayPollInterval&&clearInterval(this.replayPollInterval),this.replayPollInterval=setInterval(()=>this.syncReplayBar(),150))};if(this.replayStep===`bar`){o(null);return}this.replayStepsFor(this.replayStep).then(e=>{a===this.replayStartSeq&&(e||this.toast(this.t(`replay.stepsFailed`),`error`),o(e))})}replayStepOptions(){let e=(0,n.timeframeToMs)(this.state.timeframe);return Jr.filter(t=>{let i=(0,n.timeframeToMs)(t);return!(i<e)||e%i!==0?!1:this.adapter?(0,r.servesTimeframe)(this.adapter,t):this.baseSeries!==null&&this.baseTimeframeMs>0&&i>=this.baseTimeframeMs&&i%this.baseTimeframeMs===0})}async replayStepsFor(e){let t=`${this.state.symbol}|${this.state.timeframe}|${e}`;if(this.replayStepsCache?.key===t)return this.replayStepsCache.steps;let a=null;if(this.adapter){let t=Math.max(1,Math.round((0,n.timeframeToMs)(this.state.timeframe)/(0,n.timeframeToMs)(e))),i=Math.min(Yr,Math.max(this.chart.getData().length,100)*t);try{a=await(0,r.withResampling)(this.adapter).fetchHistory(this.state.symbol,e,i)}catch{a=null}}else this.baseSeries&&(a=(0,n.timeframeToMs)(e)===this.baseTimeframeMs?this.baseSeries:i(this.baseSeries,e));return!a||a.length===0?null:(this.replayStepsCache={key:t,steps:a},a)}replayTotal(){return this.chart.isReplayActive()?this.chart.getReplayProgress().total:this.chart.getData().length}syncReplayBar(){let e=this.replayBar;if(!e?.isMounted()||e.getMode()!==`replay`)return;if(!this.chart.isReplayActive()){this.teardownReplayUi();return}let t=this.chart.getReplayProgress(),n=this.chart.getReplayState();e.setProgress(t.current,t.total),e.setState(n===`stopped`?`paused`:n),e.setEnded(n!==`playing`&&t.total>0&&t.current>=t.total-1)}stepReplay(e){if(this.replayBar?.getMode()!==`replay`)return;let t=this.chart.getReplayProgress();this.chart.getReplayState()===`playing`&&this.chart.replayPause(),this.chart.replaySeek(Math.max(0,Math.min(t.total-1,t.current+e))),this.replayBar.setState(`paused`),this.syncReplayBar()}handleReplayKey(e){if(e.defaultPrevented)return!1;let t=document.activeElement;return t&&(t.tagName===`INPUT`||t.tagName===`TEXTAREA`||t.tagName===`SELECT`||t.isContentEditable)?!1:e.shiftKey&&(e.key===`ArrowRight`||e.key===`ArrowLeft`)&&this.replayBar?.getMode()===`replay`?(e.preventDefault(),e.stopPropagation(),this.stepReplay(e.key===`ArrowRight`?1:-1),!0):e.key===`Escape`&&this.replayBar?.getMode()===`select`?(this.exitReplay(),!0):!1}positionReplayShade(e){let t=this.replayShade;if(!t)return;let n=this.chart.getPlotRect();if(e===null||e<n.x||e>n.x+n.width){t.hidden=!0;return}t.hidden=!1,t.style.left=`${e}px`,t.style.top=`${n.y}px`,t.style.width=`${n.x+n.width-e}px`,t.style.height=`${n.height}px`}exitReplay(){this.teardownReplayUi(),this.chart.replayStop()}teardownReplayUi(){this.replayPollInterval&&=(clearInterval(this.replayPollInterval),null),this.replayShade?.remove(),this.replayShade=null,this.chartContainer.removeEventListener(`mouseleave`,this.hideReplayShade),this.replayBar?.unmount(),this.replayBar=null}applySettings(e){this.settingsState={...this.settingsState,...e},(e.scaleMode!==void 0||e.logScale!==void 0||e.invertScale!==void 0)&&this.layoutSession?.changed(),this.scheduleLegend(),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.legendVisible!==void 0&&this.chart.setLegend({visible:e.legendVisible}),e.barCountdown!==void 0&&this.chart.setBarCountdownVisible(e.barCountdown),e.indicatorValueLabels!==void 0&&this.chart.setIndicatorValueLabelsVisible(e.indicatorValueLabels),e.crosshairMode!==void 0&&this.chart.setCrosshairMode(e.crosshairMode),e.autoScale!==void 0&&this.chart.setAutoScale(e.autoScale),e.invertScale!==void 0&&this.chart.setInvertScale(e.invertScale),e.leftPriceScale!==void 0&&this.chart.setLeftPriceScaleVisible(e.leftPriceScale),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),this.watchlist?.setLocale(e.numberLocale||void 0)),e.timezone!==void 0&&this.chart.setTimezone(s(e.timezone)),e.highLowLines!==void 0&&this.chart.setHighLowLines(e.highLowLines),e.extendedHours!==void 0&&this.chart.setExtendedHours(e.extendedHours),e.mainSeriesVisible!==void 0&&this.chart.setMainSeriesVisible(e.mainSeriesVisible),e.chartTypeOptions!==void 0&&this.chart.setChartTypeOptions({renko:{},lineBreak:{},kagi:{},pointAndFigure:{},rangeBars:{},...e.chartTypeOptions});let t={...this.chart.getTheme()},r=!1;e.candleUpColor!==void 0&&(t.candleUp=e.candleUpColor,t.volumeUp=(0,n.volumeColor)(e.candleUpColor),r=!0),e.candleDownColor!==void 0&&(t.candleDown=e.candleDownColor,t.volumeDown=(0,n.volumeColor)(e.candleDownColor),r=!0),e.candleUpWick!==void 0&&(t.candleUpWick=e.candleUpWick,r=!0),e.candleDownWick!==void 0&&(t.candleDownWick=e.candleDownWick,r=!0),e.backgroundColor!==void 0&&(t.background=e.backgroundColor,r=!0),e.gridColor!==void 0&&(t.grid=e.gridColor,r=!0),r&&this.chart.setTheme(t)}resetSettings(){let e={...this.settingsState};this.settingsState={...this.settingsDefaults},this.applySettings(this.settingsState);let t={...this.settingsState};JSON.stringify(e)!==JSON.stringify(t)&&this.chart.recordUndo({undo:()=>this.restoreSettings(e),redo:()=>this.restoreSettings(t)})}changeSettings(e){let t=Object.keys(e);if(t.includes(`scaleMode`)||t.includes(`logScale`))for(let e of[`scaleMode`,`logScale`])t.includes(e)||t.push(e);let n=()=>Object.fromEntries(t.map(e=>[e,this.settingsState[e]])),r=n();this.applySettings(e);let i=n();JSON.stringify(r)!==JSON.stringify(i)&&this.chart.recordUndo({subject:`settings:${Object.keys(e).sort().join(`,`)}`,undo:()=>this.restoreSettings(r),redo:()=>this.restoreSettings(i)})}restoreSettings(e){this.applySettings(e),this.settings?.refresh(this.settingsState)}async connectStream(){if(!this.adapter)return;let e=++this.connectSeq;this.state={...this.state,connectionState:`connecting`,connectionMessage:this.t(`status.connecting`)},this.updateUI(),this.loading.begin(this.chart.getData().length>0);try{if(this.chart.disconnectStream(),await this.chart.connect({adapter:this.adapter,symbol:this.state.symbol,timeframe:this.state.timeframe,historyLimit:this.options.historyLimit??500,historyPageSize:this.options.historyPageSize}),e!==this.connectSeq||this.destroyed)return;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.loading.hasFailed()?this.state={...this.state,connectionState:`error`}:(this.loading.end(),this.state={...this.state,connectionState:`connected`,connectionMessage:this.t(`status.live`)}),this.refetchCompares()}catch(t){if(e!==this.connectSeq||this.destroyed)return;this.loading.fail(this.t(`status.connectionFailed`)),this.state={...this.state,connectionState:`error`,connectionMessage:t instanceof Error?t.message:this.t(`status.connectionFailed`)}}this.updateUI()}scheduleLegend(){!this.indicatorLegend||this.legendFrame||(this.legendFrame=requestAnimationFrame(()=>{this.legendFrame=0,this.renderLegend()}))}renderLegend(){if(!this.indicatorLegend||this.destroyed)return;let t=this.chart.getData().length-1,n=this.chart.isTimeAligned()?this.legendHoverIndex:null,r=n===null?t:Math.min(Math.max(n,0),t),i=new Map;for(let e of this.chart.getIndicatorPanes())(e.instanceIds??[e.instanceId]).forEach((t,n)=>i.set(t,{...e.rect,row:n}));let a=this.settingsState.numberLocale||`en-US`,o=this.chart.getActiveIndicators().map(t=>{let n=i.get(t.instanceId)??null,o=r>=0?this.chart.getIndicatorOutput(t.instanceId)?.series?.[r]:null,s=this.chart.getIndicatorStyle(t.instanceId)?.colors??[],c=pr(t.descriptor,o,s);return{instanceId:t.instanceId,label:e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName),visible:t.visible,values:c.map(e=>({text:n?gr(e.value,a):this.chart.formatPrice(e.value),color:e.color})),pane:n?{x:n.x+Wr,y:n.y+Math.min(Gr+n.row*Kr,Math.max(Gr,n.height-Kr)),width:n.width-2*Wr}:null}}),s=this.chart.getPlotRect(),c=this.chart.getMaximizedPane(),l=e=>o.find(t=>t.instanceId===e)?.label??``,u=this.chart.getIndicatorPanes().map(e=>({instanceId:e.instanceId,x:e.rect.x+e.rect.width-Wr,y:e.rect.y+qr,label:l(e.instanceId),collapsed:this.chart.isPaneCollapsed(e.instanceId),maximized:c===e.instanceId,canMoveUp:this.chart.canMovePane(e.instanceId,-1),canMoveDown:this.chart.canMovePane(e.instanceId,1)}));this.indicatorLegend.update(o,{left:s.x+Wr,top:this.chart.getLegendBottom()+1},u)}runPaneAction(e,t){t===`up`||t===`down`?this.chart.movePane(e,t===`up`?-1:1):t===`collapse`||t===`expand`?this.chart.setPaneCollapsed(e,t===`collapse`):this.chart.setMaximizedPane(t===`maximize`?e:null),this.scheduleLegend()}openLegendMenu(e,t){let n=this.legendMenu;if(!n)return;if(n.isOpen()){n.close();return}let r=[`price`,...this.chart.getIndicatorPanes().map(e=>e.instanceId)],i=1+this.chart.getIndicatorPanes().findIndex(t=>t.instanceIds.includes(e)),a=r[i-1],o=r[i+1],s=t=>t!==void 0&&this.chart.canMoveIndicatorToPane(e,t),c=[];s(a)&&c.push({id:`move:${a}`,label:this.t(a===`price`?`legend.movePrice`:`legend.moveUp`),icon:`arrowUp`}),s(o)&&c.push({id:`move:${o}`,label:this.t(`legend.moveDown`),icon:`arrowDown`}),s(`new`)&&c.push({id:`move:new`,label:this.t(`legend.moveNew`),icon:`plus`}),a!==`price`&&s(`price`)&&c.push({id:`move:price`,label:this.t(`legend.movePrice`),icon:`trendingUp`}),c.length>0&&c.push(`separator`),c.push({id:`settings`,label:this.t(`legend.settings`),icon:`settings`},{id:`remove`,label:this.t(`legend.remove`),icon:`trash`,danger:!0});let l=t.getBoundingClientRect(),u=this.root.getBoundingClientRect();n.open(c,l.left-u.left,l.bottom-u.top+2,t=>{t===`settings`?this.openIndicatorSettings(e):t===`remove`?this.handleRemoveIndicator(e):t.startsWith(`move:`)&&this.chart.moveIndicatorToPane(e,t.slice(5)),this.scheduleLegend()},t)}updateUI(){this.scheduleLegend(),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`?n.DARK_THEME:e===`light`?n.LIGHT_THEME:typeof e==`object`?e:n.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}};function ei(t,i){let a=e=>{let t=(0,r.sourceParam)(e.descriptor);return t&&(0,n.parseIndicatorSource)(e.params[t])?.instanceId||null},o=new Set([t]);for(let e=!0;e;){e=!1;for(let t of i){let n=a(t);n&&o.has(n)&&!o.has(t.instanceId)&&(o.add(t.instanceId),e=!0)}}let s=[];for(let t of i){if(o.has(t.instanceId))continue;let r=e.C(t.id,t.params,t.descriptor.defaultConfig,t.descriptor.shortName);for(let e of t.descriptor.plots??[])s.push({value:(0,n.indicatorSource)(t.instanceId,e.key),label:`${r}: ${e.title}`})}return s}function ti(){try{return typeof localStorage<`u`?localStorage:null}catch{return null}}var ni=10,ri=5*6e4,ii=864e5;function ai(e,t){if(e.length===0)return null;let r=t&&(0,n.isValidTimeZone)(t)?t:null,i=e=>{let t=e<1e11?e*1e3:e;return Math.floor((t+(r?(0,n.zoneOffsetMinutes)(r,t)*6e4:0))/ii)},a=e[e.length-1],o=i(a.time),s=e.length-1;for(;s>0&&i(e[s-1].time)===o;)s--;let c=-1/0,l=1/0,u=0;for(let t=s;t<e.length;t++)c=Math.max(c,e[t].high),l=Math.min(l,e[t].low),u+=e[t].volume??0;return{open:e[s].open,high:c,low:l,close:a.close,volume:u,prevClose:s>0?e[s-1].close:void 0}}function oi(e,t){let n=e/6e4,[r,i]=Math.abs(n)<60?[Math.round(n)||Math.sign(n)||1,`minute`]:Math.abs(n)<1440?[Math.round(n/60),`hour`]:[Math.round(n/1440),`day`];try{return new Intl.RelativeTimeFormat(t,{numeric:`auto`}).format(r,i)}catch{return new Intl.RelativeTimeFormat(`en`,{numeric:`auto`}).format(r,i)}}function si(e,t){try{return new Intl.NumberFormat(t,{notation:`compact`,maximumFractionDigits:2}).format(e)}catch{return String(e)}}function ci(e,t){let n=e?.sessions??[];if(n.length===0)return;let r;try{let e=new Intl.DateTimeFormat(t,{weekday:`short`,timeZone:`UTC`});r=Array.from({length:7},(t,n)=>e.format(Date.UTC(1970,0,4+n)))}catch{r=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`]}let i=e=>{let t=[...new Set((e??[]).filter(e=>Number.isInteger(e)&&e>=0&&e<=6))].sort((e,t)=>e-t);return t.length===0||t.length===7?``:t.every((e,n)=>n===0||e===t[n-1]+1)&&t.length>2?`${r[t[0]]}–${r[t[t.length-1]]}`:t.map(e=>r[e]).join(`, `)};return n.map(e=>[`${e.start}–${e.end}`,i(e.days)].filter(Boolean).join(` `)).join(`, `)}function li(e){return!!e&&/^(ar|he|iw|fa|ur|ps|yi|dv|ckb|sd|ug)(-|$)/i.test(e)}var ui={symbol:!1,interval:!1,crosshair:!0,time:!1,drawings:!1,replay:!1},di=[`symbol`,`interval`,`crosshair`,`time`,`drawings`,`replay`],$={"1x1":{cols:1,rows:1},"1x2":{cols:2,rows:1},"2x1":{cols:1,rows:2},"2x2":{cols:2,rows:2},"1x3":{cols:3,rows:1},"3x1":{cols:1,rows:3},"2x3":{cols:3,rows:2},"3x2":{cols:2,rows:3}};function fi(e){return typeof e==`string`&&Object.prototype.hasOwnProperty.call($,e)}function pi(e){return JSON.parse(JSON.stringify(e))}function mi(e,t,n=16){let r=(20-2*(e-1))/e,i=(20-2*(t-1))/t,a=``;for(let n=0;n<t;n++)for(let t=0;t<e;t++)a+=`<rect x="${2+t*(r+2)}" y="${2+n*(i+2)}" width="${r}" height="${i}" rx="1"/>`;return`<svg width="${n}" height="${n}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" aria-hidden="true">${a}</svg>`}function hi(e){if(typeof e!=`object`||!e)return null;let t=e;if(t.v!==1||t.kind!==`grid`||!fi(t.layout)||!Array.isArray(t.cells))return null;let n=t.cells.map(Xn);if(n.some(e=>e===null))return null;let r=typeof t.sync==`object`&&t.sync!==null?t.sync:{},i={...ui};for(let e of di)typeof r[e]==`boolean`&&(i[e]=r[e]);let a=typeof t.active==`number`&&Number.isInteger(t.active)?t.active:0;return{v:1,kind:`grid`,layout:t.layout,sync:i,active:a,cells:n}}var gi=class{root;cellsEl;cells=[];layout;sync;active=0;hovered=null;relayDepth=0;uiTheme=null;parked=new Map;drawingFrame=0;drawingSource=null;layoutButtons=new Map;syncButtons=new Map;layoutsButton=null;session=null;layoutsUI=null;t;destroyed=!1;unregisterKeys=()=>{};onKeyDown=e=>{!(e.ctrlKey||e.metaKey)||e.altKey||e.shiftKey||e.key!==`s`&&e.key!==`S`||!this.layoutsUI||K()||!G(this.root,!0)||(e.preventDefault(),this.layoutsUI.save())};constructor(e,n={}){this.options=n,this.layout=fi(n.layout)?n.layout:`1x2`,this.sync={...ui,...n.sync},this.t=t.n(t.o(n.widget?.locale,n.widget?.messages)),g(),this.root=document.createElement(`div`),this.root.className=`tcw-root tcw-grid`,this.root.dataset.tcwTheme=n.widget?.theme===`light`?`light`:`dark`,P(this.root,N(n.widget?.ui),{variables:n.widget?.ui!==void 0}),n.bar!==!1&&this.root.appendChild(this.buildBar()),this.cellsEl=document.createElement(`div`),this.cellsEl.className=`tcw-grid-cells`,this.root.appendChild(this.cellsEl),e.appendChild(this.root),this.applyShape();for(let e=0;e<this.shapeCount();e++)this.cells.push(this.createCell(e));this.markActive();let r=this.cells[0]?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;r&&(this.root.dataset.tcwTheme=r),n.layouts!==!1&&this.setupLayouts(n.layouts===!0||n.layouts===void 0?{}:n.layouts),this.unregisterKeys=Kn(this.root),document.addEventListener(`keydown`,this.onKeyDown)}get relaying(){return this.relayDepth>0}quietly(e){this.relayDepth++;try{return e()}finally{this.relayDepth--}}getWidget(e){return this.cells[e]?.widget??null}getWidgets(){return this.cells.map(e=>e.widget)}getActiveIndex(){return this.active}getActiveWidget(){return this.cells[this.active].widget}setActive(e){e<0||e>=this.cells.length||e===this.active||(this.active=e,this.markActive(),this.options.onActiveChange?.(e,this.cells[e].widget),this.session?.changed())}getLayout(){return this.layout}setLayout(e){if(e===this.layout||!fi(e))return;this.layout=e;let t=this.shapeCount();for(;this.cells.length>t;){let e=this.cells.length-1,t=this.cells.pop();this.parked.set(e,t.widget.captureLayout()),this.destroyCell(t)}this.applyShape();for(let e=this.cells.length;e<t;e++){let t=this.createCell(e);this.cells.push(t),this.unpark(e,t)}this.active>=t&&(this.active=0,this.options.onActiveChange?.(0,this.cells[0].widget)),this.markActive(),this.renderBar(),this.session?.changed()}getSync(){return{...this.sync}}setUI(e){let t=N(e);P(this.root,t);for(let e of this.cells)e.widget.setUI(t);this.uiTheme=t}getUI(){return N(this.uiTheme??this.options.widget?.ui)}setSync(e){let t=this.sync;if(this.sync={...this.sync,...e},t.crosshair&&!this.sync.crosshair)for(let e of this.cells)e.widget.getChart().setCrosshairTime(null);let n=this.cells[this.active];if(n&&!this.relaying){let e=n.widget.getSymbol(),r=n.widget.getTimeframe();!t.symbol&&this.sync.symbol&&this.relay(n,t=>void t.setSymbol(e)),!t.interval&&this.sync.interval&&this.relay(n,e=>void e.setTimeframe(r)),!t.drawings&&this.sync.drawings&&this.mergeDrawings()}this.renderBar(),this.session?.changed()}setTheme(e){for(let t of this.cells)t.widget.setTheme(e);this.followTheme()}getLayoutSession(){return this.session}captureLayout(){let e=[...this.parked.entries()].sort(([e],[t])=>e-t).map(([,e])=>e);return{v:1,kind:`grid`,layout:this.layout,sync:{...this.sync},active:this.active,cells:[...this.cells.map(e=>e.widget.captureLayout()),...e]}}async restoreLayout(e){this.relayDepth++;let t;try{this.parked.clear(),this.setLayout(e.layout),this.sync={...e.sync},this.renderBar();let n=this.cells.length;e.cells.slice(n).forEach((e,t)=>this.parked.set(n+t,e)),t=await Promise.allSettled(this.cells.map((t,n)=>e.cells[n]?t.widget.restoreLayout(e.cells[n]):Promise.resolve()))}finally{this.relayDepth--}if(this.destroyed)return;this.setActive(Math.min(Math.max(0,e.active),this.cells.length-1));let n=t.find(e=>e.status===`rejected`);if(n)throw n.reason}getLayoutContent(){return JSON.stringify(this.captureLayout())}async applyLayoutContent(e){let t=hi(Zn(e));return t?(await this.restoreLayout(t),!0):!1}destroy(){if(!this.destroyed){this.destroyed=!0,document.removeEventListener(`keydown`,this.onKeyDown),this.unregisterKeys(),this.drawingFrame&&cancelAnimationFrame(this.drawingFrame),this.session?.destroy(),this.layoutsUI?.destroy();for(let e of this.cells)this.destroyCell(e);this.cells=[],this.root.remove(),_()}}shapeCount(){let{cols:e,rows:t}=$[this.layout];return e*t}applyShape(){let{cols:e,rows:t}=$[this.layout];this.cellsEl.style.gridTemplateColumns=`repeat(${e}, minmax(0, 1fr))`,this.cellsEl.style.gridTemplateRows=`repeat(${t}, minmax(0, 1fr))`}createCell(e){let n=document.createElement(`div`);n.className=`tcw-grid-cell`,n.setAttribute(`role`,`region`),n.setAttribute(`aria-label`,t.r(this.t(`grid.chart`),{n:e+1})),this.cellsEl.appendChild(n);let r=this.options.widget??{},i=this.options.cells?.[e]??{},a=this.cells[this.active]?.widget,o={},s=new $r(n,{...r,...i,...a&&this.sync.symbol?{symbol:a.getSymbol()}:{},...a&&this.sync.interval?{timeframe:a.getTimeframe()}:{},...this.options.adapter&&!i.adapter?{adapter:this.options.adapter(e)}:{},...this.uiTheme?{ui:this.uiTheme}:{},layouts:!1,onSymbolChange:e=>{i.onSymbolChange?.(e),r.onSymbolChange?.(e),this.sync.symbol&&this.relay(o,t=>void t.setSymbol(e)),this.session?.changed()},onTimeframeChange:e=>{i.onTimeframeChange?.(e),r.onTimeframeChange?.(e),this.sync.interval&&this.relay(o,t=>void t.setTimeframe(e)),this.session?.changed()}});return o.el=n,o.widget=s,this.wireCell(o),n.addEventListener(`pointerdown`,()=>this.setActive(this.cells.indexOf(o)),!0),n.addEventListener(`pointerenter`,()=>{this.hovered=o}),n.addEventListener(`pointerleave`,()=>{this.hovered===o&&(this.hovered=null)}),this.options.onChartAdd?.(s,e),o}wireCell(e){let t=e.widget.getChart(),n=()=>this.cells.filter(t=>t!==e);t.on(`crosshairMove`,e=>{let t=e.payload.bar?.time;if(!(!this.sync.crosshair||t===void 0))for(let e of n())e.widget.getChart().setCrosshairTime(t)}),t.on(`crosshairLeave`,()=>{if(this.sync.crosshair)for(let e of n())e.widget.getChart().setCrosshairTime(null)}),t.on(`visibleRangeChange`,n=>{if(!this.sync.time||this.relaying||(this.hovered??this.cells[this.active])!==e)return;let{from:r,to:i}=n.payload,a=t.getData(),o=a[r]?.time,s=a[i]?.time;o===void 0||s===void 0||this.relay(e,e=>e.getChart().setVisibleRange(o,s))});for(let n of[`drawingCreate`,`drawingUpdate`,`drawingRemove`])t.on(n,()=>{this.sync.drawings&&!this.relaying&&this.copyDrawingsSoon(e)});t.on(`replayStep`,t=>{if(!this.sync.replay||this.relaying)return;let{until:n}=t.payload;this.relay(e,e=>{let t=e.getChart();if(t.isReplayActive()){t.replaySeekToTime(n);return}let r=_i(t.getData(),n);r>=0&&t.replayStart({startIndex:r,paused:!0})})}),t.on(`replayState`,t=>{!this.sync.replay||this.relaying||t.payload.state!==`stopped`||this.relay(e,e=>{e.getChart().isReplayActive()&&e.getChart().replayStop()})}),t.on(`stateChange`,()=>this.session?.changed()),t.on(`themeChange`,()=>{this.relaying||this.followTheme(e)})}destroyCell(e){this.hovered===e&&(this.hovered=null),this.drawingSource===e&&(this.drawingSource=null),this.quietly(()=>e.widget.destroy()),e.el.remove()}relay(e,t){this.relaying||this.quietly(()=>{for(let n of this.cells)n!==e&&t(n.widget)})}unpark(e,t){let n=this.parked.get(e);if(!n)return;this.parked.delete(e);let r=this.cells[this.active]?.widget,i={...n,...r&&this.sync.symbol?{symbol:r.getSymbol()}:{},...r&&this.sync.interval?{timeframe:r.getTimeframe()}:{}};this.relayDepth++,t.widget.restoreLayout(i).catch(()=>t.widget.toast(this.t(`layouts.openFailed`),`error`)).finally(()=>{this.relayDepth--})}copyDrawingsSoon(e){this.drawingSource=e,!this.drawingFrame&&(this.drawingFrame=requestAnimationFrame(()=>{this.drawingFrame=0;let e=this.drawingSource;this.drawingSource=null,e&&!this.destroyed&&!this.relaying&&this.copyDrawings(e)}))}copyDrawings(e){let t=e.widget.getSymbol(),n=e.widget.getChart().getDrawings();this.quietly(()=>{for(let r of this.cells)r!==e&&r.widget.getSymbol()===t&&r.widget.getChart().setDrawings(pi(n))})}mergeDrawings(){let e=new Map;for(let t of this.cells)e.set(t.widget.getSymbol(),[...e.get(t.widget.getSymbol())??[],t]);this.quietly(()=>{for(let t of e.values()){if(t.length<2)continue;let e=new Map;for(let n of t)for(let t of n.widget.getChart().getDrawings())e.has(t.id)||e.set(t.id,t);let n=[...e.values()];for(let e of t)e.widget.getChart().setDrawings(pi(n))}})}followTheme(e=this.cells[this.active]){let t=e?.el.querySelector(`.tcw-root`)?.dataset.tcwTheme;t&&(this.root.dataset.tcwTheme=t,this.quietly(()=>{for(let n of this.cells)n!==e&&n.el.querySelector(`.tcw-root`)?.dataset.tcwTheme!==t&&n.widget.setTheme(t)}))}markActive(){this.cells.forEach((e,t)=>e.el.classList.toggle(`tcw-grid-cell-active`,t===this.active&&this.cells.length>1))}buildBar(){let e=document.createElement(`div`);e.className=`tcw-grid-bar`,e.setAttribute(`role`,`toolbar`),e.setAttribute(`aria-label`,this.t(`grid.bar`));let n=document.createElement(`div`);n.className=`tcw-grid-group`,n.setAttribute(`role`,`group`),n.setAttribute(`aria-label`,this.t(`grid.layout`));let r=this.options.layoutChoices?.filter(fi)??Object.keys($);for(let e of r){let{cols:r,rows:i}=$[e],a=r*i===1?this.t(`grid.single`):t.r(this.t(`grid.layoutOption`),{count:r*i,cols:r,rows:i}),o=document.createElement(`button`);o.type=`button`,o.className=`tcw-btn-icon`,o.title=a,o.setAttribute(`aria-label`,a),o.innerHTML=mi(r,i),o.addEventListener(`click`,()=>this.setLayout(e)),this.layoutButtons.set(e,o),n.appendChild(o)}let i=document.createElement(`div`);i.className=`tcw-grid-group`,i.setAttribute(`role`,`group`),i.setAttribute(`aria-label`,this.t(`grid.sync`));let a=document.createElement(`span`);a.className=`tcw-grid-label`,a.innerHTML=`${S(`link`,13)}<span>${w(this.t(`grid.sync`))}</span>`,i.appendChild(a);for(let e of di){let t=document.createElement(`button`);t.type=`button`,t.className=`tcw-btn tcw-grid-sync`,t.textContent=this.t(`grid.sync.${e}`),t.title=this.t(`grid.sync.${e}.hint`),t.addEventListener(`click`,()=>this.setSync({[e]:!this.sync[e]})),this.syncButtons.set(e,t),i.appendChild(t)}let o=document.createElement(`span`);return o.className=`tcw-toolbar-spacer`,e.append(n,this.sep(),i,o),this.options.layouts!==!1&&(this.layoutsButton=document.createElement(`button`),this.layoutsButton.type=`button`,this.layoutsButton.className=`tcw-dropdown-trigger tcw-layouts-btn`,this.layoutsButton.setAttribute(`aria-haspopup`,`menu`),this.layoutsButton.addEventListener(`click`,()=>{this.layoutsButton&&this.layoutsUI?.openMenu(this.layoutsButton)}),e.appendChild(this.layoutsButton)),this.renderBar(),e}sep(){let e=document.createElement(`span`);return e.className=`tcw-toolbar-sep`,e}renderBar(){for(let[e,t]of this.layoutButtons){let n=e===this.layout;t.classList.toggle(`tcw-active`,n),t.setAttribute(`aria-pressed`,String(n))}for(let[e,t]of this.syncButtons)t.classList.toggle(`tcw-active`,this.sync[e]),t.setAttribute(`aria-pressed`,String(this.sync[e]));this.renderLayoutsButton()}renderLayoutsButton(){let e=this.layoutsButton;if(!e)return;let t=this.session?.current()?.name??this.t(`layouts.unnamed`),n=this.session?.isDirty()??!1,r=`${this.t(`toolbar.layouts`)}: ${t}${n?` (${this.t(`layouts.unsavedChanges`)})`:``}`;e.innerHTML=`${S(`save`,14)}<span class="tcw-layouts-label">${w(t)}</span>`+(n?`<span class="tcw-layouts-dirty" aria-hidden="true"></span>`:``)+S(`chevronDown`,12),e.title=r,e.setAttribute(`aria-label`,r)}setupLayouts(t){let n=new e.t(t.storage??e.i(`tcw:grid-layouts:`),{capture:()=>{let e=this.cells[this.active].widget;return{content:this.getLayoutContent(),symbol:e.getSymbol(),timeframe:e.getTimeframe()}},apply:async e=>{if(!await this.applyLayoutContent(e.content))throw Error(`Not a grid layout`)}},{autoSave:t.autoSave,debounceMs:t.debounceMs,kind:`grid`,onChange:()=>this.renderLayoutsButton(),onError:()=>this.toast(this.t(`layouts.saveFailed`),`error`)});this.session=n,this.layoutsUI=new kn(n,{root:this.root,t:this.t,toast:(e,t)=>this.toast(e,t),formatTime:e=>{let{date:t,time:n}=q(e,null);return`${t} ${n}`}}),this.renderLayoutsButton(),t.openLast&&n.list().then(([e])=>e&&!this.destroyed?this.layoutsUI?.open(e.id):void 0,()=>void 0)}toast(e,t=`info`){this.cells[this.active]?.widget.toast(e,t)}};function _i(e,t){let n=-1;for(let r=0;r<e.length&&e[r].time<t;r++)n=r;return n}exports.CHART_TYPE_ICONS=b,exports.ChartWidget=$r,exports.ChartWidgetGrid=gi,exports.DEFAULT_GRID_SYNC=ui,exports.DRAWING_TOOL_ICONS=y,exports.EN_MESSAGES=t.c,exports.GRID_SHAPES=$,exports.LayoutSession=e.t,exports.MAX_LAYOUT_NAME=e.n,exports.UI_ICONS=v,exports.VI_MESSAGES=t.s,exports.WIDGET_UI_PRESETS=vt,exports.applyWidgetUI=P,exports.cleanLayoutName=e.r,exports.createChartTypeIcon=ce,exports.createIcon=S,exports.createToolIcon=C,exports.findWidgetLocale=t.i,exports.iconSvg=x,exports.localStorageLayouts=e.i,exports.memoryLayouts=e.a,exports.readGridLayout=hi,exports.readWatchlists=O,exports.readWidgetLayout=Xn,exports.registerWidgetLocale=t.a,exports.resolveWidgetUI=N,exports.widgetUIVariables=Tt;
|
|
4304
4304
|
//# sourceMappingURL=index.cjs.map
|