@barchart/chart-lib 2.366.0 → 2.366.1
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.
- chart-lib/barchart.chart.js +1 -1
- chart-lib/package.json +1 -1
chart-lib/barchart.chart.js
CHANGED
|
@@ -6,4 +6,4 @@ return new Date(NaN);var n=function(e){var t,i={},s=Bc.dateTimePattern.exec(e);s
|
|
|
6
6
|
return new Date(NaN);if(a){var l,c=a.getTime(),u=0;if(n.time&&(u=function(e){var t,i,s;if(t=Bc.HH.exec(e))return Yc(i=parseFloat(t[1].replace(",",".")))?i%24*Vc:NaN;if(t=Bc.HHMM.exec(e))return Yc(i=parseInt(t[1],10),s=parseFloat(t[2].replace(",",".")))?i%24*Vc+s*Hc:NaN;if(t=Bc.HHMMSS.exec(e)){i=parseInt(t[1],10),s=parseInt(t[2],10);var n=parseFloat(t[3].replace(",","."));return Yc(i,s,n)?i%24*Vc+s*Hc+1e3*n:NaN}return null}(n.time),isNaN(u)))/* @__PURE__ */
|
|
7
7
|
return new Date(NaN);if(n.timeZone||i.timeZone){if(l=xc(n.timeZone||i.timeZone,new Date(c+u)),isNaN(l))/* @__PURE__ */
|
|
8
8
|
return new Date(NaN)}else l=Rc(new Date(c+u)),l=Rc(new Date(c+u+l));return new Date(c+u+l)}/* @__PURE__ */
|
|
9
|
-
return new Date(NaN)}function kc(e,t,i){t=t||0,i=i||0;var s=/* @__PURE__ */new Date(0);s.setUTCFullYear(e,0,4);var n=7*t+i+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+n),s}var Wc=[31,28,31,30,31,30,31,31,30,31,30,31],Uc=[31,29,31,30,31,30,31,31,30,31,30,31];function $c(e){return e%400==0||e%4==0&&e%100!=0}function Gc(e,t,i){if(t<0||t>11)return!1;if(null!=i){if(i<1)return!1;var s=$c(e);if(s&&i>Uc[t])return!1;if(!s&&i>Wc[t])return!1}return!0}function zc(e,t,i){return!(t<0||t>52)&&(null==i||!(i<0||i>6))}function Yc(e,t,i){return(null==e||!(e<0||e>=25))&&((null==t||!(t<0||t>=60))&&(null==i||!(i<0||i>=60)))}var jc,Kc,qc={exports:{}},Xc={exports:{}};function Zc(){return jc||(jc=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(null==e)throw new TypeError("assign requires that input parameter not be null or undefined");for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.exports=t.default}(Xc,Xc.exports)),Xc.exports}function Jc(){return Kc||(Kc=1,function(e,t){var i=(mc||(mc=1,function(e){e.exports=function(e){return e&&e.__esModule?e:{default:e}},e.exports.__esModule=!0,e.exports.default=e.exports}(gc)),gc.exports).default;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,s.default)({},e)};var s=i(/* @__PURE__ */Zc());e.exports=t.default}(qc,qc.exports)),qc.exports}const Qc=/* @__PURE__ */He(/* @__PURE__ */Jc());const eu=[Ka.Open,Ka.High,Ka.Low,Ka.Last,Ka.Close,Ka.TradingDay,Ka.PreviousClose,Ka.PreviousHigh,Ka.PreviousLow,Ka.PreviousOpen,Ka.Volume,Ka.Change,Ka.PercentChange,Ka.YearHigh,Ka.YearLow,Ka.WeekPreviousClose,Ka.WeekPreviousHigh,Ka.WeekPreviousLow,Ka.MonthPreviousClose,Ka.MonthPreviousHigh,Ka.MonthPreviousLow];class tu{recordCache;translateSymbolBack;_subject;constructor(){this.recordCache=/* @__PURE__ */new Map,this.translateSymbolBack=/* @__PURE__ */new Map}get subject(){if(!ie(this._subject)){const t=dc(Math.max(gs.MINIMUM_THROTTLE,Gv().config.throttleMillis||0)),i=dc(gs.BACKGROUND_TAB_THROTTLE),s=()=>globalThis.document?.hidden?i:t;this._subject=(new ql).pipe((e=s,zl(function(t,i){var s=null,n=null,r=function(){null==n||n.unsubscribe();var t=s;s=[],t&&i.next(t),ac(e()).subscribe(n=Yl(i,r,Rl))};r(),t.subscribe(Yl(i,function(e){return null==s?void 0:s.push(e)},function(){s&&i.next(s),i.complete()},void 0,function(){return s=n=null}))})),pc(e=>e.length>0))}var e;return this._subject}addRecordForSymbol(e,t){const i=Ws(e);i!==e&&this.translateSymbolBack.set(i,e),this.recordCache.set(e,t)}removeRecordForSymbol(e){this.recordCache.delete(e);const t=Ws(e);this.translateSymbolBack.has(t)&&this.translateSymbolBack.delete(t)}findRecordForSymbol(e){const t=this.translateSymbolBack.has(e)?this.translateSymbolBack.get(e):e;return this.recordCache.get(t)}getSupportedFields(){return eu}makeAndCacheRecord(e,t){if(e===gs.PLACEHOLDER_SYMBOL_NAME)return new el(gs.PLACEHOLDER_SYMBOL_NAME);if(this.recordCache.has(e))return this.recordCache.get(e);const i=t(e),s=this.getSupportedFields();return i.addFields(...s),this.addRecordForSymbol(e,i),i.ready().then(e=>{this.postInit(e,i)}),i}evictUnused(e,t){for(const[i,s]of this.recordCache)e.has(s)||(t(s),this.removeRecordForSymbol(i))}postInit(e,t){}}class iu extends tu{getRecord(e){return this.makeAndCacheRecord(e,()=>new cl(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}}class su extends tu{getRecord(e){return this.makeAndCacheRecord(e,()=>new ll(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}}class nu extends tu{constructor(){super(),this.onMarketUpdate=this.onMarketUpdate.bind(this)}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),Gv().connection.off("marketUpdate",this.onMarketUpdate,e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new al(e))}postInit(e,t){e&&Gv().connection.on("marketUpdate",this.onMarketUpdate,t.translated)}onMarketUpdate(e){if(e.type===gs.REALTIME_INITIAL_QUOTE){const t=this.updateFromQuote(e,!0);this.subject.next({topic:qa.RT_QUOTE,data:e,updated:t})}else if(e.type===gs.REALTIME_TRADE){const t=Gv().connection.getMarketState().getQuote(e.symbol),i=this.updateFromQuote(t);this.subject.next({topic:qa.RT_TRADE,data:e,updated:i}),e.symbol===gs.DEBUG_SYMBOL&&console.log(`Trade\nSymbol: ${e.symbol} \t%cPrice: ${e.tradePrice} \t%cSize: ${e.tradeSize} \t%cTime: ${Si(e.time,gs.DEBUG_TIME_FORMAT)} \t%cSession: ${e.session}`,"color:#0f0","color:#a7a","color:#f96","color:#bee")}else if(e.type===gs.REALTIME_VOLUME){const t=this.updateFromVolume(e);0!==t&&(this.subject.next({topic:qa.RT_VOLUME,data:e,updated:t}),e.symbol===gs.DEBUG_SYMBOL&&console.log(`Volume\n Symbol: ${e.symbol} \t%cValue: ${e.value} \t%cSession: ${e.session}`,"color:#a7a","color:#bee"))}}updateFromQuote(e,t=!1){const i=this.findRecordForSymbol(e.symbol);i.resetUpdated(),i.update(Ka.Open,e.openPrice),i.update(Ka.High,e.highPrice),i.update(Ka.Low,e.lowPrice),i.update(Ka.Last,e.lastPrice),i.update(Ka.Close,e.lastPrice);const s=(e,t)=>{ie(t)&&i.update(e,t)};return s(Ka.Volume,e.volume),i.update(Ka.PreviousClose,e.previousPrice),t&&(s(Ka.PreviousOpen,e.previousOpenPrice),s(Ka.PreviousHigh,e.previousHighPrice),s(Ka.PreviousLow,e.previousLowPrice)),i.computeWellKnown(),i.updated}updateFromVolume(e){const t=this.findRecordForSymbol(e.symbol);return t.resetUpdated(),t.update(Ka.Volume,e.value),t.updated}}class ru extends tu{localTimeZone;constructor(){super(),this.localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone}get feed(){return Gv()}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),this.feed.unsubscribe(e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new al(e))}postInit(e,t){e&&this.feed.subscribe(t.translated)}onSnapshot(e,t){const i=this.findRecordForSymbol(t),s=Gv().metaDataSource.getMetaData(t);if(!s.isReady)return;const n=(e,t)=>{if(te(t)){const n=s.asPrice(t);return i.update(e,n),n}};i.resetUpdated();const r=n(Ka.Open,e.open?.price),o=n(Ka.High,e.high?.price),a=n(Ka.Low,e.low?.price),l=n(Ka.Last,e.last?.price);if(te(n(Ka.Close,e.close?.price))||te(n(Ka.Close,e.settlement?.price))||n(Ka.Close,e.last?.price),te(e.instrumentStatus?.tradeDate)){const t=e.instrumentStatus.tradeDate%100;i.update(Ka.TradingDay,t)}te(e.volume?.volume)&&i.update(Ka.Volume,s.asQuantity(e.volume.volume));const c=this.toExchangeTime(e.transactionTime,s.timeZone);te(n(Ka.PreviousClose,e.prevClose?.price))||n(Ka.PreviousClose,e.previousSession?.settlement?.price),n(Ka.PreviousOpen,e.previousSession?.open?.price),n(Ka.PreviousHigh,e.previousSession?.high?.price),n(Ka.PreviousLow,e.previousSession?.low?.price),n(Ka.YearHigh,e.yearHigh?.price),n(Ka.YearLow,e.yearLow?.price),i.computeWellKnown();const u={topic:"rt.quote",data:{symbol:t,openPrice:r,highPrice:o,lowPrice:a,lastPrice:l,tradeTime:c},updated:i.updated};this.subject.next(u)}skip(e){return void 0===e||e.blockTrade||e.doesNotUpdateLast||e.doesNotUpdateVolume}asDate(e){return!te(e)||e.isZero()?null:new Date(e.div(1e6).toNumber())}toExchangeTime(e,t){const i=this.asDate(e);if(null===i)return null;const s=function(e,t,i){if("string"==typeof e&&!e.match(Nc)){var s=Qc(i);return s.timeZone=t,Fc(e,s)}var n=Fc(e,i),r=Lc(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()).getTime(),o=xc(t,new Date(r));return new Date(r+o)}(i,this.localTimeZone);return function(e,t,i){var s=Fc(e,i),n=xc(t,s,!0),r=new Date(s.getTime()-n),o=/* @__PURE__ */new Date(0);return o.setFullYear(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),o.setHours(r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()),o}(s,t)}onUpdate(e,t){if(!this.recordCache.has(t))return void Hv(`[OpenFeed] update for unsubscribed symbol: ${t}`,"warn");const i=Gv().metaDataSource.getMetaData(t);if(!i.isReady)return;const s=this.toExchangeTime(e.transactionTime,i.timeZone);if(e.trades?.trades)for(const{trade:n}of e.trades.trades){if(this.skip(n))continue;const e=i.asPrice(n.price);if(null===e)continue;const r=i.asQuantity(n.quantity),o=this.toExchangeTime(n.transactionTime,i.timeZone),a=this.findRecordForSymbol(t),l=["High","Low","Volume","TradingDay"].map(e=>Ka[e]),[c,u,h,d]=l.map(e=>a.getValue(e));(!te(u)||e<u)&&a.update(Ka.Low,e),(!te(c)||e>c)&&a.update(Ka.High,e),a.update(Ka.Last,e),a.update(Ka.Close,e),a.update(Ka.Volume,(te(h)?h:0)+r),a.computeWellKnown();const p={data:{symbol:t,tradePrice:e,tradeSize:r,session:n.session,time:o??s,tradingDay:d},topic:"rt.trade",updated:a.updated};this.subject.next(p)}}}function ou(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return i.length>=t?e.apply(null,i.slice(0,t).reverse()):function(){for(var s=arguments.length,n=new Array(s),r=0;r<s;r++)n[r]=arguments[r];return ou(e,t,i.concat(n))}}const au=ou(Xe,2),lu=ou(ot,2),cu=ou(Ze,2),uu=ou(function(e,t){return Ke(2,arguments),Ze(e,3*je(t))},2),hu=ou(at,2),du=ou(function(e,t){return Ke(2,arguments),Xe(e,7*je(t))},2),pu=ou(lt,2),fu=ou(Si,2),mu=ou(Di,2);function gu(e,t){switch(e){case a.Tick:return hu(t);case a.Intraday:return lu(t);case a.Day:return au(t);case a.Week:return du(t);case a.Month:return cu(t);case a.Quarter:return uu(t);case a.Year:return pu(t);default:throw new Error(`Unexpected aggregation unit ${a[e]}`)}}function yu(e,t){return t.getFullYear()-1-(t.getFullYear()-1)%e}function Au(e){return yu(10,e)}function Su(e,t){return yu(100,e)===Au(t)}function Tu(e){return new Date(e*gs.OPTIONS_DATA_INCREMENT+gs.OPTIONS_DATA_BASE)}function vu(e,t=gs.ZERO_DATE){const i=/* @__PURE__ */new Date(`${e}T00:00:00`);return ht(i)?i:t}function Pu(e){return e.size-1}class Cu{container;supportsChunks=!0;retryCountForChunk=1;constructor(){this.container=null}get base(){return this.container}ready(){return Promise.resolve()}processRetrieved(){}getFirstDate(e){return this.base.getTimeData()[0]}getLastDate(){return this.base.getLastDataPoint(Ka.DateTime)}prepend(e){this.base.prepend(e),this.processRetrieved()}append(e){this.base.append(e),this.processRetrieved()}}class bu extends Cu{constructor(e){super(),this.container=e,this.retryCountForChunk=gs.FETCH_TICK_CHUNK_RETRY_COUNT}getFirstDate(e){const t=super.getFirstDate(0);return e>0&&e<this.retryCountForChunk?At(Di(t,e)):t}process(e){const t=this.container,i=t.size>0?t.getLastDataPoint(Ka.Last):null,s=t.getLastDataPoint(Ka.DateTime);let n=e.time;return void 0!==s&&n<=s&&(n=Qe(s,1)),t.addDataPoint(Ka.DateTime,n),t.addDataPoint(Ka.Last,e.tradePrice),t.addDataPoint(Ka.TradeSize,e.tradeSize),t.addDataPoint(Ka.Change,ie(i)?e.tradePrice-i:null),t.hasField(Ka.TradingDay)&&t.addDataPoint(Ka.TradingDay,e.tradingDay),{isUpdate:!1,time:n.getTime(),index:Pu(t)}}}class Eu extends Cu{agg;durationAdd;constructor(e,t){super(),this.agg=t,this.container=e,this.durationAdd=function(e){switch(e.unit){case a.Tick:case a.Intraday:case a.Day:return gu(e.unit,e.size);case a.Week:case a.Month:case a.Quarter:case a.Year:return gu(e.unit,1);default:throw new Error(`Unexpected aggregation unit ${a[e.unit]}`)}}(t)}isSameBar(e,t){switch(this.agg.unit){case a.Tick:case a.Intraday:case a.Day:return bi(t,this.durationAdd(e));case a.Week:return Mi(e,t);case a.Month:return _i(e,t);case a.Quarter:return xi(e,t);case a.Year:return Ii(e,t);default:throw new Error(`Unexpected aggregation unit ${a[this.agg.unit]}`)}}fixupTimeBasedAggregationTimestamp(e){return e}isCorrection(e,t){const i=bi(t,e);return i&&Hv("Currently not handling data corrections (updates of the past historical data)","error"),i}computeNextStamp(e,t){if(this.isCorrection(e,t))return null;let i=e;for(;!this.isSameBar(i,t);)i=this.durationAdd(i);return i}isUpdate(e,t,i,s){return function(e,t){Ke(2,arguments);var i=qe(e),s=qe(t);return i.getTime()===s.getTime()}(i,e)}getPosition(e){if(0===this.container.size){const t=this.fixupTimeBasedAggregationTimestamp(e.time);return{lastTimestamp:null,newTimestamp:t,nextTimestamp:t,isUpdate:!1}}const t=this.container.getLastDataPoint(Ka.DateTime),i=e.time,s=this.computeNextStamp(t,i);if(null===s)return null;const n=this.isUpdate(t,i,s,e);return null===n?null:{lastTimestamp:t,newTimestamp:i,nextTimestamp:s,isUpdate:n}}createBar(e,t,i,s,n,r,o){const a=this.container,l=a.size>0?a.getLastDataPoint(Ka.Close):null;a.addDataPoint(Ka.DateTime,r),a.addDataPoint(Ka.Open,e),a.addDataPoint(Ka.High,t),a.addDataPoint(Ka.Low,i),a.addDataPoint(Ka.Close,s),a.addDataPoint(Ka.Change,ie(l)?s-l:null),a.addDataPoint(Ka.Volume,n),a.hasField(Ka.OpenInterest)&&a.addDataPoint(Ka.OpenInterest,null),a.hasField(Ka.TradingDay)&&a.addDataPoint(Ka.TradingDay,o??null)}addBar(e,t){const{nextTimestamp:i}=t,{tradePrice:s,tradingDay:n}=e;return this.createBar(s,s,s,s,e.tradeSize,i,n),{isUpdate:!1,time:i.getTime(),index:Pu(this.container)}}updateLastBar(e,t,i,s){const n=this.container,r=e=>n.getLastDataPoint(e);if(ie(e)&&e>r(Ka.High)&&n.setLastDataPoint(Ka.High,e),ie(t)&&t<r(Ka.Low)&&n.setLastDataPoint(Ka.Low,t),ie(i)){n.setLastDataPoint(Ka.Close,i);const e=n.getData(Ka.Close)[n.size-2];n.setLastDataPoint(Ka.Change,i-e)}if(ie(s)){const e=n.getLastDataPoint(Ka.Volume)+s;n.setLastDataPoint(Ka.Volume,e)}}changeLastBar(e,t){const{lastTimestamp:i}=t,s=e.tradePrice;return this.updateLastBar(s,s,s,e.tradeSize),{isUpdate:!0,time:i.getTime(),index:Pu(this.container)}}process(e){const t=this.getPosition(e);if(null===t)return null;const i=fu(gs.DEBUG_TIME_FORMAT);return t.isUpdate?(e.symbol===gs.DEBUG_SYMBOL&&console.log(`Adding ${this.agg.describe()} Bar\nBars %cnot same %c${i(t.lastTimestamp)} < ${i(t.newTimestamp)} %cnext is %c${i(t.nextTimestamp)}`,"color:#f00","color:#f96","","color:#fff"),this.changeLastBar(e,t)):ie(e.tradePrice)?(e.symbol===gs.DEBUG_SYMBOL&&console.log(`Updating ${this.agg.describe()} Bar\nBars %csame %c${i(t.lastTimestamp)} == ${i(t.newTimestamp)}`,"color:#0f0","color:#f96"),this.addBar(e,t)):null}alignToQuote(e){if(ie(e.lastPrice,e.time))return this.updateLastBar(e.highPrice,e.lowPrice,e.lastPrice,void 0),{isUpdate:!0,time:e.time.getTime(),index:Pu(this.container)}}}class Lu extends Eu{innerBuilder;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.processRetrieved()}get base(){return this.innerBuilder.container}fixupTimeBasedAggregationTimestamp(e){return Di(e,pt(e,gs.START_OF_LAST_CENTURY)%this.agg.size)}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:0,tradePrice:0,tradingDay:0};[Ka.Open,Ka.High,Ka.Low].forEach(i=>{t.tradePrice=this.base.getData(i)[e],super.process(t)}),t.tradePrice=this.base.getData(Ka.Close)[e],t.tradeSize=this.base.getData(Ka.Volume)[e],super.process(t)}}process(e){return this.innerBuilder.process(e),super.process(e)}}class Mu{fields;storage={};constructor(e){this.fields=e,this.clear()}clear(){this.storage={},this.fields.forEach(e=>{this.storage[e.id]=[]})}fixupTransition(e,t){if(e!==Ka.Change||!this.hasField(Ka.Close)||t<1)return;const i=this.storage[e.id],s=this.storage[Ka.Close.id];i[t]=s[t]-s[t-1]}concat(e,t,i){this.storage[e.id]=t.concat(i),this.fixupTransition(e,t.length)}prependData(e,t){this.checkField(e),this.concat(e,t,this.getData(e))}prepend(e){const t=e.getLastDataPoint(Ka.DateTime).getTime()===this.getTimeData()[0].getTime(),i=e.size;e.fields.forEach(s=>{t&&e.getData(s).splice(i-1,1),this.prependData(s,e.getData(s))})}appendData(e,t){this.checkField(e),this.concat(e,this.getData(e),t)}append(e){const t=e.getTimeData()[0].getTime()===this.getLastDataPoint(Ka.DateTime).getTime(),i=this.size;return e.fields.forEach(s=>{t&&this.getData(s).splice(i-1,1),this.appendData(s,e.getData(s))}),e.size-(t?1:0)}getTimeData(){return this.getData(Ka.DateTime)}getData(e){return this.storage[e.id]}setData(e,t){this.checkField(e),this.storage[e.id]=t}hasField(e){return-1!==this.fields.findIndex(t=>t.id===e.id)}get size(){return 0===this.fields.length?0:this.getData(this.fields[0]).length}get isEmpty(){return 0===this.size}checkField(e){if(!this.hasField(e))throw new Error(`This container does not store values for field ${e.id}`)}addDataPoint(e,t){this.checkField(e);this.getData(e).push(t)}getLastDataPoint(e){this.checkField(e);return k(this.getData(e))}setLastDataPoint(e,t){this.checkField(e);const i=this.getData(e);i[i.length-1]=t}keepOnlyLast(e){if(this.size<=e)return;const t=this.size-e;this.fields.forEach(e=>this.getData(e).splice(0,t))}}class _u extends Mu{constructor(){super([])}get size(){return 0}}class xu extends Mu{wrapper;constructor(e,t){super(e),this.wrapper=t}isWrapped(e){return le(this.wrapper,e.id)}hasField(e){return this.isWrapped(e)||super.hasField(e)}getData(e){return this.isWrapped(e)?this.wrapper[e.id]():super.getData(e)}}const Iu=gs.RENKO_KAGI_NAMES;function Du(e){const{Method:t,Period:i,Source:s,BrickSize:n}=fe(e);return{method:oe(t,[Iu.ATR,Iu.TRD,Iu.PCT],Iu.ATR),period:Number.isFinite(i)?i:14,source:oe(s,[Iu.CLS,Iu.HL],Iu.CLS),brickSize:Number.isFinite(n)?n:10}}function Ou(e,t,i){return e.getData(t)[i]}function wu(e,t){const[i,s]=[Ka.High,Ka.Low].map(i=>Ou(e,i,t)),n=Ou(e,Ka.Close,t-1);return Math.max(i-s,Math.abs(i-n),Math.abs(s-n))}function Ru(e,t){if(e.size<t)return null;const i=t-1,s=[];s.push(Ou(e,Ka.High,0)-Ou(e,Ka.Low,0));for(let r=1;r<t;++r)s.push(wu(e,r));let n=w(s);for(let r=t;r<e.size;++r){n=(n*i+wu(e,r))/t}return n}const Nu=e=>Ka[e],Vu=["DateTime","Open","High","Low","Close","Volume"].map(Nu),Hu=Vu.concat(["Change","Projection","BarIndex"].map(Nu));class Bu extends Cu{innerBuilder;inputs;brickSize;lastFinalBrick;projectionCount;refPrices;constructor(e,t){super(),this.supportsChunks=!1,this.innerBuilder=e,this.inputs=ue(t.inputs),this.brickSize=null,this.container=new Mu(Hu),this.processRetrieved()}get base(){return this.innerBuilder.container}baseVal(e,t){return this.base.getData(e)[t]}isLastBase(e){return e===this.base.size-1}getValuesAt(e,t){const[i,s,n,r,o,a]=Vu.map(i=>t.getData(i)[e]);return{date:i,open:s,high:n,low:r,close:o,volume:a}}getBrickAt(e){return this.getValuesAt(e,this.container)}getBarAt(e){return this.getValuesAt(e,this.base)}getBricksCount(e){return Math.floor(e/this.brickSize)}getMove(e,t,i){const[s,n]=this.refPrices(t.close,t.high,t.low),r=s-e.high,o=e.low-n;return{climbing:(i&&r>0||r>=this.brickSize)&&r>=o,falling:(i&&o>0||o>=this.brickSize)&&o>r,moveUp:r,moveDown:o}}initFirstBrick(e,t){const i=Math.max(this.brickSize,se(t.close-t.close%this.brickSize,4));e.open=e.high=e.low=e.close=i,e.date=t.date,e.volume=e.change=0}findSafeStartIndex(){let e=0,t=this.base.size-1;const i=2*gs.RENKO_MAX_BARS;for(;t>0&&e<i;){const i=wu(this.base,t);e+=Math.floor(i/this.brickSize),t--}return t}processRetrieved(){const e=Du(this.inputs),{method:t,period:i,source:s}=e;if(this.brickSize=e.brickSize,t===Iu.ATR)this.brickSize=Ru(this.base,i);else if(t===Iu.PCT)if((this.base?.size??0)>0){const e=this.base.getLastDataPoint(Ka.Close);this.brickSize=e*this.brickSize/100}else this.brickSize=null;if(!ie(this.brickSize))return;this.refPrices=s===Iu.HL?(e,t,i)=>[t,i]:(e,t,i)=>[e,e];const n={},r=this.findSafeStartIndex();for(let o=r;o<this.base.size;o++){const e=this.getBarAt(o);if(o===r){this.initFirstBrick(n,e);continue}const t=this.isLastBase(o),{climbing:i,falling:s,moveUp:a,moveDown:l}=this.getMove(n,e,t);if(!i&&!s){n.volume+=e.volume;continue}n.proj=Number(t),n.barIndex=o;const c=e.date.getTime();if(i){const e=this.getBricksCount(a);for(let t=0;t<e;++t)this.constructClimbing(n,c,t,this.brickSize);t&&(this.constructClimbing(n,c,e,a%this.brickSize),this.projectionCount=e+1)}else if(s){const e=this.getBricksCount(l);for(let t=0;t<e;++t)this.constructFalling(n,c,t,this.brickSize);t&&(this.constructFalling(n,c,e,l%this.brickSize),this.projectionCount=e+1)}t||(this.lastFinalBrick=this.container.size-1,n.volume=0)}this.container.keepOnlyLast(gs.RENKO_MAX_BARS)}constructClimbing(e,t,i,s,n=!0){const r=e.high,o=e.close;e.open=e.low=r,e.high=e.close=r+s,e.date=new Date(t+i),e.change=e.close-o,n?this.addToContainer(e):this.updateLastDataPoint(e)}constructFalling(e,t,i,s,n=!0){const r=e.low,o=e.close;e.open=e.high=r,e.low=e.close=r-s,e.date=new Date(t+i),e.change=e.close-o,n?this.addToContainer(e):this.updateLastDataPoint(e)}process(e){const t=this.innerBuilder.process(e);return this.processUpdate(t)}alignToQuote(e){const t=this.innerBuilder.alignToQuote(e);return this.processUpdate(t)}rebuild(){return this.container.clear(),this.processRetrieved(),{isUpdate:!1,time:0,index:-1}}processUpdate(e){if(!Number.isFinite(this.lastFinalBrick))return null;const t=this.base.size-1,i=this.getBarAt(t),s=this.getBrickAt(this.lastFinalBrick),{climbing:n,falling:r,moveUp:o,moveDown:a}=this.getMove(s,i,!0),l=1===this.container.getLastDataPoint(Ka.Projection);if(!n&&!r)return l?this.rebuild():null;const c=n?o:a,u=this.getBricksCount(c)+1;if(l&&this.projectionCount===u){const e=this.getBrickAt(this.container.size-1),s=this.getBrickAt(Math.min(this.container.size-2,0));return e.proj=1,e.barIndex=t,e.open===e.high?e.low=e.close=i.close:e.open===e.low&&(e.high=e.close=i.close),e.change=e.close-s.close,this.updateLastDataPoint(e),{isUpdate:!0,time:e.date.getTime(),index:this.container.size-1}}return this.rebuild()}addToContainer(e){const t=this.container;t.addDataPoint(Ka.DateTime,e.date),t.addDataPoint(Ka.Open,e.open),t.addDataPoint(Ka.Close,e.close),t.addDataPoint(Ka.High,e.high),t.addDataPoint(Ka.Low,e.low),t.addDataPoint(Ka.Change,e.change),t.addDataPoint(Ka.Volume,e.volume),t.addDataPoint(Ka.Projection,e.proj),t.addDataPoint(Ka.BarIndex,e.barIndex)}updateLastDataPoint(e){const t=this.container;t.setLastDataPoint(Ka.DateTime,e.date),t.setLastDataPoint(Ka.Open,e.open),t.setLastDataPoint(Ka.Close,e.close),t.setLastDataPoint(Ka.High,e.high),t.setLastDataPoint(Ka.Low,e.low),t.setLastDataPoint(Ka.Change,e.change),t.setLastDataPoint(Ka.Volume,e.volume),t.setLastDataPoint(Ka.Projection,e.proj),t.setLastDataPoint(Ka.BarIndex,e.barIndex)}}const Fu=[Ka.DateTime,Ka.TradingDay,Ka.Last,Ka.TradeSize,Ka.Change],ku=[Ka.DateTime,Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Volume,Ka.Change],Wu=[...ku,Ka.OpenInterest],Uu=[...Wu,Ka.Symbol],$u=[Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Change];function Gu(e,t){const i=Ki(e);if(t.isTick)return Fu;{let e=ku;return t.isMultiContract?e=Uu:(i||t.isEndOfDay)&&(e=Wu),t.isIntraday?[...e,Ka.TradingDay]:e}}class zu{symbol;aggregation;offset;container;previousTime;timeZone;isFuture;needsResolution;hasOpenInterest;padded;constructor(e,t,i=0,s=!1){this.symbol=e,this.aggregation=t,this.offset=i||0,this.previousTime=/* @__PURE__ */new Date(0),this.timeZone=this.getTimeZone(),this.isFuture=Fi(e),this.padded=s,this.needsResolution=ji(e),this.hasOpenInterest=Ki(e)}makeContainer(){return new Mu(Gu(this.symbol,this.aggregation))}parse(e){this.container=this.makeContainer();const t=e.split("\n"),i=this.getParseFunc();if(null!==i){const e=i.bind(this);t.forEach(t=>{const i=t.trim();if(i){const t=i.split(",");e(t)}})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){const t=e.length-5;0!==t&&1!==t||(this.container.addDataPoint(Ka.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(Ka.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(Ka.Last,parseFloat(e[3+t])),this.container.addDataPoint(Ka.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(Ka.Change,this.calculateChange(Ka.Last)))}nullify(e){return null==e||0===e?null:e}parseMinutes(e){const t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,i=t?1:0;e.length===7+i&&(this.container.hasField(Ka.Symbol)&&this.container.addDataPoint(Ka.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(Ka.DateTime,this.parseDate(e[0+i])),this.container.addDataPoint(Ka.TradingDay,parseInt(e[1+i])),this.container.addDataPoint(Ka.Open,parseFloat(e[2+i])),this.container.addDataPoint(Ka.High,parseFloat(e[3+i])),this.container.addDataPoint(Ka.Low,parseFloat(e[4+i])),this.container.addDataPoint(Ka.Close,parseFloat(e[5+i])),this.container.addDataPoint(Ka.Volume,this.nullify(parseInt(e[6+i]))),this.container.addDataPoint(Ka.Change,this.calculateChange()))}parseFloatOrNull(e){const t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){const t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){const t=this.aggregation.isMultiContract,i=7+(this.hasOpenInterest?1:0);e.length===i&&(t&&this.container.addDataPoint(Ka.Symbol,e[0]),this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(Ka.High,parseFloat(e[3])),this.container.addDataPoint(Ka.Low,parseFloat(e[4])),this.container.addDataPoint(Ka.Close,parseFloat(e[5])),this.container.addDataPoint(Ka.Volume,this.nullify(this.parseIntOrNull(e[6]))),this.hasOpenInterest&&this.container.addDataPoint(Ka.OpenInterest,this.nullify(this.parseIntOrNull(e[7]))),this.container.addDataPoint(Ka.Change,this.calculateChange()))}calculateChange(e=Ka.Close){const t=this.container.size;if(t>1){const i=this.container.getData(e);return i[t-1]-i[t-2]}return 0}parseTimestamp(e){switch(this.aggregation.unit){case a.Tick:case a.Intraday:return function(e,t=gs.ZERO_DATE){const i=new Date(e.replace(" ","T"));return ht(i)?i:t}(e);default:return vu(e)}}parseDate(e){const t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?lt(t,this.offset):(!function(e,t){Ke(2,arguments);var i=qe(e),s=qe(t);return i.getTime()>s.getTime()}(t,this.previousTime)?this.previousTime=Qe(this.previousTime,1):this.previousTime=t,this.previousTime)}getTimeZone(){return qi(this.symbol)}}const{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:Yu,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:ju}=gs;class Ku{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case a.Tick:return gs.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case a.Intraday:return t&&e.spec===l.Nearest?Yu:ju;case a.Day:case a.Week:case a.Month:case a.Quarter:case a.Year:return gs.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return""}}addExtraParams(e){}makeUrl(e){const t={},i=Ws(e.symbol);t.symbol=i;const s=e.aggregation,n=this.getDataParam(s);if(n.length>0&&(t.data=n),s.size>1&&s.unit===a.Intraday){const e=s.spec===l.PerRange?1:s.size;t.interval=e.toString()}const[r,o]=e.range,c=null!==r,u=null!==o;if(c&&(t.start=this.toHistoricalFeedDate(r,s)),!c||e.alwaysUseBarsToFetch){let i=e.barsToFetch||gs.DEFAULT_MAX_RECORDS;s.unit===a.Tick&&s.spec!==l.None&&(i*=gs.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=i.toString()}u&&(t.end=this.toHistoricalFeedDate(o,s)),t.volume=s.isContractVolume?"contract":"total",t.order="asc",t.dividends=s.dividendsAdjust.toString(),t.backadjust=s.backAdjust.toString(),t.daystoexpiration=s.daysToExpiration.toString(),t.contractroll=s.contractRoll,s.isTick&&(t.type="T",t.skipOldEmulation="true"),!0===e.extendedHours&&(t.formt="true"),t.splits=(e?.splits??!0).toString(),t.padded=(e.padded??!1).toString(),this.addExtraParams(t);const h=ge(t),d=Fi(i);return`/${this.getPageNameFor(s,d)}?${h}`}toHistoricalFeedDate(e,t){return Si(e,t.isTick||t.isIntraday?gs.FMT_HIST_FEED_PARAM_DATE_TIME:gs.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t="";const i=this.getSpecPart(e);switch(e.unit){case a.Tick:case a.Intraday:break;case a.Day:t=`daily${i}`;break;case a.Week:t=`weekly${i}`;break;case a.Month:t=`monthly${i}`;break;case a.Quarter:t=`quarterly${i}`;break;case a.Year:t=`yearly${i}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===l.Continue?"continue":"nearest":""}getParser(e){const t=Ws(e.symbol);return new zu(t,e.aggregation,e.offset,e.padded)}async retrieve(e){const t=this.makeUrl(e),i=e.aggregation.unit===a.Tick?"timeseriesNew":"timeseries",s=await Fv(i,t);return this.getParser(e).parse(s)}}class qu{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){const t=Ws(e.symbol),i=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==a.Day)return i;const s={symbol:t};this.addExtraParams(s);const n=`/${this.getPageName()}.json?${ge(s)}`,r=await Fv("ondemand",n);try{const e=JSON.parse(r);if(200===e.status.code){const t=e.results;if(this.iterateForward)for(let e=0;e<t.length;e++)this.processRow(t[e],e,i);else for(let e=t.length-1;e>=0;e--)this.processRow(t[e],e,i);return i}}catch(o){Hv(`Failed parsing the JSON result from OnDemand, error is ${o.message}`)}return i}}class Xu extends qu{emptyContainer(e,t){return new Mu(Gu(e,t))}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){const s=i.hasField(Ka.Symbol),n=t>0?i.getLastDataPoint(Ka.Close):null;i.addDataPoint(Ka.DateTime,vu(e.date)),s&&i.addDataPoint(Ka.Symbol,e.symbol),i.addDataPoint(Ka.Open,e.open),i.addDataPoint(Ka.High,e.high),i.addDataPoint(Ka.Low,e.low),i.addDataPoint(Ka.Close,e.close),i.addDataPoint(Ka.Volume,e.volume),i.addDataPoint(Ka.OpenInterest,e.openInterest);const r=null===n?null:se(e.close-n,2);i.addDataPoint(Ka.Change,r)}}const Zu={WeighImplVolHigh:"weightedImpliedVolatility",WeighImplVolLow:"weightedImpliedVolatility",WeighImplVol:"weightedImpliedVolatility",WeighImplVolHigh5D:"weightedImpliedVolatilityHigh5d",WeighImplVolLow5D:"weightedImpliedVolatilityLow5d",WeighImplVol5D:"weightedImpliedVolatility5d",WeighImplVolHigh1M:"weightedImpliedVolatilityHigh1m",WeighImplVolLow1M:"weightedImpliedVolatilityLow1m",WeighImplVol1M:"weightedImpliedVolatility1m",WeighImplVolHigh3M:"weightedImpliedVolatilityHigh3m",WeighImplVolLow3M:"weightedImpliedVolatilityLow3m",WeighImplVol3M:"weightedImpliedVolatility3m",WeighImplVolHigh6M:"weightedImpliedVolatilityHigh6m",WeighImplVolLow6M:"weightedImpliedVolatilityLow6m",WeighImplVol6M:"weightedImpliedVolatility6m",WeighImplVolHigh1Y:"weightedImpliedVolatilityHigh1y",WeighImplVolLow1Y:"weightedImpliedVolatilityLow1y",WeighImplVol1Y:"weightedImpliedVolatility1y",WeighImplVolHighYTD:"weightedImpliedVolatilityHighYtd",WeighImplVolLowYTD:"weightedImpliedVolatilityLowYtd",WeighImplVolYTD:"weightedImpliedVolatilityYtd",WeighImplVolChg:"weightedImpliedVolatilityChange",ImplVolRank5D:"impliedVolatilityRank5d",ImplVolRank1M:"impliedVolatilityRank1m",ImplVolRank3M:"impliedVolatilityRank3m",ImplVolRank6M:"impliedVolatilityRank6m",ImplVolRank1Y:"impliedVolatilityRank1y",ImplVolRankYTD:"impliedVolatilityRankYtd",ImplVolPerc5D:"impliedVolatilityPercentile5d",ImplVolPerc1M:"impliedVolatilityPercentile1m",ImplVolPerc3M:"impliedVolatilityPercentile3m",ImplVolPerc6M:"impliedVolatilityPercentile6m",ImplVolPerc1Y:"impliedVolatilityPercentile1y",ImplVolPercYTD:"impliedVolatilityPercentileYtd",OptTotVol:"totalVolume",OptCallVol:"callVolume",OptPutVol:"putVolume",PutCallVolRatio:"putCallVolumeRatio",TotalOpenInt:"totalOpenInterest",CallOpenInt:"callOpenInterest",PutOpenInt:"putOpenInterest",PutCallOIRatio:"putCallOpenInterestRatio",DateTime:"date"};class Ju{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){const t=Ws(e.symbol).replace(/\.bz$/i,""),i=e.fields.concat(Ka.DateTime),s=()=>new Mu(i);if(e.aggregation.unit!==a.Day)return s();const n=`/get?${ge({symbol:t,apiKey:"default",fields:i.map(e=>Zu[e.id]).join(",")})}`,r=await Fv("options",n);try{const e=JSON.parse(r).data,t=s(),n=e=>Number.parseFloat(e.replace(/,/g,""));return e.forEach(e=>{i.forEach(i=>{i===Ka.DateTime?t.addDataPoint(Ka.DateTime,vu(e.date)):t.addDataPoint(i,n(e[Zu[i.id]]))})}),t}catch(o){Hv(`Failed parsing options JSON historical data result, error is ${o.message}`)}return s()}}class Qu extends Eu{innerBuilder;isBuildingBars;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=gs.FETCH_TICK_CHUNK_RETRY_COUNT,this.processRetrieved()}get base(){return this.innerBuilder.container}getFirstDate(e){return this.innerBuilder.getFirstDate(e)}get startFromIndex(){return 0}processRetrieved(){this.container.clear(),this.isBuildingBars=!0;const e=[Ka.DateTime,Ka.TradeSize,Ka.Last,Ka.TradingDay],[t,i,s,n]=e.map(e=>this.base.getData(e));for(let r=this.startFromIndex;r<this.base.size;r++){const e={isTrade:!0,time:t[r],tradeSize:i[r],tradePrice:s[r],tradingDay:n[r]};super.process(e)}this.isBuildingBars=!1}process(e){const t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}}class eh extends Qu{constructor(e,t,i){super(e,t,i)}fixupTimeBasedAggregationTimestamp(e){return function(e,t){return Ke(2,arguments),at(e,-je(t))}(e,vt(e,Et(Oi(e,1)))%this.agg.size)}}class th extends Qu{series;constructor(e,t,i,s){super(e,i,s),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}}const ih=new Ga("_TICK_COUNT");class sh extends th{anchorTimestamp=null;constructor(e,t,i,s){super(e,t,i,s)}get startFromIndex(){let e=0;const t=this.base.getTimeData();if(ie(this.anchorTimestamp))e=U(t,e=>e===this.anchorTimestamp);else{const i=this.base.size;if(i>2)for(let s=i-2;s>2;--s){const i=t[s].valueOf();if(i-t[s-1].valueOf()>1&&t[s+1].valueOf()-i>1){e=s;break}}this.anchorTimestamp=t[e]}return e>this.agg.size&&(e%=this.agg.size),Math.max(e,0)}addBar(e,t){const i=super.addBar(e,t);return this.container.addDataPoint(ih,1),i}changeLastBar(e,t){const i=super.changeLastBar(e,t),s=this.container.getLastDataPoint(ih);return this.container.setLastDataPoint(ih,s+1),i}isUpdate(e,t,i,s){return this.container.getLastDataPoint(ih)<this.agg.size}}const nh=new Ga("_VOLUME_TALLY");class rh extends th{constructor(e,t,i,s){super(e,t,i,s)}addBar(e,t){const i=this.container,s=(i.getLastDataPoint(nh)||0)+e.tradeSize,n=Math.floor(s/this.agg.size),r=s%this.agg.size,o=s<this.agg.size;i.size>0&&(i.setLastDataPoint(Ka.Volume,o?1:n),i.setLastDataPoint(nh,s));const a=super.addBar(e,t);return i.setLastDataPoint(Ka.Volume,1),i.addDataPoint(nh,o?0:r),a}changeLastBar(e,t){const i=this.container,s=super.changeLastBar(e,t);i.setLastDataPoint(Ka.Volume,1);const n=i.getLastDataPoint(nh)??0;return i.setLastDataPoint(nh,n+e.tradeSize),s}isUpdate(e,t,i,s){if(!ut(e,t))return!1;const n=this.container.getLastDataPoint(nh)??0;return s.tradeSize+n<this.agg.size}}class oh extends Eu{innerBuilder;metadata;range;step;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.range=i.size,this.step=1;const n=Gv().getMetaDataSource();this.metadata=n.getMetaData(s)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return ps.call(this,async()=>{const e=await this.metadata.ready();return e&&(this.step=this.metadata.minMovement,this.processRetrieved()),e})}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){const t=this.base.getData(Ka.Volume)[e],i=this.useHighOrLow(e);if(!ie(i)){this.updateLastBar(void 0,void 0,void 0,t);continue}const s={isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:t,tradePrice:i,tradingDay:0};super.process(s)}}useHighOrLow(e){const t=this.base.getData(Ka.Close)[e];if(0==this.container.size)return t;const i=this.container.getLastDataPoint(Ka.High),s=this.container.getLastDataPoint(Ka.High),n=this.base.getData(Ka.High)[e],r=this.base.getData(Ka.Low)[e],o=n>i,a=r<s;return o&&a?n-t<t-r?n:r:o?n:a?r:void 0}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}isUpdate(e,t,i,s){return!0}process(e){return this.innerBuilder.process(e),super.process(e)}changeLastBar(e,t){const i=e.tradePrice,s=this.container.getLastDataPoint(Ka.Low)+this.priceRange;if(i>s)return this.changeAndAddBar(s,e,t);const n=this.container.getLastDataPoint(Ka.High)-this.priceRange;return i<n?this.changeAndAddBar(n,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,i){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(Ka.Projection,0),this.addBar(t,i)}addBar(e,t){return this.container.addDataPoint(Ka.Projection,1),super.addBar(e,t)}}const ah=[Ka.Open,Ka.High,Ka.Low,Ka.Close],lh=[Ka.BARCOLIX,Ka.High,Ka.Low],ch=gs.RENKO_KAGI_NAMES;function uh(e){const{BoxSizeMethod:t,Period:i,ReversalAmount:s}=fe(e);return{method:oe(t,[ch.ATR,ch.TRD],ch.ATR),period:Number.isFinite(i)?i:14,reversal:Number.isFinite(s)?s:30}}class hh extends Eu{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ue(i.inputs),this.reversal=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,i){return e.getData(t)[i]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}addBar(e,t){if(super.addBar(e,t),this.container.addDataPoint(Ka.BARCOLIX,null),this.container.size>1){const e=this.dataAt(Ka.Close,this.container.size-2);this.setLast(Ka.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,i,s){const n=s.tradePrice,r=e=>e>=0,o=n-this.getLast(Ka.Close),a=r(o),l=Math.abs(o)>=this.reversal,[c,u,h,d]=ah.map(e=>this.getLast(e)),p=d-c,f=r(p)!==a||0===p;return f&&!l||!f&&(a?n<u:n>h)?null:Math.abs(p)<this.reversal||!f||!l}computeBarColor(){const e=e=>this.dataAt(Ka.Close,e)>this.dataAt(Ka.Open,e),t=this.container.size;if(t>1){const i=e(t-1),[s,n,r]=lh.map(e=>this.dataAt(e,t-2)),[,o,a]=lh.map(e=>this.dataAt(e,t-1));let l=s;0===s&&i&&o>n?l=1:1===s&&!i&&a<r&&(l=0),this.setLast(Ka.BARCOLIX,l)}else this.setLast(Ka.BARCOLIX,e(0)?1:0)}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);const t=super.process(e);return this.computeBarColor(),t}processRetrieved(){const e=uh(this.inputs),{method:t,period:i,reversal:s}=e;if(this.reversal=s,t===ch.ATR&&(this.reversal=Ru(this.base,i)),ie(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.baseAt(Ka.DateTime,e),tradePrice:this.baseAt(Ka.Close,e),tradeSize:this.baseAt(Ka.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}function dh(e){const{LineCount:t}=fe(e);return{lineBreak:Number.isFinite(t)?t:3}}class ph extends Eu{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.inputs=ue(s.inputs);const n=dh(this.inputs);this.lineBreak=n.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:this.base.getData(Ka.Volume)[e],tradePrice:this.base.getData(Ka.Close)[e],tradingDay:0}}processRetrieved(){if(this.container.clear(),!(this.base.size<2)){this.startLine(this.readTrade(1));for(let e=1;e<this.base.size-1;e++){const t=this.readTrade(e);this.insertBar(t,t.time)}super.process(this.readTrade(this.base.size-1))}}process(e){return this.innerBuilder.process(e),super.process(e)}updateLastBar(e,t,i,s){const n=this.findOpen(i,0,1);this.currentVolume+=s,null!==n?(super.updateLastBar(void 0,void 0,i,void 0),this.container.setLastDataPoint(Ka.Open,n),this.container.setLastDataPoint(Ka.Low,Math.min(n,i)),this.container.setLastDataPoint(Ka.High,Math.max(n,i))):this.resetProjection()}resetProjection(){const e=this.container;e.setLastDataPoint(Ka.High,null),e.setLastDataPoint(Ka.Low,null),e.setLastDataPoint(Ka.Open,null),e.setLastDataPoint(Ka.Close,null),e.setLastDataPoint(Ka.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(Ka.DateTime,t.nextTimestamp);const i=this.changeLastBar(e,t);return i.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},i}addBar(e,t){const i=this.container,{nextTimestamp:s}=t;if(1===i.getLastDataPoint(Ka.Projection)){const s=i.getLastDataPoint(Ka.Close);if(null===this.findOpen(s,this.lineBreak,1))return this.updateProjection(e,t);i.setLastDataPoint(Ka.Projection,0),i.setLastDataPoint(Ka.Volume,this.currentVolume),this.currentVolume=0}return!this.isProjection(s)&&this.insertBar(e,s)||this.addProjection(e,s)?{isUpdate:!1,time:s.getTime(),index:this.container.size-1}:null}insertBar(e,t){this.currentVolume+=e.tradeSize;const i=e.tradePrice,s=this.findOpen(i,this.lineBreak);return null!==s&&(this.createBar(s,Math.max(s,i),Math.min(s,i),i,this.currentVolume,t),this.container.addDataPoint(Ka.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;const i=e.tradePrice,s=this.findOpen(i,0);return null!==s&&(this.createBar(s,Math.max(s,i),Math.min(s,i),i,0,t),this.container.addDataPoint(Ka.Projection,1),!0)}findOpen(e,t,i=0){if(!ie(e))return null;const s=this.container,n=s.size-1-i,r=s.getData(Ka.Close)[n],o=s.getData(Ka.Open)[n];if(r>o){if(e<=r){if(e>=o)return null;for(let i=0;i<Math.min(s.size,t);i++){if(e>=s.getData(Ka.Low)[n-i])return null}return o}return r}if(e>=r){if(e<=o)return null;for(let i=0;i<Math.min(s.size,t);i++){if(e<=s.getData(Ka.High)[n-i])return null}return o}return r}startLine(e){this.container.addDataPoint(Ka.Projection,0);const t=this.readTrade(0);this.createBar(t.tradePrice,Math.max(t.tradePrice,e.tradePrice),Math.min(t.tradePrice,e.tradePrice),e.tradePrice,e.tradeSize+t.tradeSize,e.time)}}const fh=gs.RENKO_KAGI_NAMES,mh=1,gh=2,yh=3;function Ah(e){switch(e){case gs.BARKIND_O:case gs.BARKIND_XO:return!0;default:return!1}}function Sh(e){switch(e){case gs.BARKIND_X:case gs.BARKIND_OX:return!0;default:return!1}}function Th(e){const t=fe(e),{Source:i,BoxSizeMethod:s,Period:n}=t,{ReversalAmount:r,BoxSize:o,OneStepBack:a}=t,l=oe(i,[fh.CLS,fh.HL],fh.CLS),c=oe(s,[fh.ATR,fh.TRD],fh.ATR),u=Number.isFinite(n)?o:14,h=Number.isFinite(r)?r:3;return{method:c,period:u,source:l,boxSize:Number.isFinite(o)?o:20,reversal:h,oneStepBack:"Yes"===a}}class vh extends Eu{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ue(i.inputs),this.boxSize=this.reversal=this.source=this.firstTrend=this.oneStepBack=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,i){return e.getData(t)[i]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}roundToBox(e){return e-e%this.boxSize}roundedDiff(e,t,i){const s=Math.abs(t-e);return e+i*this.roundToBox(s)}get closeBased(){return this.source===fh.CLS}get currentKind(){return this.getLast(Ka.BARKIND)}getTrendField(e){return this.closeBased?Ka.Close:e?Ka.Low:Ka.High}getTrendPrice(e,t){if(this.closeBased)return e.tradePrice;const i=e;return t?i._lowPrice:i._highPrice}changeLastBar(e,t){const i=Ah(this.currentKind),s=i?-1:1,n=this.getLast(this.getTrendField(i)),r=this.getTrendPrice(e,i);return e.tradePrice=this.roundedDiff(n,r,s),super.changeLastBar(e,t),null}addBar(e,t){const i=0===this.container.size,s=Ah(this.currentKind),n=s?1:-1,r=i?null:this.getLast(Ka.Close),o=this.getTrendPrice(e,!s),a=i?this.roundToBox(this.baseAt(Ka.Open,0)):r;if(e.tradePrice=a+n*(i?0:this.boxSize),super.addBar(e,t),!i){const e=this.roundedDiff(r,o,n);this.updateLastBar(e,e,e)}return this.container.addDataPoint(Ka.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){const e=Ah(this.currentKind)?gs.BARKIND_OX:gs.BARKIND_XO;this.setLast(Ka.BARKIND,e)}canInplaceReverse(){return!function(e){switch(e){case gs.BARKIND_OX:case gs.BARKIND_XO:return!0;default:return!1}}(this.currentKind)&&this.getLast(Ka.High)===this.getLast(Ka.Low)}isUpdate(e,t,i,s){const n=Ah(this.currentKind),r=this.getTrendPrice(s,n),o=this.getTrendPrice(s,!n),a=e=>e>=0,l=r-this.getLast(Ka.Close),c=a(l),u=Math.abs(l)>=this.boxSize,h=o-this.getLast(Ka.Close),d=a(h),p=Math.abs(h)>=this.reversal*this.boxSize;return n?!(c||!u)||(d&&p?!(!this.oneStepBack||!this.canInplaceReverse())&&(this.inplaceReverse(),!0):null):!(!c||!u)||(!d&&p?!(!this.oneStepBack||!this.canInplaceReverse())&&(this.inplaceReverse(),!0):null)}findFirstDiffLargerThanBox(e,t){const i=this.baseAt(Ka.Open,0),s=this.innerBuilder.container.size;for(let n=1;n<s;++n){const s=this.baseAt(e,n)-i;if(Math.abs(s)>this.boxSize){if(t===mh&&s>0)return[n,gs.BARKIND_X];if(t===gh&&s<0)return[n,gs.BARKIND_O];if(t===yh)return[n,s>0?gs.BARKIND_X:gs.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){const[,e]=this.findFirstDiffLargerThanBox(Ka.Close,yh);return e}{const[e,t]=this.findFirstDiffLargerThanBox(Ka.High,mh),[i,s]=this.findFirstDiffLargerThanBox(Ka.Low,gh);return null===t&&null===s?null:null===s?t:null===t?s:e<i?t:s}}computeBarColor(){const e=this.container.size;let t=this.firstTrend;if(e>1){t=Ah(this.dataAt(Ka.BARKIND,e-2))?gs.BARKIND_X:gs.BARKIND_O}this.setLast(Ka.BARKIND,t)}process(e){return this.isProcessingRetrieved||this.innerBuilder.process(e),null===this.firstTrend?null:super.process(e)}processRetrieved(){const e=Th(this.inputs),{method:t,period:i,reversal:s,source:n,boxSize:r,oneStepBack:o}=e;if(this.reversal=s,this.source=n,t===fh.ATR?this.boxSize=Ru(this.base,i):this.boxSize=r,ie(this.reversal,this.boxSize)&&(this.oneStepBack=o&&1===this.reversal,this.container.clear(),this.firstTrend=this.findFirstBarTrend(),null!==this.firstTrend)){this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.baseAt(Ka.DateTime,e),tradePrice:this.baseAt(Ka.Close,e),_highPrice:this.baseAt(Ka.High,e),_lowPrice:this.baseAt(Ka.Low,e),tradeSize:this.baseAt(Ka.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}const Ph=new Wo(a.Intraday,0);class Ch{constructor(e){this.query=e,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new el(e.symbol)}container;canLoadMoreData=!0;alignToQuote=!1;record;isLoading=!1;serverComputedSeries;builder;retriever;streamingSubscription;records;get isTotalVolumeMode(){const e=this.query.symbol,t=this.query.aggregation;return Fi(e)&&!t.isContractVolume&&t.isEndOfDay}getHasVisible(e){return null!=this.query.visibleRange&&null!=this.query.visibleRange[e]}get hasVisibleFrom(){return this.getHasVisible("from")}get hasVisibleTo(){return this.getHasVisible("to")}refresh(){this.query.aggregation.isEndOfDay?this.alignToQuote=!0:this.loadMoreData(!1)}makeInnerBuilder(e){const t=this.query.aggregation;if(!t.isTick)return new Eu(e,t);switch(t.spec){case l.None:case l.PerSeconds:case l.PerCount:case l.PerVolume:return new bu(e);default:throw new Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}}makeBuilder(e){const t=this.makeInnerBuilder(e),i=this.query.aggregation,s=(e,t=[])=>new Mu(Gu(this.query.symbol,e).concat(t)),n=t;switch(this.query.curveStyle){case o.Renko:return new Bu(n,this.query);case o.Kagi:{const e=s(Ph,[Ka.BARCOLIX]);return new hh(n,e,this.query)}case o.PointAndFigure:{const e=s(Ph,[Ka.BARKIND]);return new vh(n,e,this.query)}case o.LineBreak:{const e=s(i,[Ka.Projection]);return new ph(n,e,i,this.query)}}if(i.isIntraday&&i.spec===l.PerRange){const e=s(Ph,[Ka.Projection]);return new oh(n,e,i,this.query.symbol)}const r=t;if(i.isTick)switch(i.spec){case l.PerSeconds:return new eh(r,s(Ph),i);case l.PerCount:{const e=s(Ph,[ih]);return new sh(r,this,e,i)}case l.PerVolume:{const e=s(Ph,[nh]);return new rh(r,this,e,i)}}return i.unit===a.Day&&i.size>1?new Lu(n,s(i),i):t}onStreamingUpdates(e){if(this.isLoading)return;e.map(e=>{if("isTrade"in e)return this.builder.process(e);if("isQuote"in e&&(J(qa.TS_QUOTEMARKER,{series:this}),this.alignToQuote)){const t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>ie(e)).filter((e,t,i)=>{if(0===t)return!0;const s=i[t-1];return s.isUpdate!==e.isUpdate||s.time!==e.time||e.timeCorrection}).forEach(e=>{if(-1===e.index)J(qa.TS_MANYCHANGED,{series:this,part:P.Unspecified});else{const t={series:this,index:e.index};J(e.isUpdate?qa.TS_DATAPOINTCHANGED:qa.TS_DATAPOINTADDED,t)}e.timeCorrection&&J(qa.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return null!==this.container}getRetriever(){return Gi(this.query.symbol)&&this.query.aggregation.isEndOfDay?new Xu:new Ku}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>{const t=this.query.aggregation.isEndOfDay,i=dl(qa.RT_TRADE,this.record.symbol),s=e.filter(i).filter(e=>ie(e.data.time)).filter(e=>"T"!==e.data.session||this.query.extendedHours&&!t).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay}));if(this.isTotalVolumeMode&&this.records){const t=this.getSiblingVolume(e);if(t>0&&s.length>0)s[0].tradeSize+=t;else if(t>0&&0===s.length){const e=this.record.getValue(Ka.Last)??this.record.getValue(Ka.Close);if(ie(e)){const i=/* @__PURE__ */new Date;s.push({isTrade:!0,tradePrice:e,tradeSize:t,time:i,tradingDay:this.record.getValue(Ka.TradingDay)})}}}const n=s.reduce((e,t)=>{const i=k(e);var s;return ie(i)&&ie(i.tradePrice)&&ie(t.tradePrice)&&i.tradePrice===t.tradePrice&&i.time.getTime()===t.time.getTime()&&i.tradingDay===t.tradingDay?i.tradeSize+=t.tradeSize:e.push((s=t,Object.assign({},s))),e},[]),r=dl(qa.RT_QUOTE,this.record.symbol);return n.concat(e.filter(r).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}getSiblingVolume(e){if(!this.records)return 0;return e.filter(e=>e.topic===qa.RT_TRADE&&e.data.symbol in this.records).filter(e=>ie(e.data.time)).filter(e=>"T"!==e.data.session).reduce((e,t)=>e+t.data.tradeSize,0)}async loadMoreData(e=!0){if(this.isLoading||!this.builder.supportsChunks||!this.retriever.supportsChunks||!this.canLoadMoreData)return Promise.resolve();this.isLoading=!0,e?await this.loadHeadChunk():await this.loadTailChunk(),this.isLoading=!1}async loadTailChunk(){const e=this.query.duplicate();let t=this.builder.getLastDate();ie(e.offset)&&0!==e.offset&&(t=lt(t,-e.offset)),e.range=[t,null];const i=await this.retriever.retrieve(e),s=this.container.size;this.builder.append(i);const n=this.container.size-s;J(qa.TS_MANYCHANGED,{series:this,part:P.Tail,count:n,index:s})}async loadHeadChunk(){let e=!1,t=null;for(let i=0;i<this.builder.retryCountForChunk&&!e;++i){const s=this.query.duplicate();let n=this.builder.getFirstDate(i);ie(s.offset)&&0!==s.offset&&(n=lt(n,-s.offset)),s.range=[null,n],t=await this.retriever.retrieve(s),e=t.size>1}this.canLoadMoreData=e,e&&null!==t&&(this.builder.prepend(t),J(qa.TS_MANYCHANGED,{series:this,part:P.Head}))}async applyNearbyFixup(e){const t=this.query.aggregation,i=t.spec===l.Nearest,s=this.query.symbol,n=Fi(s);return!n||!t.isMultiContract||!i||e.size<1||this.serverComputedSeries?n&&ji(s)?await Hi(s):s:e.getLastDataPoint(Ka.Symbol)}async ready(){return ps.call(this,async()=>{this.retriever=this.getRetriever();const e=await this.retriever.retrieve(this.query),t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=Gv().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.isTotalVolumeMode&&await this.setupTotalVolumeSubscriptions(),this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0})}async setupTotalVolumeSubscriptions(){const e=Zi(this.query.symbol);if(e)try{const t=(await Xi(e)).map(e=>e.name).filter(e=>e!==this.record.symbol),i=Gv().getRecordSource();this.records={};for(const e of t)this.records[e]=i.getRecord(e);await Promise.all(Object.values(this.records).map(e=>e.ready()))}catch(t){this.records=void 0}}getCacheableEntities(e){e.add(this)}shutdown(){ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.records=void 0}}class bh{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new _u}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}}class Eh{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return null!==this.container}loadMoreData(e){throw new Error("Should not be called.")}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}}class Lh{constructor(e){this.query=e,this.container=null,this.supplyCustomDemoData="DemoSite"===Gv().config.mode}container;supplyCustomDemoData;canLoadMoreData=!0;isLoading=!0;refresh(){}loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return null!==this.container}shutdown(){}parseEvents(e){const t=new Mu([Ka.DateTime,Ka.Dividends,Ka.Earnings,Ka.Splits,Ka.Custom]),i=e.split("\n"),s=(e,i,s,n)=>{const r=i===s?n:null;t.addDataPoint(e,r)};return i.forEach(e=>{if(""===e.trim())return;const i=e.split(",");if(4!==i.length)return;const n=vu(i[1]);t.addDataPoint(Ka.DateTime,n),s(Ka.Dividends,"Dividend",i[2],i[3]),s(Ka.Earnings,"Earnings",i[2],i[3]),s(Ka.Splits,"Split",i[2],i[3]),this.supplyCustomDemoData?s(Ka.Custom,"Custom","Custom",gs.FAKE_CUSTOM_EVENT):s(Ka.Custom,"Custom",i[2],i[3])}),t}makeUrl(){const e={};e.symbols=this.query.symbol,e.start="19700102",e.end="20501230",gs.EVENTS_BUILT_IN.forEach(t=>e[t]=this.query[t]);return`/queryevents.ashx?${ge(e)}`}async retrieve(){const e=this.makeUrl(),t=await Fv("timeseries",e);return this.parseEvents(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),this.isLoading=this.canLoadMoreData=!1,!0))}getCacheableEntities(e){e.add(this)}}class Mh{constructor(e){this.query=e,this.query=e,this.container=null}container;canLoadMoreData=!1;isLoading=!0;get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}shutdown(){}parseFundamental(e){const t=JSON.parse(e),i=t.status.code,s=204===i;if(200!==i&&!s)return null;const n=new Mu(this.query.fields.concat(Ka.DateTime));if(s)return n;const r=this.query.fields[0],o=r.id.substring(0,1).toLowerCase()+r.id.substring(1);return t.results.reverse().forEach(e=>{n.addDataPoint(Ka.DateTime,vu(e.date)),n.addDataPoint(r,parseFloat(e[o]))}),this.isLoading=!1,n}makeUrl(){const e={count:0,rawData:1};e.symbols=this.query.symbol,e.frequency=this.query.aggregation.unit===a.Quarter?"Quarter":"Annual";const t=ge(e);return`/${this.query.seriesKind===m.BalanceSheet?"getBalanceSheets":"getIncomeStatements"}.json?${t}`}async retrieve(){const e=this.makeUrl(),t=await Fv("ondemand",e);return this.parseFundamental(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}function _h(e,t){const i=e.findIndex(e=>e>t);return Math.max(i<0?e.length:i,0)}class xh{records;streamingSubscription;setSymbols(e){const t=Gv().getRecordSource();this.records=e.reduce((e,i)=>{const s=t.getRecord(i);return this.addFieldsToRecord(s,i),e[i]=s,e},{})}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}onStreamingUpdates(e){e.forEach(e=>{const t=e.data,i=this.records[t.symbol];ie(i)&&this.process(i)}),this.notifyAboutUpdates()}async retrieve(){const e=Object.values(this.records);return(await Promise.all(e.map(e=>e.ready()))).every(I)&&(this.onRecordsReady(),e.forEach(e=>this.process(e)),this.streamingSubscription=this.getStreamingSubscription()),this.hasData}async ready(){return ps.call(this,async()=>await this.retrieve())}shutdown(){ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class Ih extends xh{symbols=[];constructor(e){super(),this.symbols=e,this.setSymbols(e)}addFieldsToRecord(e,t){e.addFields(Ka.Symbol),e.update(Ka.Symbol,t)}notifyAboutUpdates(){J(qa.RT_QUOTEGROUP,{source:this})}process(e){}onRecordsReady(){}get hasData(){return!0}getValue(e){const t=this.records[e];return void 0===t?null:t.getValue(Ka.Close)}}class Dh extends xh{query;dataPoints;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){super(),this.query=e,this.setSymbols(e.symbols),this.dataPoints=e.symbols.length,this.container=null,this.fields=[Ka.DateTime,Ka.Close,Ka.Symbol]}addFieldsToRecord(e,t){e.addFields(Ka.DateTime,Ka.Symbol),e.update(Ka.DateTime,Ji(t)),e.update(Ka.Symbol,t)}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return null!==this.container&&this.container.size===this.dataPoints}notifyAboutUpdates(){J(qa.TS_MANYCHANGED,{series:this,part:P.Unspecified})}onRecordsReady(){this.container=new Mu(this.fields)}findOrAddIndex(e){let t=this.container.getData(Ka.Symbol).indexOf(e.symbol);if(t<0){const i=this.container.getData(Ka.DateTime),s=Ji(e.symbol);t=_h(i,s),this.fields.forEach(e=>this.container.getData(e).splice(t,0,null))}return t}process(e){const t=this.fields.map(t=>{const i=e.getValue(t);if("Close"!==t.id)return i;return e.getValue(Ka.Last)??i});if(!R(t))return;const i=this.findOrAddIndex(e);this.fields.forEach((e,s)=>this.container.getData(e)[i]=t[s])}getCacheableEntities(e){e.add(this)}}class Oh{query;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){this.query=e,this.fields=[Ka.DateTime,Ka.Close,Ka.Symbol],this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}shutdown(){}insertValues(e,t,i){const s=(t,i,s)=>e.getData(i).splice(t,0,s),n=e.getData(Ka.DateTime),r=Ji(t),o=_h(n,r);s(o,Ka.DateTime,r),s(o,Ka.Close,i),s(o,Ka.Symbol,t)}parseHistoricalForward(e){const t=new Mu(this.fields);return e.split("\n").filter(e=>e.trim().length>0).forEach(e=>{const i=e.split(","),s=i[0];this.insertValues(t,s,parseFloat(i[5]))}),t}makeUrl(){const e={};e.symbols=this.query.symbols.join(","),e.maxrecords=1,e.data="daily",e.end=x(mu(this.query.offset),fu(gs.FMT_HIST_FEED_PARAM_DATE_ONLY))(/* @__PURE__ */new Date);return`/querylatesteod.ashx?${ge(e)}`}async retrieve(){const e=this.makeUrl(),t=await Fv("timeseries",e);return this.parseHistoricalForward(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}class wh extends Ch{constructor(e){super(e)}getRetriever(){return new Ju}onStreamingUpdates(e){}}class Rh{cacheSeries;seriesCache;constructor(e=!1){this.cacheSeries=e,this.seriesCache=/* @__PURE__ */new Map}getTimeSeries(e){return ie(e.symbol)&&e.symbol===gs.PLACEHOLDER_SYMBOL_NAME?new bh(e):this.getSeries(e)}evictUnused(e){for(const[t,i]of this.seriesCache)!e.has(i)&&i.isCached&&(i.isCached=!1,i.shutdown(),this.seriesCache.delete(t))}refresh(){for(const e of this.seriesCache.values())"function"==typeof e.refresh&&e.refresh()}getSeries(e){const t=(e.cacheMe||this.cacheSeries)&&!e?.alwaysUseBarsToFetch,i=e.getHashKey();if(t&&this.seriesCache.has(i))return this.seriesCache.get(i);{const s=this.makeSeries(e);return s.isCached=t,t&&this.seriesCache.set(i,s),s}}makeSeries(e){switch(e.seriesKind){case m.Normal:return new Ch(e);case m.BalanceSheet:case m.IncomeStatement:return new Mh(e);case m.Events:return new Lh(e);case m.Forward:return new Dh(e);case m.HistoricalForward:return new Oh(e);default:case m.Options:return new wh(e);case m.Study:throw new Error(`The series kind '${m[e.seriesKind]}' is not supported yet.`)}}}var Nh={lessThanXSeconds:{one:"moins d’une seconde",other:"moins de {{count}} secondes"},xSeconds:{one:"1 seconde",other:"{{count}} secondes"},halfAMinute:"30 secondes",lessThanXMinutes:{one:"moins d’une minute",other:"moins de {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"environ 1 heure",other:"environ {{count}} heures"},xHours:{one:"1 heure",other:"{{count}} heures"},xDays:{one:"1 jour",other:"{{count}} jours"},aboutXWeeks:{one:"environ 1 semaine",other:"environ {{count}} semaines"},xWeeks:{one:"1 semaine",other:"{{count}} semaines"},aboutXMonths:{one:"environ 1 mois",other:"environ {{count}} mois"},xMonths:{one:"1 mois",other:"{{count}} mois"},aboutXYears:{one:"environ 1 an",other:"environ {{count}} ans"},xYears:{one:"1 an",other:"{{count}} ans"},overXYears:{one:"plus d’un an",other:"plus de {{count}} ans"},almostXYears:{one:"presqu’un an",other:"presque {{count}} ans"}},Vh={date:ai({formats:{full:"EEEE d MMMM y",long:"d MMMM y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:ai({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:ai({formats:{full:"{{date}} 'à' {{time}}",long:"{{date}} 'à' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Hh={lastWeek:"eeee 'dernier à' p",yesterday:"'hier à' p",today:"'aujourd’hui à' p",tomorrow:"'demain à' p'",nextWeek:"eeee 'prochain à' p",other:"P"},Bh={code:"fr",formatDistance:function(e,t,i){var s,n=Nh[e];return s="string"==typeof n?n:1===t?n.one:n.other.replace("{{count}}",String(t)),null!=i&&i.addSuffix?i.comparison&&i.comparison>0?"dans "+s:"il y a "+s:s},formatLong:Vh,formatRelative:function(e,t,i,s){return Hh[e]},localize:{ordinalNumber:function(e,t){var i=Number(e),s=null==t?void 0:t.unit;if(0===i)return"0";return i+(1===i?s&&["year","week","hour","minute","second"].includes(s)?"ère":"er":"ème")},era:ui({values:{narrow:["av. J.-C","ap. J.-C"],abbreviated:["av. J.-C","ap. J.-C"],wide:["avant Jésus-Christ","après Jésus-Christ"]},defaultWidth:"wide"}),quarter:ui({values:{narrow:["T1","T2","T3","T4"],abbreviated:["1er trim.","2ème trim.","3ème trim.","4ème trim."],wide:["1er trimestre","2ème trimestre","3ème trimestre","4ème trimestre"]},defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:ui({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],wide:["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"]},defaultWidth:"wide"}),day:ui({values:{narrow:["D","L","M","M","J","V","S"],short:["di","lu","ma","me","je","ve","sa"],abbreviated:["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],wide:["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"]},defaultWidth:"wide"}),dayPeriod:ui({values:{narrow:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"mat.",afternoon:"ap.m.",evening:"soir",night:"mat."},abbreviated:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"matin",afternoon:"après-midi",evening:"soir",night:"matin"},wide:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"du matin",afternoon:"de l’après-midi",evening:"du soir",night:"du matin"}},defaultWidth:"wide"})},match:{ordinalNumber:di({matchPattern:/^(\d+)(ième|ère|ème|er|e)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e)}}),era:hi({matchPatterns:{narrow:/^(av\.J\.C|ap\.J\.C|ap\.J\.-C)/i,abbreviated:/^(av\.J\.-C|av\.J-C|apr\.J\.-C|apr\.J-C|ap\.J-C)/i,wide:/^(avant Jésus-Christ|après Jésus-Christ)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^av/i,/^ap/i]},defaultParseWidth:"any"}),quarter:hi({matchPatterns:{narrow:/^T?[1234]/i,abbreviated:/^[1234](er|ème|e)? trim\.?/i,wide:/^[1234](er|ème|e)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:hi({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(janv|févr|mars|avr|mai|juin|juill|juil|août|sept|oct|nov|déc)\.?/i,wide:/^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^av/i,/^ma/i,/^juin/i,/^juil/i,/^ao/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:hi({matchPatterns:{narrow:/^[lmjvsd]/i,short:/^(di|lu|ma|me|je|ve|sa)/i,abbreviated:/^(dim|lun|mar|mer|jeu|ven|sam)\.?/i,wide:/^(dimanche|lundi|mardi|mercredi|jeudi|vendredi|samedi)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^di/i,/^lu/i,/^ma/i,/^me/i,/^je/i,/^ve/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:hi({matchPatterns:{narrow:/^(a|p|minuit|midi|mat\.?|ap\.?m\.?|soir|nuit)/i,any:/^([ap]\.?\s?m\.?|du matin|de l'après[-\s]midi|du soir|de la nuit)/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^min/i,noon:/^mid/i,morning:/mat/i,afternoon:/ap/i,evening:/soir/i,night:/nuit/i}},defaultParseWidth:"any"})},options:{weekStartsOn:1,firstWeekContainsDate:4}};const Fh=/{value:([^}]+)}/,kh=/%([aAdewbBmyYHkIlMpPSL])+/g,Wh={Second:{Period:"PT1S",Multipliers:[.01,.02,.05,.1,.2,.5,1,2,5,10,15,30]},Minute:{Period:"PT1M",Multipliers:[1,2,5,10,15,30]},Hour:{Period:"PT1H",Multipliers:[1,2,3,4,6,8,12]},Day:{Period:"P1D",Multipliers:[1,2]},Week:{Period:"P1W",Multipliers:[1,2]},Month:{Period:"P1M",Multipliers:[1,2,3,4,6]},Year:{Period:"P1Y",Multipliers:[1,2,5,10,25,50,100,250]}};const Uh=/* @__PURE__ */new Map;function $h(e){if(!ie(e))return null;if(!Uh.has(e)){const i=ie(t=e)?t.replace(Fh,(e,t)=>t.replace(kh,(e,t)=>gs.PHP_TO_UNICODE_TS_35_MAP[t])):t;Uh.set(e,i)}var t;return Uh.get(e)}class Gh{barWidth;unitWidth;minTickInterval;duration;format;prevDate;size;constructor({barWidth:e,unitWidth:t,formatString:i,minTickInterval:s,duration:n},r){this.size=r,this.barWidth=e,this.unitWidth=t,this.minTickInterval=s,this.duration=n,this.format=$h(i),this.prevDate=null}get noPrevDate(){return!ie(this.prevDate)}formatDate(e,t){return ad(e,this.format||t)}asTick(e,t,i){return this.prevDate=e,{date:e,priority:t,text:this.formatDate(e,i)}}checkPrev(e){return!!this.noPrevDate&&(this.prevDate=e,!0)}}const zh="yyyy",Yh="LLL ''yy",jh=()=>function(){if("fr"===od())return!0;return!1}()?"d LLL":"LLL d",Kh="HH:mm";class qh extends Gh{repeatEach;repeatCounter;constructor(e){super(e),this.repeatEach=gs.TIME_SCALE_MAX_SPACE_NO_TICKS/this.barWidth,this.repeatCounter=0}asTick(e,t,i){return this.repeatCounter=0,super.asTick(e,t,i)}getTick(e){if(!ut(this.prevDate,e))return this.asTick(e,1,"EEE");if(!Li(this.prevDate,e))return this.asTick(e,2,Kh);this.repeatCounter++;const t=this.repeatCounter===this.repeatEach;return!function(e,t){Ke(2,arguments);var i=Ct(e),s=Ct(t);return i.getTime()===s.getTime()}(this.prevDate,e)||t?this.asTick(e,t?4:3,Kh):null}}class Xh extends Gh{getTick(e){const t=this.checkPrev(e),i=0===this.minTickInterval||0==(e=>vt(e,nt(e)))(e)%(this.minTickInterval/1e3),s=!ut(this.prevDate,e),n=function(e){return Ke(1,arguments),qe(e).getMinutes()}(e),r=!Li(this.prevDate,e)||t&&0===n;if(i){if(s)return this.asTick(e,1,jh());if(r)return this.asTick(e,2,Kh);if(0==n%30&&this.size<15)return this.asTick(e,3,Kh);if(0==n%15&&this.size<=5)return this.asTick(e,4,Kh)}return null}}class Zh extends Gh{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<22*Wh.Day.One,this.monthYear=this.duration>22*Wh.Day.One&&this.duration<7*Wh.Month.One,this.year=this.duration>7*Wh.Month.One}useTuesday(e){return!!this.noPrevDate||2===vi(e)&&ft(e,this.prevDate)>1728e5}getTick(e){this.checkPrev(e);const t=!_i(e,this.prevDate),i=!Ii(e,this.prevDate);return this.monthDay?1===vi(e)||this.useTuesday(e)?this.asTick(e,1,jh()):null:this.monthYear?t?this.asTick(e,1,Yh):null:this.year&&i?this.asTick(e,1,zh):null}}class Jh extends Gh{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<4*Wh.Week.One,this.monthYear=this.duration>4*Wh.Week.One&&this.duration<6*Wh.Month.One,this.year=this.duration>6*Wh.Month.One}getTick(e){this.checkPrev(e);const t=!_i(e,this.prevDate),i=!Ii(e,this.prevDate);return this.monthDay?this.asTick(e,1,jh()):this.monthYear?t?this.asTick(e,1,Yh):null:this.year&&i?this.asTick(e,1,zh):null}}class Qh extends Gh{showMonths;constructor(e){super(e),this.showMonths=this.duration<7*Wh.Month.One}getTick(e){this.checkPrev(e);const t=!Ii(e,this.prevDate);return this.showMonths?this.asTick(e,1,Yh):t?this.asTick(e,1,zh):null}}class ed extends Gh{constructor(e){super(e)}getTick(e){this.checkPrev(e);return!Ii(e,this.prevDate)?this.asTick(e,1,zh):null}}function td(e){const t=function(e){return(e.valueOf()-gs.OPTIONS_DATA_BASE)/gs.OPTIONS_DATA_INCREMENT}(e);return t.toString()}function id(e){return ie(e)?`${e.toFixed(2)}%`:""}function sd(e,t,i=!1){const s=e.plots[0],n=s.curves[0],r=ie(n)&&n.fields.length>0?n.fields[0]:null;if(!ie(r))return"";const o={range:e.fullDomain,allDigits:!1,forceTrailingZeros:i};return Md(s,e.pane.presenter,o),s.metaData.format(t,r,o)}function nd(e,t,i=!1){return e.comparison===d.Percent?id(t):sd(e,t,i)}function rd(e,t,i){const s=e.view?.xAxis?.overrideFormatter;if(s)return s(t);if(ie(e.display.xAxis.isOrdinal))return td(t);const n=i||e.display.xAxis.format;if(ie(n)){return ad(t,$h(n))}const r=e.data.aggregation,o=e.display?.xAxis?.nonEodLabelWithDate??!1;return r.isEndOfDay?ld(r,t):cd(r,t,o)}function od(){const e=ce(Gv().config,null,"overrides","xAxis","getLocaleName");if(ie(e)&&"function"==typeof e)try{return e()}catch(t){Hv(`Failed retrieving the locale name, error is ${t.message}`,"warn")}}function ad(e,t){return Si(e,t,function(){if("fr"===od())return{locale:Bh}}())}function ld(e,t){if(!ht(t))return"";switch(e.unit){case a.Tick:case a.Intraday:case a.Day:case a.Week:default:return ad(t,"P");case a.Month:return ad(t,"LLL yyyy");case a.Quarter:return ad(t,"qqq yyyy");case a.Year:return ad(t,"yyyy")}}function cd(e,t,i){if(!ht(t))return"";return ad(t,`${i?"P ":""} ${e.isTick?"pp":"p"}`)}const ud=(e,t)=>e.at(t);class hd{constructor(e){this.presenter=e,this._dates=[],this.invalidate()}_dates=[];pendingRebuild=!1;checkRebuild(){this.pendingRebuild&&this.rebuild()}get withPrologLength(){return this.checkRebuild(),this._dates.length+gs.TIMELINE_PROLOG_PADDING_BARS}get withPrologEpilogLength(){return this.withPrologLength+gs.TIMELINE_EPILOG_PADDING_BARS}get firstSeriesIndex(){return gs.TIMELINE_PROLOG_PADDING_BARS}get lastSeriesIndex(){return this.checkRebuild(),0===this._dates.length?0:this.withPrologLength-1}get withoutPrologEpilogLength(){return this.checkRebuild(),this._dates.length}at(e){if(this.checkRebuild(),e<0||e>=this.withPrologEpilogLength)return null;if(e<gs.TIMELINE_PROLOG_PADDING_BARS){const t=W(this._dates),i=e-gs.TIMELINE_PROLOG_PADDING_BARS;return this.applyDateShift(t,i)}if(e>=this.withPrologLength){const t=k(this._dates),i=e-this.withPrologLength+1;return this.applyDateShift(t,i)}return this._dates[e-gs.TIMELINE_PROLOG_PADDING_BARS]}get length(){return this.checkRebuild(),this._dates.length>0?this.withPrologEpilogLength:0}slice(e,t){this.checkRebuild();const i=[];for(let s=e;s<t;++s)i.push(this.at(s));return i}tryToCorrectLastBar(e,t,i=!0){i&&this.checkRebuild();const s=+e,n=G(this._dates,s,Number),r=+this._dates[n];return n===this._dates.length-1&&r===s&&(this._dates[n]=t,!0)}mergeDateIntoTimeline(e,t=!0){t&&this.checkRebuild();const i=+e,s=G(this._dates,i,Number),n=+this._dates[s];if(n!==i){const t=s+(i>n?1:0);return this._dates.splice(t,0,e),t+this.firstSeriesIndex}return-1}invalidate(){this._dates.length=0,this.pendingRebuild=!0}rebuild(){if(this.presenter.isEmpty)return;const e=this.presenter.mainPlot.timeSeries;if(!e.hasData)return;const t=e.container.getTimeData();for(let i=t.length-1;i>=0;i--)this._dates[i]=t[i];this.presenter.allPlots.forEach(t=>{if(t.timeSeries===e)return;if(!t.timeSeries.hasData)return;t.timeSeries.container.getTimeData().forEach(e=>this.mergeDateIntoTimeline(e,!1))}),this.pendingRebuild=!1}applyDateShift(e,t){const{unit:i,size:s}=this.presenter.data.aggregation;switch(i){case a.Year:return Ze(e,12*t);case a.Quarter:return Ze(e,3*t);case a.Month:return Ze(e,t);case a.Week:return Xe(e,7*t);case a.Day:return this.addTradingDays(e,t);case a.Intraday:return Qe(e,s*t*gs.ONE_MINUTE_MILLIS);case a.Tick:return Qe(e,1e3*t)}}addTradingDays(e,t){const i=this.presenter.display?.xAxis?.isOrdinal;if(i)return Xe(e,t);if(!e||!Number.isFinite(t)||!Number.isInteger(t))return Xe(e,t);const s=t>0?1:-1;if(0===t){const t=e.getDay();return 0===t?Xe(e,1):6===t?Xe(e,2):e}let n=Math.abs(t),r=e,o=r.getDay();if(s>0?0===o?(r=Xe(r,1),n--):6===o&&(r=Xe(r,2),n--):0===o?(r=Xe(r,-2),n--):6===o&&(r=Xe(r,-1),n--),n<=0)return r;const a=Math.trunc(n/5);a>0&&(r=Xe(r,7*a*s),n-=5*a);let l=14;for(;n>0;){if(--l<0)return Xe(e,t);r=Xe(r,s),o=r.getDay(),0!==o&&6!==o&&n--}return r}}const dd={delete:'<path d="M225.8 286.2l225.8 225.8-225.8 225.8c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3l-225.8-225.8 225.8-225.8c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>',circle:'<circle cx="512" cy="512" r="512"/>',rectangle:'<rect width="1024" height="1024"/>',chevronUp:'<path d="M798.2 609.8l-256.0-256.0c-16.7-16.7-43.7-16.7-60.3 0.0l-256.0 256.0c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3z"></path>',chevronDown:'<path d="M225.8 414.2l256.0 256.0c16.7 16.7 43.7 16.7 60.3 0.0l256.0-256.0c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>',eye:'<path d="M950.9 411.4q-86.9 134.9-217.7 201.7 34.9-59.4 34.9-128.6 0.0-105.7-75.1-180.9t-180.9-75.1-180.9 75.1-75.1 180.9q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 76.0-117.1 190.6-186.6t248.3-69.4 248.3 69.4 190.6 186.6zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM1024.0 411.4q0.0-19.4-11.4-39.4-80.0-131.4-215.1-210.6t-285.4-79.1-285.4 79.4-215.1 210.3q-11.4 20.0-11.4 39.4t11.4 39.4q80.0 130.9 215.1 210.3t285.4 79.4 285.4-79.4 215.1-210.3q11.4-20.0 11.4-39.4z"></path>',eyeSlash:'<path d="M317.1 197.1l44.6 80.6q-49.7 36.0-77.7 90.9t-28.0 116.0q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 95.4-147.4 244.0-214.3zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM746.9 740.0q0.0-4.0-0.6-5.1-60.0-107.4-180.0-323.4t-180.6-324.0l-28.0-50.9q-5.7-9.1-16.0-9.1-6.9 0.0-76.6 40.0-9.1 5.7-9.1 16.0 0.0 6.9 25.1 49.7-81.7 37.1-150.6 98.9t-119.1 140.0q-11.4 17.7-11.4 39.4t11.4 39.4q87.4 134.3 217.1 212.0t283.4 77.7q50.9 0.0 102.9-9.7l30.9 55.4q5.7 9.1 16.0 9.1 2.9 0.0 10.3-3.4t17.7-8.9 18.9-10.6 18.0-10.6 11.1-6.6q9.1-5.7 9.1-15.4zM768.0 484.6q0.0-79.4-45.1-144.9t-119.4-94.0l160.0 286.9q4.6-25.7 4.6-48.0zM1024.0 411.4q0.0-20.0-11.4-39.4-22.3-36.6-62.3-82.9-85.7-98.3-198.6-152.6t-239.7-54.3l42.3 75.4q121.1 10.3 224.3 78.3t172.3 175.4q-65.7 102.3-161.1 168.0l36.0 64.0q54.3-36.6 104.3-87.4t82.6-105.1q11.4-19.4 11.4-39.4z"></path>',moreActions:'<path d="M597.3 512a85.3 85.3 0 1 0-170.6 0 85.3 85.3 0 0 0 170.6 0zm298.7 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0zm-597.3 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0z"></path>'};function pd(e){return!0===Gv().config.useAllFieldsForComparison&&e.mainPlot.mainCurve.isOhlc&&e.mainAxis.comparison===d.None&&e.mainPane.axes.map(e=>e.plots).flat().reduce((e,t)=>e+(t.isSymbol?1:0),0)>1}const fd=new Wo;function md({plots:e,isMultiSymbol:t,isMultiContract:i,date:s,time:n,dateFieldName:r,hideSymbols:o,revealingClose:a}){const l=o&&a,c=[Td(r,s,null,"heading"),n?Td("Time",n,null,"heading"):""],u=e.map(e=>{if(0===e.values.length)return null;const s=(e=>{const s=e.name.startsWith(gs.FAKE_SYMBOL_PREFIX);switch(e.type){case f.Expression:return!0;case f.Symbol:return!(!t&&!i||s)||!o;default:return!1}})(e)?vd(f[e.type],e.name,e.values[0].color):"",n=e.values.map(t=>Td(t.id===Ka.Close.id&&l?e.description:t.longName,t.value,t.color));if(e.events&&e.events.length){const t=e.events.map(e=>vd(`${e.field.name} (${ld(fd,e.date)})`,e.value,e.color));n.push(...t)}return n.unshift(s),ie(e.unalignedDate)&&n.unshift(Td("Date",e.unalignedDate,e.values[0].color,"heading")),n}).filter(e=>null!=e).flat();return`<table class="values-table">${c.concat(u).filter(e=>""!==e).join("")}</table>`}function gd(e,{panes:t,date:i,time:s,isMultiSymbol:n},r=!1,o=!1,a=!1,l=!1,c=!1,u=!1){return t.map((h,d)=>{const p=r?h.plots:h.plots.filter(e=>!e.isMain),m=e.mainPlot.axis.pane.id===h.id,g=a&&m?`<span class="field-name" style="padding-right:5px">${i} ${s||""}</span>`:"",y=p.map(t=>function(e,t,i,s,n,r,o,a){const{id:l,name:c,type:u,error:h,description:d,values:p,events:m,isMain:g}=e,y=a.display.tooltip,A=h||d,S="value-title"+(g?" value-main":""),T=f[u],v=["Study","BalanceSheet","IncomeStatement"].includes(T)||"Expression"===T&&!i,P=!v||a.hasLegend&&i?"":Cd(l),C=function(e,t){const i=Ad(t?"eye":"eyeSlash"),s=t?"Hide":"Show",n=`${s} plot`;return`<a class="show-hide-plot" data-plot-id="${e}" data-act="${s}" title="${n}">${i}</a>`}(l,e.visible),b=o?function(e){const t=Ad("moreActions");return`<a class="more-actions" data-plot-id="${e}" data-act="Menu" title="Actions">${t}</a>`}(l):"",E=pd(a)&&e.type===f.Symbol,L=(g||E)&&(!s||e.values.length>1),M=e=>L?e.abbreviation:"Close"===e.id&&r?d+" ":null,_=t?p.map(e=>Pd(M(e),e.value,e.color)).join(" ")+function(e){if(e&&e.length){return`Event ${e.map(e=>Pd(`${e.field.name} (${ld(fd,e.date)})`,e.value,e.color)).join(" ")}`}return""}(m):"",x=e=>`<div class="box" style="background-color:${e.color}"></div>`,I=!g&&"Expression"!==T,D=p.slice(0,I?p.length:1).map(x).join(""),O=t?"":D,w="Name"===y.mainTitle?c:d,R=n?e.visible&&t?"":`${d}`:`${w}`;let N=s&&E?`${d} (${R})`:R;y.showMainTitle||(N="");const V=()=>{const e=a.data?.aggregation.toShortString(),t=a.data?.aggregation.describe();return`<span class="value-main" title="${t}">·${e}·</span>`},H=e.isMain?V():"";return`\n <div class="plot">\n ${P} ${C} ${b} ${O}\n <a class="${S}" ${A?`title="${A}" `:""}data-plot-id="${l}">${N}</a>\n ${H} ${_}\n </div>\n `.trim()}(t,o,m,n,l,c,u,e)),A=`${g}${y.join("")}`,S=function(e,t){const i=e>0,s=e<t-1;return[`${i?Sd(!0,e):""}`,`${s?Sd(!1,e):""}`].join(" ").trim()}(d,t.length);return{id:`bc-tip-${h.id.substring(0,8)}`,isMainPane:m,content:A,moveContent:S,bounds:h.bounds}})}function yd(e){return`bchart-icon-${e}`}function Ad(e,t=null,i=10){return`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="${i}px" height="${i}px" ${ie(t)?`style="fill:${t}"`:""}><use xlink:href="#${yd(e)}"></use></svg>`}function Sd(e,t){const i=e?"Up":"Down";return`<span data-pane="${t}" data-dir="${i}" title="Move ${i}" class="move-pane">${Ad(`chevron${i}`)}</span>`}function Td(e,t,i=null,s=[]){"string"==typeof s&&(s=s.split(" "));const n="string"==typeof i?` style="color: ${i}"`:"";return`\n <tr class="${["value-row",...s].join(" ")}">\n <td class="field-name">${e}</td>\n <td${n} class="field-value">${t}</td>\n </tr>\n `}function vd(e,t,i=null){return Td(e,t,i,"value-title")}function Pd(e,t,i){const s="string"==typeof i?` style="color: ${i}"`:"";return`${ie(e)?`<span class="field-name">${e}</span>`:""}<span${s} class="field-value">${t}</span>`}function Cd(e){return`<a class="delete-plot" data-plot-id="${e}" title="Delete plot">${Ad("delete")}</a>`}function bd(e,t,i,s,n,r){const a=function(e,t){const i=e.data.aggregation,s=e.display.xAxis,n=s.isOrdinal,r=te(n)&&n,o=r?s.ordinalName??"Value":"Date";return{date:r?td(t):ld(i,t),time:i.isEndOfDay||r?null:cd(i,t,!1),isMultiSymbol:_d(e),isMultiContract:i.isMultiContract,dateFieldName:o}}(e,t);a.offset=i,a.lastBarRefresh=!1,a.chartId=e.elementId;const l=i=>i.axes.map(e=>e.plots).flat().filter(t=>!n||t===e.mainPlot).map(i=>function(e,t,i,{isMultiContract:s},n){const r=n.isStudy;if(!n.timeSeries.hasData)return null;const a=n.timeSeries.container;n.type,f.Expression;const l=n.axis.comparison!==d.None,c=n.axis.comparison===d.Percent,u=(e,s)=>n.customPlotValues&&s!==Ka.DateTime?[n.getValueAt(s,t,i),0]:Ld(e,s,t,l),h=n,p=r?`${Gr(h.model.study).meta.title} ${h.fullParams}`:n.metaData.name||"",m={isMain:n.main,type:n.type,typeName:f[n.type],name:n.title,description:p,exchange:n.metaData.exchange||"",error:h.errorText,id:n.id,visible:n.visible};if(ie(h.yearOffset)&&0!=h.yearOffset){const i=e.data.aggregation,s=function(e,t){return Ke(2,arguments),lt(e,-je(t))}(t,h.yearOffset);m.unalignedDate=ld(i,s)}const g=n.curves[0];s&&n.type===f.Symbol&&a.hasField(Ka.Symbol)&&(t.valueOf()===gs.ZERO_DATE.valueOf()?m.name=n.timeSeries.container?.getLastDataPoint(Ka.Symbol):m.name=u(g,Ka.Symbol)[0]);const y={},A={range:n.axis.yScale.domain(),allDigits:!0};Md(n,e,A);const S=(e,t)=>{const i=(t===Ka.Change||t===Ka.PercentChange)&&e>0?"+":"";return c?i+id(e):i+n.metaData.format(e,t,A)},T=pd(e),v=/* @__PURE__ */new Set;return m.values=n.curves.filter(e=>e.visible).map(e=>(!n.main&&n.isSymbol&&T?$u:e.fields).map(t=>{if(v.has(t))return null;v.add(t);const[i,s]=u(e,t),a=n.axis.yScale.priceToY(i);y[t.id]=!0;const l=n.customPlotValues?h.getColorOf(t):e.getColor(s,e.style!==o.HollowCandles,t);let c=S(i,t).trim();if(ie(i)&&t===Ka.Change){const[t]=u(e,Ka.PercentChange);ie(t)&&(c+=` (${S(t,Ka.PercentChange)})`)}return{abbreviation:xd(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${r?h.params:""}`.trim(),color:Sn(l),val:i,y:a,value:c}}).filter(e=>null!==e)).flat(),m.events=n.findEvents(u(g,Ka.DateTime)).filter(e=>e.field!==Ka.Custom),m}(e,t,r,a,i)).filter(e=>null!==e);return a.panes=e.panes.map(e=>({bounds:Ed(e),id:e.id,plots:l(e)})),a}function Ed(e){const t=e.getBounds();if(!ie(t))return;const{x:i,y:s,width:n,height:r}=t,{leftOffset:o,rightOffset:a}=e.presenter.view;return{top:s,left:i+o,right:a,bottom:s+r,width:n,height:r}}function Ld(e,t,i,s=!1){const n=e.plot,r=n.timeSeries.container,o=n.axis.pane.presenter.timeline,a=G(o,+i,Number,ud),l=o.at(a-e.shift);if(null===l)return[null,0];const c=r.getTimeData(),u=G(c,+l,Number);return[!c[u]||c[u].getTime()!==l.getTime()?null:e.dataAt(t,u,!s),u]}function Md(e,t,i){ie(e.precision)?i.overridePrecision=e.precision:e.isStudy&&ie(t.mainPlot?.precision)&&!ie(Gr(e.model.study).meta.decimals)&&(i.overridePrecision=t.mainPlot.precision)}function _d(e){const t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===f.Symbol&&e.symbol!==t)}function xd(e){return e.id===Ka.Change.id?"Δ":e.id.substring(0,1)}class Id{plot;id;fields=[];colors=[];style=o.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle="Solid";varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=Pe(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=ie(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(Ka.Close)}get name(){return this.isOhlc?"":this.fields[0].name}get isHeikinAshiStyle(){return this.style===o.HeikinAshi}get isCandle(){return this.style===o.Candlestick||this.style===o.HollowCandles||this.style===o.HeikinAshi}get isHollowCandles(){return this.style===o.HollowCandles}get isElderImpulseSystemStyle(){return this.style===o.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===o.PercentChange}get isOhlcStyle(){return this.style===o.OHLC}get isHlcStyle(){return this.style===o.HLC}get isRangeStyle(){return this.style===o.Range}get isRenko(){return this.style===o.Renko}get isKagi(){return this.style===o.Kagi}get isPointAndFigure(){return this.style===o.PointAndFigure}get isLineBreak(){return this.style===o.LineBreak}get isBaseline(){return this.style===o.Baseline}get isLineLike(){return[o.Line,o.Area,o.Baseline,o.PercentChange].includes(this.style)}get isColumn(){return this.style===o.Column}get isMultiColumn(){return this.style===o.MultiColumn}get isStackedColumn(){return this.style===o.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>r[e])),this.colors=e.colors,this.fields=e.fields.map(e=>Ka[e]),this.style=o[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,i=!0){const s=!this.plot.isComparison(d.None),n=e===Ka.PercentChange,r=e===Ka.Change,o=n||(!i||s)&&r,a=this.timeSeries.container.hasField(Ka.Last)?Ka.Last:Ka.Close,l=o?a:e,u=(e,t)=>{const i=this.timeSeries.container.getData(e)[t];return e.type!==c.Number?i:this.plot.priceMapper(i,t,e)},h=u(l,t);if(!o)return h;if(t<=1)return 0;const p=u(l,t-1),f=h-p;return n?0===p?0:f/p:f}timeSeriesAt(e){const t=this.timeSeries.container.getTimeData(),i=t.length;return e<0||e>i-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){const e=this.view.xAxis.xScale;if(!ie(e.extent()))return null;return 0!==this.shift?e.extent().map(t=>e.timeline.at(t-this.shift)):e.domain()}get yScale(){return this.plot?.yScale??this.axis.yScale}getCore(){const e=this.timeSeries;if(!e.hasData||!this.visible)return null;const t=this.view.xAxis.xScale.extent();if(!ie(t))return null;const i=this.yScale.domain();if(!ie(i))return null;return{ts:e,extent:t,domain:i,range:this.yScale.range()}}drawHover(e,t,i){if(!this.isLineLike)return;if(null===this.getCore())return;const[s,n]=Ld(this,this.pickMainField(),t);if(!ie(s))return;e.save(),_n(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=Sn(this.getColor(n)),e.beginPath();Yd(e,i,this.priceToY(s),this.lineMarker??"Circle",1.3333),e.fill(),e.restore()}draw(e){const t=this.getCore();if(null===t)return;const{ts:i,extent:s,domain:n,range:r}=t;e.save(),e.setLineDash([]);const a=i.container.getTimeData(),l=this.shiftedTimeDomain[0],c={bar:this.view.xAxis.xScale.bar,domain:n,range:r,slice:s,start:G(a,+l,Number)||0},u=ie(this.zones);this.isOhlc?Gd.call(this,e,c):this.isRenko||this.isLineBreak?Bd.call(this,e,c):this.style===o.Ribbon?this.varyColorPerBar?ep.call(this,e,c):Qd.call(this,e,c,this.colors[0]):this.style===o.Area?u?Nd.call(this,e,c,Od,!0):Od.call(this,e,c,this.colors,!0):this.isColumn||this.isMultiColumn?u?Nd.call(this,e,c,kd,!0):kd.call(this,e,{...c,range:[null,null]}):this.isStackedColumn?Fd.call(this,e,c):this.isBaseline?Hd.call(this,e,c):this.style===o.Step?u?Nd.call(this,e,c,Ud):Ud.call(this,e,c,this.colors[0]):this.isKagi?Zd.call(this,e,c):this.isPointAndFigure?Jd.call(this,e,c):this.style===o.Dots?Wd.call(this,e,c):this.style===o.Line||this.isPercentChangeStyle?u?Nd.call(this,e,c,jd):this.varyColorPerBar?qd.call(this,e,c):jd.call(this,e,c):Hv(`Drawing of the curve style '${this.style}' is not implemented yet`,"error"),e.restore()}pickMainField(){return 1===this.fields.length?this.fields[0]:this.fields.includes(Ka.Last)?Ka.Last:this.fields.includes(Ka.Close)?Ka.Close:this.fields[0]}get zoneColors(){if(!ie(this._zoneColors)){const e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return-1===t&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?Sn(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(Ka.BARCOLIX))return null;const t=this.dataAt(Ka.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,i=null){if(this.varyColorPerBar){const i={};if(this.isOhlc||this.isRenko||this.isLineBreak){const t=this.dataAt(Ka.Open,e),s=this.dataAt(Ka.High,e),n=this.dataAt(Ka.Low,e),r=this.dataAt(Ka.Close,e),o=this.dataAt(Ka.Change,e);i.open=t,i.high=s,i.low=n,i.close=r,i.change=o}else if(this.plot.isStudy&&!["VOL","MAVOL"].includes(this.plot.model.study)){const t=this.pickMainField(),s=this.dataAt(t,e-1),n=this.dataAt(t,e),r=ie(s),o=ie(n);i.change=r?o?n-s:-1:o?1:0}else{const t=this.plot.axis.pane.presenter.data.aggregation;t.isTick&&t.spec===l.None||(i.open=this.dataAt(Ka.Open,e),i.close=this.dataAt(Ka.Close,e)),i.change=this.dataAt(Ka.Change,e)}let s;const n=function(e,{open:t,close:i,change:s},n){const r=n.length>2&&e!==o.HLC,a=ie(t,i),l=a&&i>t,c=a&&i===t,u=s>0,h=0===s;return{useSame:r,isUp:l,isSame:c,isUpPrev:u,isSamePrev:h,isDown:!l&&!c,isDownPrev:!u&&!h}}(this.style,i,this.colors),a=this.getComputedColor(e);switch(this.style){case o.Candlestick:case o.Renko:case o.LineBreak:case o.Range:case o.HeikinAshi:case o.OHLC:case o.HLC:case o.Column:{if(ie(a)){s=a;break}let t=n.useSame?n.isUp:n.isUp||n.isSame,i=n.isSame;const o=this.attributes||[],l=this.plot.isStudy&&!["HASMO","VOL","MAVOL"].includes(this.plot.model.study);if((o.includes(r.ChangeBased)||l)&&(t=n.useSame?n.isUpPrev:n.isUpPrev||n.isSamePrev,i=n.isSamePrev),s=this.colors[t?1:0],n.useSame&&i&&(s=this.colors[2]),this.isRenko||this.isLineBreak||this.isRangeStyle){1===this.dataAt(Ka.Projection,e)&&(s=Pn(.5,!0)(s))}break}case o.ElderImpulseSystem:s=this.colors[this.dataAt(Ka.BREL,e)];break;case o.HollowCandles:{const e=this.colors[n.isUpPrev||n.isSamePrev?1:0];s=t&&(n.isUp||n.isSame)?gs.COLOR_TRANSPARENT:e;break}case o.Line:case o.PercentChange:case o.Ribbon:case o.Kagi:if(ie(a)){s=a;break}s=this.colors[0];break;case o.PointAndFigure:{const t=Sh(this.dataAt(Ka.BARKIND,e))?1:0;s=this.colors[t];break}default:throw new Error(`Unexpected style ${o[this.style]} for a curve with varying colors`)}return ie(s)||(s=this.colors[0]),s}if(this.zones){const t=this.pickMainField(),i=this.dataAt(t,e),s=this.getColorsFromZone(i);return this.style===o.Area?this.pickAreaStroke(s):s.length>0?s[0]:this.colors[0]}{const e=e=>e===i;return(this.isMultiColumn||this.isStackedColumn)&&ie(i)?this.colors[function(e,t){return Math.min(Math.max(t,0),e.length-1)}(this.colors,this.fields.findIndex(e))]:this.colors[0]}}}function Dd([e,t],i,s){let n=i;const r=this.timeSeries.container.size;for(let o=e;o<=t;o++){for(;this.timeSeriesAt(n)<this.timelineAt(o-this.shift)&&n<r;)++n;if(n===r)break;const e=this.timeSeriesAt(n)>this.timelineAt(o-this.shift);s.call(this,n,e)}}function Od(e,t,i,s=!1){jd.call(this,e,t,this.pickAreaStroke(i)),tp.call(this,e,t,i[0],s)}function wd(e,t){const i=ie(e),s=ie(t);let n,r;const o=this.pane.getBounds();if(i)if(s){const i=this.priceToY(e),s=this.priceToY(t);n=(i+s)/2,r=new xn(o.x,s,o.width,i-s)}else n=this.priceToY(e),r=new xn(o.x,o.y,o.width,n-o.y);else n=this.priceToY(t),r=new xn(o.x,n,o.width,o.y+o.height-n);return[n,r]}const Rd=(e,t)=>{const i=Pn(.6)(e),s=Cn(.6)(e),n="linLighten"===t;return[n?s:i,e,n?i:s]};function Nd(e,t,i,s=!1,n){let r;this.zones.forEach((o,a)=>{const l=o.value,[c,u]=wd.call(this,r,l);e.save(),_n(e,u),s&&(t.range=[null,c]);let h=this.zoneColors[a];if(o.gradient){const t=Rd(h,o.gradient),i=e.createLinearGradient(0,u.y,0,u.y+u.height);i.addColorStop(0,t[0]),i.addColorStop(.5,t[1]),i.addColorStop(1,t[2]),h=i}else ie(n)&&(h=n(a,h));i.call(this,e,t,h),e.restore(),r=l})}function Vd(e,t){const{x:i,width:s}=this.pane.getBoundsWithoutScales();e.save(),e.lineWidth=1,e.strokeStyle="#888",e.setLineDash(An("dot")),$n(e,t,i,i+s),e.restore()}function Hd(e,t){const[i,s]=t.range,{baseLevel:n}=function(e){const{BaseLevel:t}=fe(e);return{baseLevel:Number.isFinite(t)?Ce(0,100,t):50}}(this.plot.inputs),r=(i-s)*n/100+s;this.zones[0].value=this.yToPrice(r),Vd.call(this,e,r);Nd.call(this,e,t,Od,!0,(t,n)=>{const o=1===t,a=Tn(n,0),l=e.createLinearGradient(0,o?i:s,0,r);return l.addColorStop(0,n),l.addColorStop(1,a),[l,Tn(n,1)]})}function Bd(e,{bar:t,slice:i,start:s}){let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;Dd.call(this,i,s,(i,s)=>{if(!s){const[s,r]=[Ka.Open,Ka.Close].map(e=>this.dataAt(e,i)).map(this.priceToY,this),o=Math.floor(t.totalWidth/2);e.fillStyle=this.getColor(i),e.beginPath(),e.rect(n-o,s,t.totalWidth,r-s),e.fill()}n+=t.totalWidth})}function Fd(e,{bar:t,slice:i,start:s}){if(!this.isFirstVisibleOfStyle())return!1;let n=this.view.xAxis.xScale.range()[0]+t.offset;const r=Kn();r.prolog(e);const o=this.plot.curves.filter(e=>e.isStackedColumn);Dd.call(this,i,s,(i,s)=>{if(!s){let s=this.priceToY(0),a=0;o.forEach(o=>{if(!o.visible)return;const l=o.fields[0];if(a+=this.dataAt(l,i),ie(a)){const c=this.priceToY(a);e.fillStyle=o.getColor(i,!1,l),e.beginPath(),e.rect(r.adjust(n),r.adjust(c),r.adjust(t.width),r.adjust(s-c)),e.fill(),s=c}})}n+=t.totalWidth}),r.epilog(e)}function kd(e,{bar:t,slice:i,start:s,range:[n,r]}){let o=this.view.xAxis.xScale.range()[0]+t.offset;const a=this.isMultiColumn,l=a?this.fields:[this.pickMainField()],c=t.width/(a?l.length:1),u=Kn();u.prolog(e),Dd.call(this,i,s,(i,s)=>{s||l.forEach((t,s)=>{const n=this.dataAt(t,i);if(ie(n)){ie(r)||(r=this.priceToY(0));const a=this.priceToY(n);e.fillStyle=this.getColor(i,!1,t),e.beginPath(),e.rect(u.adjust(o+s*c),u.adjust(a),u.adjust(c),u.adjust(r-a)),e.fill()}}),o+=t.totalWidth}),u.epilog(e)}function Wd(e,{bar:t,slice:i,start:s}){let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;e.fillStyle=this.getColor(0);const r=Math.max(1,this.lineWidth||gs.CURVE_STYLE_DOTS_RADIUS),o=2*Math.PI;e.beginPath(),Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const t=this.priceToY(s);e.moveTo(n+r,t),e.arc(n,t,r,0,o)}}n+=t.totalWidth}),e.fill()}function Ud(e,{bar:t,slice:i,start:s},n){let r=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const o=Kn();o.prolog(e),e.strokeStyle=n,e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(An(this.dashStyle)),e.beginPath();let a=!1,l=null;Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const n=this.priceToY(s);if(a)e.lineTo(r,l),e.lineTo(r,n);else{const s=this.dataAt(t,i-1);if(ie(s)){const t=this.priceToY(s);e.moveTo(-1,t),e.lineTo(r,t),e.lineTo(r,n)}else e.moveTo(r,n);a=!0}l=n}}r+=t.totalWidth}),e.stroke(),o.epilog(e)}const $d=[Ka.Open,Ka.High,Ka.Low,Ka.Close];function Gd(e,{bar:t,slice:i,start:s}){const n=this.presenter.display.chart.showMinMaxArc;let r=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const o=Kn();o.prolog(e);let a=null,l=null,c=null,u=null;const h=t=>{this.isCandle?(this.isHollowCandles?t.outlineColor=this.getColor(t.ix,!1):(this.colors.length>3&&(t.outlineColor=this.colors[3]),this.colors.length>4&&(t.wickColor=this.colors[4])),function(e,{x:t,adjust:i,width:s,y:[n,r,o,a],color:l,outlineColor:c,wickColor:u,isMin:h,isMax:d},p){const f=s/2;e.lineWidth=p,e.fillStyle=l,e.strokeStyle=c||l,e.beginPath(),e.rect(i(t-f),n,s,i(a-n)),e.fill(),e.stroke(),e.strokeStyle=u||c||l,e.beginPath(),e.moveTo(t,Math.min(a,n)),e.lineTo(t,r),e.moveTo(t,Math.max(a,n)),e.lineTo(t,o),e.stroke();const m=0===bn(l).a;e.strokeStyle=m?c:l,zd(e,h,d,t,o,r,f)}(e,t,this.lineWidth)):(this.isOhlcStyle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&function(e,{x:t,adjust:i,width:s,y:[n,r,o,a],color:l,isMin:c,isMax:u},h,d){const p=s/2;e.lineWidth=h,e.strokeStyle=l,e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),d&&(e.moveTo(i(t-p),n),e.lineTo(t,n));e.moveTo(i(t+p),a),e.lineTo(t,a),e.stroke(),zd(e,c,u,t,o,r,p)}(e,t,this.lineWidth,!this.isHlcStyle)};Dd.call(this,i,s,(e,i)=>{if(!i){const i=$d.map(t=>this.dataAt(t,e)),[s,n,d,p]=i;if(ie(s,n,d,p)){const f={x:o.adjust(r),adjust:o.adjust,width:t.width,y:[s,n,d,p].map(this.priceToY,this).map(o.adjust),isMin:!1,isMax:!1,ix:e,color:this.getColor(e)},m=Math.min(...i),g=Math.max(...i);(!ie(a)||m<a)&&(a=m,c=f),(!ie(l)||g>l)&&(l=g,u=f),h(f)}}r+=t.totalWidth}),n&&(ie(c)&&(c.isMin=!0,h(c)),ie(u)&&(u.isMax=!0,h(u))),o.epilog(e)}function zd(e,t,i,s,n,r,o,a=3){t&&kn(e,{x:s,y:n+a},o,0,Math.PI),i&&kn(e,{x:s,y:r-a},o,0,Math.PI,!0)}function Yd(e,t,i,s,n=1){const r=gs.MARKER_SIZE*n,o=1.25*r;switch(s){case"Circle":e.moveTo(t+r,i),e.arc(t,i,r,0,2*Math.PI);break;case"Square":e.rect(t-r,i-r,2*r,2*r);break;case"TriangleUp":e.moveTo(t-o,i+o),e.lineTo(t+o,i+o),e.lineTo(t,i-o),e.lineTo(t-o,i+o);break;case"TriangleDown":e.moveTo(t-o,i-o),e.lineTo(t+o,i-o),e.lineTo(t,i+o),e.lineTo(t-o,i-o);break;case"Diamond":e.moveTo(t,i-o),e.lineTo(t+o,i),e.lineTo(t,i+o),e.lineTo(t-o,i),e.lineTo(t,i-o)}}function jd(e,{bar:t,slice:i,start:s},n=null){const r=n||this.getColor(0),o=te(this.lineMarker);o&&(e.fillStyle=r,e.beginPath());let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const l=[],c=this.pickMainField();Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.dataAt(c,i);if(ie(t)){const i=this.priceToY(t);o&&Yd(e,a,i,this.lineMarker),l.push({x:a,y:i})}}a+=t.totalWidth}),o&&e.fill(),e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(An(this.dashStyle)),te(this.lineSmoothing)?function(e,t,i,s){if(t.length<2)return;const n=function(e,t){const i=[];for(let s=0;s<e.length-1;s++){const n=e[s-1]||e[s],r=e[s],o=e[s+1],a=e[s+2]||o,l=r.x+(o.x-n.x)/t,c=r.y+(o.y-n.y)/t,u=o.x-(a.x-r.x)/t,h=o.y-(a.y-r.y)/t;i.push({cp1x:l,cp1y:c,cp2x:u,cp2y:h,x:o.x,y:o.y})}return i}(t,s);e.beginPath(),e.strokeStyle=i,e.moveTo(t[0].x,t[0].y);for(const r of n)e.bezierCurveTo(r.cp1x,r.cp1y,r.cp2x,r.cp2y,r.x,r.y);e.stroke()}(e,l,r,this.lineSmoothing):Kd(e,l,r)}function Kd(e,t,i){if(t.length>1){e.beginPath(),e.strokeStyle=i;const s=t[0];e.moveTo(s.x,s.y);for(let i=1;i<t.length;i++){const s=t[i];e.lineTo(s.x,s.y)}e.stroke()}}function qd(e,{bar:t,slice:i,start:s}){e.lineWidth=this.lineWidth,e.lineCap="square",this.dashStyle&&e.setLineDash(An(this.dashStyle));let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,r=null,o=null,a=[];Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const t=this.priceToY(s);o=this.getColor(i),r!==o&&(Kd(e,a,r),a.length>0&&(a=[a.pop()]),r=o),a.push({x:n,y:t})}}n+=t.totalWidth}),Kd(e,a,o)}const Xd=[null,null,null,null];function Zd(e,{bar:t,slice:i,start:s}){e.lineWidth=Math.max(1,.5*t.width),e.lineJoin="miter",e.miterLimit=1.5;let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const r=Kn();r.prolog(e);let o=null,a=null,l=[];Dd.call(this,i,s,(i,s)=>{if(!s){const s=e=>$d.map(t=>this.dataAt(t,e)),[c,u,h,d]=s(i),[,p,f]=i<0?Xd:s(i-1);if(ie(c,u,h,d)){const s=r.adjust(n),m=r.adjust(n-t.totalWidth),g=[c,u,h,d].map(this.priceToY,this).map(r.adjust),y=r.adjust(this.priceToY(u>p?p:f));a=this.getColor(i);const A=ie(o)&&o!==a,S=c===u?1:2,T=c===u?2:1;l.push({x:m,y:g[0]}),l.push({x:s,y:g[S]}),A&&(l.push({x:s,y:y}),Kd(e,l,o),l=[]),A&&l.push({x:s,y:y}),l.push({x:s,y:g[T]}),o=a}}n+=t.totalWidth}),Kd(e,l,a),r.epilog(e)}function Jd(e,{bar:t,slice:i,start:s}){const n=this.view.xAxis.xScale.range()[0],r=t.totalWidth/2;let o=n+t.offset+t.width/2;const a=Kn();a.prolog(e);const l=this.plot.timeSeries.builder.boxSize,c=l/2;Dd.call(this,i,s,(i,s)=>{if(!s){const[t,s]=[Ka.High,Ka.Low].map(e=>this.dataAt(e,i)),n=this.colors[0],u=this.colors[1],h=this.dataAt(Ka.BARKIND,i),d=Sh(h),p=h===gs.BARKIND_XO,f=h===gs.BARKIND_OX;if(ie(t,s))for(let i=t;i>=s;i-=l){const l=a.adjust(o),[h,m]=[l-r,l+r],[g,y,A]=[i,i-c,i+c].map(e=>this.priceToY(e)),S=i===t&&p||i===s&&f?!d:d;e.beginPath(),S?(e.strokeStyle=u,e.moveTo(h,y),e.lineTo(m,A),e.moveTo(h,A),e.lineTo(m,y)):(e.strokeStyle=n,e.ellipse(l,g,r,y-g,0,0,2*Math.PI)),e.stroke()}}o+=t.totalWidth}),a.epilog(e)}function Qd(e,{bar:t,slice:i,start:s},n){e.fillStyle=n;const[r,o]=this.fields;let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const l=[];if(Dd.call(this,i,s,(e,i)=>{if(!i){const t=this.dataAt(r,e),i=this.dataAt(o,e);ie(t,i)&&l.push({x:a,upY:this.priceToY(t),downY:this.priceToY(i)})}a+=t.totalWidth}),l.length>0){e.beginPath(),e.moveTo(l[0].x,l[0].upY);for(let i=1;i<l.length;++i)e.lineTo(l[i].x,l[i].upY);const t=l.length-1;e.lineTo(l[t].x,l[t].downY);for(let i=t-1;i>=0;--i)e.lineTo(l[i].x,l[i].downY);e.closePath(),e.fill()}}function ep(e,{bar:t,slice:i,start:s}){const[n,r]=this.fields;let o=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=[];const l=t=>{if(a.length>1){e.beginPath(),e.fillStyle=t,e.moveTo(a[0].x,a[0].upY);for(let t=1;t<a.length;++t)e.lineTo(a[t].x,a[t].upY);const i=a.length-1;e.lineTo(a[i].x,a[i].downY);for(let t=i-1;t>=0;--t)e.lineTo(a[t].x,a[t].downY);e.closePath(),e.fill()}};let c=null,u=null;Dd.call(this,i,s,(e,i)=>{if(!i){const t=this.dataAt(n,e),i=this.dataAt(r,e);if(ie(t,i)){const s=this.priceToY(t),n=this.priceToY(i);u=this.getColor(e),c!==u&&(l(c),a.length>0&&(a=[a.pop()]),c=u),a.push({x:o,upY:s,downY:n})}}o+=t.totalWidth}),l(u)}function tp(e,{bar:t,slice:i,start:s,range:[n,r]},o,a){if(a){const t=e.createLinearGradient(0,n,0,r);t.addColorStop(0,o),t.addColorStop(1,Tn(o,0)),e.fillStyle=t}else e.fillStyle=o;e.beginPath();let l=null;const c=this.pickMainField();let u=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,h=!1,d=null;Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.dataAt(c,i);if(ie(t)){const i=this.priceToY(t);h?e.lineTo(u,i):(e.moveTo(l=u,i),h=!0),d=u}}u+=t.totalWidth}),e.lineTo(d,r),e.lineTo(l,r),e.closePath(),e.fill()}class ip{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,i=m.Normal,s=[null,null]){this.symbol=e,this.aggregation=t,this.range=s,this.seriesKind=i,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(!ie(this.curveStyle)||!gs.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return"Standard";switch(this.curveStyle){case o.Renko:{const{method:e,period:t,source:i,brickSize:s}=Du(this.inputs);return`Renko;${"ATR"===e?`ATR;${t}`:`${e};${s}`};${i}`}case o.Kagi:{const{method:e,period:t,reversal:i}=uh(this.inputs);return`Kagi;${"ATR"===e?`ATR;${t}`:`User;${i}`}`}case o.PointAndFigure:{const e=Th(this.inputs),{method:t,period:i,reversal:s,boxSize:n,source:r,oneStepBack:o}=e;return`PointAndFigure;${"ATR"===t?`ATR;${i}`:`User;${n}`};${r};${s};${o}`}case o.LineBreak:{const{lineBreak:e}=dh(this.inputs);return`LineBreak;${e}`}default:return o[this.curveStyle]}}get needsExtraKey(){return[m.Options,m.BalanceSheet,m.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(";")}`:""}getHashKey(){const e=this.aggregation.getHashKey(),t=this.getBuilderKey(),i=this.getExtraKey(),s=this.extendedHours??!1;return`${this.symbol}|${e}|${s}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${i}`}duplicate(){const e=new ip(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return e.cacheMe=this.cacheMe,e.barsToFetch=this.barsToFetch,e.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,e.offset=this.offset,e.chartId=this.chartId,e.curveStyle=this.curveStyle,e.extendedHours=this.extendedHours,e.fields=ue(this.fields),e.splits=this.splits,e.padded=this.padded,e}}var sp,np={exports:{}},rp=np.exports;var op=(sp||(sp=1,function(e,t){var i,s;i="object"==typeof window&&window||rp||Ve,s={},i.PubSub?(s=i.PubSub,console.warn("PubSub already loaded, using existing version")):(i.PubSub=s,function(e){var t={},i=-1,s="*";function n(e){var t;for(t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function r(e){return function(){throw e}}function o(e,t,i){try{e(t,i)}catch(s){setTimeout(r(s),0)}}function a(e,t,i){e(t,i)}function l(e,i,s,n){var r,l=t[i],c=n?a:o;if(Object.prototype.hasOwnProperty.call(t,i))for(r in l)Object.prototype.hasOwnProperty.call(l,r)&&c(l[r],e,s)}function c(e,t,i){return function(){var n=String(e),r=n.lastIndexOf(".");for(l(e,e,t,i);-1!==r;)r=(n=n.substr(0,r)).lastIndexOf("."),l(e,n,t,i);l(e,s,t,i)}}function u(e){var i=String(e);return Boolean(Object.prototype.hasOwnProperty.call(t,i)&&n(t[i]))}function h(e){for(var t=String(e),i=u(t)||u(s),n=t.lastIndexOf(".");!i&&-1!==n;)n=(t=t.substr(0,n)).lastIndexOf("."),i=u(t);return i}function d(e,t,i,s){var n=c(e="symbol"==typeof e?e.toString():e,t,s);return!!h(e)&&(!0===i?n():setTimeout(n,0),!0)}e.publish=function(t,i){return d(t,i,!1,e.immediateExceptions)},e.publishSync=function(t,i){return d(t,i,!0,e.immediateExceptions)},e.subscribe=function(e,s){if("function"!=typeof s)return!1;e="symbol"==typeof e?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var n="uid_"+String(++i);return t[e][n]=s,n},e.subscribeAll=function(t){return e.subscribe(s,t)},e.subscribeOnce=function(t,i){var s=e.subscribe(t,function(){e.unsubscribe(s),i.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){var i;for(i in t)Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)&&delete t[i]},e.countSubscriptions=function(e){var i,s,n=0;for(i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)){for(s in t[i])n++;break}return n},e.getSubscriptions=function(e){var i,s=[];for(i in t)Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)&&s.push(i);return s},e.unsubscribe=function(i){var s,n,r,o=function(e){var i;for(i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e))return!0;return!1},a="string"==typeof i&&(Object.prototype.hasOwnProperty.call(t,i)||o(i)),l=!a&&"string"==typeof i,c="function"==typeof i,u=!1;if(!a){for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(n=t[s],l&&n[i]){delete n[i],u=i;break}if(c)for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&n[r]===i&&(delete n[r],u=!0)}return u}e.clearSubscriptions(i)}}(s)),void 0!==e&&e.exports&&(t=e.exports=s),t.PubSub=s,e.exports=t=s}(np,np.exports)),np.exports);const ap=/* @__PURE__ */He(op);function lp(e,t){const i=e.query?.duplicate();if(ie(i)&&i.symbol!==gs.PLACEHOLDER_SYMBOL_NAME&&"Standard"===i.getBuilderKey()){0!==i.barsToFetch&&(i.barsToFetch=i.barsToFetch*gs.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);const e=t(i);return e.serverComputedSeries=!0,e}return new bh}function cp(e){return new Ga(e,c.Number,h.Study,e)}class up{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=/* @__PURE__ */new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=Pe(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw new Error("Should not be called.")}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(const t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){pe(this,e);const t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return gs.EMPTY_ARRAY}get hasData(){return null!==this.container}get source(){if(ie(this._source))return this._source;const e=ie(this.inputs)?this.inputs[gs.INPUT_SOURCE]:null;return ie(e)?Ka[e]:null}set source(e){this._source=e}async ready(){return ps.call(this,async()=>{this.basisChangedToken=this.useNotifications?ap.subscribe(qa.TS_ALL,this.onBasisChanged.bind(this)):null;const e={tag:Pe(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(I);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===qa.TS_EVENTSCHANGED||e===qa.TS_LOADING||this.innerSeries.some(e=>!e.hasData))return;if(!this.shouldTriggerOurRecalc(t.series)||null===this.base||this===t.series)return;const i={tag:Pe(),src:t.series};switch(e){case qa.TS_MANYCHANGED:this.calculate(i);break;case qa.TS_DATAPOINTCHANGED:case qa.TS_DATAPOINTADDED:{const s=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(i,s,e===qa.TS_DATAPOINTADDED);break}case qa.TS_TIMELINECORRECTION:case qa.TS_QUOTEMARKER:break;default:throw new Error("Unknown time series message, likely forgot to handle it")}}shutdown(){this.useNotifications&&this.basisChangedToken&&ap.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){const i=this.calculateAt(e);if(null!==i){Object.keys(i).forEach(e=>{const s=i[e],n=this.studyFields[e];t?this.container.addDataPoint(n,s):this.container.setLastDataPoint(n,s)})}}notify(e,t){J(e,{series:this,index:t})}calculateCommon(e,t=null,i=-1,s=!0){const n=-1===i,r=n?t=>{!ie(e.src)&&ie(t.calcCtx)||t.calculate(e)}:t=>t.recalculateAt(e,i,s);if(null===this.base)return;if(this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)return;this.calcCtx=e;if(this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>r(e)),n&&(this.container=this.makeContainer()),void 0!==this.calculateAt)if(n){const e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}else this.calculateDataPoint(i,s);t&&(ie(e.src)||this.initialNotification)&&this.notify(t,i)}calculate(e){this.calculateCommon(e,qa.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,i){this.computedServerSide||(!i&&te(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED,t,i))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,i){const s=this.innCont(e),n=s.size;return i<0||i>n-1?null:s.getData(t)[i]}innHasData(e){const t=this.innCont(e);return ie(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(Ka.DateTime,Ka.Symbol)}makeContainer(){const e=this.defaultWrappers.concat(this.getWrappers()),t=Object.keys(this.studyFields).map(e=>this.studyFields[e],this);return new xu(t,this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,i,s=this.base){return s.getData(i).slice(e-t+1,e+1)}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}}class hp extends up{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}}class dp extends hp{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){const[t,i,s,n]=[Ka.Open,Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e),this);let r=null,o=null,a=null,l=null;const c=w([t,i,s,n]);if(e<1)r=w([t,n]),o=i,a=s,l=0;else{const[t,n]=[Ka.Open,Ka.Close].map(t=>this.container.getData(t)[e-1],this);r=w([t,n]),o=Math.max(i,r,c),a=Math.min(s,r,c),l=c-n}return{[Ka.Open.id]:r,[Ka.High.id]:o,[Ka.Low.id]:a,[Ka.Close.id]:c,[Ka.Change.id]:l}}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}class pp extends up{constructor(e,t){super(e,t),My(this)}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)&&s.hasField(this.source)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=w(n.filter(D)):R(n)&&(t=w(n))}return{[this.target.id]:t}}getWrappers(){return this.source===Ka.Volume?this.wrapBaseFields(Ka.Volume,Ka.TradeSize,Ka.Change,Ka.Open,Ka.Close):[]}}class fp extends up{multiplier;constructor(e,t,i){super(e,t),this.multiplier=i(this.period),My(this)}calculateAt(e){let t=null;const[i,s]=_y(this);if(this.atLeast(e,2)&&s.hasField(this.source)){const n=this.container.getData(this.target)[e-1];if(null!==n){t=(this.innVal(i,this.source,e)-n)*this.multiplier+n}else{const i=this.period;if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=w(n.filter(D)):R(n)&&(t=w(n))}}}return{[this.target.id]:t}}}class mp extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=Ka.OpenInterest;return this.base.hasField(i)&&(t=this.baseVal(i,e)),{[i.id]:t}}}const gp={inField:Ka.MA,outFields:[Ka.ENVU,Ka.ENVD],func:ay},yp={inField:Ka.EMA,outFields:[Ka.ENVEXPU,Ka.ENVEXPD],func:ly},Ap={inField:Ka.SMA,outFields:[Ka.ENVSMOU,Ka.ENVSMOD],func:cy};class Sp extends up{kind;perc;constructor(e,t,i){super(e,i),this.kind=t,this.perc=this.inputs.Percent/100;const s=t.func(i,this.inputs.Period,e.source);this.addInner(s)}calculateAt(e){let t=null,i=null;const s=this.innVal(1,this.kind.inField,e);if(null!==s){const e=s*this.perc;t=s+e,i=s-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:i}}}class Tp extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period1,this.source),s=ay(t,this.inputs.Period2,this.source),n=by(this.target,(e,t,i)=>t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}}const vp={fields:[Ka.MACD,Ka.MACDS,Ka.MACDH],avgFunc:ay,mapFunc:Ey,histogramVaryColor:!0},Pp={fields:[Ka.MACD,Ka.MACDS,Ka.MACDH],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!0},Cp={fields:[Ka.MACD,Ka.CTLTM,Ka.CTM],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!1},bp={fields:[Ka.MACD,Ka.CTLTMF,Ka.CPMI],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!1},Ep={fields:[Ka.PPO,Ka.PPOS,Ka.PPOH],avgFunc:ly,mapFunc:Ly,histogramVaryColor:!0},Lp={fields:[Ka.PVO,Ka.PVOS,Ka.PVOH],avgFunc:ly,mapFunc:Ly,histogramVaryColor:!1};class Mp extends up{histogramVaryColor=!1;histogramField;get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){const i=this.container.getData(this.histogramField)[e],s=this.container.getData(this.histogramField)[e-1];if(ie(i,s)){const n=i<=0;t=n?1:3,e>0&&(n&&i>s&&(t=0),!n&&i<s&&(t=2))}}return{[Ka.BARCOLIX.id]:t}}}class _p extends Mp{fields;constructor(e,t,i){super(e,i),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];const s=t.avgFunc(i,e.inputs.Period1,e.source,void 0),n=t.avgFunc(i,e.inputs.Period2,e.source,void 0),r=by(this.fields[0],t.mapFunc,s,n),o=t.avgFunc(r,e.inputs.Period3,r.target,this.fields[1]),a=by(this.fields[2],Ey,r,o);this.addInner(r,o,a)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}}const xp=cp("_AVG_GAIN"),Ip=cp("_AVG_LOSS");class Dp extends up{constructor(e,t,i){super(e,i);const s=Sy(i,this.inputs.Period,this.source,Ka.RSI,t),n=Oy(e,"MA","Average")(s,this.inputs.PeriodAvg,Ka.RSI,Ka.RSIAVG);this.addInner(s,n)}getWrappers(){return[this.wrapInner(Ka.RSI,1),this.wrapInner(Ka.RSIAVG,2)]}}class Op extends up{highest;index;constructor(e,t,i,s){super(e,s),this.highest=t,this.index=i}calculateAt(e){let t=null;const i=this.inputs.Period;if(this.atLeast(e,i)){const s=this.past(e,i,this.source);R(s)&&(t=this.highest?Math.max(...s):Math.min(...s),this.index&&(t=i-s.indexOf(t)-1))}return{[this.target.id]:t}}}class wp extends up{toHighest;field;highField;lowField;constructor(e,t,i){super(e,i),this.toHighest=t;const s=ie(e.source),n=e.source,r=s?n:Ka.Close;this.field=r;const o=s?n:Ka.High;this.highField=o;const a=s?n:Ka.Low;this.lowField=a;const l=dy(i,e.inputs.Period,this.highField,Ka.HH,!0),c=dy(i,e.inputs.Period,this.lowField,Ka.LL,!1);this.addInner(l,c)}calculateAt(e){let t=null;const i=this.baseVal(this.field,e),s=this.innVal(1,Ka.HH,e),n=this.innVal(2,Ka.LL,e);if(R([i,s,n])){const e=this.toHighest?s:n,r=s-n;0!==r&&(t=(i-e)/r*100)}return{[this.target.id]:t}}}const Rp=cp("RawPercK");class Np extends up{kField;constructor(e,t,i,s){super(e,s);const n=py(s,this.inputs.Period1,t?Rp:i,!1),r=Oy(e,"MA"),o=r(n,this.inputs.Period2,n.target,t?i:Ka.PercD),a=t?r(o,this.inputs.Period3,o.target,Ka.PercD):o;this.kField=i,t?this.addInner(o,a):this.addInner(n,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(Ka.PercD,2)]}}function Vp(e,t,i,s,n){if(null===n)return null;const r=e*n,o=s+r,a=s-r;switch(t){case Ka.BOLLBU:return o;case Ka.BOLLBL:return a;case Ka.BOLLBW:return(o-a)/s*100;default:return null}}class Hp extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=this.inputs.Period,n=this.source,r=ay(i,s,n,Ka.BOLLBM),o="Modified"===t,a=vy(o?function(e,t,i=Ka.PCTCHG){return ny("PCTCHG",{source:t,target:i,inputs:fy},e)}(i,n):i,s,o?Ka.PCTCHG:n),l=this.inputs.Width,c=e=>_(Vp,l,e),u=by(Ka.BOLLBU,c(Ka.BOLLBU),r,a),h=by(Ka.BOLLBL,c(Ka.BOLLBL),r,a),d=by(Ka.BOLLBW,c(Ka.BOLLBW),r,a),p=Oy(e,"MA","Average")(d,this.inputs.PeriodAvg,Ka.BOLLBW,Ka.BOLLBWA);this.addInner(r,a,u,h,d,p)}calculateAt(e){const t=this.innVal(3,Ka.BOLLBU,e),i=this.innVal(4,Ka.BOLLBL,e),s=this.innVal(1,Ka.BOLLBM,e),n=this.innVal(5,Ka.BOLLBW,e),r=this.innVal(6,Ka.BOLLBWA,e);let o=null;switch(ie(t,i)&&(o=(this.baseVal(Ka.Close,e)-i)/(t-i)),this.kind){case"Regular":return{[Ka.BOLLBU.id]:t,[Ka.BOLLBL.id]:i,[Ka.BOLLBM.id]:s};case"Width":return{[Ka.BOLLW.id]:t-i};case"Percent":return{[Ka.BOLLP.id]:o};case"BandWidth":return{[Ka.BOLLBW.id]:n,[Ka.BOLLBWA.id]:r};case"Modified":{let t=null,i=null,n=null,r=null;const o=this.innVal(2,Ka.MSD,e);if(ie(o)){const e=this.inputs.MultInside,a=this.inputs.MultOutside;t=s+e*o,n=s-e*o,i=s+a*o,r=s-a*o}return{[Ka.MBBUI.id]:t,[Ka.MBBLI.id]:n,[Ka.MBBUO.id]:i,[Ka.MBBLO.id]:r,[Ka.MBBM.id]:s}}default:return null}}}const Bp=cp("_ABS_CHG"),Fp=cp("_MA_ABS_CHG"),kp=cp("_CHG");const Wp=cp("_PDM"),Up=cp("_MDM"),$p=cp("_TRS"),Gp=cp("_PDS"),zp=cp("_MDS"),Yp=cp("_DX");class jp extends up{useEma;adxField;multiplier;constructor(e,t,i,s){super(e,s),this.useEma=t,this.adxField=i,this.multiplier=2/(this.inputs.AdxSmoothing+1);const n=my(s,Ka.TR);this.addInner(n)}get helpers(){return[Wp,Up,$p,Gp,zp,Yp]}sum(e,t,i,s){let n=null;if(this.atLeast(e-1,s-1)){let r=this.past(e-1,s-1,t,this.container);r.push(i),R(r)&&(n=r.reduce((e,t,i)=>e+t,0))}return n}smooth1(e,t,i,s){let n=null;const r=this.inputs.DiLength,o=this.container.getData(i)[e-1];return n=null!==o?o-o/r+s:this.sum(e,t,s,r),n}smooth2(e,t,i,s){const n=this.container.getData(i)[e-1],r=this.inputs.AdxSmoothing;if(null!==n)return this.useEma?(s-n)*this.multiplier+n:(n*(r-1)+s)/r;{const i=this.sum(e,t,s,r);if(null!==i)return i/r}return null}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null,l=null,c=null;if(e>0){const u=this.past(e,2,Ka.High),h=this.past(e,2,Ka.Low),d=Math.max(u[1]-u[0],0),p=Math.max(h[0]-h[1],0);t=d>p?d:0,i=p>d?p:0;const f=this.container.getData(Ka.TR)[e];n=this.smooth1(e,Wp,Gp,t),r=this.smooth1(e,Up,zp,i),s=this.smooth1(e,Ka.TR,$p,f),(n>0||r>0)&&0!==s&&(o=n/s*100,a=r/s*100,l=100*Math.abs(o-a)/(o+a),c=this.smooth2(e,Yp,this.adxField,l))}return{[Wp.id]:t,[Up.id]:i,[$p.id]:s,[Gp.id]:n,[zp.id]:r,[Ka.PDI.id]:o,[Ka.MDI.id]:a,[Yp.id]:l,[this.adxField.id]:c}}getWrappers(){return[this.wrapInner(Ka.TR,1)]}}class Kp extends up{calculateAtFunc;constructor(e,t,...i){super(e,...i),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,i)=>{const s=t;let n=s.target;if(!ie(n)){n=s.container.hasField(Ka.Close)?Ka.Close:s.container.fields[0]}return this.innVal(i,n,e)}),i=null;return R(t)&&(i=this.calculateAtFunc(e,...t)),{[this.target.id]:i}}}function qp(e,t){const i=this.baseVal(Ka.High,t),s=this.baseVal(Ka.Low,t);return{[e.id]:(i+s)/2}}function Xp(e,t){const i=this.baseVal(Ka.High,t),s=this.baseVal(Ka.Low,t);return{[e.id]:i-s}}class Zp extends up{calculateAtFunc;constructor(e,t,i){super(e,i),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}}const Jp=cp("_RANGE"),Qp=cp("_MOV_RANGE"),ef={fields:[Ka.KCUP,Ka.KCLOW,Ka.KCMID],midSeries:e=>yy(e,Ka.TP),midTarget:Ka.TP,rangeSeries:e=>Cy(Jp,M(Xp,Jp),e),rangeTarget:Jp,func:"MA",useMultiplier:!1},tf={fields:[Ka.KBUP,Ka.KBLOW,Ka.KBMID],midSeries:e=>e,midTarget:Ka.Close,rangeSeries:e=>my(e,Ka.TR),rangeTarget:Ka.TR,func:"EMA",useMultiplier:!0};class sf extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=t.midSeries(i),n=Oy(e,t.func,"Average"),r=n(s,this.inputs.Period,t.midTarget,t.fields[2]),o=n(t.rangeSeries(i),this.inputs.Period,t.rangeTarget,Qp);this.addInner(r,o)}calculateAt(e){const t=this.innVal(1,this.kind.fields[2],e),i=this.innVal(2,Qp,e),s=null!==t&&null!==i,n=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:s?t+i*n:null,[this.kind.fields[1].id]:s?t-i*n:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}}class nf extends up{isWidth;constructor(e,t,i){super(e,i),this.isWidth=t;const s=dy(i,this.inputs.Period,Ka.High,Ka.DONUP,!0),n=dy(i,this.inputs.Period,Ka.Low,Ka.DONLOW,!1);this.addInner(s,n)}calculateAt(e){const t=this.innVal(1,Ka.DONUP,e),i=this.innVal(2,Ka.DONLOW,e),s=null===t&&null===i;return this.isWidth?{[Ka.DONW.id]:s?null:t-i}:{[Ka.DONMID.id]:s?null:(t+i)/2}}getWrappers(){return[this.wrapInner(Ka.DONUP,1),this.wrapInner(Ka.DONLOW,2)]}}const rf=cp("_HIND"),of=cp("_LIND");class af extends up{constructor(e,t,i){super(e,i),this.justWidth=t,this.justWidth=t;const s=this.inputs.Period,n=dy(i,s,Ka.High,rf,!0,!0),r=dy(i,s,Ka.Low,of,!1,!0);this.addInner(n,r)}calculateAt(e){let t=null,i=null,s=null;const n=this.innVal(1,rf,e),r=this.innVal(2,of,e);if(null!==n&&null!==r){const e=this.period;t=(e-n)/e*100,i=(e-r)/e*100,s=t-i}return this.justWidth?{[Ka.ARNOSC.id]:s}:{[Ka.ARNUP.id]:t,[Ka.ARNLOW.id]:i}}}const lf=cp("_MIDPOINT");const cf=cp("_MIDPOINT");class uf extends up{multiplyVol;constructor(e,t,i){super(e,i),this.multiplyVol=t}calculateAt(e){const t=[Ka.High,Ka.Low,Ka.Close,Ka.Volume],[i,s,n,r]=t.map(t=>this.baseVal(t,e));let o=i===s?0:(n-s-(i-n))/(i-s);return this.multiplyVol&&(o*=r),{[this.target.id]:o}}}const hf=cp("_RANGE");const df=cp("_MATP");class pf extends up{isBull;constructor(e,t,i){super(e,i),this.isBull=t;const s=ly(i,this.inputs.Period,this.source);this.addInner(s)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.EMA,e);return null!==i&&(t=this.isBull?this.baseVal(Ka.High,e)-i:this.baseVal(Ka.Low,e)-i),{[this.isBull?Ka.ERBLPOW.id:Ka.ERBRPOW.id]:t}}}const ff=cp("_FORCE");const mf=cp("_RANGE"),gf=cp("_EMA1"),yf=cp("_EMA2"),Af=cp("_RATIO");const Sf={isNegative:!1,fields:[Ka.PVI,Ka.PVIEMA]},Tf={isNegative:!0,fields:[Ka.NVI,Ka.NVIEMA]};class vf extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=Cy(this.kind.fields[0],M(function(e,t){let i=1e3;if(t>0){const s=[Ka.Close,Ka.Volume],[n,r]=s.map(e=>this.baseVal(e,t)),[o,a]=s.map(e=>this.baseVal(e,t-1)),l=this.container.getData(this.target)[t-1];if(e?r<a:r>a){i=l*((n-o)/o+1)}else i=l}return{[this.target.id]:i}},this.kind.isNegative),i),n=ly(s,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(s,n)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}}const Pf=cp("_LOGPC");const Cf=cp("_SWING_INDEX");const bf=cp("_MIN_CLOSE"),Ef=cp("_MAX_CLOSE");const Lf=cp("_EP"),Mf=cp("_AF"),_f=cp("_POS");const xf=cp("_IDY"),If=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],Df=e=>Array(e).fill(0);function Of(e,t,i){let s=e[i-1];return 0===t&&(s=e[i]),t<0&&(s=e[i+1]),s}function wf(e,t,i,s,n){const r=n[18];let o=s+1,a=0;for(let l=0;l<r;++l){let i=0,s=0;for(let n=1;n<6;++n){if(o--,e[o]<=0)continue;const r=e[o]-t[o];1==n&&(i=s=r),r>i&&(i=r),r<s&&(s=r)}a=a+i-s}return a=a/r*function(e,t){return Of(e,t,4)}(n,i[s]),a}function Rf(e,t,i,s,n){let r=s;const o=function(e,t){return Of(e,t,7)}(n,i[s]);let a=0;do{r--,e[r]>0&&a++}while(a<o&&r>0);return t[s]-t[r]}function Nf(e,t,i,s,n,r,o,a,l,c){const u=function(e,t){return Of(e,t,10)}(n,i[s]),h=function(e,t){return Of(e,t,13)}(n,i[s]),d=function(e,t){return Of(e,t,16)}(n,i[s]),p=l+c+t[s]-e[s];let f=100;n[20]>0&&(f=n[20]);let m=u*a/f;a>h&&(m=u*h/f);const g=2*c,y=e[s]+(p-g)-(p-g)*m,A=e[s]+(p-p*m),S=[r,o];return(1===a||1!==d||y>r)&&(S[0]=y),(1===a||1!==d||A<o)&&(S[1]=A),S}function Vf(e,t,i){let s=0,n=-1,r=0,o=1;for(let a=0;a<i;++a){if(t[a]=0,null==e[a])continue;if(s++,21==s&&(o=2),31==s&&(o=3),r+=e[a]*o,s<40)continue;t[a]=r/70;let l=0;for(let t=n+1;t<i&&(null==e[t]||(l++,1==l&&(n=t),1!=l&&21!=l&&31!=l||(r-=e[t]),31!=l));++t);}}const Hf=1,Bf=2,Ff=3,kf={[Hf]:{param:"cot",func:"parseCotLineChart",fields:[Ka.DateTime,Ka.COTLCCMSP,Ka.COTLCLGSP,Ka.COTLCSMSP]},[Bf]:{param:"cotadv",func:"parseDisaggregated",fields:[Ka.DateTime,Ka.COTDAGPRO,Ka.COTDAGSPD,Ka.COTDAGMNM,Ka.COTDAGOTH]},[Ff]:{param:"cotfin",func:"parseFinancialTradersReport",fields:[Ka.DateTime,Ka.COTFTRDLI,Ka.COTFTRASM,Ka.COTFTRLVF,Ka.COTFTROTH]}};class Wf extends up{wrappers;constructor(e,t,i){super(e,lp(i,e=>new Uf(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=kf[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}}class Uf extends Ch{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new $f(this.kind)}onStreamingUpdates(e){}}class $f extends Ku{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[kf[this.kind].param]="y"}getParser(e){return new Gf(e.symbol,e.aggregation,this.kind)}}class Gf extends zu{kind;constructor(e,t,i){super(e,t,0),this.kind=i}makeContainer(){return new Mu(kf[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[kf[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(Ka.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(Ka.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(Ka.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(Ka.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(Ka.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(Ka.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(Ka.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(Ka.COTFTROTH,parseInt(e[5]))}}class zf extends Wf{constructor(e,t){super(e,1,t)}}const Yf={Day:[Ka.PreviousHigh,Ka.PreviousLow,Ka.PreviousClose],Week:[Ka.WeekPreviousHigh,Ka.WeekPreviousLow,Ka.WeekPreviousClose],Month:[Ka.MonthPreviousHigh,Ka.MonthPreviousLow,Ka.MonthPreviousClose]};class jf extends up{disabled;record;streamingSubscription;constructor(e,t,i){if(super(e,i),this.disabled=!ie(i.query)||!ie(i.query.symbol),!this.disabled){let e=i.query.symbol;e.endsWith(".BZ")&&(e=e.slice(0,-3)),this.record=Gv().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>{const t=dl(qa.RT_QUOTE,this.record.symbol);return e.filter(t)}),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return ps.call(this,async()=>ie(this.record)?await this.record.ready()&&await super.ready():await super.ready(),"asyncReadyWork2")}onStreamingUpdates(e){if(this.record){const e={tag:Pe(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return Yf[e].map(e=>this.record.getValue(e))}}class Kf extends Ch{constructor(e){super(e)}getRetriever(){return Bi(this.query.symbol)?new Jf:new qf}onStreamingUpdates(e){}}class qf extends Ku{addExtraParams(e){e.impl="y"}getParser(e){return new Zf(e.symbol,e.aggregation)}}function Xf(){return new Mu([Ka.DateTime,Ka.IMPVOL])}class Zf extends zu{constructor(e,t){super(e,t)}makeContainer(){return Xf()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.IMPVOL,parseFloat(e[8])))}}class Jf extends qu{emptyContainer(e,t){return Xf()}get iterateForward(){return!1}getPageName(){return"getFuturesOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date.substring(0,10)));const s=te(e.impliedVolatility);i.addDataPoint(Ka.IMPVOL,s?100*e.impliedVolatility:null)}}const Qf=cp("_ABS_CHG"),em=cp("_DS1_EMA1"),tm=cp("_DS1_EMA2"),im=cp("_DS2_EMA1"),sm=cp("_DS2_EMA2");const nm=cp("_DIFF");const rm=cp("_SUM");const om=cp("_ABS_CHG"),am=cp("_HH_LL"),lm=cp("_MULMA");class cm extends hp{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){const i=(e,t)=>this.baseVal(e,t),s=[Ka.Open,Ka.High,Ka.Low,Ka.Close],n=s.map(t=>i(t,e));if(R(n)){const r=s.map(t=>i(t,e-1));if(R(r)){t=n.map((e,t)=>100*(e-r[t])/r[t]);const[i,s]=z(t);if(t[1]=s,t[2]=i,e>1){const i=this.container.getData(Ka.Close)[e-1];t[4]=t[3]-i}}}}return{[Ka.Open.id]:t[0],[Ka.High.id]:t[1],[Ka.Low.id]:t[2],[Ka.Close.id]:t[3],[Ka.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}const um=cp("_DIST"),hm=cp("_EMA_DIST1"),dm=cp("_EMA_DIST2"),pm=cp("_DIFF"),fm=cp("_EMA_DIFF1"),mm=cp("_EMA_DIFF2");const gm=cp("_CHG"),ym=cp("_M1"),Am=cp("_M2");class Sm extends up{constructor(e,t){super(e,t);const i=Cy(gm,function(e){const t=Ka.Close,i=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[gm.id]:i}},t),s=by(ym,(e,t)=>t>=0?t:0,i),n=by(Am,(e,t)=>t>=0?0:-t,i);this.addInner(s,n)}perc(e,t){return 100*e/t}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i+1)){const s=this.past(e,i,ym,this.innCont(1)),n=this.past(e,i,Am,this.innCont(2));if(R(s)&&R(n)){const e=O(s),i=O(n);t=this.perc(e-i,e+i)}}return{[Ka.CHDMOMOSC.id]:t}}}const Tm=cp("_MAX"),vm=cp("_MIN"),Pm=cp("_ISUPTREND");const Cm=cp("_TRENDUP"),bm=cp("_TRENDDOWN"),Em=cp("_TREND");const Lm=cp("_CUM_PRICE"),Mm=cp("_CUM_VOL"),_m=cp("_PER_CHG");class xm extends up{constructor(e,t){super(e,t);const i=this.source,s=Cy(i,M(xy,i),t);this.addInner(s)}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}}const Im=cp("_DIFF"),Dm=[Im,Ka.Buy,Ka.Sell];function Om(e,t,i,s){let n=null,r=null,o=null;ie(i,s)&&(o=i-s);const a=t>0?e.getData(Im)[t-1]:null;return ie(o,a)&&(n=o>0&&a<=0?1:null,r=o<0&&a>=0?-1:null),{[Im.id]:o,[Ka.Buy.id]:n,[Ka.Sell.id]:r}}const wm=cp("_PVM"),Rm=cp("_NVM");function Nm(e,t,i){return new Vm(e,t,i)}class Vm{constructor(e,t,i){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[i.mapper(t)]=t,e),{}),this.policy=i,this.exprSymbols=pa(e),this.valueSymbols=this.exprSymbols.filter(e=>void 0===this.innerLookup[e]),this.onlyForTimeline=B(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;const t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!ie(this.exprModel)}get hasData(){return null!==this.container}get sourceFields(){return this._sourceFields||(this._sourceFields=Array.from(this.policy.fieldMap.keys())),this._sourceFields}get targetFields(){return this._targetFields||(this._targetFields=Array.from(this.policy.fieldMap.values())),this._targetFields}async ready(){return ps.call(this,async()=>{this.basisChangedToken=ap.subscribe(qa.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=ap.subscribe(qa.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));const e=this.innerSeries.map(e=>e.ready());void 0!==this.policy.valueProvider&&e.push(this.policy.valueProvider.ready());const t=(await Promise.all(e)).every(I);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>ie(e.container))&&this.calculateCommon(qa.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===i.Manual)return;if(e===qa.TS_EVENTSCHANGED||e===qa.TS_LOADING)return;if(!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!ie(e.container)))return;const s=this.policy.mapper(t.series);if(e===qa.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(s))return;switch(this.policy.recompute===i.Everything?qa.TS_MANYCHANGED:e){case qa.TS_MANYCHANGED:this.calculate();break;case qa.TS_DATAPOINTCHANGED:case qa.TS_DATAPOINTADDED:this.recalculate(e===qa.TS_DATAPOINTADDED);break;case qa.TS_TIMELINECORRECTION:case qa.TS_QUOTEMARKER:break;default:throw new Error("Unknown time series message, likely forgot to handle it")}}shutdown(){this.basisChangedToken&&ap.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(ap.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,i)=>{if(t===Ka.Volume)return O(this.exprSymbols.map(t=>e.inn[t].values[i]??0));return ua(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[i]??null)})}pickMainField(){let e=null;for(const t of this.policy.fieldMap.values())if(null==e)e=t;else if(t===Ka.Close){e=t;break}return e}calculateLastChange(){const e=this.container,t=e.size;if(t<=1)return;const i=this.pickMainField(),s=e.getData(i)[t-2],n=e.getData(i)[t-1];ie(s,n)&&e.setLastDataPoint(Ka.Change,n-s)}calculateDataPoint(e,t){const i=this.calculateAt(e);if(null===i)return;e.atLeastOne=!0;const[s,n]=z(i,0,3);i[1]=n,i[2]=s,this.targetFields.forEach((e,s)=>{const n=i[s];t?this.container.addDataPoint(e,n):this.container.setLastDataPoint(e,n)}),t&&(this.container.addDataPoint(Ka.Change,null),this.container.addDataPoint(Ka.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){J(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,i){const s=this.innerLookup[e].container.getData(i);return t<0||t>=s.length?null:s[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,Ka.DateTime)}timeline(e){return e.container.getData(Ka.DateTime)}getRangeHelper(){switch(this.policy.missing){case t.UseNext:case t.UseNone:return Math.min;case t.UsePrevious:return Math.max;default:throw new Error("Unknow missing bar policy, likely forgot to implement it.")}}getRange(){const e=this.getRangeHelper();return{begin:new Date(e(...this.symbols.map(e=>W(this.timeline(this.innerLookup[e]))))),end:new Date(e(...this.symbols.map(e=>k(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,i){const s=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case t.UseNext:case t.UseNone:return s.findIndex(e=>e.valueOf()>=i.valueOf());case t.UsePrevious:return U(s,e=>e.valueOf()<=i.valueOf());default:throw new Error("Unknow missing bar policy, likely forgot to implement it.")}}checkPos(e){const t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!(ie(e.timeStamp)||this.policy.stretch(e.symbol)&&1!==t))}fillPosSymbolAt(e,i,s){e.index=i,e.timeStamp=this.timeStampAt(e.symbol,i);const n=(this.policy.missing===t.UseNone||this.policy.skipLeadingEmpty&&!s.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==s.timeStamp.valueOf();return e.values=this.sourceFields.map(t=>n?null:this.fieldValueAt(e.symbol,i,t)),e}skippable(e){return!!this.innerLookup[e].container.isEmpty&&(this.policy.noDataApproach===s.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===s.ModelTransformRequired)}get symbols(){const e=Object.keys(this.innerLookup);return ie(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){const t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return 0===this.symbols.length||(this.symbols.forEach(i=>{const s=this.findIndex(i,e),n={symbol:i,index:-1,timeStamp:/* @__PURE__ */new Date(0),values:[]};t.inn[i]=this.fillPosSymbolAt(n,s,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t)),t}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;ie(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>null!==e.timeStamp).map(e=>e.timeStamp.valueOf()))),this.policy.missing===t.UsePrevious?this.getInner(e).forEach(t=>{const i=ie(t.timeStamp);(i&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!i&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===t.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){return this.container.getLastDataPoint(Ka.DateTime).valueOf()<e.timeStamp.valueOf()}calculateCommon(e=null,t=null,i=!0){try{if(t)this.calculateDataPoint(t,i);else if(this.container=this.makeContainer(),!this.isExprInError){const e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(s){this.crashedComputationReported||(Hv(s,"error"),this.crashedComputationReported=!0)}}calculate(){const{yes:e,no:t}=V(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===s.ModelTransformRequired){const i=e=>e.map(this.policy.mapper),s=this.policy.modelTransform(i(e),i(t));null!==s&&(this.exprModel=s)}this.calculateCommon(qa.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;const t=this.getLastPos(),i=this.shouldAdd(t);this.calculateCommon(i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED,t,i)}recalculateAt(e,t,i){return this.recalculate(i)}makeContainer(){const e=[Ka.DateTime,Ka.Change].concat(this.targetFields);return new Mu(e)}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}}const Hm=cp("_AVG");const Bm=cp("_HAO"),Fm=cp("_HAH"),km=cp("_HAL"),Wm=cp("_HAC");const Um=cp("_DELTA");const $m=cp("_DIFF"),Gm=cp("_RANK"),zm=cp("_CHG"),Ym=cp("_AVG"),jm=cp("_HBRAKE_CHG"),Km=cp("_HEIGHT_DELTA"),qm=cp("_ACTION"),Xm=cp("_REVERSAL"),Zm=10,Jm=e=>[e>0,e<0],Qm=[null,null,null],eg=0,tg=1,ig=2;function sg([e,t],i){let s=null;if(i>0){const t=this.baseVal(e,i-1);ie(t)&&(s=this.baseVal(e,i)-t)}return{[t.id]:s}}class ng extends up{useHandbrake;constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,Ce(1,999,this.inputs.FastPeriod),Ka.Close),n=Ce(0,999,this.inputs.SlowPeriod),r=n>0,o=r?i(t,n,Ka.Close):t,a=by($m,r?(e,t,i)=>t-i:(e,t,i)=>i-t,s,o),l=Cy(zm,M(sg,[Ka.Close,zm]),t),c=Cy(Gm,function(e){const t=Math.abs(this.baseVal($m,e));let i=null,s=0,n=0;for(let r=e-1;r>=0&&s<200;--r){s++,Math.abs(this.baseVal($m,r))<t&&n++}return s>0&&(i=Math.floor(n/s*Zm)),i===Zm&&i--,{[Gm.id]:i}},a),u=Ce(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;const h=i(t,u,Ka.Close,Ym),d=Cy(jm,M(sg,[Ym,jm]),h);this.addInner(l,a,c,d)}get helpers(){return[Km,Ka.BARCOLIX,qm,Xm]}getStateAt(e){const t=this.innVal(2,$m,e);return ie(t)?Jm(t):Qm}findPreviousKnownState(e){for(let t=e-1;t>0;t--){const e=this.getStateAt(t);if(e===Qm)return Qm;const[i,s]=e;if(i||s)return e}return Qm}getBuySell(e){const t=this.getStateAt(e);if(t===Qm)return Qm;const[i,s]=t,n=this.findPreviousKnownState(e),[r,o]=n;if(!i&&!s)return n===Qm?Qm:[r,o,!1];const a=i!==r||s!==o;return a?[r,o,a]:[i,s,a]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,i=null,s=0,n=-1,r=eg;const[o,a,l]=this.getBuySell(e),[c,u]=[Xm,qm].map(t=>this.getPrev(t,e)),[h,d]=[0,-1].map(t=>this.innVal(4,jm,e+t));if(n=l?Zm:this.innVal(3,Gm,e),this.useHandbrake&&ie(h,d)){const t=!o&&h>0||!a&&h<0;l?(n=t?Zm:12,r=u):!0!==c&&u!==tg||(o&&d>0||a&&d<0?(n=this.innVal(3,Gm,e),r=ig):(n=t?11:13,r=tg))}if(ie(this.innVal(2,$m,e))){const t=this.innVal(1,zm,e),[i,n]=Jm(t),r=Math.abs(t);(o&&i||a&&n)&&(s=r),(o&&n||a&&i)&&(s=-r)}return o?t=1:a&&(i=1),{[Ka.JPIB.id]:t,[Ka.JPIS.id]:i,[Ka.BARCOLIX.id]:n,[Km.id]:s,[qm.id]:r,[Xm.id]:l}}}const rg={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:"EMA",Height:"Fixed"};const og=cp("_SMTH_ROC"),ag=cp("_TEN_SMTH_ROC");function lg(e,t,i,s,n){return new fp({source:s,target:n,outFields:[n],aggregation:i,inputs:ty(t)},e,e=>2/e)}const cg=cp("_VOL_AVG");const ug=(()=>{const e=(t=51,se(Math.pow(.5,1/t),6));var t;const i=Y(52,t=>Math.pow(e,t)),s=52/O(i);return i.map(e=>e*s)})(),hg=["Renko","Kagi","PointAndFigure","LineBreak"];function dg(e){return e===l.Continue||e===l.Nearest}class pg extends up{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,i){super(e,i,lp(i,e=>{if(!jr(v[Gv()?.config.mode??"Unspecified"]))return i;const t=e.duplicate(),s=e.aggregation;if(s.hasSpec)return dg(s.spec)?i:new bh(t,!0);const n=s.unit===a.Intraday&&s.size<=5,r=function(e,t){switch(e){case a.Intraday:return t>=240?3:t>=120?2:1;case a.Day:default:return 5;case a.Week:return 15;case a.Month:return 60;case a.Quarter:case a.Year:return 240}}(s.unit,s.size);t.aggregation=n?new Wo(a.Tick,s.size,l.PerSeconds):new Wo(a.Intraday,r);const o=n?1:3;t.barsToFetch=Math.min(gs.MAX_INTRADAY_BARS,o*e.barsToFetch);return new Ch(t)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof bh,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){const e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<20&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,i){if(e.src!==this.innerSeries[0])return;const s=i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED;this.notify(s,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(Ka.Change,1),this.wrapInner(Ka.Open,1),this.wrapInner(Ka.Close,1)]}}const fg=cp("_DR");class mg extends up{constructor(e,t,i){super(e,i);const s=Cy(fg,e=>{const t=this.baseVal(Ka.High,e),i=this.baseVal(Ka.Low,e);return{[fg.id]:ie(t,i)?t-i:null}},i),n=Oy(e,"MA")(s,this.inputs.Period,fg,Ka.ADR);if(t){const e=(e,t,i)=>ie(t,i)&&0!==i?t/i*100:null,t=by(this.target,e,n,i);this.addInner(t)}else this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}}const gg=cp("_EMA1"),yg=cp("_EMA2"),Ag=cp("_MACD"),Sg=cp("_PCTK"),Tg=cp("_PCTD"),vg=cp("_PCTK2");const Pg=cp("_EMA1"),Cg=cp("_EMA2"),bg=cp("_CORE");class Eg extends up{isEmpty=!1;constructor(e,t){if(super(e,t),Hy(t)&&e.aggregation?.isEndOfDay){let i=["$ADVT","$DECT"];switch(this.inputs.Source){case"TotalStocks":default:break;case"NYSEStocks":i=["$ADVN","$DECN"];break;case"NasdaqStocks":i=["$AVDQ","$DECQ"]}const s=this.getSeries(t.query,i[0]),n=this.getSeries(t.query,i[1]),r=this.getTargetSeries(e,s,n);this.addInner(s,n,r),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;const e=Cy(Ka.Close,(e,t)=>null,t),i=Cy(Ka.Close,(e,t)=>null,t),s=Cy(this.target,(e,t)=>null,t);this.addInner(e,i,s),this.canLoadMoreData=!1}}get baseIndex(){return this.isEmpty?0:1}getSeries(e,t){const i=e.duplicate();i.symbol=t;return Gv().getTimeSeriesDataSource().getTimeSeries(i)}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e!==this.innerSeries[0]&&((e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2))}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}}const Lg=cp("_INN_HL_ACC_IX"),Mg=new Wo;class _g extends up{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof bh)this.canLoadMoreData=!1;else{const r="PriceIndex"===this.inputs.Source?"$MADX":"$FADX",o=this.getSeries(t.query,r);if(this.addInner(o),this.isWeekly=e.aggregation.unit===a.Week,this.isWeekly){const e=this.getSeries(t.query,r,Mg),o=(i=e,s=this.inputs,new _g({aggregation:Mg,source:null,target:n=Lg,outFields:[n],inputs:{...s}},i));this.addInner(o)}this.canLoadMoreData=!0,this.initialNotification=!0}var i,s,n}getSeries(e,t,i){const s=e.duplicate();s.symbol=t,i&&(s.aggregation=i,s.barsToFetch=15*gs.US_TRADING_DAYS_PER_YEAR);return Gv().getTimeSeriesDataSource().getTimeSeries(s)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null;const i=this.period;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.Close);R(s)&&(t=O(s))}return{[this.target.id]:t}}calculateAtWeekly(e){const t=this.container?.size??-1;let i=null;const s=this.innCont(2);if(t>0&&e===t-1)i=s.getLastDataPoint(Lg);else{const t=this.container.getTimeData()[e],n=s.getTimeData();let r=G(n,t),o=n[r],a=null;for(;r<s.size&&Mi(t,o);)a=r,r+=1,o=n[r];null!==a&&(i=s.getData(Lg)[a])}return{[this.target.id]:i}}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e!==this.innerSeries[0]&&(e===this.innerSeries[1]&&this.innHasData(1))}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}}const xg=cp("_RSI1"),Ig=cp("_RSI1_MOM"),Dg=cp("_RSI2"),Og=cp("_RSI2_MA");const wg=cp("_MUL_ATR");class Rg extends up{constructor(e,t){super(e,lp(t,t=>{const i=Gv().getTimeSeriesDataSource();return t.seriesKind=m.Options,t.fields=e.outFields,i.getTimeSeries(t)})),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}}const Ng=cp("_CORE");class Vg extends Ch{constructor(e){super(e)}getRetriever(){return Bi(this.query.symbol)?new Fg:Gi(this.query.symbol)?new kg:new Bg}}function Hg(){const e=[Ka.DateTime,Ka.Delta,Ka.Gamma,Ka.Theta,Ka.Vega];return new Mu(e)}class Bg{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return Hg()}}class Fg extends qu{emptyContainer(e,t){return Hg()}get iterateForward(){return!1}getPageName(){return"getFuturesOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date.substring(0,10))),i.addDataPoint(Ka.Delta,e.delta),i.addDataPoint(Ka.Gamma,e.gamma),i.addDataPoint(Ka.Theta,e.theta),i.addDataPoint(Ka.Vega,e.vega)}}class kg extends qu{emptyContainer(e,t){return Hg()}addExtraParams(e){e.fields="delta,gamma,theta,vega"}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date)),i.addDataPoint(Ka.Delta,e.delta),i.addDataPoint(Ka.Gamma,e.gamma),i.addDataPoint(Ka.Theta,e.theta),i.addDataPoint(Ka.Vega,e.vega)}}const Wg=cp("_RSI1"),Ug=cp("_RSI2");const $g=cp("_ANCHR");const Gg=cp("_HH_N"),zg=cp("_LL_N"),Yg=cp("_HH_H1"),jg=cp("_LL_H1"),Kg=cp("_HH_H2"),qg=cp("_LL_H2");const Xg=cp("_MIDPOINT"),Zg=cp("_VALUE");class Jg extends up{constructor(e,t){super(e,t),My(this)}computeMidranks(e){const t=e.length,i=e.map((e,t)=>({v:e,i:t}));i.sort((e,t)=>e.v-t.v);const s=new Array(t);let n=0;for(;n<t;){let e=n;const r=i[n].v;for(;e+1<t&&i[e+1].v===r;)e++;const o=(n+1+(e+1))/2;for(let t=n;t<=e;t++)s[i[t].i]=o;n=e+1}return s}pearsonCorrelation(e){const t=e.length;if(t<2)return null;const i=(t+1)/2;let s=0;for(let c=0;c<t;c++)s+=e[c];const n=s/t;let r=0,o=0,a=0;for(let c=0;c<t;c++){const t=c+1-i,s=e[c]-n;r+=t*s,o+=t*t,a+=s*s}const l=Math.sqrt(o*a);return 0===l?null:r/l}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);if(n.every(e=>null!==e)){const e=this.computeMidranks(n),i=this.pearsonCorrelation(e);null!==i&&(t=100*i)}}return{[Ka.RCI.id]:t}}}const Qg=cp("_ATR");const ey={_TR:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=this.baseVal(Ka.High,e),s=this.baseVal(Ka.Low,e);if(e>0){const n=this.baseVal(Ka.Close,e-1);t=Math.max(i-s,Math.abs(i-n),Math.abs(s-n))}else t=i-s;return{[this.target.id]:t}}},_RSI:class extends up{isModified;constructor(e,t){super(e,t);const i=e.inputs.Modified;this.isModified=i}get helpers(){return[xp,Ip]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,i=null,s=null;const n=this.period;if(this.atLeast(e,n+1)){if(null===this.container.getData(this.target)[e-1]||this.isModified){const t=this.past(e,n+1,this.source);if(R(t)){const e=N(1,n),r=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));i=w(r),s=w(o)}}else{const t=this.container.getData(xp)[e-1],r=this.container.getData(Ip)[e-1],o=this.past(e,2,this.source);i=(t*(n-1)+this.gain(1,o))/n,s=(r*(n-1)+this.loss(1,o))/n}null!==i&&null!==s&&(t=100-100/(1+i/s))}return{[xp.id]:i,[Ip.id]:s,[this.target.id]:t}}},MA:pp,MAEXP:class extends fp{constructor(e,t){super(e,t,e=>2/(e+1))}},MAHLC:class extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period1,Ka.High,Ka.MAHI),s=ay(t,this.inputs.Period2,Ka.Low,Ka.MALO);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.MAHI,1),this.wrapInner(Ka.MALO,2)]}},VOL:class extends mp{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.TradeSize,Ka.Change,Ka.Open,Ka.Close)}},MAENV:class extends Sp{constructor(e,t){super(e,gp,t)}},MAENVEXP:class extends Sp{constructor(e,t){super(e,yp,t)}},MAENVSMO:class extends Sp{constructor(e,t){super(e,Ap,t)}},MATRI:class extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period,this.source),s=ay(i,this.inputs.Period,Ka.MA,Ka.TMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.TMA,2)]}},MAWEI:class extends up{triangle;constructor(e,t){super(e,t);const i=this.period;this.triangle=i*(i+1)/2,My(this)}weightedAverage(e){const t=e.length;if(0===t)return null;const i=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,i)=>e+t*(i+1),0)/i}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=this.weightedAverage(n.filter(D)):R(n)&&(t=this.weightedAverage(n))}return{[this.target.id]:t}}},MAVOL:pp,MASMO:class extends fp{constructor(e,t){super(e,t,e=>1/e)}},MACD:class extends _p{constructor(e,t){super(e,vp,t)}},MACDEXP:class extends _p{constructor(e,t){super(e,Pp,t)}},MACDV:class extends Mp{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=Ka.MACDVH;const i=Oy(e,"EMA","Average"),s=i(t,e.inputs.Period1,e.source,void 0),n=i(t,e.inputs.Period2,e.source,void 0),r=gy(t,e.inputs.Period2,e.inputs.Average),o=by(Ka.MACDV,(e,t,i,s)=>(t-i)/s*100,s,n,r),a=i(o,e.inputs.Period3,o.target,Ka.MACDVS),l=by(Ka.MACDVH,Ey,o,a);this.addInner(o,a,l)}getWrappers(){return[this.wrapInner(Ka.MACDV,1),this.wrapInner(Ka.MACDVS,2),this.wrapInner(Ka.MACDVH,3)]}},GMMA:class extends up{constructor(e,t){super(e,t);for(let i=1;i<=12;++i){const s=Vy(e.inputs,i);this.addInner(ly(t,s,Ka.Close,e.outFields[i-1]))}}getWrappers(){return N(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},OSCI:Tp,OSCIVOL:Tp,RSI:class extends Dp{constructor(e,t){super(e,!1,t)}},RSIMOD:class extends Dp{constructor(e,t){super(e,!0,t)}},RSISTO:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period,this.source),s=this.inputs.Range,n=Cy(Ka.STORSI,function(e){let t=null;if(this.atLeast(e,s)){const i=this.past(e,s,Ka.RSI,this.base),n=z(i),r=n[0],o=n[1];t=(k(i)-r)/(o-r)}return{[Ka.STORSI.id]:t}},i),r=Oy(e,"MA","Average")(n,this.inputs.PeriodAvg,Ka.STORSI,Ka.STORSIAVG);this.addInner(n,r)}getWrappers(){return[this.wrapInner(Ka.STORSI,1),this.wrapInner(Ka.STORSIAVG,2)]}},RSA:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period1,this.source,Wg),s=Sy(t,this.inputs.Period2,this.source,Ug),n=by(Ka.RSA,(e,t,i)=>(t+i)/2,i,s),r=Oy(e,"MA","Average")(n,this.inputs.PeriodAvg,Ka.RSA,Ka.RSAAVG);this.addInner(n,r)}getWrappers(){return[this.wrapInner(Ka.RSA,1),this.wrapInner(Ka.RSAAVG,2)]}},WPERCR:class extends wp{constructor(e,t){super(e,!0,t)}},HHLL:class extends up{constructor(e,t){super(e,t);const i=dy(t,this.inputs.Period1,Ka.High,Ka.HH,!0),s=dy(t,this.inputs.Period2,Ka.Low,Ka.LL,!1);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.HH,1),this.wrapInner(Ka.LL,2)]}},WGCL:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=[Ka.Close,Ka.High,Ka.Low],[s,n,r]=i.map(t=>this.baseVal(t,e));return t=(2*s+n+r)/4,{[this.target.id]:t}}},STOCHF:class extends Np{constructor(e,t){super(e,!1,Ka.PercK,t)}},STOCHS:class extends Np{constructor(e,t){super(e,!0,Ka.PercK,t)}},BBANDS:class extends Hp{constructor(e,t){super(e,"Regular",t)}},BWIDTH:class extends Hp{constructor(e,t){super(e,"Width",t)}},BPERC:class extends Hp{constructor(e,t){super(e,"Percent",t)}},OBVOL:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.OBVOL,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e),n=this.baseVal(Ka.Close,e-1);let r=this.container.getData(this.target)[e-1];ie(r)||(r=0),t=i>n?r+s:i<n?r-s:r}return{[this.target.id]:t}},t),s=Oy(e,"MA","Average")(i,this.period,Ka.OBVOL,Ka.OBVOLAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.OBVOL,1),this.wrapInner(Ka.OBVOLAVG,2)]}},ATR:class extends up{constructor(e,t){super(e,t);const i=my(t,Ka.TR),s=Oy(e,"SMA")(i,this.inputs.Period,Ka.TR,this.target),n=ay(s,this.inputs.Period2,Ka.ATR,Ka.ATRMA);this.addInner(s,n)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(Ka.ATRMA,2)]}},ADR:class extends mg{constructor(e,t){super(e,!1,t)}},ATRP:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.ATR,e),s=this.baseVal(Ka.Close,e);return ie(i,s)&&s>0&&(t=i/s*100),{[Ka.ATRP.id]:t}}},ADRP:class extends mg{constructor(e,t){super(e,!0,t)}},ADX:class extends jp{constructor(e,t){super(e,!1,Ka.ADX,t)}},ADXMOD:class extends jp{constructor(e,t){super(e,!0,Ka.ADXM,t)}},ADL:class extends up{constructor(e,t){super(e,t);const i=Ty(t);this.addInner(i)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,Ka.MFMUL,e),{[this.target.id]:t}}},ADWM:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.ADWM,function(e){let t=null,i=null;if(e>0){const s=this.baseVal(Ka.Close,e-1),n=Math.max(s,this.baseVal(Ka.High,e)),r=Math.min(s,this.baseVal(Ka.Low,e)),o=this.baseVal(Ka.Close,e);if(t=o>s?o-r:o<s?o-n:0,e>1){i=(e>2?this.container.getData(Ka.ADWM)[e-1]:0)+t}}return{[Ka.ADWM.id]:i}},t),s=ay(i,this.inputs.Period,Ka.ADWM,Ka.ADWMMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.ADWM,1),this.wrapInner(Ka.ADWMMA,2)]}},CHAOSC:class extends up{constructor(e,t){super(e,t);const i=Ka.ADL;let s=function(e,t=Ka.ADL){return ny("ADL",sy(t),e)}(t,i),n=ly(s,3,i),r=ly(s,10,i),o=by(e.target,(e,t,i)=>t-i,n,r);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},TP:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=w([Ka.Close,Ka.High,Ka.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},KELCHN:class extends sf{constructor(e,t){super(e,ef,t)}},KELBND:class extends sf{constructor(e,t){super(e,tf,t)}},DONCHN:class extends nf{constructor(e,t){super(e,!1,t)}},DONWIDTH:class extends nf{constructor(e,t){super(e,!0,t)}},PVT:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e),n=this.baseVal(Ka.Close,e-1);let r=this.container.getData(this.target)[e-1];ie(r)||(r=0);t=r+(i-n)/n*s}return{[this.target.id]:t}}},ROC:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i+1)){const s=this.baseVal(this.source,e-i);if(null!==s&&0!==s){t=(this.baseVal(this.source,e)-s)/s*100}}return{[this.target.id]:t}}},TRIX:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=ly(s,this.inputs.Period,s.target),r=Ay(n,1,n.target,this.target);this.addInner(r)}getWrappers(){return[this.wrapInner(this.target,1)]}},PPMOV:class extends up{constructor(e,t){super(e,t);const i=yy(t,Ka.PVPT);this.addInner(i)}calculateAt(e){const t=this.innVal(1,Ka.PVPT,e),i=this.baseVal(Ka.High,e),s=this.baseVal(Ka.Low,e);return{[Ka.PVPTR.id]:t+i-s,[Ka.PVPTS.id]:t-i+s}}getWrappers(){return[this.wrapInner(Ka.PVPT,1)]}},PIVPTS:class extends jf{constructor(e,t){super(e,Yf[e.inputs.Previous],t)}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null;if(!this.disabled){const e=this.getValues(this.inputs.Previous);if(R(e)){const[l,c,u]=e;t=(l+c+u)/3;const h=2*t;i=h-c,s=h-l;const d=l-c;n=t+d,r=t-d,o=l+2*(t-c),a=c-2*(l-t)}}return{[Ka.PPTPIV.id]:t,[Ka.PPTR1.id]:i,[Ka.PPTR2.id]:n,[Ka.PPTR3.id]:o,[Ka.PPTS1.id]:s,[Ka.PPTS2.id]:r,[Ka.PPTS3.id]:a}}},CPP:class extends jf{constructor(e,t){super(e,Yf.Day,t)}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null,l=null;if(!this.disabled){const e=this.getValues("Day");if(R(e)){const[c,u,h]=e,d=c-u,[p,f,m,g]=[2,4,6,12].map(e=>1.1/e*d);a=h+p,r=h+f,s=h+m,t=h+g,i=h-g,n=h-m,o=h-f,l=h-p}}return{[Ka.CPPH4.id]:a,[Ka.CPPH3.id]:r,[Ka.CPPH2.id]:s,[Ka.CPPH1.id]:t,[Ka.CPPL1.id]:i,[Ka.CPPL2.id]:n,[Ka.CPPL3.id]:o,[Ka.CPPL4.id]:l}}},ARNUPDW:class extends af{constructor(e,t){super(e,!1,t)}},ARNOSC:class extends af{constructor(e,t){super(e,!0,t)}},TCHN:class extends up{constructor(e,t){super(e,t);const i="Close"===e.inputs.Range,s=Ny(t);if(!i&&s){const e=Cy(Ka.TCHNUP,(e,t)=>null,t),i=Cy(Ka.TCHNLOW,(e,t)=>null,t);this.addInner(e,i)}else{let s=dy(t,e.inputs.PeriodUpper,i?Ka.Close:Ka.High,Ka.TCHNUP,!0),n=dy(t,e.inputs.PeriodLower,i?Ka.Close:Ka.Low,Ka.TCHNLOW,!1);this.addInner(s,n)}}getWrappers(){return[this.wrapInner(Ka.TCHNUP,1),this.wrapInner(Ka.TCHNLOW,2)]}},TCHRE:class extends up{constructor(e,t){super(e,t);const i=function(e,t,i){const s="TCHN",n={PeriodUpper:t,PeriodLower:t,Range:i},r=ry(s);return ny(s,{inputs:n,outFields:r,source:null},e)}(t,e.inputs.Period,e.inputs.Range);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.TCHNUP,e),s=this.innVal(1,Ka.TCHNLOW,e),n=this.inputs.Adjustment,r=this.inputs.Retracement;return"Long"===r?t=ie(i)?i-n:null:"Short"===r&&(t=ie(s)?s+n:null),{[this.target.id]:t}}},ALLG:class extends up{constructor(e,t){super(e,t);const i=Cy(lf,M(qp,lf),t),s=cy(i,e.inputs.Period1,lf,Ka.ALJAW),n=cy(i,e.inputs.Period2,lf,Ka.ALTEETH),r=cy(i,e.inputs.Period3,lf,Ka.ALLIPS);this.addInner(s,n,r)}calculateAt(e){return{[Ka.ALJAW.id]:this.innVal(1,Ka.ALJAW,e),[Ka.ALTEETH.id]:this.innVal(2,Ka.ALTEETH,e),[Ka.ALLIPS.id]:this.innVal(3,Ka.ALLIPS,e)}}},PLTLN:class extends up{constructor(e,t){super(e,t)}calculateAt(e){return{[Ka.PLTLN.id]:this.inputs.Position}}},AWEOSC:class extends up{constructor(e,t){super(e,t);const i=Cy(cf,M(qp,cf),t),s=ay(i,this.inputs.Period1,cf),n=ay(i,this.inputs.Period2,cf),r=by(Ka.AWOS,(e,t,i)=>t-i,s,n),o=ay(r,this.inputs.Period3,r.target,Ka.AWOSMA);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.AWOS,1),this.wrapInner(Ka.AWOSMA,2)]}},MFV:class extends uf{constructor(e,t){super(e,!0,t)}},CLV:class extends uf{constructor(e,t){super(e,!1,t)}},CHAMF:class extends up{constructor(e,t){super(e,t);const i=Ty(t);this.addInner(i)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.Volume),n=this.past(e,i,Ka.MFMUL,this.innCont(1));if(R(s)&&R(n)){const e=O(s);0!==e&&(t=O(n)/e)}}return{[this.target.id]:t}}},CHAVOL:class extends up{constructor(e,t){super(e,t);const i=Ay(ly(Cy(hf,M(Xp,hf),t),this.inputs.Period1,hf),this.inputs.Period2,Ka.EMA,this.target);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},DPO:class extends up{shift;constructor(e,t){super(e,t);const i=this.inputs.Period;this.shift=Math.floor(i/2)+1;const s=ay(t,i,e.source);this.addInner(s)}calculateAt(e){let t=null;const i=this.shift,s=this.innVal(1,Ka.MA,e-i);return null!==s&&(t=this.baseVal(this.source,e)-s),{[this.target.id]:t}}},CCI:class extends up{constructor(e,t){super(e,t);const i=yy(t),s=ay(i,this.inputs.Period,i.target,df);this.addInner(i,s)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){let s=this.past(e,i,Ka.TP,this.innCont(1));if(R(s)){const i=this.innVal(2,df,e);if(null!==i){const n=s.reduce((e,t,s)=>e+Math.abs(i-t),0)/this.period;t=(this.innVal(1,Ka.TP,e)-i)/(.015*n)}}}return{[this.target.id]:t}}},EMV:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.EMV,function(e){let t=null;if(e>0){const i=[Ka.High,Ka.Low,Ka.Volume],[s,n,r]=i.map(t=>this.baseVal(t,e)),o=[Ka.High,Ka.Low],[a,l]=o.map(t=>this.baseVal(t,e-1));t=((s+n)/2-(a+l)/2)/(r/1e6/(s-n))}return{[this.target.id]:t}},t),s=ay(i,this.inputs.Period,Ka.EMV,Ka.EMVMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.EMV,1),this.wrapInner(Ka.EMVMA,2)]}},ERBRPOW:class extends pf{constructor(e,t){super(e,!1,t)}},ERBLPOW:class extends pf{constructor(e,t){super(e,!0,t)}},FI:class extends up{constructor(e,t){super(e,t);const i=ly(Cy(ff,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e);t=(i-this.baseVal(Ka.Close,e-1))*s}return{[this.target.id]:t}},t),this.inputs.Period,ff,Ka.FI);this.addInner(i)}getWrappers(){return[this.wrapInner(Ka.FI,1)]}},MI:class extends up{constructor(e,t){super(e,t);const i=ly(Cy(mf,M(Xp,mf),t),9,mf,gf),s=ly(i,9,gf,yf),n=by(Af,(e,t,i)=>t/i,i,s);this.addInner(n)}calculateAt(e){let t=null;if(this.atLeast(e,25)){const i=this.past(e,25,Af,this.innCont(1));R(i)&&(t=O(i))}return{[this.target.id]:t}}},MOM:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=Cy(Ka.MOM,_(Iy,i,Ka.Close),t),n=ay(s,this.inputs.Movement,Ka.MOM,Ka.MOMMA);this.addInner(s,n)}getWrappers(){return[this.wrapInner(Ka.MOM,1),this.wrapInner(Ka.MOMMA,2)]}},MFI:class extends up{constructor(e,t){super(e,t);const i=yy(t);this.addInner(i)}calculateAt(e){let t=null;const i=this.period+1;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.TP,this.innCont(1)),n=this.past(e,i,Ka.Volume).map(e=>null!=e?e:0);if(R(s)&&R(n)){let e=0,r=0;for(let t=1;t<i;++t){const i=s[t]*n[t];s[t]>s[t-1]?e+=i:r+=i}t=100-100/(1+e/r)}}return{[this.target.id]:t}}},MSD:class extends up{constructor(e,t){super(e,t),My(this);const i=ay(t,this.inputs.Period,this.source);this.addInner(i)}calculateAt(e){let t=null;const[i,s]=_y(this),n=this.innVal(i+1,Ka.MA,e);if(null!==n){const i=this.inputs.Period;let r=this.past(e,i,this.source,s);r=r.map(e=>(e-n)*(e-n)),t=Math.sqrt(w(r))}return{[this.target.id]:t}}getWrappers(){const[e]=_y(this);return[this.wrapInner(Ka.MA,e+1)]}},NVI:class extends vf{constructor(e,t){super(e,Tf,t)}},PVI:class extends vf{constructor(e,t){super(e,Sf,t)}},PPO:class extends _p{constructor(e,t){super(e,Ep,t)}},PVO:class extends _p{constructor(e,t){super(e,Lp,t)}},HV:class extends up{constructor(e,t){super(e,t);const i=Math.sqrt(Ry(e.aggregation));if(0===i){const e=Cy(this.target,(e,t)=>null,t);this.addInner(e)}else{const s=function(e,t){let i=null;const s=this.baseVal(Ka.MSD,t);return null!==s&&(i=100*s*e),{[Ka.HV.id]:i}},n=vy(Cy(Pf,M(function(e,t){let i=null;if(t>0){const s=this.baseVal(e,t),n=this.baseVal(e,t-1);null!==s&&null!==n&&(i=Math.log(s/n))}return{[Pf.id]:i}},Ka.Close),t),e.inputs.Period,Pf,Ka.MSD),r=Cy(Ka.HV,M(s,i),n);this.addInner(r)}}getWrappers(){return[this.wrapInner(this.target,1)]}},PERF:class extends up{noOp;constructor(e,t){super(e,t);const i="VisibleStart"===this.inputs.Anchor;this.noOp=i}calculateAt(e){let t=null;const i=this.baseVal(this.source,0),s=this.baseVal(this.source,e);return this.noOp?t=s:null!==i&&null!==s&&(t=(s-i)/i*100),{[this.target.id]:t}}},WASI:class extends up{constructor(e,t){super(e,t)}get helpers(){return[Cf]}ohlcVals(e){return[Ka.Open,Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,i,s){const n=Math.abs(e-s),r=Math.abs(t-s),o=Math.abs(e-t),a=Math.max(n,r,o),l=.25*Math.abs(s-i);return a===n?n-.5*r+l:a===r?r-.5*n+l:o+l}calculateAt(e){let t=null,i=null;if(e>0){let s=this.container.getData(Cf)[e-1];ie(s)||(s=0);const[n,r,o,a]=this.ohlcVals(e),[l,c,u,h]=this.ohlcVals(e-1);if(R([n,r,o,a,l,h])){const e=Math.max(Math.abs(r-h),Math.abs(o-h)),c=this.inputs.Limit;t=(a-h+.5*(a-n)+.25*(h-l))/this.obtainR(r,o,l,h)*50*(e/c),i=s+t}}return{[Cf.id]:t,[this.target.id]:i}}},WWVOL:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Ef,bf]}calculateAt(e){let t=null,i=null,s=null,n=null,r=this.innVal(1,Ka.ATR,e);if(null!==r){const o=this.baseVal(Ka.Close,e),a=this.baseVal(Ka.Close,e-1),l=this.period;s=Math.max(...this.past(e,l,Ka.Close)),n=Math.min(...this.past(e,l,Ka.Close));const c=r*this.inputs.Constant;if(null===this.innVal(1,Ka.ATR,e-1)){o>a?t=s-c:i=n+c}else{const r=[Ka.WWVSARU,Ka.WWVSARD,Ef,bf],[a,l,u,h]=r.map(t=>this.container.getData(t)[e-1]);s=u,n=h;null!==a?o<a?(n=o,i=o+c):(s=Math.max(o,s),t=s-c):o>l?(s=o,t=o-c):(n=Math.min(o,n),i=n+c)}}return{[Ef.id]:s,[bf.id]:n,[Ka.WWVSARU.id]:t,[Ka.WWVSARD.id]:i}}},PARTP:class extends up{constructor(e,t){super(e,t)}get helpers(){return[Lf,Mf,_f]}hlcVals(e){return[Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null;if(e>0){const[a,l,c]=this.hlcVals(e),[u,h,d]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),f=this.reciprocal(this.inputs.Limit);if(1===e){r=c>d?1:-1;const e=1===r;o=e?h:u,s=e?Math.max(a,u):Math.min(l,h),n=p,e?t=o:i=o}else{const c=[_f,Ka.PARSARS,Ka.PARSARL,Lf,Mf],[d,m,g,y,A]=c.map(t=>this.me(t,e-1)),S=1===d,T=S?g:m,v=A*Math.abs(y-T);r=S?T+v>l?-1:1:T-v<a?1:-1;const P=d===r;if(o=P?S?Math.min(T+v,h,this.baseVal(Ka.Low,e-2)):Math.max(T-v,u,this.baseVal(Ka.High,e-2)):y,s=P?S?Math.max(a,y):Math.min(l,y):1===r?a:l,n=A,P){(S?s>y:s<y)&&A<f&&(n=A+p)}else n=p;1===r?t=o:i=o}}return{[Lf.id]:s,[Mf.id]:n,[_f.id]:r,[Ka.PARSARS.id]:i,[Ka.PARSARL.id]:t}}},MOVLR:class extends up{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);const i=this.period;this.xSum=i*(i+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=i*(i+1)*(2*i+1)/6}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){let s=this.past(e,i,this.source);if(R(s)){const e=O(s),n=(i*O(s.map((e,t)=>e*(t+1)))-this.xSum*e)/(i*this.x2Sum-this.xSum2);t=(e-n*this.xSum)/i+n*i}}return{[this.target.id]:t}}},TRSP:class extends up{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];const i=["VelocityUpTrend","VelocitySideTrend","VelocityDownTrend"].map(t=>e.inputs[t]||"3").map(Number);If.splice(6,3,...i)}get helpers(){return[xf]}prepareComputation(){const e=this.base.getData(Ka.Close);let t=0,i=0;const s=e.length;for(;i<72&&t<s;)null!=e[t]&&i++,t++;this.haveEnoughData=t<s,this.firstUsefulIndex=t,this.s3=Df(s),this.itr=Df(s),this.haveEnoughData&&Vf(e,this.s3,s)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,i){const s=this.base.getData(Ka.Close),n=s.length;this.haveEnoughData&&Vf(s,this.s3,n),super.recalculateAt(e,t,i)}calculateAt(e){let t=null,i=null,s=null;const n=t=>this.us(t,e-1);if(0===e)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&null!==this.baseVal(Ka.Close,e)){let r=n(Ka.TRSP1),o=n(Ka.TRSP2);s=n(xf),null===r&&null===o&&(r=o=this.baseVal(Ka.Close,this.firstUsefulIndex)),null===s&&(s=1);const a=this.base.getData(Ka.Close);s=function(e,t,i,s,n,r){let o=i;do{o--}while(e[o]<=0);return t[i]=t[o],e[i]>n&&t[o]<=0&&(t[i]=t[o]+1),e[i]<s&&t[o]>=0&&(t[i]=t[o]-1),r++,t[i]!==t[o]&&(r=1),r}(a,this.itr,e,r,o,s);const l=Rf(a,this.s3,this.itr,e,If),c=wf(a,this.s3,this.itr,e,If);[r,o]=Nf(a,this.s3,this.itr,e,If,r,o,s,l,c),this.itr[e]>=0&&(t=r),this.itr[e]<=0&&(i=o)}return{[xf.id]:s,[Ka.TRSP1.id]:t,[Ka.TRSP2.id]:i}}},COTLC:zf,COTDAG:class extends Wf{constructor(e,t){super(e,2,t)}},COTFTR:class extends Wf{constructor(e,t){super(e,3,t)}},IMPVOL:class extends up{constructor(e,t){super(e,lp(t,e=>new Kf(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(Ka.IMPVOL,0)]}},CTM:class extends _p{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,Cp,t)}},CPMI:class extends _p{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,bp,t)}},DEMA:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=by(Ka.DEMA,(e,t,i)=>2*t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.DEMA,1)]}},EOSC:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period1,this.source),s=ly(t,this.inputs.Period2,this.source),n=by(Ka.EOSC,(e,t,i)=>t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.EOSC,1)]}},TEMA:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=ly(s,this.inputs.Period,s.target),r=by(Ka.TEMA,(e,t,i,s)=>3*(t-i)+s,i,s,n);this.addInner(r)}getWrappers(){return[this.wrapInner(Ka.TEMA,1)]}},TSI:class extends up{constructor(e,t){super(e,t);const i=(e,t,i,s,n,r)=>{const o=ly(e,t,i,s);return ly(o,n,s,r)},s=Cy(Qf,M((e,t)=>({[e.id]:Math.abs(this.baseVal(Ka.Change,t))}),Qf),t),n=i(t,e.inputs.Period1,Ka.Change,em,e.inputs.Period2,tm),r=i(s,e.inputs.Period1,Qf,im,e.inputs.Period2,sm),o=by(Ka.TSI,(e,t,i)=>100*t/i,n,r),a=ly(o,e.inputs.Period3,Ka.TSI,Ka.TSISIG);this.addInner(o,a)}getWrappers(){return[this.wrapInner(Ka.TSI,1),this.wrapInner(Ka.TSISIG,2)]}},ADJATR:class extends up{constructor(e,t){super(e,t);const i=Cy(Bp,M((e,t)=>{let i=0;return t>0&&(i=this.baseVal(e,t)-this.baseVal(e,t-1)),{[Bp.id]:Math.abs(i)}},this.source),t),s=Oy(e,"MA")(i,this.inputs.Period,Bp,Fp),n=by(Ka.ADJATR,(e,t)=>2*t,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.ADJATR,1)]}},COTR:class extends up{constructor(e,t){super(e,t);const i=Cy(kp,e=>{let t=0;return e>0&&(t=this.baseVal(Ka.Close,e)-this.baseVal(Ka.Close,e-1)),{[kp.id]:t}},t),s=function(e){const t=e.inputs.TypeOfATR.toLowerCase();return wy[t]}(e),n=s(t,this.inputs.Period,this.inputs.Smoothing),r=by(this.target,(e,t,i)=>ie(t)&&ie(i)?t/i:null,i,n);this.addInner(r)}getWrappers(){return[this.wrapInner(this.target,1)]}},MCGD:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,Ka.Close);this.addInner(i)}calculateAt(e){let t=null;const i=e>0?this.container.getData(this.target)[e-1]:null,s=this.innVal(1,Ka.EMA,e);if(te(i)){const n=this.baseVal(this.source,e),r=Math.pow(n/i,4);t=i+(n-i)/(.6*this.period*r);const o=e=>Math.log10(Math.abs(e-t))>1,a=o(i)||o(s);Number.isFinite(t)&&!a||(t=null)}else t=s;return{[this.target.id]:t}}},HMA:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=Math.floor(i/2),n=this.allowEmptyValues,r=uy(t,s,this.source,Ka.WMA,n),o=uy(t,i,this.source,Ka.WMA,n),a=uy(by(nm,(e,t,i)=>2*t-i,r,o),Math.floor(Math.sqrt(i)),nm,this.target,n);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},COPP:class extends up{constructor(e,t){super(e,t);const i=Ay(t,this.inputs.PeriodRocLong),s=Ay(t,this.inputs.PeriodRocShort),n=uy(by(rm,(e,t,i)=>t+i,i,s),this.inputs.PeriodWma,rm,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},REATRS:class extends up{constructor(e,t){super(e,t);const i="Close"===e.inputs.TurtleChnField,s="Long"===e.inputs.Direction,n=Ny(t);if(!i&&n){const e=Cy(this.target,(e,t)=>null,t);this.addInner(e)}else{const e=ay(Cy(om,M((e,t)=>({[om.id]:t>0?e*Math.abs(this.baseVal(Ka.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,om,Ka.MA),n=s?Ka.High:Ka.Low,r=dy(t,this.inputs.PeriodTurtleChn,i?Ka.Close:n,am,s),o=by(lm,(e,t)=>this.inputs.FactorAdjATR*t,e),a=s?-1:1,l=(e,t,i)=>t+a*i,c=by(this.target,l,r,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},LINRCHN:class extends up{state;constructor(e,t){super(e,t),this.resetState()}resetState(){const e=this.inputs.ExtendLines??"None";this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:"Left"===e||"Both"===e,extendRight:"Right"===e||"Both"===e}}calculateAt(e){const t=this.inputs.Period,i=this.inputs.Width;if(e===this.base.size-1&&this.base.size>=t){this.resetState();const e=t*(t+1)/2,s=e*e,n=t*(t+1)*(2*t+1)/6;let r=0,o=0,a=1;const l=this.base.size-t;for(let i=0;i<t;++i){const e=this.baseVal(Ka.Close,l+i);r+=e,o+=a*e,a+=1}const c=(t*o-e*r)/(t*n-s),u=r/t-c*e/t;let h=0;for(let i=0;i<t;++i){const e=this.baseVal(Ka.Close,l+i)-(u+c*(i+1));h+=e*e}const d=Math.sqrt(h/t);this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=c,this.state.intercept=u,this.state.stdDevWidth=ie(d)?i*d:null}return{}}getCurrentState(){return this.state}},CSHO:class extends up{computeDone;constructor(e,t){super(e,t,lp(t,e=>{const t=ue(e);var i;t.symbol=Fi(i=e.symbol)?`${Zi(i)}Y00`:null;return ie(t.symbol)?new Ch(t):new bh(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){const e=this.innCont(0);if(!ie(e)||0===e.size)return;const t=this.innCont(1),i=e.getTimeData(),s=t.getTimeData(),n=t.getData(Ka.Close),r=Array(i.length).fill(null);if(!(this.innerSeries[1]instanceof bh)){let o=0;const a=e.size,l=t.size;for(let e=0;e<a;++e){for(;o<l&&s[o].getTime()<i[e].getTime();)o++;o<l&&s[o].getTime()===i[e].getTime()&&(r[e]=n[o])}}this.container.setData(this.target,r)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(qa.TS_MANYCHANGED,-1))}},CSHB:class extends up{constructor(e,t){super(e,t,function(e,t=Ka.CSHO){return ny("CSHO",sy(t),e)}(t))}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){const t=(t,i)=>ie(this.innCont(t))?this.innVal(t,i,e):null,i=t(0,Ka.Close),s=t(1,Ka.CSHO);return{[this.target.id]:ie(s)&&ie(i)?s-i:null}}},MKTCAP:class extends up{computeDone;constructor(e,t){super(e,t,lp(t,e=>{const t=new ip(e.symbol,new Wo(e.aggregation.unit===a.Year?a.Year:a.Quarter,1),m.BalanceSheet);return t.fields=[Ka.SharesOutstanding],t.cacheMe=!0,new Mh(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){const e=this.innCont(0);if(!ie(e)||0===e.size)return;const t=this.innCont(1);if(!ie(t)||0===t.size)return;const i=e.getTimeData(),s=t.getTimeData(),n=t.getData(Ka.SharesOutstanding),r=e.getData(Ka.Close),o=Array(i.length);let a=0;const l=e.size,c=t.size;for(let u=0;u<l;++u){const e=i[u].getTime();for(;a<c-1&&s[a+1].getTime()<=e;)a++;if(a<c&&s[a].getTime()<=e){const e=n[a],t=r[u];o[u]=ie(e,t)?e*t:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(qa.TS_MANYCHANGED,-1))}},CTPI:class extends Np{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,Ka.CTPI,t)}},PCTCHG:class extends up{constructor(e,t){super(e,t),My(this)}calculateAt(e){let t=null;const[i]=_y(this);if(e>0){const s=this.innVal(i,this.source,e-1);if(null!==s){t=100*(this.innVal(i,this.source,e)-s)/s}}return{[this.target.id]:t}}},OPINT:class extends mp{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(Ka.TradeSize,Ka.Change)}},STOMOMIX:class extends up{constructor(e,t){super(e,t);const i=dy(t,e.inputs.Period1,Ka.High,Ka.HH,!0),s=dy(t,e.inputs.Period1,Ka.Low,Ka.LL,!1),n=ly(by(um,(e,t,i)=>this.baseVal(Ka.Close,e)-(t+i)/2,i,s),e.inputs.Period2,um,hm),r=ly(n,e.inputs.Period2,hm,dm),o=ly(by(pm,(e,t,i)=>t-i,i,s),e.inputs.Period2,pm,fm),a=ly(o,e.inputs.Period2,fm,mm),l=by(Ka.STOMOMIX,(e,t,i)=>100*t/i,r,a);this.addInner(l)}getWrappers(){return[this.wrapInner(this.target,1)]}},CHDMOMOSC:class extends up{constructor(e,t){super(e,t);const i=new Sm(e,t),s=Oy(e,"MA","Average")(i,this.inputs.PeriodAvg,Ka.CHDMOMOSC,Ka.CHDMOMOSCAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.CHDMOMOSC,1),this.wrapInner(Ka.CHDMOMOSCAVG,2)]}},VSTOP:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Tm,vm,Pm]}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=1;const l=this.baseVal(Ka.Close,e),c=e=>((e,t)=>ie(e)?e:t)(e,0),u=(e,t)=>this.container.getData(e)[t];e>0&&(s=Math.max(c(u(Tm,e-1)),l),r=Math.min(c(u(vm,e-1)),l),a=u(Pm,e-1));const h=this.inputs.Multiplier,d=this.innVal(1,Ka.ATR,e);if(ie(d)){const c=1===a,p=c?s-h*d:r+h*d;let f=u(c?Ka.VSTOPUP:Ka.VSTOPLOW,e-1);ie(f)||(f=0);const m=c?Math.max(f,p):Math.min(f,p);o=l-m>=0?1:0;const g=o!=a;i=g?l:s,n=g?l:r,t=g?1===o?i-h*d:n+h*d:m}return{[Ka.VSTOPUP.id]:1===o?t:null,[Ka.VSTOPLOW.id]:1===o?null:t,[Tm.id]:i,[vm.id]:n,[Pm.id]:o}}},SUPTR:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Cm,bm,Em,Ka.BARCOLIX]}calculateAt(e){let t=0,i=0,s=0,n=null,r=0;const o=this.innVal(1,Ka.ATR,e);if(ie(o)){const a=(e,t)=>ie(e)?e:t,l=[Ka.Close,Ka.High,Ka.Low],[c,u,h]=l.map(t=>this.baseVal(t,e)),d=(u+h)/2,p=this.baseVal(Ka.Close,e-1),f=this.inputs.Multiplier,m=d-f*o,g=d+f*o,y=[Cm,bm,Em],[A,S,T]=y.map(t=>this.container.getData(t)[e-1]);t=p>A?Math.max(m,A):m,i=p<S?Math.min(g,S):g,s=c>S?1:c<A?-1:a(T,1);const v=1===s;n=v?t:i,r=v?1:0}return{[Cm.id]:t,[bm.id]:i,[Em.id]:s,[Ka.SUPTR.id]:n,[Ka.BARCOLIX.id]:r}}},ICHCLD:class extends up{constructor(e,t){super(e,t);const i=(e,t,i)=>by(i,(e,t,i)=>(t+i)/2,e,t),s=(e,s)=>i((e=>dy(t,e,Ka.Low,Ka.LL,!1))(e),(e=>dy(t,e,Ka.High,Ka.HH,!0))(e),s),n=s(e.inputs.PeriodConversionLine,Ka.CONVLN),r=s(e.inputs.PeriodBaseLine,Ka.BASELN),o=i(n,r,Ka.LEADSP1),a=s(e.inputs.PeriodLaggingSpan2,Ka.LEADSP2);this.addInner(n,r,o,a)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){const t=this.innVal(3,Ka.LEADSP1,e)>this.innVal(4,Ka.LEADSP2,e)?1:0;return{[Ka.LAGGSP.id]:this.baseVal(Ka.Close,e),[Ka.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(Ka.CONVLN,1),this.wrapInner(Ka.BASELN,2),this.wrapInner(Ka.LEADSP1,3),this.wrapInner(Ka.LEADSP2,4)]}},VWAP:class extends xm{constructor(e,t){super(e,t)}get helpers(){return[Lm,Mm,_m]}isSame(e,t){switch(this.inputs.AnchorPeriod){case"Session":default:return ut(e,t);case"Week":return Mi(e,t);case"Month":return _i(e,t);case"Quarter":return xi(e,t);case"Year":return Ii(e,t);case"Decade":return function(e,t){return Au(e)===Au(t)}(e,t);case"Century":return Su(e,t)}}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(1===this.valueAt(_m,t))return t;return 0}calculateAt(e){let t=null,i=null,s=null,n=null,r=null;const o=e>0,a=o?this.dateAt(e-1):gs.ZERO_DATE,l=this.dateAt(e),c=o&&this.isSame(a,l),u=c?this.valueAt(Lm,e-1):0,h=c?this.valueAt(Mm,e-1):0,d=this.innVal(0,Ka.Volume,e),p=u+this.innVal(1,this.source,e)*d,f=h+d;if(t=p/f,c){const o=this.findPrevPeriodChange(e-1),a=this.container.getData(Ka.VWAP).slice(o,e);a.push(t);const l=w(a),c=a.map(e=>(e-l)*(e-l)),u=Math.sqrt(w(c)),h=this.inputs.Stdev1stMultiplier*u;i=t+h,s=t-h;const d=this.inputs.Stdev2ndMultiplier*u;n=t+d,r=t-d}else i=t,s=t,n=t,r=t;return{[Lm.id]:p,[Mm.id]:f,[_m.id]:c?0:1,[Ka.VWAP.id]:t,[Ka.VWAPSD1U.id]:i,[Ka.VWAPSD1L.id]:s,[Ka.VWAPSD2U.id]:n,[Ka.VWAPSD2L.id]:r}}},MACROSS:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,e.inputs.Period1,this.source,Ka.MAS),n=i(t,e.inputs.Period2,this.source,Ka.MAL);this.addInner(s,n)}get helpers(){return Dm}calculateAt(e){const t=this.innVal(1,Ka.MAS,e),i=this.innVal(2,Ka.MAL,e);return Om(this.container,e,t,i)}getWrappers(){return[this.wrapInner(Ka.MAS,1),this.wrapInner(Ka.MAL,2)]}},PACROSS:class extends up{_maIndex;_maTarget;constructor(e,t){super(e,t),My(this);const i=Oy(e,"MA","Average")(t,e.inputs.Period,this.source);this.addInner(i);const[s]=_y(this);this._maIndex=s+1,this._maTarget=i.target}get helpers(){return Dm}calculateAt(e){const t=this.innVal(this._maIndex,this._maTarget,e),[,i]=_y(this),s=i.getData(this.source)[e],n=Om(this.container,e,s,t);return n[this.target.id]=t,n}},VOIN:class extends up{constructor(e,t){super(e,t);const i=Cy(wm,function(e){return{[wm.id]:e>0?Math.abs(this.baseVal(Ka.High,e)-this.baseVal(Ka.Low,e-1)):null}},t),s=Cy(Rm,function(e){return{[Rm.id]:e>0?Math.abs(this.baseVal(Ka.Low,e)-this.baseVal(Ka.High,e-1)):null}},t),n=my(t,Ka.TR);this.addInner(i,s,n)}calculateAt(e){let t=null,i=null;const s=this.period;if(this.atLeast(e,s)){const n=this.past(e,s,wm,this.innCont(1)),r=this.past(e,s,Rm,this.innCont(2)),o=this.past(e,s,Ka.TR,this.innCont(3));if(R(n)&&R(r)&&R(o)){const e=O(n),s=O(r),a=O(o);t=e/a,i=s/a}}return{[Ka.PLVI.id]:t,[Ka.MNVI.id]:i}}},DIFA:class extends up{isPercent;constructor(e,t){super(e,t);const i=Oy(e,"MA","Average")(t,this.period,this.source,Hm);this.isPercent="Percentage"===e.inputs.Distance,this.addInner(i)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null,i=null;const s=this.innVal(1,Hm,e),n=this.baseVal(this.source,e);if(null!=s&&0!==s){t=n-s,this.isPercent&&(t=100*t/s);const r=t<=0;if(i=r?1:3,e>0){const s=this.container.getData(this.target)[e-1];null!==s&&(r&&t>s&&(i=0),!r&&t<s&&(i=2))}}return{[this.target.id]:t,[Ka.BARCOLIX.id]:i}}},DOSC:class extends up{constructor(e,t){super(e,t);const i=ly(Sy(t,this.inputs.PeriodRsi,this.source,Ka.RSI),this.inputs.PeriodEma1,Ka.RSI,Ka.EMA),s=ly(i,this.inputs.PeriodEma2,Ka.EMA,Ka.EMA),n=ay(s,this.inputs.PeriodMa,Ka.EMA,Ka.MA);const r=by(Ka.DOSCH,(e,t,i)=>t-i,s,n),o=ay(r,this.inputs.PeriodSig,Ka.DOSCH,Ka.DOSCS);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.DOSCH,1),this.wrapInner(Ka.DOSCS,2)]}},BBANDW:class extends Hp{constructor(e,t){super(e,"BandWidth",t)}},MARIB:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=this.inputs.Increment,n=Math.min(Math.max(0,this.inputs.Count),10);for(let r=0;r<n;++r){const e=ay(t,i+r*s,this.source,this.outFields[r]);this.addInner(e)}}getWrappers(){const e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},HASMO:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"EMA","Smoothing1"),s=e.inputs.Period1,n=i(t,s,Ka.Open),r=i(t,s,Ka.High),o=i(t,s,Ka.Low),a=i(t,s,Ka.Close),l=by(Wm,(e,t,i,s,n)=>(t+i+s+n)/4,n,r,o,a);const c=by(Bm,function(e,t,i,s){let n=null;if(e>0){const s=this.container.getData(Bm)[e-1],r=this.innVal(2,Wm,e-1);ie(s,r)?n=(s+r)/2:ie(t,i)&&(n=(t+i)/2)}return n},n,a,l),u=by(Fm,(e,t,i,s)=>ie(t,i,s)?Math.max(t,Math.max(i,s)):null,r,c,l),h=by(km,(e,t,i,s)=>ie(t,i,s)?Math.min(t,Math.min(i,s)):null,o,c,l),d=Oy(e,"EMA","Smoothing2"),p=e.inputs.Period2,f=d(c,p,Bm,Ka.Open),m=d(u,p,Fm,Ka.High),g=d(h,p,km,Ka.Low),y=d(l,p,Wm,Ka.Close),A=Cy(Ka.Change,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Close,e-1);ie(i,s)?t=i-s:ie(i)&&!ie(s)&&(t=0)}return{[Ka.Change.id]:t}},y);this.addInner(f,m,g,y,A)}getWrappers(){return[this.wrapInner(Ka.Open,1),this.wrapInner(Ka.High,2),this.wrapInner(Ka.Low,3),this.wrapInner(Ka.Close,4),this.wrapInner(Ka.Change,5)]}},TTMSQZ:class extends up{constructor(e,t){super(e,t);const i=e.inputs,s=ly(t,i.PeriodEmaKeltner,Ka.Close),n=gy(t,i.PeriodAtrKeltner);function r(e,t,i,s){return ie(i,s)?i+e*s:null}const o=i.MultiplierKeltner,a=by(Ka.KCUP,M(r,o),s,n),l=by(Ka.KCLOW,M(r,-o),s,n),c=function(e,t,i,s=Ka.Close){const n="BBANDS",r=ry(n),o={[gs.INPUT_PERIOD]:t,[gs.INPUT_WIDTH]:i};return ny(n,{source:s,inputs:o,outFields:r},e)}(t,i.PeriodBollinger,i.WidthBollinger),u=function(e,t){const i="DONCHN",s=ry(i);return ny(i,{inputs:ty(t),outFields:s,source:null},e)}(t,i.PeriodMomentum),h=ay(t,i.PeriodMomentum,Ka.Close);const d=Py(by(Um,function(e,t,i,s){let n=null;const r=this.innVal(1,Ka.DONMID,e);return ie(r,s)&&(n=t-(r+s)/2),n},t,u,h),i.PeriodMomentum,Um,Ka.TTMSQZOSC);this.addInner(a,l,c,d)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null,i=null,s=-1;const n=this.innVal(1,Ka.KCUP,e),r=this.innVal(2,Ka.KCLOW,e),[o,a]=[Ka.BOLLBU,Ka.BOLLBL].map(t=>this.innVal(3,t,e));o<n&&a>r?t=0:i=0;const l=this.innVal(4,Ka.TTMSQZOSC,e),c=e>0?this.innVal(4,Ka.TTMSQZOSC,e-1):null;if(ie(l))if(ie(c)){const e=c<l;s=l>=0?e?3:2:e?1:0}else s=2;return{[Ka.TTMSQZON.id]:t,[Ka.TTMSQZOFF.id]:i,[Ka.BARCOLIX.id]:s}}getWrappers(){return[this.wrapInner(Ka.TTMSQZOSC,4)]}},CRS:class extends up{constructor(e,n){if(super(e,n),Hy(n)){const r=Gv().getTimeSeriesDataSource(),o=n.query.duplicate();o.symbol=this.inputs.Symbol.toUpperCase();const l=r.getTimeSeries(o),c=e=>e.query?.symbol,u=(e,t)=>`{${c(e)}} / {${c(t)}}`,{model:h}=ca(u(n,l),!1),d=(e=>{const n=e.unit===a.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:i.Manual,missing:n?t.UseNext:t.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,Ka.CRS]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}})(e.aggregation),p=new Vm(h,[n,l],d),f=Oy(e,"MA","Average")(p,this.period,Ka.CRS,Ka.CRSAVG);this.addInner(l,p,f),this.canLoadMoreData=!0,this.initialNotification=!0}else{const e=Cy(Ka.Close,(e,t)=>null,n),t=Cy(Ka.CRS,(e,t)=>null,n),i=Cy(Ka.CRSAVG,(e,t)=>null,n);this.addInner(e,t,i),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(Ka.CRS,2),this.wrapInner(Ka.CRSAVG,3)]}},JPI:ng,CTTP:class extends ng{constructor(e,t){const i=Ur("JPI");e.inputs=fe(i.defaults.inputs.filter(e=>"HandbrakePeriod"!==e.name)),super(e,t)}},CTTI:class extends ng{constructor(e,t){e.inputs=structuredClone(rg),super(e,t)}},DRS:class extends up{get indexSymbol(){return this.inputs[gs.INPUT_SYMBOL]}constructor(e,n){if(super(e,n),Hy(n)){const r=Gv().getTimeSeriesDataSource(),o=n.query.duplicate();o.symbol=this.indexSymbol;const l=r.getTimeSeries(o),c=`{${n.query.symbol}} / {${l.query.symbol}} * 100`,{model:u}=ca(c,!1),h=(e=>{const n=e.unit===a.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:i.Manual,missing:n?t.UseNext:t.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,Ka.DRS]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}})(e.aggregation),d=new Vm(u,[n,l],h);this.addInner(l,d),this.canLoadMoreData=!0,this.initialNotification=!0}else{const e=Cy(Ka.Close,(e,t)=>null,n),t=Cy(Ka.DRS,(e,t)=>null,n);this.addInner(e,t),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(Ka.DRS,2)]}},MRS:class extends up{get indexSymbol(){return this.inputs[gs.INPUT_SYMBOL]}constructor(e,t){super(e,t);const i=function(e,t,i,s=Ka.DRS){return ny("DRS",{target:s,inputs:iy(t),aggregation:i,source:null},e)}(t,this.indexSymbol,e.aggregation),s=ay(i,this.period,Ka.DRS);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){const t=this.innVal(1,Ka.DRS,e),i=this.innVal(2,Ka.MA,e);let s=null;return ie(t,i)&&0!==i&&(s=100*(t/i-1)),{[Ka.MRS.id]:s}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},PMO:class extends up{constructor(e,t){super(e,t);const i=Ay(t,1),s=e.aggregation,n=lg(i,this.inputs.Period1,s,Ka.ROC,og),r=lg(by(ag,(e,t)=>10*t,n),this.inputs.Period2,s,ag,Ka.PMO),o=ly(r,this.inputs.Period3,Ka.PMO,Ka.PMOS);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.PMO,1),this.wrapInner(Ka.PMOS,2)]}},RVOL:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA")(t,this.period,Ka.Volume,cg,!0);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(0,Ka.Volume,e),s=this.innVal(1,cg,e);return ie(i,s)&&0!==s&&(t=i/s),{[this.target.id]:t}}},WGALPH:class extends up{isDaily;isFeasible=!0;constructor(e,t){super(e,t),this.isFeasible=!(t instanceof bh||hg.includes(o[t.query.curveStyle])),this.isDaily=e.aggregation.unit===a.Day}acceptable(e,t,i,s){if(!this.isDaily)return e>0&&i-t>=5;if(0===s)return!0;return!Mi(this.baseVal(Ka.DateTime,t),this.baseVal(Ka.DateTime,i))}pluckValues(e){let t=0;const i=[];let s=e+5;for(let n=0;t<53&&e-n>0;n++){const r=e-n,o=this.baseVal(this.source,r);this.acceptable(o,r,s,t)&&(i.push(o),s=r,t++)}return i}calculateAt(e){let t=null;if(this.isFeasible&&e>=131){let i=1;const s=this.pluckValues(e),n=s.length;if(n>=27)for(let e=0;e<n-1;e++){let t=s[e]/s[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*ug[e]+1,i*=t}t=100*(i-1)}return{[this.target.id]:t}}},VOLAP:class extends pg{constructor(e,t){super(e,!1,t)}},AVWAP:class extends xm{constructor(e,t){super(e,t)}get helpers(){return[Lm,Mm]}isSameOhlcBar(e,t){const{unit:i,size:s}=this.aggregation;switch(i){case a.Tick:return e===t;case a.Intraday:return bi(t,ot(e,s));case a.Day:return bi(t,Xe(e,s));case a.Week:return Mi(e,t);case a.Month:return _i(e,t);case a.Quarter:return xi(e,t);case a.Year:return Ii(e,t);default:throw new Error(`Unexpected aggregation unit ${a[i]}`)}}calculateAt(e){let t=null,i=null,s=null;const n=this.inputs.Anchor,r=this.dateAt(e);if(bi(n,r)||this.isSameOhlcBar(r,n)){const n=e>0,r=n?this.valueAt(Lm,e-1):0,o=n?this.valueAt(Mm,e-1):0,a=this.innVal(0,Ka.Volume,e);i=r+this.innVal(1,this.source,e)*a,s=o+a,t=i/s}return{[Lm.id]:i,[Mm.id]:s,[Ka.AVWAP.id]:t}}},KST:class extends up{constructor(e,t){super(e,t);const i=this.source,s=Cy(i,M(xy,i),t),n=Ay(s,this.inputs.PeriodRoc1,i),r=Ay(s,this.inputs.PeriodRoc2,i),o=Ay(s,this.inputs.PeriodRoc3,i),a=Ay(s,this.inputs.PeriodRoc4,i),l=ay(n,this.inputs.PeriodMa1,Ka.ROC,Ka.MA1),c=ay(r,this.inputs.PeriodMa2,Ka.ROC,Ka.MA2),u=ay(o,this.inputs.PeriodMa3,Ka.ROC,Ka.MA3),h=ay(a,this.inputs.PeriodMa4,Ka.ROC,Ka.MA4),d=by(Ka.KST,(e,t,i,s,n)=>t+2*i+3*s+4*n,l,c,u,h),p=ay(d,this.inputs.PeriodSig,Ka.KST,Ka.KSTSIG);this.addInner(d,p)}getWrappers(){return[this.wrapInner(Ka.KST,1),this.wrapInner(Ka.KSTSIG,2)]}},STC:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.PeriodShort,Ka.Close,gg),s=ly(t,this.inputs.PeriodLong,Ka.Close,yg),n=by(Ag,(e,t,i)=>t-i,i,s),r=this.inputs.PeriodStoch1,o=this.inputs.PeriodStoch2,a=Oy(e,"EMA"),l=a(py(n,r,Sg,!1,Ag),o,Sg,Tg),c=a(py(l,r,vg,!1,Tg),o,vg,this.target);this.addInner(c)}getWrappers(){return[this.wrapInner(this.target,1)]}},MCCLO:class extends Eg{constructor(e,t){super(e,t)}getTargetSeries(e,t,i){const s=(e,t,i)=>t-i,n="Yes"===this.inputs.RatioAdjusted,r=by(bg,n?(e,t,i)=>(t-i)/(t+i)*1e3:s,t,i),o=ly(r,this.inputs.Period1,bg,Pg),a=ly(r,this.inputs.Period2,bg,Cg);return by(this.target,s,o,a)}},NHLAI:_g,CMBCI:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period1Rsi,Ka.Close,xg),s=Cy(Ig,_(Iy,this.inputs.Period1Mom,xg),i),n=ay(Sy(t,this.inputs.Period2Rsi,Ka.Close,Dg),this.inputs.Period2Ma,Dg,Og),r=by(Ka.CMBCI,(e,t,i)=>t+i,s,n),o=ay(r,this.inputs.PeriodFastMa,Ka.CMBCI,Ka.CMBCIF),a=ay(r,this.inputs.PeriodSlowMa,Ka.CMBCI,Ka.CMBCIS);this.addInner(r,o,a)}getWrappers(){return[this.wrapInner(Ka.CMBCI,1),this.wrapInner(Ka.CMBCIF,2),this.wrapInner(Ka.CMBCIS,3)]}},COTI:class extends up{constructor(e,t){super(e,function(e){return new zf({source:Ka.Close,inputs:{},outFields:ry("COTLC")},e)}(t));const i=Number.parseInt(this.inputs.History),s=6===i?26:52*i,n=py(this.innerSeries[0],s,Ka.COTI,!1,Ka.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.COTI,1)]}},CHEXI:class extends up{isLong;constructor(e,t){super(e,t),this.isLong="Long"===this.inputs.Direction;const i=this.period,s=gy(t,i),n=this.inputs.Multiplier,r=by(wg,(e,t)=>null===t?null:n*t,s),o=dy(t,i,Ka.High,Ka.HH,!0),a=dy(t,i,Ka.Low,Ka.LL,!1);this.addInner(r,o,a)}calculateAt(e){let t=null,i=null;const s=this.innVal(1,wg,e);if(null!==s)if(this.isLong){t=this.innVal(2,Ka.HH,e)-s}else{i=this.innVal(3,Ka.LL,e)+s}return{[Ka.CHEXL.id]:t,[Ka.CHEXS.id]:i}}},MBBANDS:class extends Hp{constructor(e,t){super(e,"Modified",t)}},OPTIV:class extends Rg{},IVRANK:class extends Rg{},IVPCTL:class extends Rg{},OPTVOLPC:class extends Rg{},OPTOIPC:class extends Rg{},OPTVOL:class extends Rg{},OPTOI:class extends Rg{},CHOP:class extends up{constructor(e,t){super(e,t);const i=gy(t,1),s=this.inputs.Period,n=dy(t,s,Ka.High,Ka.HH,!0),r=dy(t,s,Ka.Low,Ka.LL,!1);this.addInner(i,n,r)}calculateAt(e){let t=null;const i=this.period;if(e>i){const s=this.past(e,i,Ka.ATR,this.innCont(1));if(R(s)){const n=O(s)/(this.innVal(2,Ka.HH,e)-this.innVal(3,Ka.LL,e));t=100*Math.log10(n)/Math.log10(i)}}return{[this.target.id]:t}}},MACLD:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,e.inputs.Period1,this.source,Ka.MACLD1),n=i(t,e.inputs.Period2,this.source,Ka.MACLD2);this.addInner(s,n)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){const t=this.innVal(1,Ka.MACLD1,e)>this.innVal(2,Ka.MACLD2,e)?1:0;return{[Ka.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(Ka.MACLD1,1),this.wrapInner(Ka.MACLD2,2)]}},BTI:class extends Eg{constructor(e,t){super(e,t)}getTargetSeries(e,t,i){const s=by(Ng,(e,t,i)=>t/(t+i),t,i);return Oy(e,"MA","Average")(s,this.inputs.Period,Ng,this.target)}},FRAMA:class extends up{constructor(e,t){super(e,t),My(this);const i=e.inputs.Period,s=Math.floor(i/2),n=dy(t,i,Ka.High,Gg,!0),r=dy(t,i,Ka.Low,zg,!1),o=dy(t,s,Ka.High,Yg,!0),a=dy(t,s,Ka.Low,jg,!1),l=dy(t,s,Ka.High,Kg,!0),c=dy(t,s,Ka.Low,qg,!1);this.addInner(n,r,o,a,l,c)}calculateAt(e){const t=this.period,i=Math.floor(t/2),[,s]=_y(this),n=s.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:n};const r=this.sourceNeedsCompute?1:0,o=this.innVal(1+r,Gg,e),a=this.innVal(2+r,zg,e),l=this.innVal(3+r,Yg,e),c=this.innVal(4+r,jg,e),u=this.innVal(5+r,Kg,e-i),h=this.innVal(6+r,qg,e-i);if(!ie(o,a,l,c,u,h))return{[this.target.id]:n};const d=(o-a)/t,p=(l-c)/i,f=(u-h)/i;let m=0;p>0&&f>0&&d>0&&(m=(Math.log(p+f)-Math.log(d))/Math.log(2));let g=Math.exp(-4.6*(m-1));g=Math.max(.01,Math.min(1,g));const y=e>0?this.container.getData(this.target)[e-1]:n,A=null!==y?g*n+(1-g)*y:n;return{[this.target.id]:A}}},FISHER:class extends up{constructor(e,t){super(e,t);const i=e.inputs.Period,s=Cy(Xg,M(qp,Xg),t),n=dy(s,i,Xg,Ka.HH,!0),r=dy(s,i,Xg,Ka.LL,!1);this.addInner(s,n,r)}get helpers(){return[Zg]}calculateAt(e){const t=this.innVal(1,Xg,e),i=this.innVal(2,Ka.HH,e),s=this.innVal(3,Ka.LL,e);if(!ie(i,s,t))return{[Ka.FISHER.id]:null,[Ka.FISHTRG.id]:null,[Zg.id]:null};const n=i-s,r=t=>this.container.getData(t)[e-1];let o=.66*((0!==n?(t-s)/n:.5)-.5)+.67*((e>0?r(Zg):null)??0);o>.99?o=.999:o<-.99&&(o=-.999);const a=e>0?r(Ka.FISHER):null,l=.5*Math.log((1+o)/(1-o))+.5*(a??0);return{[Ka.FISHER.id]:l,[Ka.FISHTRG.id]:a,[Zg.id]:o}}},PC:class extends up{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=Ry(e.aggregation),this.stdDevs=this.toInt("StandardDeviations"),this.periodForecast=this.toInt("PeriodForecast");const i=this.getHistVolPeriod();if(null!==i){const s=function(e,t,i,s=Ka.Close,n=Ka.HV){return ny("HV",{source:s,target:n,aggregation:i,inputs:ty(t)},e)}(t,i,e.aggregation);this.addInner(s)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return"Custom"===this.volatilityParam}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(Ka.HV))/100}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null;if(this.haveVolatility){const a=this.base.size-this.periodForecast;if(e>=a){const l=this.base.getLastDataPoint(Ka.Close),c=e-a+1,u=l*this.getVolatilityPercent()*Math.sqrt(c/this.unitsPerYear);if(t=l+u,i=l-u,this.stdDevs>1){const e=2*u;if(s=l+e,n=l-e,this.stdDevs>2){const e=3*u;r=l+e,o=l-e}}}}return{[Ka.PCUP1.id]:t,[Ka.PCDN1.id]:i,[Ka.PCUP2.id]:s,[Ka.PCDN2.id]:n,[Ka.PCUP3.id]:r,[Ka.PCDN3.id]:o}}recalculateAt(e,t,i){const s={tag:Pe(),src:this.innerSeries[0]};i&&this.calculate(s)}},GREEKS:class extends up{constructor(e,t){super(e,lp(t,e=>new Vg(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(Ka.Delta,0),this.wrapInner(Ka.Gamma,0),this.wrapInner(Ka.Theta,0),this.wrapInner(Ka.Vega,0)]}},PVACP:class extends pg{constructor(e,t){super(e,!0,t)}},TDI:class extends up{constructor(e,t){super(e,t),My(this);const i=e.inputs.PeriodRSI,s=e.inputs.PeriodTradeSignal,n=e.inputs.PeriodMarketBase,r=e.inputs.PeriodBB,[o]=_y(this),a=Sy(this.innerSeries[o],i,this.source,Ka.TDIPRC),l=ay(a,s,Ka.TDIPRC,Ka.TDITSL),c=ay(a,n,Ka.TDIPRC,Ka.TDIMBL),u=vy(a,r,Ka.TDIPRC,Ka.MSD);this.addInner(a,l,c,u)}calculateAt(e){const t=this.inputs.MultiplierBB,i=this.sourceNeedsCompute?1:0,s=this.innVal(1+i,Ka.TDIPRC,e),n=this.innVal(2+i,Ka.TDITSL,e),r=this.innVal(3+i,Ka.TDIMBL,e),o=this.innVal(4+i,Ka.MSD,e);let a=null,l=null;if(ie(r,o)){const e=t*o;a=r+e,l=r-e}return{[Ka.TDIPRC.id]:s,[Ka.TDITSL.id]:n,[Ka.TDIMBL.id]:r,[Ka.TDIUPR.id]:a,[Ka.TDILWR.id]:l}}},PPS:class extends up{isLong;isPercent;constructor(e,t){super(e,t);const i=e.inputs.Period,s=e.inputs.Range,n=e.inputs.Direction;this.isLong="Long"===n,this.isPercent="Percent"===e.inputs.Type;const r="Close"===s;let o=Ka.Close;r||(o=this.isLong?Ka.High:Ka.Low);const a=dy(t,i,o,$g,this.isLong);this.addInner(a)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null;const i=this.innVal(1,$g,e),s=this.inputs.StopValue;if(null!==i){const e=this.isPercent?i*s/100:s;t=this.isLong?i-e:i+e}const n=this.isLong?1:0;return{[Ka.PPS.id]:t,[Ka.BARCOLIX.id]:n}}},RCI:class extends up{constructor(e,t){super(e,t);const i=this.source,s=new Jg({source:i,target:Ka.RCI,inputs:{Period:e.inputs.Period}},t),n=e.inputs.PeriodSignal,r=Oy(e,"MA","Smoothing")(s,n,Ka.RCI,Ka.RCISIG);this.addInner(s,r)}getWrappers(){return[this.wrapInner(Ka.RCI,1),this.wrapInner(Ka.RCISIG,2)]}},ZIGZAG:class extends up{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow="High/Low"===e.inputs.Method,this.isAtrMode="ATR"===e.inputs.PercentMode,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||My(this),this.isAtrMode){const t=e.inputs.PeriodAtr,[i]=this.useHighLow?[0]:_y(this),s=gy(this.innerSeries[i],t,"SMA",Qg);this.addInner(s)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(Ka.High,e);const[,t]=_y(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(Ka.Low,e);const[,t]=_y(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(Ka.Close,e);const[,t]=_y(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){const t=!this.useHighLow&&this.sourceNeedsCompute?1:0,i=this.innVal(1+t,Qg,e),s=this.getAtrDenom(e);if(null===i||null===s||0===s)return 0;const n=i/s*100;return this.atrMult*n}return this.percent}pct(e,t){return 0===e?0:(t-e)/e*100}resetState(){this.state={mode:0,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:/* @__PURE__ */new Map}}calculateAt(e){const t=this.getHigh(e),i=this.getLow(e),s=this.getDevPct(e);if(null===t||null===i)return{};if(0===e){this.resetState();const i=this.useHighLow?this.baseVal(Ka.Close,e):t;return this.setPivot(i,e),this.setCandidate(i,e),{}}if(0===this.state.mode)this.pct(this.state.pivotPrice,t)>=s?(this.state.mode=1,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,i)>=s&&(this.state.mode=-1,this.setCandidate(i,e));else if(1===this.state.mode){const n=t>=this.state.candPrice;n&&this.setCandidate(t,e);const r=(this.state.candPrice-i)/this.state.candPrice*100;if(!n&&r>=s){const t=this.state.candIndex,s=this.state.candPrice;this.state.confirmedPivots.set(t,s),this.setPivot(s,t),this.setCandidate(i,e),this.state.mode=-1}}else if(-1===this.state.mode){const n=i<=this.state.candPrice;n&&this.setCandidate(i,e);const r=(t-this.state.candPrice)/this.state.candPrice*100;if(!n&&r>=s){const i=this.state.candIndex,s=this.state.candPrice;this.state.confirmedPivots.set(i,s),this.setPivot(s,i),this.setCandidate(t,e),this.state.mode=1}}return{}}getCurrentState(){return this.state}}};function ty(e){return{[gs.INPUT_PERIOD]:e}}function iy(e){return{[gs.INPUT_SYMBOL]:e}}function sy(e){return{target:e,source:null,inputs:fy}}function ny(e,t,i){if(le(ey,e))return new ey[e](t,i);const s=Gv()?.config.extensions?.studyProvider;if(s){const n=s.factory(e,t,i);if(n)return n}throw new Error(`Study ${e} has not been implemented yet.`)}function ry(e){return Ur(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>Ka[e])}function oy(e,t,i,s){return{source:t,target:i,inputs:ty(e),allowEmptyValues:s}}function ay(e,t,i,s=Ka.MA,n=!1){return ny("MA",oy(t,i,s,n),e)}function ly(e,t,i,s=Ka.EMA,n=!1){return ny("MAEXP",oy(t,i,s,n),e)}function cy(e,t,i,s=Ka.SMA,n=!1){return ny("MASMO",oy(t,i,s,n),e)}function uy(e,t,i,s=Ka.WMA,n=!1){return ny("MAWEI",oy(t,i,s,n),e)}function hy(e,t,i,s=Ka.HMA,n=!1){return ny("HMA",oy(t,i,s,n),e)}function dy(e,t,i,s,n,r=!1){return new Op({source:i,target:s,inputs:ty(t)},n,r,e)}function py(e,t,i,s,n=null){return new wp({source:n,target:i,inputs:ty(t)},s,e)}const fy={};function my(e,t=Ka.TR){return ny("_TR",sy(t),e)}function gy(e,t,i="SMA",s=Ka.ATR){return ny("ATR",{target:s,inputs:{[gs.INPUT_PERIOD]:t,[gs.INPUT_SMOOTHING]:i},source:null},e)}function yy(e,t=Ka.TP){return ny("TP",sy(t),e)}function Ay(e,t,i=Ka.Close,s=Ka.ROC){return ny("ROC",{source:i,target:s,inputs:ty(t)},e)}function Sy(e,t,i,s=Ka.RSI,n=!1){return ny("_RSI",{source:i,target:s,inputs:{...ty(t),Modified:n}},e)}function Ty(e,t=Ka.MFMUL){return ny("MFV",sy(t),e)}function vy(e,t,i,s=Ka.MSD){return ny("MSD",{source:i,target:s,inputs:ty(t)},e)}function Py(e,t,i,s=Ka.MOVLR){return ny("MOVLR",{source:i,inputs:ty(t),target:s},e)}function Cy(e,t,i){return new Zp(sy(e),t,i)}function by(e,t,...i){return new Kp(sy(e),t,...i)}function Ey(e,t,i){return t-i}function Ly(e,t,i){return(t-i)/i*100}function My(e){const t=e.source;if(e.sourceNeedsCompute=function(e){switch(e.id){case"HL/2":case"OC/2":case"HLC/3":case"OHLC/4":case"HLCC/4":return!0;default:return!1}}(t),e.sourceNeedsCompute){const i=Cy(t,M(xy,t),e.innerSeries[0]);e.addInner(i)}}function _y(e){const t=e.sourceNeedsCompute?1:0;return[t,e.innCont(t)]}const xy=function(e,t){const i=[Ka.Open,Ka.High,Ka.Low,Ka.Close],[s,n,r,o]=i.map(e=>this.baseVal(e,t));let a=null;const l=e.id;switch(l){case"Open":a=s;break;case"High":a=n;break;case"Low":a=r;break;case"Close":a=o;break;case"HL/2":a=(n+r)/2;break;case"OC/2":a=(s+o)/2;break;case"HLC/3":a=(n+r+o)/3;break;case"OHLC/4":a=(s+n+r+o)/4;break;case"HLCC/4":a=(n+r+o+o)/4}return{[l]:a}},Iy=function(e,t,i){let s=null;if(this.atLeast(i,e+1)){const n=this.baseVal(t,i-e);if(null!==n){s=this.baseVal(t,i)-n}}return{[this.target.id]:s}},Dy={sma:cy,ma:ay,ema:ly,wma:uy,hma:hy};function Oy(e,t,i="Smoothing"){const s=(e.inputs[i]??t).toLowerCase();return Dy[s]}const wy={atr:gy,adjatr:function(e,t,i="MA",s=Ka.Close,n=Ka.ADJATR){return ny("ADJATR",{source:s,target:n,inputs:{[gs.INPUT_PERIOD]:t,[gs.INPUT_SMOOTHING]:i}},e)}};function Ry(e){switch(e.unit){case a.Day:return 252;case a.Week:return 52;case a.Month:return 12;default:return 0}}function Ny(e){const t=[Ka.High,Ka.Low];return e instanceof Vm&&2!==F(e.targetFields,t).length}function Vy(e,t){return e[`Period${t}`]}function Hy(e){return!(e instanceof bh)&&e.query instanceof ip}class By extends hp{constructor(e,t){super(e,t,ly(t,13,Ka.Close),function(e,t,i,s,n=Ka.Close){return ny("MACDEXP",{source:n,inputs:{Period1:t,Period2:i,Period3:s},outFields:[Ka.MACD,Ka.MACDS,Ka.MACDH]},e)}(t,12,26,9,Ka.Close)),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=n.Same;const i=this.innVal(1,Ka.EMA,e),s=this.innVal(1,Ka.EMA,e-1),r=this.innVal(2,Ka.MACDH,e),o=this.innVal(2,Ka.MACDH,e-1);return ie(i,s,r,o)&&(i>s&&r>o?t=n.Up:i<s&&r<o&&(t=n.Down)),{[Ka.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Change,Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}function Fy(e,t){return ie(t)?(this[e]=t,null):this[e]}class ky{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return Fy.call(this,"_domain",e)}range(e){return Fy.call(this,"_range",e)}padding(e){return Fy.call(this,"_padding",e)}get ready(){return ie(this._domain,this._range)}}const Wy=1/Math.log2(10);function Uy(e,t){const i=(s=e[0],n=e[1],(n-=s)>0?e=>(e-s)/n:e=>isNaN(n)?NaN:.5);var s,n;const r=((e,t)=>i=>e*(1-i)+t*i)(t[0],t[1]);return e=>r(i(e))}function $y(e){return Math.sign(e)*Math.log10(1+Math.abs(e/Wy))}function Gy(e){return Math.sign(e)*Wy*(-1+Math.pow(10,Math.abs(e)))}const zy=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]];class Yy extends ky{constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!function(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e===t)return!0;for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let i=I,s=I;switch(this.scaleType){case p.Linear:break;case p.Logarithmic:i=$y,s=Gy;break;default:throw new Error("Unexpected scale type (neither linear nor log)")}const n=this._domain.map(i),r=this.rangeWithPadding(),o=e=>r[1]-e+r[0];return(t?s:o)((t?Uy(r,n):Uy(n,r))((t?o:i)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];const[t,i]=this._range.map(e=>this.mapValue(e,!0));if(t===i&&e>0)return[t];const[s,n]=this._domain;if(this.scaleType===p.Linear||s<0||n>1e5)return jy(t,i,e);const r=this.findLogBand(s),o=this.findLogBand(n),a=2*e;return o-r===0?jy(t,i,a):this.getLogTicks(r,o,a,i<t)}findLogBand(e){return zy.findIndex(([t,i])=>e>=t&&e<i)}getLogTicks(e,t,i,s){const n=[...this._domain];let r=[];try{for(let o=e;o<=t;o++){let[a,l]=zy[o];o===e?a=n[0]:o===t&&(l=n[1]),this.domain([a,l]);const[c,u]=this._range.map(e=>this.mapValue(e,!0)),h=jy(c,u,i);r=s?h.concat(r):r.concat(h)}}finally{this.domain(n)}return function(e,t){const i=e.length;for(let s=1;s<i;++s){const i=e[s];let n=s-1;for(;n>=0&&t(e[n],i);)e[n+1]=e[n],n-=1;e[n+1]=i}}(r,s?(e,t)=>e>t:(e,t)=>e<t),r}checkTicks(){return this.scaleType===p.Logarithmic}}function jy(e,t,i){let s,n,r,o,a=-1;if(i=+i,(e=+e)===(t=+t)&&i>0)return[e];if((s=t<e)&&(n=e,e=t,t=n),0===(o=function(e,t,i){const s=Math.sqrt(50),n=Math.sqrt(10),r=Math.sqrt(2),o=(t-e)/Math.max(0,i),a=Math.floor(Math.log(o)/Math.LN10),l=o/Math.pow(10,a);return a>=0?(l>=s?10:l>=n?5:l>=r?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=s?10:l>=n?5:l>=r?2:1)}(e,t,i))||!isFinite(o))return[];if(o>0)for(e=Math.ceil(e/o),t=Math.floor(t/o),r=new Array(n=Math.ceil(t-e+1));++a<n;)r[a]=(e+a)*o;else for(e=Math.floor(e*o),t=Math.ceil(t*o),r=new Array(n=Math.ceil(e-t+1));++a<n;)r[a]=(e-a)/o;return s&&r.reverse(),r}const Ky={color:gs.COLOR_TRANSPARENT},qy={color:gs.COLOR_TRANSPARENT,width:0,dashStyle:"Solid"},Xy=[Ka.Open,Ka.High,Ka.Low,Ka.Close],Zy=new Set(Xy.map(e=>e.id)),Jy=new xn(0,0,0,0);class Qy{axis;id;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=f.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=Pe(),this.record=new el(""),this.metaData=new en,this.timeSeries=new bh,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=/* @__PURE__ */new Map}get title(){return""}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&ie(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(f.Symbol)}get isExpression(){return this.is(f.Expression)}get isStudy(){return this.is(f.Study)}get isForward(){return this.is(f.Forward)}get isSeasonal(){return this.is(f.Seasonal)}getValueAt(e,t,i){return null}wrapIfAdvancedStyle(e){let t=e;const i=e=>({outFields:e,inputs:{},source:null});if(this.mainCurve.isHeikinAshiStyle)t=new dp(i($u.slice()),e);else if(this.mainCurve.isElderImpulseSystemStyle){const s=$u.slice().concat(Ka.BREL);t=new By(i(s),e)}else this.mainCurve.isPercentChangeStyle&&(t=new cm(i($u.slice()),e));return t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=f[e.type];const t=e;this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),ie(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{const t=new Id;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new Yy(p.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){ie(this.timeSeries)&&ie(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){const e=this.axis.pane.presenter,t=new ip(null,e.data.aggregation,m.Normal,[me(ce(e.data,null,"range","from")),me(ce(e.data,null,"range","to"))]);return t.barsToFetch=e.data.maxDataPoints||gs.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=ce(e.display,null,"xAxis","visibleRange"),t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return ie(this.detachedScale,this.yScale)&&this.detachedScale}getDetachedScaleMargins(){return gs.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;const{y:t,height:i}=e,{top:s,bottom:n}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+s*i),Math.floor(t+i-n*i)])}drawLevels(e){e.save();const t=gs.OUT_OF_SCREEN;for(const i of this.levels.filter(e=>e.visible)){const s=this.priceToY(i.value);nr(e,rr({line:i.line,fill:Ky})),Wn(e,{x:-1,y:s},{x:t,y:s})}e.restore()}drawBands(e){e.save();const t=gs.OUT_OF_SCREEN;for(const i of this.bands){const s=this.priceToY(i.range.to),n=this.priceToY(i.range.from);nr(e,rr({fill:i.fill,line:qy}));Fn(e,new xn(-1,s,t,n-s),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return this.hasEvents&&this.hasEventsData?this.eventsSeries.container.fields.filter(e=>e!==Ka.DateTime):[]}getEventsAt(e){const t=this.eventsSeries.container,i=i=>t.getData(i)[e];return this.getEventFields().map(t=>{const s=i(t);if(!ie(s))return null;const n=this.getEventFor(t);if(!ie(n))return null;const r={field:t,value:s,date:i(Ka.DateTime),text:n.title,color:n.color};if(t===Ka.Custom&&s===gs.FAKE_CUSTOM_EVENT){const t=e%2==0;return{...r,value:t?"___news":"___video",text:t?"N":"V"}}return r}).filter(e=>null!=e)}getRefEventField(e,t,i){return t?e.isOhlc?Ka.High:i.isTick?Ka.Last:Ka.Close:e.fields[0]}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){const i=this.axis.pane.presenter,s=i.view.xAxis.xScale,n=s.domain();if(!ie(n)||!ie(n[0],n[1]))return;const r=(e,t=Ka.DateTime)=>e.container.getData(t),o=r(this.eventsSeries),l=this.getRefPlot(i),c=l.timeSeries,u=r(c),h=i.data.aggregation,d=l===i.mainPlot,p=r(c,this.getRefEventField(l.mainCurve,d,h)),{chart:{fontFamily:f}}=this.axis.pane.presenter.display,m=o.map((e,r)=>{if(!(e=>e.valueOf()>=n[0].valueOf()&&e.valueOf()<=n[1].valueOf())(e))return[];return this.getEventsAt(r).map(e=>{const n=function(e,t){const{unit:i}=e;return i===a.Year?Mt(t):i===a.Quarter?bt(t):i===a.Month?Et(t):i===a.Week?it(t):i===a.Day?nt(t):t}(h,e.date),r=G(u,+n,Number),o=p[r];t.has(r)||t.set(r,-1);let l=t.get(r);t.set(r,++l);const c=s.timeToX(n),d=i.view.getEventRadius(),f=this.axis.yScale.priceToY(o)-l*(d+d+d);return{visible:!0,...e,x:c,y:f,r:d,rect:Jy}})}).flat();e.save();let g=!0;m.forEach(t=>{t.rect=function(e,{x:t,y:i,r:s,color:n,text:r},o){const a=s;e.fillStyle=n,e.beginPath();const l=s+s,c=l,u=new xn(t-s,i-a-c,l,c);e.fillRect(u.x,u.y,u.width,u.height);const h=(1.6*s).toFixed(0);return e.font=`700 ${h}px "${o}"`,e.fillStyle="#fff",e.textAlign="center",e.textBaseline="middle",e.beginPath(),e.fillText(r,t,i-.9*c),u}(e,t,f),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=m,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){const{x:t,y:i,r:s,date:n,value:r}=e;this.customEventPopup?.show({x:t+2*s,y:i-2*s},n,r)}getCustomEventDataAt(e){if(!this._eventsData)return null;const t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===Ka.Custom?t:null}hitTestCustomEvent(e){return null!==this.getCustomEventDataAt(e)}tryHandleCustomEventClick(e){const t=this.getCustomEventDataAt(e);return!!ie(t)&&(this.showCustomEventPopup(t),!0)}isEmpty(){const e=this.timeSeries;return ie(e)&&e.hasData&&e.container.isEmpty}draw(e){if(this.visible){ie(this.levels)&&this.drawLevels(e),ie(this.bands)&&this.drawBands(e);for(const t of this.curves)t.draw(e)}}drawTopmost(e,t){this.hasEventsData&&this.drawEvents(e,t)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,i,s){if(!ie(e)||!this.timeSeries.hasData)return e;if(!this.shouldPriceMap(i,s))return e;const[n,r]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!ie(n)||!ht(n))return e;if(this._firstVisibleDate!==n){this._firstVisibleDate=n;const e=this.timeSeries.container.getTimeData(),t=t=>G(e,+t,Number);this.visFromIndex=t(n),this.visToIndex=t(r),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(i)||this.canPriceMap(t,i),this.priceMap(e,t,i,!1,s)}isOhlcMapping(e){return this.mainCurve.isOhlc&&(t=e,Zy.has(t.id));var t}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===Ka.PreviousClose?Ka.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){const i=this.getRefPriceMapField(t),s=this.dataOf(i);let n=null,r=this.visFromIndex;for(;null===n&&r<=this.visToIndex;)n=s[r++];this._priceMapFirstIndex.set(i,null!==n?r-1:Number.NaN)}priceMap(e,t,i,s=!1,n=d.None){const r=this.getRefPriceMapField(i),o=this._priceMapFirstIndex.get(r);if(!Number.isFinite(o))return e;const a=this.dataOf(r)[o];if(this.isComparison(d.Percent)||n===d.Percent){return s?a+a*e/100:(e>=a?1:-1)*(100*Math.abs(e-a))/Math.abs(a)}return s?a+e:e-a}shouldPriceMap(e,t){return ie(t)?t!==d.None:this.isComparison(d.Percent)||this.isComparison(d.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}}class eA extends Qy{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!ie(this.timeSeries)||!ie(this.timeSeries.record))return null;const e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(Ka[e])}getTimeSeries(){const e=Gv().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.resolved,this.mainCurve.style){case o.Renko:case o.Kagi:case o.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case o.Range:t.barsToFetch=4e3;break;case o.LineBreak:t.inputs=this.inputs}const i=this.axis.pane;if(ie(i.alignedToYear)){const e=Ji(t.symbol);null!==e&&(this.yearOffset=i.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}const s=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(s),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){const e=Gv().getMetaDataSource();this.metaData=e.getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;const e=Gv().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:m.Events,getHashKey:function(){return Object.values(this).filter(e=>"function"!=typeof e).join("|")}};gs.EVENTS.forEach(e=>{t[e]=ce(this.events,!1,e,"show")}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(qa.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return!!ie(this.events)&&gs.EVENTS.some(e=>ce(this.events,!1,e,"show"))}findEvents(e){if(!this.hasEventsData||null===e[0]||null===e[1])return[];const t=e[0],i=e[1];if(i>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){const e=this.timeSeries.container.getTimeData()[i-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,i)=>this.compare(e,t)?this.getEventsAt(i):[]).flat()}fromModel(e){super.fromModel(e);const t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=function(e){switch(e.unit){case a.Tick:return ko;case a.Intraday:case a.Day:return Vo;case a.Week:return Ho;case a.Month:return Bo;case a.Quarter:return Fo;case a.Year:return Ii;default:return ko}}(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){const t=this.events[e.id.toLowerCase()];return ie(t)&&t.show?t:null}async initialize(){return ps.call(this,async()=>(this.resolved=await Hi(this.symbol),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}class tA extends eA{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${a[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=a[e.fundamental],super.fromModel(e)}makeQuery(){let e=new ip(this.symbol,new Wo(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}}class iA{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){const e=Gv().config.touchCrosshairDelayMillis;return ie(e)&&Number.isFinite(e)?e:gs.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,i){q()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,i),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,i){this.cancelLongPress(),this.performLongPress(e,t,i)}cancelLongPress(){q()&&ie(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,i){}}function sA(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}class nA extends iA{constructor(e,t,i){super(),this.annotation=e,this.previous=t,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,i)}cursorSet;moved;snapToSupported;performLongPress(e,t,i){qA(this.annotation,i)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),sA(this.annotation))return;const{point:t,view:i,offset:s}=e;if(!te(t)||t.axis!==this.annotation.axis)return;i.drawCrosshair({ap:t,offset:s}),this.cursorSet||(this.previous.axis.pane.presenter.view.setCursor(y.Move),this.cursorSet=!0);const n=fn(t.point,this.previous.point);this.annotation.offset(n),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=t,this.moved=!0}onMouseUp(e){this.cancelLongPress(),JS(this.annotation,this.moved,E.Moved)}}class rA{constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;onMouseMove(e){if(this.alignPointsMode=e.getModifier(S.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),sA(this.annotation))return;const{point:t,view:i,offset:s}=e;if(i.drawCrosshair({ap:t,offset:s}),ie(t)){const e=this.annotation.points[this.pointIndex],i=fn(t.point,e.point);switch(e.moveDirection){case T.Both:e.update(t.price,t.time);break;case T.Horizontal:e.update(e.price,t.time);break;case T.Vertical:e.update(t.price,e.time)}this.moved=e.moveDirection!==T.None,this.moved&&this.annotation.wasPointMovedByTool(e,i)}this.annotation.requestRedraw()}onMouseUp(e){JS(this.annotation,this.moved,E.PointMoved)}}class oA{constructor(e,t,i){this.anchor=e,this.isVertical=t,this.axis=i}hitTest(e){return!!ie(this.anchor)&&(this.isVertical?Math.abs(e.x-this.anchor.x)<=gs.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=gs.HIT_TEST_TOLERANCE)}draw(e){const t=gs.OUT_OF_SCREEN;this.isVertical?Un(e,this.anchor.x,-t,t):$n(e,this.anchor.y,-t,t)}}class aA{id;axis;_price;_time;passive=!1;moveDirection=T.Both;visible=!0;point;constructor(e,t,i){this.id=Pe(),this.axis=e,void 0!==t&&void 0!==i&&(this.price=t,this.time=i,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==T.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){const e=this.axis.toPoint(this);ie(e)&&ne(e.x)&&ne(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time="number"==typeof t?new Date(t):t,this.toPoint()}updateFromPoint(e){const t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){if(!this.visible)return!1;return this.distance(e)<=gs.HIT_TEST_TOLERANCE}distance(e){const t=e.x-this.point.x,i=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+i*i)-gs.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(ie(this.point)){let i=gs.HALF_ANN_POINT_DIMENSION;ie(t)&&t.locked&&(i*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,i,i,0,0,2*Math.PI),e.stroke()}}}function lA(e){return 0===bn(e.fill.color).a?e.line.color:e.fill.color}function cA(e,t){return{uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function uA(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}class hA{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=Pe()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){return this.drawPoints(e,t),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>void 0!==e.point)}getPriceScaleAdornments(){return gs.EMPTY_ARRAY}getTimeScaleAdornments(){return gs.EMPTY_ARRAY}extractTraits(e=!0){const t=ue(this.traits),i=_r(this.name);return Object.keys(t).forEach(s=>{const n=i.includes(s);(e&&!n||!e&&n)&&delete t[s]}),e||["line","fill","zIndex"].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:se(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(mn(t.point,e))})}get traits(){return this._traits||(this._traits=ue(this.defaultTraits)),this.adjustFill&&(this._traits.fill.color=lA(this._traits),this.adjustFill=!1),this._traits}set traits(e){void 0!==e&&ye(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return rr(this.traits)}get defaultTraits(){return sr(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return rr(this.defaultTraits)}get adornStyle(){const e=ue(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=gs.COLOR_TRANSPARENT,rr(e)}get pointsStyle(){const e=ue(this.defaultTraits);return e.line.dashStyle="Solid",rr(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}isPointDrawn(e){return void 0!==e.price}drawPoints(e,t){this.points.forEach(i=>{const s=this.isPointDrawn(i),n=ie(e);!t||!s&&n||i.toPoint(),n&&s&&(this.isSelected||this.drawn)&&(nr(e,this.pointsStyle),i.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new aA(this.axis))}toModel(){const e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:ue(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){const t=this.activePoints;t.length===e.length&&t.forEach((t,i)=>{const s=e[i];t.update(s.price,s.time)})}updateFrom(e,t,i,s,n){"boolean"==typeof s&&(this.visible=s),"boolean"==typeof n&&(this.locked=n);const r=ie(e)?ue(e):{};ie(t)&&ye(r,t),this.traits=r,ie(i)&&this.updatePoints(i)}priceMap(e){return this.axis.priceMap(e)}flip(e){const t=this.getFlipAnchorIndices();if(!te(t))return;const i=this.points[t[0]],s=this.points[t[1]];if(e){const e=s.time;s.update(s.price,i.time),i.update(i.price,e)}else{const e=s.price;s.update(i.price,s.time),i.update(e,i.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}}function dA(e,t,i,s){return function(n,r=!0){const o=new t(n,e,i);return r?n.appendAnnotation(o):o.drawn=!1,ie(s)&&(o.traits=s),o}}class pA{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,i,s,n){this.axis=n,ie(e,t)&&(this.angle=gn(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=i?this.extendPoint(t,-1):e,this.p2=s?this.extendPoint(e,1):t),this.extended=i||s}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){const i=Math.max(Math.abs(e.x),Math.abs(t.x)),s=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(i*i+s*s)+gs.OUT_OF_SCREEN}hitTest(e){return!!ie(this.p1,this.p2)&&yn([this.p1,this.p2],e,gs.HIT_TEST_TOLERANCE)}draw(e){ie(this.p1,this.p2)&&(Wn(e,this.p1,this.p2),this.extended)}getAdornOffset(e){const t=Vn(e),i=Rn(e,1);var s,n;return(s=this.p1,n=this.p2,-(s.y-n.y)/(s.x-n.x))<0&&(t.y=i+5),t}}class fA{style;axis;rect;constructor(e,t,i,s){this.axis=s,this.rect=new xn(e.x,e.y,t,i)}hitTest(e){return this.rect.contains(e)}draw(e,t){Fn(e,this.rect)}}class mA extends hA{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.prepareDraw(e,t)&&!this.drawn){const t=this.getElements();nr(e,this.style),t.forEach((t,i)=>{nr(e,this.getStyleForElement(t,i)),t.draw(e)}),nr(e,this.adornStyle),this.adornElements(t,e);const i=this.getMarkers();nr(e,this.style),i.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(void 0===this.countCache||this.countCache.time1!==e||this.countCache.time2!==t){const i=this.axis.pane.presenter.view,s=Math.abs(i.toIndex(e)-i.toIndex(t));this.countCache={time1:e,time2:t,barCount:s}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.visible){const t=this.getElements(),i=this.getMarkers();if(t.some(t=>t.hitTest(e)))return!0;return!!i.some(t=>t.hitTest(e))||this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,i)=>this.points[t+i].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return ae(this.traits?.singleStyle,!0)}get showBackground(){return ae(this.traits?.showBackground,!1)}get backgroundOpacity(){return ae(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return rr({line:{color:gs.COLOR_TRANSPARENT,dashStyle:"Solid",width:0},fill:this.traits[e]})}lineOnlyStyle(e){return rr({fill:{color:gs.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new pA(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Tn(Sn(e),this.backgroundOpacity)}getTraitsFor(e){const t={fill:{color:gs.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground?(t.fill.color=this.applyBackgroundOpacity(t.line.color),t):t}getFlipAnchorIndices(){return 2===this.points.length?[0,1]:null}}class gA extends mA{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return gs.AT_FACTORS}get factors(){return Jn(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[gs.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[gs.AT_LEVELS_KIND]}get labels(){return this.traits[gs.AT_LABELS]}get isExtended(){return 3===this.points.length}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,i){let s=this.isBefore(e,t);return i||(s=!s),this.points[s?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[gs.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){const i=this.levelsKind===gs.AT_LEVELS_PERCENTS;let s="";if(this.showLevels&&(s=i?`${(100*e).toFixed(1)}%`:e.toString()),this.showPrices){const e=this.priceMap(this.axis.toPrice(t));s=(s+` (${nd(this.axis,e)})`).trim()}return s}getAdornPointAndAlign(e,t){const i=this.labels,s=e instanceof pA,n=(e,t,i)=>({pt:e,align:t,offset:i});switch(i){case gs.AT_LABELS_LEFT:return n(s?e.anchor1:e,g.Right,-t);default:case gs.AT_LABELS_RIGHT:return n(s?e.anchor2:e,g.Left,t);case gs.AT_LABELS_CENTER:return n(s?dn(e.anchor1,e.anchor2):e,g.Center,0)}}getColoredElements(e){const t=this.singleStyle;return this.factors.map(i=>{const s=e(i);return null===s?null:(t||(s.style=rr(this.getTraitsFor(i))),s._data={factor:i.value},s)}).filter(e=>null!==e)}hitTestAdornments(e,t){const i=this.showLevels,s=this.getTextRef();if(!i||null===s)return!1;const n=this.axis.pane.presenter,r=n.view?.mainContext;if(!r)return!1;let o=null,a=!1;r.save();const{chart:{fontFamily:l},yAxis:{fontSize:c}}=n.display;r.font=`${c??12}px ${l}`;for(const u of e){if(!ie(u._data))continue;const{factor:e}=u._data,{ref:i,spacing:n,offsetY:l,text:c}=s(o,u,e),{pt:h,align:d,offset:p}=this.getAdornPointAndAlign(i,n);if(Hn(r,c,this.getAdornTextPoint(r,l,h,p),d).contains(t)){a=!0;break}o=u}return r.restore(),a}adornElementsForColoredFactors(e,t,i,s){const n=this.singleStyle,r=this.showBackground,o=this.showLevels,a=this.applyBackgroundOpacity(this.traits.line.color),l=s.fillStyle;let c=null;e.forEach(e=>{if(!ie(e._data))return;const{factor:u}=e._data;if(r){const i=t(c,e);s.fillStyle=n?a:e.style.fillStyle,s.fill(i)}if(o){const{ref:t,spacing:r,offsetY:o,text:a}=i(c,e,u),{pt:h,align:d,offset:p}=this.getAdornPointAndAlign(t,r),f=this.getAdornTextPoint(s,o,h,p),m=n?l:e.style.strokeStyle;Bn(s,a,f,d,m)}c=e})}getAdornTextPoint(e,t,i,s){const n=Rn(e,.75);return mn(i,{x:s,y:!0===t?n/2:t})}}class yA extends mA{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get rect(){const[e,t,,]=this.getScreenPoints(),i={x:e.x,y:Math.min(e.y,t.y)},s=new fA(i,t.x-e.x,Math.abs(e.y-t.y),this.axis);return s.style=this.rectStyle,s}get reverse(){return!1}getLinesDataAtLevels(e,t){let[i,s]=this.points;if(this.reverse&&([i,s]=[s,i]),null==this.lines){const n=(e,t=!1)=>i=>({level:i.value,domain:e(i.value),traits:this.getTraitsFor(i),isPrice:t}),r=s.price-i.price,o=n(e=>i.price+e*r,!0),a=e?.map(o)??[],l=this.axis.pane.presenter.timeline,c=G(l,+i.time,Number,ud),u=G(l,+s.time,Number,ud)-c,h=n(e=>+l.at(c+Math.floor(e*u))),d=t?.map(h)||[];this.lines={prices:a,times:d,barsDiff:u,priceDiff:r}}return this.lines}makeColoredLine(e,t,i){const s=this.makeLine(e,t);return this.singleStyle||(s.style=rr(i.traits)),s._data={level:i.level,isPrice:i.isPrice},s}getLineElements(e){const[t,i]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{const s=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:s},{x:i.x,y:s},e)}),timeLines:e.times.map(e=>{const s=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:s,y:t.y},{x:s,y:i.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}}class AA extends aA{constructor(e,t,i){super(e),this.priceRef=t,this.timeRef=i,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}}class SA{constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return ie(this.points[0].point,this.points[1].point)?new xn(this.left,this.top,this.width,this.height):null}}function TA(e){const t=new aA(e),i=new aA(e);return[t,i,new AA(e,t,i),new AA(e,i,t)]}class vA extends hA{helper;constructor(e,t){super(e,t),this.points=TA(e),this.helper=new SA(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return!!this.prepareDraw(e,t)&&(nr(e,this.style),!0)}updatePoints(e){this.allowPricesChangeUI&&2===e.length&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}}class PA{constructor(e,t,i){this.points=e,this.lines=t,this.axis=i,this.helper=new SA(this.points)}helper;_actualWidth=0;_fontSizeForWidth=0;hitTest(e){const t=this.getRect();return!!te(t)&&(t.width=this._actualWidth,t.contains(e))}getRect(){return this.helper.getRect()}get fontSize(){if(0===this.lines.length)return 0;const{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(0===this.lines.length)return;e.save();const{x:t,y:i}=this.getRect(),{chart:{fontFamily:s}}=this.axis.pane.presenter.display,n=this.fontSize;e.textAlign="left",e.textBaseline="top",e.font=`${n}px ${s}`,this.lines.forEach((s,r)=>{const o=i+n*r;e.fillText(s,t,o)}),this.computeActualWidth(e),e.restore()}}class CA extends mA{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=TA(e),this.adjustFill=!0}get textLines(){return this.traits[gs.AT_TEXT_LINES]}set textLines(e){this.traits[gs.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!ie(this._textAnnElement)&&this.visible&&(this._textAnnElement=new PA(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,i,s,n){super.updateFrom(e,t,i,s,n),this._textAnnElement=void 0}getElements(){return this.visible?[this.textElement]:[]}}class bA extends CA{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return!!this.visible&&this.textElement.hitTest(e)}get prices(){return this.traits.prices}get pricesPoints(){const e=this.points[0].time;return this.prices.map(t=>new aA(this.axis,t,e))}updateFrom(e,t,i,s,n){super.updateFrom(e,t,i,s,n),ie(e?.textLines)&&(this.textLines=e.textLines)}getElements(){const e=super.getElements(),t=this.pricesPoints.map(e=>new oA(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();const e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){const{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){const[t,i]=this.defaultFont;e.save(),e.font=`${t}px ${i}`;const s=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:n,y:r}=this.points[0].point;this.points[1].updateFromPoint({x:n+s,y:r+this.textLines.length*t}),e.restore()}}class EA{constructor(e){this.annId=e}annotation;onKeyDown(e){if(null==this.annId)return;const{key:t,code:i,presenter:s}=e;if(X(t,i)){if(ie(this.annotation)){this.annotation.axis.deleteAnnotation(this.annotation,!1),s.view.redraw()}ZS(s,{toolChange:E.Cancelled,annId:this.annId})}}}class LA extends EA{constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}onMouseDown(e){const{point:t,button:i}=e;if(void 0===t)return;const s=te(this.annotation);if(i===A.Left)if(s){const e=!this.thirdPoint||this.dragged?1:2;this.annotation.points[e].update(t.price,t.time),this.dragged=!1,this.signalChange(),this.thirdPoint&&2!==e||this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange();return!0}onMouseMove(e){const{point:t,view:i,offset:s}=e;return i.drawCrosshair({ap:t,offset:s}),ie(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(S.Shift),this.dragged?(this.annotation.points[1].update(t.price,t.time),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.annotation.points[2].update(t.price,t.time),this.signalChange())),!0}finish(){JS(this.annotation,!0,E.Created)}isAccidentalMouseUp(e){const{point:t}=e,i=this.annotation.points[0].point;return pn(t.point,i)<gs.HIT_TEST_TOLERANCE}onMouseUp(e){void 0!==this.annotation?this.isAccidentalMouseUp(e)?this.dragged=!0:(this.dragged=!1,this.thirdPoint||this.finish()):eT(e)}}class MA extends LA{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}}class _A extends LA{constructor(e){super(e,!1),this.snapToSupported=!1}onMouseMove(e){const{point:t,view:i,offset:s}=e;if(i.drawCrosshair({ap:t,offset:s}),ie(this.annotation)&&this.dragged){const[e,i]=this.annotation.points;i.update(t.price,t.time);const s=fn(i.point,e.point),n=e.point.y+s.x*Math.sign(s.y)*Math.sign(s.x),r=this.annotation.axis.toPrice(n);i.update(r,t.time),this.signalChange()}return!0}}class xA extends EA{constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!ie(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew){return{height:100,fontSize:"100%",color:lA(sr(this.anchor.axis.pane.presenter.display,"Text"))}}{const e=this.existing.textElement;return{height:1.05*e.getRect().height,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[gs.AT_FILL].color}}}onMouseDown(e){const{point:t}=e;if(this.isNew)if(0===this.clicks){if(void 0===t)return void eT(e);t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing();else this.onEndEditing()}startEditing(){this.textArea=document.createElement("textarea");const{x:e,y:t}=this.anchor.point,i=this.anchor.axis.pane.getBounds(),s=i.x+i.width-this.anchor.point.x,{height:n,fontSize:r,color:o}=this.styleProps();os(this.textArea,{position:"absolute",top:`${t}px`,left:`${e}px`,border:"none",outline:"none",overflow:"hidden",height:`${n}px`,width:`${s}px`,resize:"none",backgroundColor:"rgba(255, 255, 255, 0.05)",zIndex:"5",fontSize:r,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join("\n"),this.existing.textLines=[""],this.existing.requestRedraw()),setTimeout(()=>this.textArea.focus(),100)}onEndEditing(){const e=this.anchor,t=this.isNew?this.factory(e.axis):this.existing,i=this.textArea.value.split("\n");if(this.isNew){const{actualWidth:s,actualHeight:n}=this.getTextDimensions(i);t.points[0].update(e.price,e.time);const{x:r,y:o}=t.points[0].point;t.points[1].updateFromPoint({x:r+s,y:o+n}),t.drawn=!1}t.textLines=i,this.textArea.onblur=null,this.getChartParent().removeChild(this.textArea),t.requestRedraw(),this.isNew||t.requestRedraw(),JS(t,!0,this.isNew?E.Created:E.TextChanged)}getTextDimensions(e){const t=globalThis.getComputedStyle(this.textArea).getPropertyValue("font-size"),i=parseFloat(t)*e.length;let s=0;const n=this.anchor.axis.pane.presenter,r=n.view.mainContext;r.save();const{chart:{fontFamily:o}}=n.display;r.font=`${t} ${o}`;for(let a=0;a<e.length;a++){const t=r.measureText(e[a]).width;t>s&&(s=t)}return r.restore(),{actualWidth:s,actualHeight:i}}}function IA(e){return Gv().config.tooltipMovement===e}function DA(){return IA("Draggable")}function OA(){return IA("Auto")}const wA=gs.TOOLTIP_STD_LEGACY_CLASS,RA=gs.TOOLTIP_STD_CLASS,NA=gs.TOOLTIP_BUBBLE_CLASS;class VA{constructor(e){this.view=e,this.tooltipElem=us(e.el,"div"),as(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${RA} ${wA}`}),this.leftSide=!0,os(this.tooltipElem,{visibility:"hidden",position:"absolute",cursor:DA()?"move":"default",zIndex:20,top:`${gs.TOOLTIP_Y_OFFSET}px`,left:`${gs.TOOLTIP_X_OFFSET}px`}),this.setMode(e.presenter.display.tooltip.mode),this.handleMouseMove=this.handleMouseMove.bind(this),this.startDrag=this.startDrag.bind(this),this.stopDrag=this.stopDrag.bind(this),this.view.el.addEventListener("mousemove",this.handleMouseMove),this.view.el.addEventListener("mouseleave",this.stopDrag),this.tooltipElem.addEventListener("mousedown",this.startDrag),this.tooltipElem.addEventListener("mouseup",this.stopDrag)}tooltipElem;leftSide;mode;isDrag=!1;canDrag;isToggling;startDrag(){this.isDrag=!0}stopDrag(){this.isDrag=!1}setMode(e){if(this.mode!==e)if(this.mode=e,e===gs.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition="none",this.tooltipElem.classList.remove(RA,wA),this.tooltipElem.classList.add(NA),os(this.tooltipElem,{pointerEvents:"none"});else if(e===gs.TOOLTIP_STD){this.canDrag=DA(),this.tooltipElem.classList.remove(NA),this.tooltipElem.classList.add(RA,wA);const e=gs.TOOLTIP_TOGGLE_SIDE_ANIM_MS;os(this.tooltipElem,{pointerEvents:"all",top:`${gs.TOOLTIP_Y_OFFSET}px`,left:`${gs.TOOLTIP_X_OFFSET}px`,transition:OA()?`left ${e}ms ease-out`:null})}}show(e,t){const i=this.tooltipElem;if(t){const{width:e,height:s,leftOffset:n,rightOffset:r}=this.view,o=i.getBoundingClientRect(),a=o.width/2,l=i.style,c=s*gs.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-c,h=t.x-a,d=t.yMax+c,p=d+o.height,f=u<0?p<s?d:0:u;let m=h;const g=e-r;m<n?m=n:m+o.width>g&&(m=g-o.width),l.top=`${f}px`,l.left=`${m}px`}"hidden"===i.style.visibility&&(i.style.visibility="visible"),ds(i,e)}hide(){this.tooltipElem.style.visibility="hidden"}remove(){this.view.el.removeEventListener("mousemove",this.handleMouseMove),this.view.el.removeEventListener("mouseleave",this.stopDrag),this.tooltipElem.removeEventListener("mousedown",this.startDrag),this.tooltipElem.removeEventListener("mouseup",this.stopDrag),ns(this.tooltipElem)}reposition(e,t){os(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===gs.TOOLTIP_STD&&OA()}handleMouseMove(e){if(this.isDrag&&this.canDrag){const{movementX:t,movementY:i}=e,{top:s,left:n}=this.tooltipElem.style,r=parseInt(s)+i,o=parseInt(n)+t;this.reposition(o,r)}else if(this.isAutoMove()){const t=this.tooltipElem.getBoundingClientRect(),i=this.view.el.getBoundingClientRect(),s=e.pageX,n=gs.TOOLTIP_TOGGLE_DISTANCE_TOLERANCE,r=i.width>2*t.width,o=s>t.x&&s<=t.right+n,a=s<t.x&&s>=t.x-n;r&&(o||a)&&this.toggleSide()}}repositionAuto(){if(this.isAutoMove()){const e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=this.tooltipElem.offsetY,i=e.x+(this.leftSide?gs.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-gs.TOOLTIP_X_OFFSET);this.reposition(i,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,gs.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}}function HA(e){e.showTooltip&&BA(e,{time:gs.ZERO_DATE,offset:gs.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function BA(e,{time:t,lastBarRefresh:i,justMain:s,offset:n,price:r}){const o=bd(e,t,n,0,s,r),{mode:a,showMainPlot:l,hideSymbols:c,revealingClose:u}=e.display.tooltip,{includeTimestamp:h,showMainPlot:d,showPlotActions:p}=Gv().config.tooltipHeaders||{},f=ie(d)?d:l,m=!!ie(h)&&h,g=!!ie(c)&&c,y=!!ie(u)&&u,A=!!ie(p)&&p,S=t.valueOf()===gs.ZERO_DATE.valueOf();switch(a){case gs.TOOLTIP_CARDS:kA(e,o,f,!S,m&&!S,!1,g,y,A,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case gs.TOOLTIP_BUBBLE:if(!S){const t=o.panes.find(e=>{const{top:t,left:i,width:s,height:r}=e.bounds;return new xn(i,t,s,r).contains(n)}),i=t.plots.find(e=>e.isMain)||t.plots[0],s=i.values.find(e=>["Close","Last"].includes(e.id)),r=s?s.y:i.values[0].y,a=t.plots.map(e=>e.values.filter(e=>"Change"!==e.id&&e.y>0).map(e=>e.y)).flat(),l=`<div class="bubble-box">${md({...o,hideSymbols:g,revealingClose:y,plots:t.plots})}</div>`;e.view.tooltip.show(l,{x:n.x,y:r,yMin:Math.min(...a),yMax:Math.max(...a)})}kA(e,o,f,!1,!1,e.hasLegend,g,y,A);break;case gs.TOOLTIP_STD:if(!S){const t=md({...o,hideSymbols:g,revealingClose:y,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}kA(e,o,f,!1,!1,e.hasLegend,g,y,A);break;case gs.TOOLTIP_EXTERNAL:e.notifyHost(qa.CH_TOOLTIPCHANGED,o);break;default:console.warn(`Unknown tooltip mode requested: ${a}`)}}function FA(e,t,i,s,n,r){os(e,{position:"absolute",display:"flex","flex-direction":t,"flex-wrap":"wrap",left:`${i+gs.CARDS_X_OFFSET}px`,top:`${n+gs.CARDS_Y_OFFSET}px`,maxWidth:r-s-2*gs.CARDS_X_OFFSET+"px"})}function kA(e,t,i=!1,s=!1,n=!1,r=!1,o=!1,a=!1,l=!1,c=0){const u=e.view.el,h=gd(e,t,i,s,n,o,a,l);h.some(e=>!ie(e.bounds))||h.forEach(({id:t,isMainPane:i,content:s,moveContent:n,bounds:{left:o,right:a,top:l,width:h}},d)=>{if(!(""===s||r&&i)){const n=ls(t,u,"div");FA(n,i&&pd(e)?"column":"row",o,a,l+c,h),cs(n,{"bcharts-card":!0,"bcharts-card-main":i,"bcharts-card-first":0===d}),n.innerHTML=s}let p=rs(`#right-${t}`,u);ie(p)||(p=document.createElement("div"),p.id=`right-${t}`,u.appendChild(p),cs(p,"bcharts-card bcharts-card-move")),os(p,{position:"absolute",display:"block",right:`${a+gs.CARDS_X_OFFSET}px`,top:`${l+c+gs.CARDS_Y_OFFSET}px`}),p.innerHTML=n})}let WA=null;function UA(){return null===WA&&(WA=Gv().config.hostingModel===b[b.Application]),WA}class $A extends iA{constructor(e){super(),this.ap=e,this.presenter=e.presenter,this.panY=e.axis.isCustomDomain}presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;activated(){}deactivated(){this.cancelLongPress()}startPan(e){this.startLongPress(this.presenter,this.ap,e),this.lastOffset=e,this.lastPanningExtremes=this.ap.axis.yScale.domain();const t=this.ap.presenter;t.enableTooltip(!1),t.view.tooltip.hide(),t.view.drawCrosshair({ap:void 0})}onMouseMove(e){if(e.pinchZoom)return void this.presenter.resetActiveTool();const{point:t,view:i,offset:s}=e;if(t&&t.axis!==this.ap.axis)return;const{x:n,y:r}=s,o=n-this.lastOffset.x,a=Math.abs(o),l=this.lastOffset.y,c=r-l,u=Math.abs(c);a>=1&&this.cancelLongPress();const h=UA();if(q()&&!h&&this.warmUp)return(a>7||u>7)&&(this.warmUp=!1,this.preventDefault=a>u),!1;if(this.preventDefault||!q()||h){if(i.xAxis.pan(o),this.panY&&t&&t.axis){u>=1&&this.cancelLongPress();const e=function(e,t,i,s){const n=i-t,r=n/e.viewBox.height,[o,a]=s,l=r*(a-o);return[o+l,a+l]}(t.axis,l,r,this.lastPanningExtremes);this.lastPanningExtremes=e,t.axis.yScale.domain(e)}this.lastOffset=s,i.redraw(),t&&t.presenter.view.setCursor(y.Grabbing)}return h||this.preventDefault}finished(){ZS(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:i}){q()&&XA(e,t,i)}performLongPress(e,t,i){e.enableTooltip(!0),e.resetActiveTool(),e.activeTool.startTouchCrosshairMode(e,t,i)}}let GA=null;class zA extends vA{constructor(e,t){super(e,t)}hitTest(e){if(!this.visible)return!1;const t=this.getRect();return null!==t&&t.contains(e)}draw(e,t){return!!super.draw(e,t)&&(Fn(e,this.getRect()),!0)}}function YA(e,t){return e<t?[e,t]:[t,e]}const jA={line:{width:1,color:"rgba(127, 127, 127, 0.3)",dashStyle:"LongDash"},fill:{color:"rgba(127, 127, 127, 0.1)"}};class KA extends LA{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(dA("Rectangle",zA,null,jA),!1)}activated(){}deactivated(){ie(this.axis,this.annotation)&&this.axis.deleteAnnotation(this.annotation,!1)}onMouseDown(e){const t=super.onMouseDown(e);if(!0===t){const{point:t}=e;this.axis=t.axis,this.presenter=t.presenter}return t}finish(){if(ie(this.axis,this.presenter)){ZS(this.presenter,{toolChange:E.Executed,annId:"ZoomIn"});const e=this.annotation.points,t=YA(e[0].price,e[1].price),i=YA(e[0].time,e[1].time),s=(e,t)=>Math.abs(t(e[0])-t(e[1])),n=s(i,e=>this.axis.toX(e)),r=s(t,e=>this.axis.toY(e)),o=this.presenter.view,a=gs.MINIMUM_ZOOM_DIMENSION;if(n>a&&r>a){const e=o.xAxis.xScale;this.axis.isCustomDomain=!0,this.axis.yScale.domain(t),e.wasZoomed=!0,e.scaleBarToFitRange(i,!1),e.domain(i)}o.redraw()}}}function qA(e,t){const i=uA(e);i.offset={x:t.x,y:t.y},i.canFlip=null!==e.getFlipAnchorIndices();const s=e.axis.pane.presenter;s.clearSelection(),s.notifyHost(qa.CH_ANNNEEDSCONTEXTMENU,i)}function XA(e,t,i){const s={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:i};e.notifyHost(qa.CH_CHTNEEDSCONTEXTMENU,s)}class ZA extends EA{constructor(e,t){super(e.annName),this.factory=e,this.maxClicks=t}clicks=0;snapToSupported=!0;isDrawingAnnotation=!0;onMouseMove(e){const{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){const{point:t,view:i}=e;if(0===this.clicks){if(void 0===t)return eT(e),!1;t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis)}this.applyToPoints(t),this.clicks++,this.clicks===this.maxClicks&&void 0!==this.annotation?(this.annotation.drawn=!1,this.annotation.requestRedraw(),"function"==typeof this.annotation.updateOtherPoints&&this.annotation.updateOtherPoints(i.mainContext),JS(this.annotation,!0,E.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}}class JA{snapToSupported=!1;constructor(e,t){setTimeout(()=>this.finalize(e,t),10)}finalize(e,t){const i=e(t);t.pane.presenter.clearSelection(),i.drawn=!1,i.requestRedraw(),JS(i,!0,E.None)}}const QA=gs.MARKER_ARROW_ANGLE*Math.PI/180/2;function eS(e,t,i=gs.MARKER_ARROW_LENGTH){return new tS(e,t,i)}class tS{constructor(e,t,i=gs.MARKER_ARROW_LENGTH){this.vertex=t,this.arrowLen=i,this.p1=e[0],this.p2=e[1]}p1;p2;hitTest(e){const{anchor:t,p1:i,p2:s}=this.getArrowPoints();return yn([t,i],e,gs.HIT_TEST_TOLERANCE)||yn([t,s],e,gs.HIT_TEST_TOLERANCE)}draw(e){const{anchor:t,p1:i,p2:s}=this.getArrowPoints();Wn(e,t,i),Wn(e,t,s)}getArrowPoints(){const e=gn(this.p1,this.p2),t="start"===this.vertex?0:Math.PI,i=e-QA+t,s=e+QA+t,n="start"===this.vertex?this.p1:this.p2;return{anchor:n,p1:{x:this.arrowLen*Math.cos(i)+n.x,y:this.arrowLen*Math.sin(i)+n.y},p2:{x:this.arrowLen*Math.cos(s)+n.x,y:this.arrowLen*Math.sin(s)+n.y}}}}class iS{hitTest(){return!1}draw(){}}class sS extends mA{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[gs.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[gs.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[gs.AT_RATIO]}getElements(){const e=this.points[0].point,t=this.points[1].point,i=new pA(e,t,this.extend1,this.extend2,this.axis),s=[];return this.extend1&&s.push(new pA(i.p1,e,!0,!1,this.axis)),s.push(new pA(e,t,!1,!1,this.axis)),this.extend2&&s.push(new pA(t,i.p2,!1,!0,this.axis)),s}formatRatio(e,t){return` (${se(e/t,3)})`}formatPercDiff(e,t){const i=(t-e)/e*100;return` (${i>0?"+":""}${se(i,2)}%)`}formatPrice(e){return nd(this.axis,this.priceMap(e))}adornElements(e,t){if(!(this.showBarCount||this.showPrices||this.showPercentDiff||this.showRatio))return;const[i,s]=this.points,n=e[this.extend1?1:0].getAdornOffset(t);if(this.showBarCount){const e=mn(dn(i.point,s.point),n);Bn(t,this.getBarCount(i.time,s.time).toFixed(0),e,g.Right)}const r=this.showRatio?this.formatRatio(i.price,s.price):"",o=`${this.showPrices?this.formatPrice(i.price):""}${r}`.trim();""!==o&&Bn(t,o,mn(i.point,n),g.Right);const a=this.showPercentDiff?this.formatPercDiff(i.price,s.price):"",l=`${this.showPrices?this.formatPrice(s.price):""}${a}`.trim();""!==l&&Bn(t,l,mn(s.point,n),g.Right)}getMarkers(){const e=this.marker;if(!e||"none"===e.vertex)return[];const{vertex:t,kind:i}=e;return("both"===t?["start","end"]:[t]).map(e=>"arrow"===i?function(e,t){return eS(e.map(e=>e.point),t)}(this.points,e):(console.warn(`There is no marker of ${i} kind`),new iS))}}class nS extends mA{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[gs.AT_SHOW_TIMESTAMPS]}getElements(){return[new oA(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}}class rS extends mA{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new oA(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}}class oS extends mA{constructor(e,t,i){super(e,t),this.addPoints(2),ie(i)&&ie(i.points)&&i.points.forEach((e,t)=>this.points[t].update(e.price,e.time))}allPoints(){const[e,t]=this.points;return ie(e,e.point,t,t.point)?[e,this.axis.toAnnotationPoint(dn(e.point,t.point)),t]:gs.EMPTY_ARRAY}line2(){return this.traits[gs.AT_LINE_2]}use52WeekPrices(){return this.traits[gs.AT_USE_52WEEK_PRICES]}getElements(){const e=this.allPoints();return e===gs.EMPTY_ARRAY?gs.EMPTY_ARRAY:e.map(e=>new pA({x:-8192,y:e.point.y},{x:gs.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){ie(this.use52WeekPrices())&&(this.traits[gs.AT_USE_52WEEK_PRICES]=!1)}getStyleForElement(e,t){const i=this.line2();if(1!==t||!ie(i))return super.getStyleForElement(e,t);const s=ue(this.traits);return s.line=i,rr(s)}getPriceScaleAdornments(){const e=this.allPoints();if(!this.showPrices||e===gs.EMPTY_ARRAY)return super.getPriceScaleAdornments();const t=this.traits.line,i=e.map(e=>({price:e.price,color:t.color})),s=this.line2();return ie(s)&&(i[1].color=s.color),i}getFlipAnchorIndices(){return null}}class aS extends gA{helper;constructor(e,t,i){super(e,t),this.addPoints(i),this.helper=new aA(e)}get showTrendLine(){return this.traits[gs.AT_SHOW_TRENDLINE]}get hasAllPoints(){return ie(...this.points.map(e=>e.point))}get line2(){return this.traits[gs.AT_LINE_2]}get extendLeft(){return this.traits[gs.AT_EXTEND_LEFT]}get extendRight(){return this.traits[gs.AT_EXTEND_RIGHT]}get reverse(){return this.traits[gs.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[gs.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){const e=ue(this.traits);return e.line=this.line2,rr(e)}return super.getStyleForElement(e,t)}getKeyPoints(){const e=e=>e.map(e=>this.points[e]);return this.isExtended?e(this.reverse?[1,0,2]:[0,1,2]):e(this.reverse?[0,1,0]:[1,0,1])}getElements(){if(!this.hasAllPoints)return[];const[e,t,i]=this.getKeyPoints(),s=t.price-e.price,n=t.price/e.price,r=this.extendLeft,o=this.extendRight,a=this.leftPoint,l=this.rightPoint,c=(e,t,i=!1)=>{const s=new pA(e,t,!i&&r,!i&&o,this.axis);return s.isTrend=i,s},u=this.levelsRespectLogScale&&this.axis.scale===p.Logarithmic,h=this.getColoredElements(({value:e})=>{const t=i.price+s*e,r=i.price*Math.pow(n,e),o=u?r:t;this.helper.update(o,i.time);const h=this.helper.point.y;return c({x:a.x,y:h},{x:l.x,y:h})});return this.showTrendLine&&(h.push(c(e.point,t.point,!0)),this.isExtended&&h.push(c((this.reverse?e:t).point,i.point,!0))),h}getAdornPointAndAlign(e,t){const i=this.labels,s=(e,t,i)=>({pt:e,align:t,offset:i}),n=this.axis.pane.getBoundsWithoutScales();switch(i){case gs.AT_LABELS_LEFT:return this.extendLeft?s({x:n.x,y:e.anchor1.y},g.Left,t):super.getAdornPointAndAlign(e,t);default:case gs.AT_LABELS_RIGHT:return this.extendRight?s({x:n.x+n.width,y:e.anchor2.y},g.Right,-t):super.getAdornPointAndAlign(e,t);case gs.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,i)=>({ref:t,spacing:5,offsetY:-5,text:this.formatLevelPrice(i,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),i.lineTo(t.p2.x,e.p1.y),On(i,t.p2),i.lineTo(e.p1.x,t.p2.y)),i},this.getTextRef(),t)}getPriceScaleAdornments(){if(!this.pricesOnScale)return super.getPriceScaleAdornments();const e=this.getElements();if(0===e.length)return super.getPriceScaleAdornments();const t=this.traits.line.color;return this.factors.map((i,s)=>{const n=e[s++].p1,r=this.singleStyle?t:i.line.color;return{price:this.axis.toPrice(n.y),color:r}})}}class lS extends aS{constructor(e,t){super(e,t,2)}}class cS extends aS{constructor(e,t){super(e,t,3)}}const uS=(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),On(i,e.p2),On(i,t.p2)),i};class hS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[gs.AT_REVERSE]}getElements(){const[e,t]=this.getScreenPoints(),i=t.y-e.y;return this.getColoredElements(({value:s})=>{const n=this.reverse?e.y+s*i:t.y-s*i;return new pA(e,{x:t.x,y:n},!1,!0,this.axis)})}getTextRef(){const[e,t]=this.getScreenPoints(),i=t.y-e.y,[s,n]=[this.leftPoint,this.rightPoint];return(r,o,a)=>{const l=this.reverse?e.y+a*i:t.y-a*i;return{ref:new pA({x:s.x,y:l},{x:n.x,y:l},!1,!1,this.axis),spacing:5,offsetY:!0,text:a.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,uS,this.getTextRef(),t)}}class dS extends hS{constructor(e,t){super(e,t)}}class pS{constructor(e,t,i,s,n,r,o){this.center=e,this.rim=t,this.radius=i,this.startAngle=s,this.endAngle=n,this.antiClockwise=r,this.axis=o,null!==t&&(this.left={x:this.center.x-this.radius,y:this.center.y},this.right={x:this.center.x+this.radius,y:this.center.y})}left=null;right=null;scale=null;clip=null;style;get hasScale(){return null!==this.scale}get hasClip(){return null!==this.clip}get hasRim(){return null!==this.rim}applyScale(e){e.translate(this.center.x,this.center.y),e.scale(this.scale.x,this.scale.y),e.translate(-this.center.x,-this.center.y)}inverseScale(e){const t=new DOMPointReadOnly(e.x,e.y),i=this.axis.pane.presenter.view.mouseContext;i.save(),i.resetTransform(),this.applyScale(i);const s=i.getTransform().inverse();return i.restore(),s.transformPoint(t)}hitTest(e){let t=999;if(this.hasRim&&(this.center.y<this.rim.y&&e.y<=this.center.y||this.center.y>=this.rim.y&&e.y>=this.center.y))t=Math.min(pn(this.left,e),pn(this.right,e));else{const i=this.hasScale?this.inverseScale(e):e,{x:s,y:n}=fn(i,this.center);if(!this.hasRim){const{startAngle:e,endAngle:t,antiClockwise:i}=this,r=Math.PI/2;if(0===e&&t===r&&!i&&(s<0||n<0))return!1;if(e===r&&t===Math.PI&&!i&&(s>0||n<0))return!1;if(e===-r&&t===Math.PI&&i&&(s>0||n>0))return!1;if(0===e&&t===-r&&i&&(s<0||n>0))return!1}t=Math.abs(Math.sqrt(s*s+n*n)-this.radius)}return t<=gs.HIT_TEST_TOLERANCE}get isAntiClockwise(){return this.hasRim?this.rim.y<=this.center.y:this.antiClockwise}draw(e){e.save(),this.hasClip&&e.clip(this.clip),this.hasScale&&this.applyScale(e),kn(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}}const fS=(e,t)=>{const i=new Path2D,{center:s}=t;if(Dn(i,s),i.arc(s.x,s.y,t.radius,t.startAngle,t.endAngle,t.isAntiClockwise??!1),null===e)return i;const n=new Path2D,{center:r}=e;return Dn(n,r),n.arc(r.x,r.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),i.addPath(n),i};class mS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){const[e,t]=this.getScreenPoints();if(!ie(e,t))return[];const i=pn(e,t),s=fn(t,e),n=s.y/i,r=s.x/i,o=this.getColoredElements(({value:t})=>{const s=i*t,o=n*s,a=r*s,l={x:e.x+a,y:e.y+o};return function(e,t,i){const s=pn(e,t);return new pS(e,t,s,0,Math.PI,null,i)}(e,l,this.axis)});if(this.showTrendLine){const i=new pA(e,t,!1,!1,this.axis);i.isTrend=!0,o.unshift(i)}return o}get showTrendLine(){return!0}getTextRef(){return(e,t,i)=>{const{center:s}=t,n=t.isAntiClockwise?-1:1;return{ref:{x:s.x,y:s.y+n*t.radius},spacing:0,offsetY:!0,text:i.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,fS,this.getTextRef(),t)}}class gS extends mS{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=ue(this.traits);return e.line=this.line2,rr(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[gs.AT_SHOW_TRENDLINE]}get line2(){return this.traits[gs.AT_LINE_2]}}class yS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return gs.AT_ANGLES}getElements(){const[e,t]=this.getScreenPoints(),{x:i,y:s}=fn(t,e);return this.getColoredElements(({value:n})=>{const r=(t,i)=>new pA(e,{x:t,y:i},!1,!0,this.axis),o="1"!==n.charAt(0),a=Number(o?n.charAt(0):n.charAt(2));return o?r(t.x,e.y+s/a):r(e.x+i/a,t.y)})}getTextRef(){return(e,t,i)=>({ref:t.anchor2,spacing:0,offsetY:!0,text:i.toString()})}adornElements(e,t){this.adornElementsForColoredFactors(e,uS,this.getTextRef(),t)}}class AS extends hS{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}getElements(){const[e,t]=this.getScreenPoints();return[new pA(e,t,!1,!1,this.axis)].concat(super.getElements())}}class SS extends mS{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}}class TS extends mA{constructor(e,t){super(e,t),this.addPoints(3)}getElements(){const e=this.points[0].point,t=this.points[1].point,i=this.points[2].point,s=(t.x+i.x)/2-e.x,n=(t.y+i.y)/2-e.y,r=[];return r.push(new pA(t,{x:t.x+s,y:t.y+n},!1,!0,this.axis)),r.push(new pA(e,{x:e.x+s,y:e.y+n},!1,!0,this.axis)),r.push(new pA(i,{x:i.x+s,y:i.y+n},!1,!0,this.axis)),r.push(new pA(t,i,!1,!1,this.axis)),r}}class vS extends vA{constructor(e,t){super(e,t)}getEllipse(){const e=this.getRect();return null===e?null:new In(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.visible)return!1;const t=this.getEllipse();return null!==t&&t.contains(e)}draw(e,t){return!!super.draw(e,t)&&(i=e,s=this.getEllipse(),i.beginPath(),i.ellipse(s.cx,s.cy,s.radiusX,s.radiusY,0,0,2*Math.PI),i.stroke(),i.fill(),!0);var i,s}}class PS extends mA{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}getLastPoint(){const[e,t,i]=this.points;var s=pn(e.point,t.point),n=gn(e.point,t.point);return{x:i.point.x+s*Math.cos(n),y:i.point.y+s*Math.sin(n)}}getElements(){const[e,t,i]=this.points;var s=[];if(s.push(new pA(e.point,t.point,this.extend1,this.extend2,this.axis)),ie(i?.price)){var n=this.getLastPoint();s.push(new pA(i.point,n,this.extend1,this.extend2,this.axis))}return s}}class CS extends vA{constructor(e,t,i){super(e,t),this.kind=i,this.adjustFill=!0}hitTest(e){if(!this.visible)return!1;const t=this.getRect();return null!==t&&t.contains(e)}get dimension(){const e="fish_hook"===this.kind?2:1;return gs.DEFAULT_SYMBOL_WIDTH_HEIGHT*e}updateOtherPoints(){this.points[1].price||this.setBottomRight()}setBottomRight(){const e=this.dimension,t=this.axis.pane.presenter.timeline,{price:i,time:s}=this.points[0],n=G(t,s,Number,ud);if(-1!==n){const s=this.axis.pane.presenter.view.xAxis.xScale.bar.totalWidth;let r=1;for(;(2*r+1)*s<e;)r++;this.points[0].update(i,t.at(n-r)),this.points[1].update(i,t.at(n+r));const o=mn(this.points[0].point,{x:0,y:-e/2}),a=mn(this.points[1].point,{x:0,y:e/2});this.points[0].updateFromPoint(o),this.points[1].updateFromPoint(a)}}draw(e,t){if(!super.draw(e,t))return!1;const i=this.getRect();return 0===i.width&&(i.width=this.dimension),Gn(e,this.kind,i),!0}}class bS extends gA{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new aA(e)}getElements(){const e=this.axis.pane.presenter.timeline,{price:t,time:i}=this.points[0],s=G(e,i,Number,ud),n=G(e,this.points[1].time,Number,ud),r=n-s;if(-1===s||-1===n)return[];return this.getColoredElements(({value:i})=>{const n=e.at(s+i*r);return null===n?null:(this.helper.update(t,n),new oA(this.helper.point,!0,this.axis))})}getTextRef(){return(e,t,i)=>({ref:t.anchor,spacing:3,offsetY:!0,text:i.toString()})}adornElements(e,t){const i=this.axis.pane.getBoundsWithoutScales();this.adornElementsForColoredFactors(e,(e,t)=>{const s=new Path2D;if(null===e)return s;const n=t.anchor.x-e.anchor.x;return s.rect(e.anchor.x,i.y,n,i.height),s},this.getTextRef(),t)}getTimeScaleAdornments(){const e=e=>({time:this.points[e].time,color:this.traits.line.color});return[e(0),e(1)]}}class ES{snapToSupported=!0;isDrawingAnnotation=!0;constructor(){}onMouseMove(e){const{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){if(q()&&e.originalEvent instanceof TouchEvent)return;const{point:t}=e,i=t.axis.pane.presenter,s={chart:i.accessor,axis:t.axis,point:{time:t.time.getTime(),price:t.price}};i.notifyHost(qa.CH_ANNPOINTPICKED,s),ZS(i,void 0)}}const LS="Open",MS="Closed";class _S extends mA{constructor(e,t,i){super(e,t),this.isLong=i,this.addPoints(4);const s=(e,t)=>this.points[e].moveDirection=t;s(1,T.Vertical),s(2,T.Vertical),s(3,T.Horizontal),this.twoDecMeta=new Qs(2)}twoDecMeta;_dataWindow;_metaData;isHit=!1;data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}getDataWindow(e,t,i=!0,s=!0){const n=this.data(Ka.DateTime),r=G(n,+e,Number),o=G(n,+t,Number),a={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[l,c,u]=[Ka.High,Ka.Low,Ka.Close].map(e=>this.data(e)),h=e=>e-r;for(let d=r;d<=o;d++)i&&-1===a.refIndex&&ie(this.entryPrice)&&this.entryPrice>=c[d]&&this.entryPrice<=l[d]&&(a.refIndex=h(d)),(!i||a.refIndex>=0&&h(d)>=a.refIndex)&&((!ie(a.highest)||l[d]>a.highest)&&(a.highest=l[d]),(!ie(a.lowest)||c[d]<a.lowest)&&(a.lowest=c[d])),i&&-1!==a.refIndex&&(-1===a.highestIndex&&l[d]>this.upperPrice&&(a.highestIndex=h(d)),-1===a.lowestIndex&&c[d]<this.lowerPrice&&(a.lowestIndex=h(d))),s&&a.data.push({high:l[d],low:c[d],close:u[d],time:n[d]});if(s&&a.data&&a.data.length>0){a.state=ie(a.highest,a.lowest)&&(this.upperPrice<a.highest||this.lowerPrice>a.lowest)?MS:LS,a.special=-1===a.highestIndex&&-1===a.lowestIndex||a.highestIndex===a.lowestIndex;const e=k(a.data);if(a.toPrice=e.close,a.toTime=e.time,a.state===MS)if(a.special){if(-1!==a.refIndex){const e=a.data[a.refIndex];a.toTime=e.time;const t=this.isLong?this.lowerPrice<a.lowest:this.upperPrice<a.highest;a.toPrice=t?this.upperPrice:this.lowerPrice}}else{const e=-1!==a.highestIndex&&-1!==a.lowestIndex;e&&a.highestIndex<a.lowestIndex||-1===a.lowestIndex?(a.toPrice=this.upperPrice,a.toTime=a.data[a.highestIndex].time):(e&&a.lowestIndex<a.highestIndex||-1===a.highestIndex)&&(a.toPrice=this.lowerPrice,a.toTime=a.data[a.lowestIndex].time)}const t=this.isLong?a.toPrice-this.entryPrice:this.entryPrice-a.toPrice;a.pAndL=se(t,2)}return a}get dataWindow(){return ie(this._dataWindow)||(this._dataWindow=this.getDataWindow(this.entryAnchor.time,this.exitAnchor.time)),this._dataWindow}getVisiblePriceRange(){const e=this.axis.yScale.domain();return e[1]-e[0]}getFutureTimestamp(){const e=this.axis.pane.presenter.timeline,t=G(e,+this.points[0].time,Number,ud),i=Math.min(e.length-1,t+50);return e.at(i).getTime()}get entryPrice(){return this.entryAnchor.price}get entryAnchor(){return this.points[0]}get upperPrice(){return this.upperAnchor.price}get upperAnchor(){return this.points[1]}get lowerPrice(){return this.lowerAnchor.price}get lowerAnchor(){return this.points[2]}get exitAnchor(){return this.points[3]}get accountSize(){return this.traits[gs.AT_ACCOUNT_SIZE]}get risk(){const e=this.traits[gs.AT_RISK_IS_PERCENT],t=this.traits[gs.AT_RISK];return se(e?t/100*this.accountSize:t,2)}get pointValue(){return this._metaData||(this._metaData=this.presenter.mainPlot.metaData),this._metaData.pointValue}formatDollarValue(e){if(!Number.isFinite(e))return gs.NOT_APPLICABLE;return`${e<0?"-":""}$${this.twoDecMeta.format(Math.abs(e))}`}get qty(){return Math.floor(this.risk/(this.isLong?this.entryPrice-this.lowerPrice:this.upperPrice-this.entryPrice))}get upperDiff(){return se(this.upperPrice-this.entryPrice,2)}get amountMultiplier(){return this.isLong?1:-1}get upperAmount(){return se(this.accountSize+this.amountMultiplier*this.qty*this.upperDiff,2)}get upperPandL(){return se(this.amountMultiplier*this.upperDiff*this.pointValue,2)}get isCompact(){return this.traits[gs.AT_COMPACT]}get upper(){const e=nd(this.axis,this.priceMap(this.upperPrice)),t=`(${se(this.upperDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get upperText(){const e=`${this.formatDollarValue(this.upperPandL)}`,t=`${this.formatDollarValue(this.upperAmount)}`,i=this.isLong?"Target":"Stop";return this.isCompact?`${this.upper} ${e}`:`${i}: ${this.upper}, P&L: ${e}, Amount: ${t}`}get lowerDiff(){return se(this.entryPrice-this.lowerPrice,2)}get lowerAmount(){return se(this.accountSize-this.amountMultiplier*this.qty*this.lowerDiff,2)}get lowerPandL(){return se(-this.amountMultiplier*this.lowerDiff*this.pointValue,2)}get lower(){const e=nd(this.axis,this.priceMap(this.lowerPrice)),t=`(${se(this.lowerDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get lowerText(){const e=`${this.formatDollarValue(this.lowerPandL)}`,t=`${this.formatDollarValue(this.lowerAmount)}`,i=this.isLong?"Stop":"Target";return this.isCompact?`${this.lower} ${e}`:`${i}: ${this.lower}, P&L: ${e}, Amount: ${t}`}get riskReward(){return se(this.isLong?this.upperDiff/this.lowerDiff:this.lowerDiff/this.upperDiff,2)}get state(){return this.dataWindow.state}get pAndL(){return this.dataWindow.pAndL}get pAndLValue(){return this.pAndL*this.pointValue}positionPoints(){const e=this.getVisiblePriceRange()/5,t=this.getFutureTimestamp();this.upperAnchor.update(this.entryPrice+e,this.entryAnchor.time),this.lowerAnchor.update(this.entryPrice-e,this.entryAnchor.time),this.exitAnchor.update(this.entryPrice,t)}get lowerStyle(){return this.fillOnlyStyle(gs.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get textStyle(){return this.fillOnlyStyle(gs.AT_FILL_TEXT)}get secondaryLineStyle(){return rr({line:{color:this.traits.line.color,dashStyle:"ShortDash"},fill:{color:gs.COLOR_TRANSPARENT}})}wasModifiedByTool(){ie(this.points[2].price)||this.positionPoints(),this._dataWindow=void 0}wasPointMovedByTool(e,t){const i=this.getVisiblePriceRange()/5e3;if(this.points.indexOf(e)<3){const t=t=>e.update(t,e.time);this.entryAnchor.price>this.upperAnchor.price&&(e===this.entryAnchor?t(this.upperAnchor.price-i):t(this.entryAnchor.price+i)),this.entryAnchor.price<this.lowerAnchor.price&&(e===this.entryAnchor?t(this.lowerAnchor.price+i):t(this.entryAnchor.price-i))}if(e===this.entryAnchor){const t=(t,i,s)=>t.update(i?e.price:t.price,s?e.time:t.time);t(this.exitAnchor,!0,!1),t(this.upperAnchor,!1,!0),t(this.lowerAnchor,!1,!0)}this.wasModifiedByTool()}get isUpperPerPAndL(){const e=this.dataWindow;return this.isLong?e.pAndL>0:e.pAndL<=0}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){const e=new pA(this.entryAnchor.point,this.exitAnchor.point,!1,!1,this.axis),t=this.exitAnchor.point.x<this.entryAnchor.point.x,i=Math.abs(this.exitAnchor.point.x-this.entryAnchor.point.x),s=(e,t)=>({x:e.x+t,y:e.y}),n=new fA(s(this.upperAnchor.point,t?-i:0),i,Math.abs(this.upperAnchor.point.y-this.entryAnchor.point.y),this.axis);n.style=this.upperStyle;const r=new fA(s(this.entryAnchor.point,t?-i:0),i,Math.abs(this.entryAnchor.point.y-this.lowerAnchor.point.y),this.axis);r.style=this.lowerStyle;const o=[e,n,r],a=this.dataWindow;if(-1!==a.refIndex){const e=a.data[a.refIndex],t=new aA(this.axis,this.entryPrice,e.time),i=new aA(this.axis,a.toPrice,a.toTime),s=new pA(t.point,i.point,!1,!1,this.axis);if(s.style=this.secondaryLineStyle,o.push(s),t.time!==i.time){const e=this.entryPrice<a.toPrice,s=new fA({x:t.point.x,y:Math.min(t.point.y,i.point.y)},i.point.x-t.point.x,Math.abs(i.point.y-t.point.y),this.axis);s.style=e?this.upperStyle:this.lowerStyle,o.push(s)}}return o}hitTest(e){if(!this.visible)return!1;const t=this.isHit||!1;return this.isHit=super.hitTest(e),this.isHit!==t&&this.requestRedraw(),this.isHit}get showTextAdornments(){return this.isHit||this.isSelected}getPriceScaleAdornments(){const e=e=>Sn(this.traits[e].color);return[{price:this.upperPrice,color:e(gs.AT_FILL)},{price:this.entryPrice,color:e(gs.AT_LINE)},{price:this.lowerPrice,color:e(gs.AT_FILL2)}]}adornElements(e,t){const[i,s,n]=e;if(this.showTextAdornments){const[e,r]=[!0,!1].map(e=>Nn(t,e)),{x:o,y:a,width:l}=s.rect,c={x:o+l/2,y:a+e},u=this.textStyle.fillStyle;Bn(t,this.upperText,c,g.Center,u,Sn(this.upperStyle.fillStyle));const{x:h,y:d,width:p,height:f}=n.rect,m={x:h+p/2,y:d+f+Math.abs(r)};Bn(t,this.lowerText,m,g.Center,u,Sn(this.lowerStyle.fillStyle));const{p1:y,p2:A}=i,{x:S,y:T}=y,{x:v}=A,P=this.state||gs.NOT_APPLICABLE,C=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${P} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.qty}`,b=this.isCompact?`${this.riskReward.toFixed(2)}`:`Risk/Reward Ratio: ${this.riskReward.toFixed(2)}`,E=e=>t.measureText(e).width,L=Math.max(E(C),E(b)),M={x:S+(v-S)/2,y:Math.abs(v-S)<1.25*L?T+Math.abs(r)+5:T+e+10},_=Sn(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);Bn(t,[C,b],M,g.Center,u,_)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}}class xS extends yA{markers;display=null;constructor(e,t){super(e,t),this.points=TA(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new iS]}isPointDrawn(e){return!!super.isPointDrawn(e)&&e.visible}makeLineArrow(e,t,i,s){const n=[dn(e,t),dn(i,s)];return[this.makeLine(n[0],n[1]),eS(n,"end",10)]}get rectColor(){return this.traits[gs.AT_FILL].color}get textColor(){return this.traits[gs.AT_FILL_TEXT].color}getMarkers(){return this.markers}formatDateDifference(e,t){if(this.presenter.data.aggregation.isEndOfDay)return`${pt(t,e)}d`;const i=function(e,t){var i,s,n,r,o;if(arguments.length<1)throw new TypeError("1 argument required, but only ".concat(arguments.length," present"));var a=tt(),l=null!==(i=null!==(s=null==t?void 0:t.locale)&&void 0!==s?s:a.locale)&&void 0!==i?i:pi,c=null!==(n=null==t?void 0:t.format)&&void 0!==n?n:Ti,u=null!==(r=null==t?void 0:t.zero)&&void 0!==r&&r,h=null!==(o=null==t?void 0:t.delimiter)&&void 0!==o?o:" ";return l.formatDistance?c.reduce(function(t,i){var s="x".concat(i.replace(/(^.)/,function(e){return e.toUpperCase()})),n=e[i];return"number"==typeof n&&(u||e[i])?t.concat(l.formatDistance(s,n)):t},[]).join(h):""}(Ci({start:e,end:t}),{format:["days","hours","minutes","seconds"]});return i.replaceAll(/(days?)|(hours?)|(minutes?)|(seconds?)/g,e=>e[0])}computeState(){}get text(){return null===this.display&&this.computeState(),this.display}getTextCoord(e,t){const i=this.points[0].price<this.points[1].price,s=Nn(t,i,this.text.length),{x:n,y:r,width:o,height:a}=e.rect;return{x:n+o/2,y:r+(i?0:a)+(i?s:Math.abs(s))}}adornElements(e,t){Bn(t,this.text,this.getTextCoord(e[0],t),g.Center,this.textColor,Sn(this.rectColor))}getDateDifference(){const[e,t]=this.points.slice(0,2).map(e=>e.time),i=Math.min(+e,+t),s=Math.max(+e,+t),n=this.data(Ka.DateTime),r=G(n,+i,Number),o=G(n,+s,Number),a=O(this.data(Ka.Volume).slice(r,o+1)),l=this.formatter.format(a,Ka.Volume),c=o-r,u=e<t?"":"-";return[`${u}${c} bars, ${u}${0===c?"":this.formatDateDifference(i,s)}`,`Vol ${l}`]}getPriceDifference(){const[e,t]=this.points.slice(0,2).map(e=>e.price),i=t-e,s=i/e;return[`${this.formatter.format(i,Ka.Close)} (${this.formatter.format(s,Ka.PercentChange)})`]}resetComputedState(){this.display=null}getFlipAnchorIndices(){return[0,1]}}class IS extends xS{getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),n=this.makeLine(e,s),r=this.makeLine(t,i),[o,a]=this.makeLineArrow(e,s,t,i);return this.markers[0]=a,[this.rect,n,r,o]}computeState(){this.display=this.getDateDifference()}}class DS extends xS{getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),n=this.makeLine(e,i),r=this.makeLine(t,s),[o,a]=this.makeLineArrow(e,i,t,s);return this.markers[0]=a,[this.rect,n,r,o]}computeState(){this.display=this.getPriceDifference()}}class OS extends xS{get drawBorder(){return this.traits[gs.AT_DRAW_BORDER]}getBorderElements(){if(!this.drawBorder)return[];const[e,t,i,s]=this.getScreenPoints();return[this.makeLine(e,s),this.makeLine(t,i),this.makeLine(e,i),this.makeLine(t,s)]}getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),[n,r]=this.makeLineArrow(e,s,t,i),[o,a]=this.makeLineArrow(e,i,t,s);this.markers=[r,a];const l=this.getBorderElements();return[this.rect,n,o].concat(l)}computeState(){this.display=this.getPriceDifference().concat(this.getDateDifference())}}class wS extends yA{constructor(e,t){super(e,t),this.points=TA(e)}get priceLevels(){return Jn(this.traits[gs.AT_PRICE_LEVELS])}get timeLevels(){return Jn(this.traits[gs.AT_TIME_LEVELS])}get showAngles(){return this.traits[gs.AT_SHOW_ANGLES]}get reverse(){return this.traits[gs.AT_REVERSE]}get showLeftLabels(){return this.traits[gs.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[gs.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[gs.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[gs.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){const i=this.getScreenPoints(),s=this.lineOnlyStyle(gs.AT_LINE_2),n=[];e.concat(t).flatMap(e=>[e.p1,e.p2]).map(e=>{n.some(t=>{return s=t,(i=e).x===s.x&&i.y===s.y;var i,s})||n.push(e)});const r=i.map(e=>n.filter(t=>{return s=e,!((i=t).x===s.x||i.y===s.y);var i,s}).map(t=>this.makeLine(e,t))).flat();return r.forEach(e=>e.style=s),r}getElements(){const e=this.getLinesDataAtLevels(this.priceLevels,this.timeLevels),{priceLines:t,timeLines:i}=this.getLineElements(e),s=this.showAngles?this.getAngles(t,i):[];return[...t,...i,...s]}adornElements(e,t){const i=this.singleStyle,s=this.showBackground,n=t.fillStyle,r=Rn(t,1)/2,{x:o,y:a}=gs.DEFAULT_ADORN_OFFSET,l=(e,i,s,n,r)=>{const o=mn(e,i);Bn(t,Number(s.toFixed(4)).toString(),o,n,r)},c=(e,i)=>{const s=new Path2D;wn(s,e.p1,i.p2),t.fillStyle=i.style.fillStyle,t.fill(s)};let u=null;if(e.forEach(e=>{if(!e._data)return;const{level:t,isPrice:h}=e._data,d=i?n:e.style.strokeStyle,p=u&&s&&!i;h?(this.showLeftLabels&&l(e.p1,{x:o,y:r},t,g.Right,d),this.showRightLabels&&l(e.p2,{x:-o,y:r},t,g.Left,d),p&&c(u,e)):(this.showTopLabels&&l(e.p1,{x:0,y:a},t,g.Center,d),this.showBottomLabels&&l(e.p2,{x:0,y:2*-a},t,g.Center,d),p&&c(u,e)),u=e}),i&&s){const e=this.applyBackgroundOpacity(this.traits.line.color),i=new Path2D,[s,n]=this.getScreenPoints();wn(i,s,n),t.fillStyle=e,t.fill(i)}}resetComputedState(){this.lines=void 0}updateFrom(e,t,i,s,n){const r=e.reverse!==this.reverse;super.updateFrom(e,t,i,s,n),r&&this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}}const RS=e=>e.map(e=>({...e,dimensions:e.value.split("x").map(Number)})),NS=(e,t)=>Math.abs(e-t)<1e-7;class VS extends yA{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=TA(e),this._parsedFans=this._parsedArcs=null}get levels(){return Jn(this.traits[gs.AT_LEVELS])}setComputedAndTraits(e,t){const i={...e,computed:t,traits:this.getTraitsFor(e)};return delete i.line,i}get computedLevels(){return this.levels.map(e=>this.setComputedAndTraits(e,e.value/5))}get showRangesRatio(){return this.traits[gs.AT_SHOW_RANGES_RATIO]}get arcs(){return Jn(this.traits[gs.AT_ARCS])}get fans(){return Jn(this.traits[gs.AT_FANS])}get reverse(){return this.traits[gs.AT_REVERSE]}get parsedFans(){return null===this._parsedFans&&(this._parsedFans=RS(this.fans)),this._parsedFans}get computedFans(){const[,,e,t]=this.getReversedScreenPoints(),{dx:i,dy:s}=this.unit,{signX:n,signY:r}=this.getOrientation();return this.parsedFans.map(o=>{const[a,l]=o.dimensions;return this.setComputedAndTraits(o,a>=l?{x:e.x,y:e.y+l/a*r*5*s}:{x:t.x+a/l*5*n*i,y:t.y})})}get parsedArcs(){return null===this._parsedArcs&&(this._parsedArcs=RS(this.arcs)),this._parsedArcs}get computedArcs(){const{dx:e}=this.unit;return this.parsedArcs.map(t=>{const[i,s]=t.dimensions;return this.setComputedAndTraits(t,Math.sqrt(e**2*(i**2+s**2)))})}getReversedScreenPoints(){const[e,t,i,s]=this.getScreenPoints();return this.reverse?[t,e,s,i]:[e,t,i,s]}get unit(){const[e,t]=this.getReversedScreenPoints();return e.x!==t.x&&e.y!==t.y?{dx:Math.abs(t.x-e.x)/5,dy:Math.abs(t.y-e.y)/5}:null}get priceBarRatio(){return this.traits[gs.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[gs.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,i){const s=this.makeLine(e,t);return this.singleStyle||(s.style=rr(i)),s}getGridLines(e,t){const i=t.x-e.x,s=t.y-e.y;return this.computedLevels.map(({computed:n,traits:r})=>{const o=e.x+n*i,a=e.y+n*s;return[this.makeStyledLine({x:o,y:e.y},{x:o,y:t.y},r),this.makeStyledLine({x:e.x,y:a},{x:t.x,y:a},r)]}).flat()}getArcs(e){const{flipX:t,flipY:i,signY:s}=this.getOrientation(),{dx:n,dy:r}=this.unit,o=NS(n,r)?null:{x:1,y:r/n},a=this.getClipPath();return this.computedArcs.map(({computed:n,traits:r})=>{const l=function(e,t,i,s,n,r){return new pS(e,null,t,i,s,n,r)}(e,n,t?s*Math.PI/2:0,t?Math.PI:s*Math.PI/2,i,this.axis);return null!==o&&(l.scale=o),l.clip=a,this.singleStyle||(l.style=rr(r)),l})}getFans(e){return this.computedFans.map(({computed:t,traits:i})=>this.makeStyledLine(e,t,i))}getElements(){if(null===this.unit)return[];const[e,t]=this.getReversedScreenPoints();return[...this.getGridLines(e,t),...this.getArcs(e),...this.getFans(e)]}getOrientation(){const[e,t]=this.getReversedScreenPoints(),i=t.x<e.x,s=t.y<e.y;return{flipX:i,signX:i?-1:1,flipY:s,signY:s?-1:1}}getClipPath(){const[e,t]=this.getReversedScreenPoints(),i=new Path2D;return wn(i,e,t),i}adornElements(e,t){if(0===e.length)return;const i=(e,i,s)=>{t.fillStyle=s;const n=i.hasScale;n&&(t.save(),i.applyScale(t)),t.fill(e),n&&t.restore()};if(this.showBackground){const s=e.filter(e=>e.radius),n=this.getClipPath();if(t.save(),t.clip(n),this.singleStyle){const e=k(s),t=fS(null,e),n=this.applyBackgroundOpacity(this.traits.line.color);i(t,e,n)}else{let e=null;s.forEach(t=>{const s=fS(e,t),n=t.style.fillStyle;i(s,t,n),e=t})}t.restore()}if(this.showRangesRatio&&null!==this.unit){const e=k(this.computedLevels),i=(this.singleStyle?this:e).traits.line.color,[,s,n,r]=this.getReversedScreenPoints(),{x:o,y:a}=gs.DEFAULT_ADORN_OFFSET,{flipX:l,signX:c,signY:u}=this.getOrientation(),h=mn(n,{x:-o*c,y:a*u}),{priceDiff:d,barsDiff:p}=this.getLinesDataAtLevels(null,null),f=l?g.Right:g.Left;Bn(t,p.toFixed(0),h,f,i);const m=mn(r,{x:2*o*c,y:-a*u}),y=l?g.Left:g.Right;Bn(t,this.formatter.format(d,Ka.Close),m,y,i);const A=mn(s,{x:-o*c,y:-a*u});Bn(t,this.priceBarRatio.toFixed(6),A,f,i)}}resetComputedState(){if(this.lines=void 0,4===this.points.length&&null!==this.unit){const{priceDiff:e,barsDiff:t}=this.getLinesDataAtLevels(null,null);this.priceBarRatio=Math.abs(e/t)}}updateFrom(e,t,i,s,n){if(super.updateFrom(e,t,i,s,n),this._parsedFans=this._parsedArcs=null,!NS(e.priceBarRatio,this.priceBarRatio)){let[t,i,,]=this.points;this.reverse&&([t,i]=[i,t]);const{priceDiff:s,barsDiff:n}=this.getLinesDataAtLevels(null,null);i.update(t.price+Math.sign(s)*e.priceBarRatio*n,i.time),this.resetComputedState()}}getFlipAnchorIndices(){return[0,1]}}const HS=(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),On(i,e.p2),On(i,t.p2),On(i,t.p1)),i};class BS extends gA{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}getElements(){const[e,t,i]=this.getScreenPoints(),{x:s,y:n}=fn(i,e),r=i=>{const[s,n]=[e,t].map(e=>mn(e,i));return new pA(s,n,this.extend1,this.extend2,this.axis)};return this.getColoredElements(({value:e})=>r({x:s*e,y:n*e}))}getTextRef(){return(e,t,i)=>({ref:t,spacing:5,offsetY:!0,text:this.formatLevelPrice(i,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,HS,this.getTextRef(),t)}}class FS extends mA{levelSize=0;alignLeft=!0;totalVolume=!1;widthPercent=30;useChange=!1;studyPlotId;gotData;boxes=[];periodType="VisibleScreen";period=0;valueRangePercent=.7;levelMode="Count";usesFinerGrainedAgg=!0;constructor(e,t,i){super(e,t),this.computed=!0,this.studyPlotId=i,this.gotData=!1}setOptions(e){switch(this.levelMode=e.LevelMode,this.levelSize=Ce(1,1e3,e.LevelSize),this.alignLeft="Left"===e.Position,this.totalVolume="Total"===e.Volume,this.widthPercent=Ce(5,100,e.WidthPercent)/100,e.BarColoring){case"OpenToClose":this.useChange=!1;break;case"CloseToClose":this.useChange=!0;break;default:{const e=this.presenter.mainPlot?.mainCurve?.attributes;this.useChange=e?.includes(r.ChangeBased)??!1}}te(e.PeriodType)&&(this.periodType=e.PeriodType),this.period=e.Period,this.valueRangePercent=e.ValueRangePercent/100;const t=v[Gv()?.config.mode??"Unspecified"];this.usesFinerGrainedAgg=jr(t)}get isCountMode(){return"Count"===this.levelMode}updateLastBox(){if(this.boxes.length>0){const e=this.boxes.pop(),t=this.getDataForRange(e.firstDate,e.lastDate);t&&this.boxes.push(t)}}invalidate(e){switch(this.periodType){case"VisibleScreen":this.gotData=!1,this.boxes=[];break;case"Bars":case"Days":switch(e){case"DataPointAdded":{const e=this.studySeries.innCont(0),t=e?.getTimeData();if(!ie(t))return;const i=t[t.length-1],s=this.boxes.length>0?this.boxes[this.boxes.length-1]:null;if(te(s)&&i.valueOf()<s.lastDate.valueOf())this.updateLastBox();else{const e=this.getDataForRange(i,this.getBoxEndFromStart(i));e&&this.boxes.push(e)}break}case"DataPointChanged":this.updateLastBox();break;case"NewChunkArrived":this.gotData=!1}}}getBoxRect(e){switch(this.periodType){case"VisibleScreen":return this.axis.pane.getBoundsWithoutScales();case"Bars":case"Days":{const t=this.axis.pane.presenter.view.xAxis.xScale.bar,i=this.axis.toY(e.min),s=this.axis.toY(e.max),n=this.axis.pane.presenter.view.toX(e.firstDate)-t.width/2;let r=0;if("Days"===this.periodType){const i=e.lastDate,s=this.axis.pane.presenter.view.xAxis.xScale.timeline,o=s.at(s.lastSeriesIndex),a=o.valueOf()<i.valueOf(),l=a?o:i,c=(a?1:-2)*t.width/2;r=this.axis.pane.presenter.view.toX(l)+c-n}else r=this.period*t.width+(this.period-1)*t.spacing;return new xn(n,s,r,i-s)}default:throw new Error("Unexpected period type for Volume At Price annotation")}}getElementsForBox(e){const t=this.getBoxRect(e),i=[];if(this.isPeriodic){const e=new fA({x:t.x,y:t.y},t.width,t.height,this.axis);e.style=this.backgroundStyle,i.push(e)}const{x:s,width:n}=t,r=n*this.widthPercent,o=e.bars[e.maxVolumeIndex];return e.bars.forEach((t,a)=>{const{upVolume:l,downVolume:c,totalVolume:u,isValue:h}=t;if(0===l&&0===c)return null;const d=this.axis.toY(e.min+a*e.zone),p=this.axis.toY(e.min+(a+1)*e.zone),f=Math.abs(d-p),m=(e,t,i=0)=>{const r=this.alignLeft?s+i:s+n-e-i,o=new fA({x:r,y:p},e,f,this.axis);return o.style=t,o},g=(e,t,i)=>e/t.totalVolume*i,y=this.studyPlot.curves[2].visible,A=y&&h?this.upValueStyle:this.upStyle,S=y&&h?this.downValueStyle:this.downStyle,T=y&&h?this.totalValueStyle:this.totalStyle;if(this.totalVolume){const e=g(u,o,r);i.push(m(e,T))}else{const e=g(c,o,r),t=g(l,o,r);i.push(m(t,A),m(e,S,t))}if(this.studyPlot.curves[1].visible&&a===e.maxVolumeIndex){const e=i[i.length-1].rect,t=this.alignLeft?e.x+e.width:s,r=(p+d)/2,o=this.alignLeft?s+n:e.x;i.push(new pA({x:t,y:r},{x:o,y:r},!1,!1,this.axis))}}),i}get isVisible(){return this.studyPlot.visible&&this.studyPlot.mainCurve.visible}getElements(){if(this.gotData||this.getData(),!this.gotData||!this.isVisible)return[];if(0===this.boxes.length)return[];switch(this.periodType){case"VisibleScreen":{const e=this.boxes[0];return e&&0!==e.bars.length?this.getElementsForBox(e):[]}case"Bars":case"Days":{const[e,t]=this.presenter.view.xAxis.xScale.domain()||[];if(!ht(e)||!ht(t))return[];let i=this.boxes.findIndex(t=>t.firstDate.getTime()<=e.getTime()&&t.lastDate.getTime()>=e.getTime());-1===i&&(i=0,this.studySeries.loadMoreData());let s=this.boxes.findIndex(e=>e.firstDate.getTime()<=t.getTime()&&e.lastDate.getTime()>=t.getTime());-1===s&&-1!==i&&(s=this.boxes.length-1);const n=[];for(let r=i;r<=s;r++)n.push(...this.getElementsForBox(this.boxes[r]));return n}default:throw new Error("Unexpected period type for Volume At Price annotation")}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}get presenter(){return this.axis.pane.presenter}get downStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get upStyle(){return this.fillOnlyStyle(gs.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(gs.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(gs.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(gs.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(gs.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(gs.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(gs.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case"VisibleScreen":default:return null;case"Days":return _t(gu(a.Day,this.period)(e),1);case"Bars":{const t=this.axis.pane.presenter.data.aggregation;return _t(gu(t.unit,t.size*this.period)(e),1)}}}getData(){const e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!dg(e.spec))return;const[t,i]=this.presenter.view.xAxis.xScale.domain()||[];if(!ht(t)||!ht(i))return;const s=gu(e.unit,e.size);switch(this.periodType){case"VisibleScreen":{const e=this.boxes[0];if(e&&e.firstDate===t&&e.lastDate===i)this.gotData=!0;else{const e=this.getDataForRange(t,i);e&&(this.boxes[0]=e)}break}case"Bars":{const[e,t]=[0,1].map(e=>this.studySeries.innCont(e));if((e?.size??0)<1||(t?.size??0)<1)return;const i=e.getTimeData();let n=0;for(this.boxes=[];n<i.length;){const e=i[n],t=n+this.period,r=_t(t<i.length?i[t]:s(i[i.length-1]),1),o=this.getDataForRange(e,r);o&&this.boxes.push(o),n+=this.period}this.gotData=!0;break}case"Days":{if(e.isEndOfDay)return this.boxes=[],void(this.gotData=!0);const[t,i]=[0,1].map(e=>this.studySeries.innCont(e));if((t?.size??0)<1||(i?.size??0)<1)return;const n=t.getTimeData(),r=t.getData(Ka.TradingDay),o=e=>{let t=0,i=n[e],s=r[e];for(let o=e;o<n.length;o++)if(rt(n[o],i)>0&&r[o]!==s&&(t+=1,i=n[o],s=r[o],t===this.period))return o;return-1};let a=0,l=n[a],c=o(a)-1;for(;(c<0||c===a)&&a<n.length;)a+=1,c=o(a)-1;for(this.boxes=[];a<n.length&&c<n.length&&a<c;){const e=_t(s(n[c]),1),t=this.getDataForRange(l,e);t&&this.boxes.push(t),a=c+1,l=n[a],c=o(a)-1}if(c<0&&a<n.length-1){const e=_t(s(n[n.length-1]),1),t=this.getDataForRange(n[a],e);t&&this.boxes.push(t)}this.gotData=!0;break}}}getBoxAt(e){if(0===this.boxes.length)return null;switch(this.periodType){case"VisibleScreen":{const t=this.boxes[0];return t.firstDate>e||t.lastDate<e?null:t}case"Bars":case"Days":{const t=e.getTime(),i=this.boxes.find(e=>e.firstDate.getTime()<=t&&e.lastDate.getTime()>=t);return i||null}}}getValueAt(e,t,i){if(!this.isVisible)return null;const s=this.getBoxAt(t);if(!s)return null;const n=this.getBarIndex(s,i);if(n<0||n>=s.bars.length)return null;const r=s.bars[n];switch(e){case Ka.UPVOL:return this.totalVolume?null:r.upVolume;case Ka.DNVOL:return this.totalVolume?null:r.downVolume;case Ka.TOTVOL:return this.totalVolume?r.totalVolume:null;case Ka.POC:case Ka.VAREA:case Ka.BARBACK:return null;default:throw new Error("Unexpected Volume At Price field")}}getBarIndex(e,t,i=!1){if(0===e.bars.length||0===e.zone)return-1;const s=Math.floor((t-e.min)/e.zone);return i?Math.min(e.bars.length-1,s):s}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}makeBox(e,t){return{min:Number.MAX_VALUE,max:Number.MIN_VALUE,zone:0,bars:[],maxVolumeIndex:-1,firstDate:e,lastDate:t}}findExtremes(e,t,i,s,n,r){const o=te(n)&&te(r);for(let a=t;a<=i;a++)if(o){const t=n[a];t>e.max&&(e.max=t);const i=r[a];i<e.min&&(e.min=i)}else{const t=s[a];t<e.min&&(e.min=t),t>e.max&&(e.max=t)}}findValueArea(e){if(-1===e.maxVolumeIndex||0===e.bars.length)return;e.bars[e.maxVolumeIndex].isValue=!0;const t=O(e.bars.map(e=>e.totalVolume))*this.valueRangePercent;let i=e.bars[e.maxVolumeIndex].totalVolume,s=e.maxVolumeIndex,n=e.maxVolumeIndex;for(;i<t;){const r=[{dir:"lower",count:2,startIdx:s-2,endIdx:s-1},{dir:"lower",count:1,startIdx:s-1,endIdx:s-1},{dir:"upper",count:2,startIdx:n+1,endIdx:n+2},{dir:"upper",count:1,startIdx:n+1,endIdx:n+1}].filter(t=>t.startIdx>=0&&t.endIdx<e.bars.length).map(t=>{const s=O(e.bars.slice(t.startIdx,t.endIdx+1).map(e=>e.totalVolume));return{...t,volume:s,newTotal:i+s}});if(0===r.length)break;const o=(e,t)=>t.newTotal<e.newTotal?t:e,a=(e,t)=>t.volume>e.volume?t:e,l=r.filter(e=>e.newTotal>=t),c=l.length>0?l.reduce(o):r.reduce(a);for(let t=c.startIdx;t<=c.endIdx;t++)e.bars[t].isValue=!0;if("lower"===c.dir?s=c.startIdx:n=c.endIdx,i=c.newTotal,i>=t)break}}tallyVolume(e,t,i,s,n,r,o){let a=Number.MIN_VALUE,l=!1;for(let c=t;c<=i;c++){const t=n[c],i=this.getBarIndex(e,t,!0);if(-1===i){l=!0;break}const u=o[c],h=this.useChange?r[c]>=0:s[c]<=n[c],d=e.bars[i];h?d.upVolume+=u:d.downVolume+=u,d.totalVolume=d.downVolume+d.upVolume,d.totalVolume>a&&(a=d.totalVolume,e.maxVolumeIndex=i)}l||this.findValueArea(e)}get isPeriodic(){return"Bars"===this.periodType||"Days"===this.periodType}get isVisibleScreen(){return"VisibleScreen"===this.periodType}getDataForRange(e,t){const i=this.makeBox(e,t),s=this.studySeries.innCont(1),n=s?.getTimeData();if(!ie(n))return null;const r=e=>G(n,+e,Number);let o=r(e),l=r(t);if(n[l].getTime()>t.getTime()&&(l-=1),o>l)return null;if(this.axis.pane.presenter.data.aggregation.unit===a.Day&&"Bars"===this.periodType){const e=s.getData(Ka.TradingDay);let t=e[o];for(;t===e[o]&&o>0;)o-=1;o+=1;let i=0;for(l=o;l<n.length&&i<this.period;)e[l]!==t&&(i+=1,t=e[l]),l+=1;l-=2}this.isVisibleScreen&&this.usesFinerGrainedAgg&&o<1e3&&this.studySeries.loadMoreData();const[c,u,h,d,p,f]=["Open","High","Low","Close","Change","Volume"].map(e=>{return t=Ka[e],s.getData(t);var t});this.findExtremes(i,o,l,d,u,h);const m=i.max-i.min,g=e=>({upVolume:0,downVolume:0,isValue:!1,totalVolume:0});if(this.isCountMode)i.zone=m/this.levelSize,i.bars=Y(this.levelSize,g);else{const e=(this.presenter.mainPlot?.metaData.minMovement??1)*this.levelSize,t=Math.max(1,Math.ceil(m/e));i.zone=m/t,i.bars=Y(t,g)}return this.tallyVolume(i,o,l,c,d,p,f),this.gotData=!0,i}}const kS=["None","Absolute","Percent"];class WS extends mA{studyPlotId;displayMode="None";visibleLabelSegments=[];constructor(e,t,i){super(e,t),this.studyPlotId=i}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}setOptions(e){const t=e.ReversalChange;var i;this.displayMode="string"==typeof(i=t)&&kS.includes(i)?t:"None"}formatSegmentValue(e,t){return"Absolute"===this.displayMode?this.formatter.format(t-e,Ka.Close):"Percent"===this.displayMode?0===e?"":this.formatter.format((t-e)/e,Ka.PercentChange):""}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.visible||!this.studyPlot.mainCurve.visible)return[];const e=this.studySeries.getCurrentState();if(!e)return[];const t=e.confirmedPivots,i=Array.from(t.keys()).sort((e,t)=>e-t);if(0===i.length)return[];const s=this.presenter.mainPlot?.timeSeries?.container;if(!s||s.size<2)return[];const n=s.getTimeData();if(!n)return[];const r=this.presenter.view,[o,a]=r.xAxis.xScale.domain()||[];if(!o||!a)return[];const l=o.getTime(),c=a.getTime();let u=-1,h=-1;for(let p=0;p<i.length;p++){const e=n[i[p]].getTime();if(-1===u&&e>=l&&(u=Math.max(0,p-1)),e<=c)h=p;else if(-1!==u)break}if(-1===u){if(i.length>0&&n[i[0]].getTime()>c)return[];u=i.length-1,h=i.length-1}else-1===h&&(h=u);h=Math.min(i.length-1,h+1);const d=[];for(let p=u;p<h;p++){const e=i[p],s=i[p+1],o=t.get(e),a=t.get(s),u=r.toX(n[e]),h=this.axis.toY(o),f=r.toX(n[s]),m=this.axis.toY(a);d.push(this.makeLine({x:u,y:h},{x:f,y:m}));const g=n[s].getTime();g>=l&&g<=c&&this.visibleLabelSegments.push({fromPrice:o,toPrice:a,toPoint:{x:f,y:m}})}if(ie(e.pivotPrice)&&ie(e.candPrice)){const t=n[e.pivotIndex].getTime();if(n[e.candIndex].getTime()>=l&&t<=c){const t=r.toX(n[e.pivotIndex]),i=this.axis.toY(e.pivotPrice),s=r.toX(n[e.candIndex]),o=this.axis.toY(e.candPrice);d.push(this.makeLine({x:t,y:i},{x:s,y:o}))}}return d}adornElements(e,t){if("None"===this.displayMode||0===this.visibleLabelSegments.length)return;const i=Math.abs(Nn(t,!0));this.visibleLabelSegments.forEach(e=>{const s=this.formatSegmentValue(e.fromPrice,e.toPrice);if(""===s)return;const n=e.toPrice>=e.fromPrice,r={x:e.toPoint.x,y:e.toPoint.y+(n?-i:i)};Bn(t,s,r,g.Right,n?"#16A34A":"#DC2626")})}}const US=[gs.AT_LINE,gs.AT_LINE_2,gs.AT_LINE_3];class $S extends mA{studyPlotId;constructor(e,t,i){super(e,t),this.studyPlotId=i}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}isCurveVisible(e){return this.studyPlot.curves[e]?.visible??!1}makeLines(){if(!this.studyPlot?.visible)return null;const e=this.studySeries.getCurrentState();if(!e||null===e.slope||null===e.intercept||null===e.stdDevWidth)return null;const{startIndex:t,endIndex:i,slope:s,intercept:n,stdDevWidth:r,extendLeft:o,extendRight:a}=e;if(null===t||null===i)return null;const l=this.presenter.mainPlot?.timeSeries?.container;if(!l||l.size<2)return null;const c=l.getTimeData();if(!c||c.length<=i)return null;const u=this.presenter.view,h=i-t+1,d=e=>n+s*(e+1),p=d(0),f=d(h-1),m=u.toX(c[t]),g=u.toX(c[i]),y=(e,t)=>{const i=this.axis.toY(p+e),s=this.axis.toY(f+e),n=new pA({x:m,y:i},{x:g,y:s},o,a,this.axis);return n._data={lineIndex:t},n};return[y(r,0),y(0,1),y(-r,2)]}getStyleForElement(e,t){const i=e._data?.lineIndex??t,s=US[i],n=this.traits[s];return n?rr({line:n,fill:{color:gs.COLOR_TRANSPARENT}}):super.getStyleForElement(e,t)}getElements(){const e=this.makeLines();return e?e.filter((e,t)=>this.isCurveVisible(t)):[]}adornElements(e,t){const i=this.makeLines();if(!i)return;if(!i.every(e=>ie(e.p1,e.p2)))return;const[s,n,r]=i,o=(e,i,s)=>{t.fillStyle=s,t.fill(HS(e,i))};this.isCurveVisible(3)&&o(s,n,this.traits?.[gs.AT_FILL]?.color),this.isCurveVisible(4)&&o(n,r,this.traits?.[gs.AT_FILL2]?.color)}}function GS(e){const t=e<0?-1:1,i=Math.abs(e)/Math.SQRT2,s=1/(1+.3275911*i);return.5*(1+t*(1-((((1.061405429*s-1.453152027)*s+1.421413741)*s-.284496736)*s+.254829592)*s*Math.exp(-i*i)))}class zS extends mA{studyPlotId;periodTarget=0;targetPrice1=0;targetPrice2=0;pricesCount=0;targetDate;computed=!1;anchorPrice=0;sigmaAnnualized=0;unitsPerYear=0;probabilityAbove=0;probabilityBelow=0;probabilityBetween=0;styles=[];constructor(e,t,i){super(e,t),this.studyPlotId=i}makeStyles(){const e=this.lineOnlyStyle(gs.AT_LINE),t=this.lineOnlyStyle(gs.AT_LINE_2);this.styles=[e,t,t]}containerOf(e){return e?.timeSeries.container}get mainCont(){return this.containerOf(this.presenter.mainPlot)}get studyCont(){return this.containerOf(this.studyPlot)}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get targetPrice(){return 0!==this.targetPrice1?this.targetPrice1:this.targetPrice2}setOptions(e){if(this.periodTarget=e.PeriodTarget,this.targetPrice1=e.TargetPrice1,this.targetPrice2=e.TargetPrice2,this.pricesCount=(0!==this.targetPrice1?1:0)+(0!==this.targetPrice2?1:0),this.pricesCount>1&&this.targetPrice1<this.targetPrice2){const e=this.targetPrice1;this.targetPrice1=this.targetPrice2,this.targetPrice2=e}}get haveInput(){return 0!==this.periodTarget&&(0!==this.targetPrice1||0!==this.targetPrice2)}get haveData(){return te(this.mainCont)&&!this.mainCont.isEmpty&&this.studySeries.haveVolatility}get studySeries(){return this.studyPlot.timeSeries}getData(){const e=this.presenter.timeline;this.targetDate=e.at(e.lastSeriesIndex+this.periodTarget),this.points=[new aA(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new aA(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=Ry(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(Ka.Close),this.sigmaAnnualized=this.studySeries.getVolatilityPercent()}computeProbabilities(){const e=this.sigmaAnnualized*Math.sqrt(this.periodTarget/this.unitsPerYear),t=t=>(t-this.anchorPrice)/(this.anchorPrice*e),i=GS(t(this.targetPrice));if(this.pricesCount>1){const e=GS(t(this.targetPrice2));this.probabilityAbove=1-i,this.probabilityBelow=e,this.probabilityBetween=i-e}else this.probabilityBelow=i,this.probabilityAbove=1-this.probabilityBelow;this.computed=!0}compute(){this.haveInput&&this.haveData&&(this.getData(),this.computeProbabilities())}getElements(){if(this.computed||this.compute(),!this.computed||!this.studyPlot.mainCurve.visible)return[];const e=[];return e.push(new oA(this.points[0].point,!0,this.axis)),e.push(new oA(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new oA(this.points[1].point,!1,this.axis)),e}getStyleForElement(e,t){return this.styles.length||this.makeStyles(),this.styles[t]}get hasPoint(){return this.points.length>0}getTimeScaleAdornments(){return this.hasPoint?[{time:this.points[0].time,color:this.traits.line.color}]:[]}getPriceScaleAdornments(){if(!this.hasPoint)return[];const e=[];return e.push({price:this.points[0].price,color:this.traits.line2.color}),this.pricesCount>1&&e.push({price:this.points[1].price,color:this.traits.line2.color}),e}adornElements(e,t){if(this.computed){const[e,i]=[!0,!1].map(e=>Math.abs(Nn(t,e))),s=this.pricesCount>1,n=this.points[0].point,r=s?this.points[1].point:n,o=this.traits.line2.color,a=Ln(o),l=Rn(t),c=["Above","Below","Between"],u=(e,t)=>`${se(100*e,2).toFixed(2)}% Probability ${c[t]}`,h=(e,i)=>Bn(t,e,i,g.Right,a,o);if(h(u(this.probabilityAbove,0),{x:n.x-10,y:n.y-e}),s){const e=n.y+(r.y-n.y+l)/2;h(u(this.probabilityBetween,2),{x:n.x-10,y:e})}h(u(this.probabilityBelow,1),{x:r.x-10,y:r.y+i})}}}const YS=new class{resizingPanes=!1;snapToSupported=!1;touchCrosshairMode=!1;notifyZoomChanged;previousTouchTimestamp=null;resizingScale=!1;resizingScaleId=null;lastScaleResizingOffset=null;touchCrosshairTimeout=null;lastResizingOffset=null;splitter;prevZoomingOffset;prevPinchDistance=null;constructor(){this.stopResizingScale(),this.notifyZoomChanged=Q(qa.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,i){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,i)}activated(){}deactivated(){}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return gs.EVENT_PIN_HIT;const t=e.presenter.selectedAnnotation;let i;void 0!==t&&(i=t.points.find(t=>t.hitTest(e.point)));let s=k(e.axis.annotations.filter(t=>t.computed?null:t.hitTest(e.point)));return void 0!==i&&null==s&&(s=t),[s,i]}stopResizingScale(){this.resizingScale=!1,this.resizingScaleId=null,this.lastScaleResizingOffset=null}resetVerticalAxis(e,t=!0){this.stopResizingScale(),e.isCustomDomain=!1,t&&e.setDomain()}resetHorizontalAxis(e,t=!0){e.view.xAxis.resetZoom(),t&&e.view.setPriceAxesDomains(),this.fireZoomChanged(e)}fireZoomChanged(e){this.notifyZoomChanged({chart:e.accessor})}onMouseDblClick({priceAxis:e,offset:t,presenter:i,view:s}){const n=s.xAxis.viewBox.contains(t);let r=!1;if(ie(e))this.resetVerticalAxis(e),r=!0;else if(n)this.resetHorizontalAxis(i),r=!0;else if(q()){const e=i.selectedAnnotation;null!=e?qA(e,t):XA(i,t)}r&&s.redraw()}onMouseEnter(){this.previousTouchTimestamp=null}computePreviousTouchStartDuration(){if(!q())return null;const e=/* @__PURE__ */(new Date).getTime(),t=ie(this.previousTouchTimestamp)?e-this.previousTouchTimestamp:null;return this.previousTouchTimestamp=e,t}onMouseDown(e){const{point:t,button:i,splitter:s,offset:n,priceAxis:r,presenter:o,originalEvent:a}=e,l=window.navigator.platform.toLowerCase().startsWith("mac"),c=l?S.Meta:S.Control,u=i===A.Right||l&&i===A.Left&&e.getModifier(S.Control);this.touchCrosshairMode&&ie(this.touchCrosshairTimeout)&&(clearTimeout(this.touchCrosshairTimeout),this.touchCrosshairTimeout=null);const h=this.computePreviousTouchStartDuration();if(ie(h)&&h<gs.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(n)&&o.notifyHost(qa.CH_LOGOCLICKED,{chart:o.accessor}),ie(t)&&o.allPlots.some(e=>e.tryHandleCustomEventClick(t.point)))return!0;if(ie(s))return this.resizingPanes=!0,this.lastResizingOffset=n,this.splitter=s,o.enableTooltip(!1),!0;if(ie(r)){return re(o.display.chart.zooming)[0]&&this.startAxisScaling(r,n),!0}if(null!=t){if(e.getModifier(c))return o.activeTool=new KA,o.activeTool.onMouseDown(e),!0;const[i,s]=this.findHit(t);if(o.clearSelection(),null!=i&&o.setSelection(i),null==i||i?.locked)return u?(this.hideCrosshairAndTooltips(o.view),null==i?XA(o,n,a):i?.locked&&qA(i,n),!0):!!this.touchCrosshairMode||(o.activeTool=new $A(t),o.activeTool.startPan(n),UA());const r=null!=s;if(u)return qA(i,n),q();{if(r&&!s.movable||!r&&!i.canMove(t.point))return!1;const e=r&&-1!==i.points.indexOf(s);return o.activeTool=e?new rA(i,s):new nA(i,t,n),q()}}return this.prevZoomingOffset=n,!1}onContextMenu(e){return!0}isLogoLink(e){const t=te(GA)&&GA.logoClickable?GA.rect:null;return ie(t)&&t.contains(e)}onMouseMove(e){const{point:t,splitter:i,priceAxis:s,view:n,presenter:r,offset:o}=e;if(ie(e.pinchZoom)&&e.pinchZoom&&ie(e.pinchDistance))return ie(this.prevPinchDistance)&&(e.delta=this.prevPinchDistance-e.pinchDistance,this.onWheel(e)),this.prevPinchDistance=e.pinchDistance,q();if(null!=i||this.resizingPanes)n.setCursor(y.ResizeVertical),this.resizingPanes&&this.resizePanes(n,o);else if(ie(t)){const[e,i]=this.findHit(t);ie(i)?t.presenter.view.setCursor(y.Crosshair):ie(e)?e.isSelected?t.presenter.view.setCursor(y.Move):t.presenter.view.setCursor(y.Hand):t.presenter.view.setCursor(y.Arrow)}else if(ie(s)){re(r.display.chart.zooming)[0]&&(n.setCursor(y.ResizeVertical),this.performAxisScaling(n,s,o))}else{if(this.prevZoomingOffset){const{x:e}=this.prevZoomingOffset,{x:t}=o,i=e-t;this.applyZoom(n.presenter,-i),this.prevZoomingOffset=o}n.setCursor(y.ResizeHorizontal)}return!t||this.resizingPanes?(this.hideCrosshairAndTooltips(n),q()):(this.isLogoLink(o)&&n.setCursor(y.Hand),this.showCrosshairAndTooltips(n,t,o),q())}showCrosshairAndTooltips(e,t,i){if(t.time&&(!q()||this.touchCrosshairMode)){e.drawCrosshair({ap:t,offset:i})&&e.presenter.showTooltip&&BA(e.presenter,{time:t.time,offset:i,price:t.price,lastBarRefresh:void 0,justMain:void 0})}}hideCrosshairAndTooltips(e,t=!1){e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&"cards"===e.tooltip.mode&&!e.presenter?.hasLegend&&HA(e.presenter)}onMouseLeave(e){const{view:t,offset:i}=e,s=t.presenter.accessor.getPaneBounds(),n=s?.every(e=>{return!e.contains(i)||(t=e,(s=i).x===t.x||s.x===t.x+t.width||s.y===t.y||s.y===t.y+t.height);var t,s});n&&(this.hideCrosshairAndTooltips(t,!0),this.stopResizeZoom(t.presenter)),t.setCursor(y.Arrow),this.touchCrosshairMode=!1}stopResizeZoom(e){this.resizingPanes&&(this.resizingPanes=!1,e.enableTooltip(!0),e.onPaneHeightsUpdated()),this.resizingScale&&this.stopResizingScale(),this.prevZoomingOffset&&delete this.prevZoomingOffset}onMouseUp({presenter:e}){if(this.stopResizeZoom(e),q()){const t=function(){const e=Gv().config.touchCrosshairTimeoutMillis;return ie(e)&&Number.isFinite(e)?e:gs.LONG_PRESS_TIMEOUT_MILLIS}();this.touchCrosshairTimeout=window.setTimeout(()=>{this.hideCrosshairAndTooltips(e.view,!0),this.touchCrosshairMode=!1},t)}}applyZoom(e,t,i=!0){if(!re(e.display.chart.zooming)[1])return;const s=Math.sign(t)*(q()?2:10),n=e.view;n.xAxis.zoom(s)&&(n.setPriceAxesDomains(),n.redraw(),i&&this.fireZoomChanged(e))}onWheel({view:e,presenter:t,getModifier:i,delta:s}){const{scrollBehavior:n}=t.display;return!(!(q()?"none"!==n:"wheel"===n||"wheel+shift"===n&&i(S.Shift))||0===s)&&(e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(),this.applyZoom(t,s),!0)}get useKeyboardShortcuts(){return Gv().config.hostingModel!==b[b.Application]}onKeyDown(e){const{key:t,code:i,presenter:s}=e;if(ie(s.selectedAnnotation)&&function(e,t){return"Backspace"===e||"Delete"===e||8===t||46===t}(t,i)){const e=s.selectedAnnotation;e.axis.deleteAnnotation(e),s.onAnnotationModifiedByTool(e,E.Deleted)}if(ie(s.selectedAnnotation)&&(X(t,i)?s.clearSelection():function(e,t){return"F2"===e||113===t}(t,i)&&s.selectedAnnotation instanceof CA&&s.selectedAnnotation.textEditable&&(s.activeTool=new xA(null,s.selectedAnnotation),s.activeTool.startEditing())),Z(t,i)||function(e,t){return"ArrowRight"===e||39===t}(t,i)){const e=Z(t,i)?1:-1,n=s.view;n.xAxis.pan(e*n.xAxis.xScale.bar.totalWidth),this.hideCrosshairAndTooltips(n),n.redraw()}const n=window.navigator.platform.toLowerCase().startsWith("mac")?S.Meta:S.Control;if(e.getModifier(n)&&this.useKeyboardShortcuts){const e=function(e,t){return"z"===e||90===t}(t,i),n=function(e,t){return"y"===e||89===t}(t,i);return e&&s.undoRedoManager.undo(),n&&s.undoRedoManager.redo(),e||n}(function(e,t){return"r"===e||82===t})(t,i)&&e.getModifier(S.Alt)&&this.resetView(s)}resetView(e){e.allAxes.forEach(e=>this.resetVerticalAxis(e,!1)),this.resetHorizontalAxis(e,!1),e.view.xAxis.goToLatest(!0)}resizePanes(e,t){const i=t.y-this.lastResizingOffset.y;if(0===i)return;const s=e.presenter.panes,[n,r]=this.splitter,o=s.map((e,t)=>{const s=e.getBounds().height;return t===n?s+i:t===r?s-i:s});if(o.some(e=>e<gs.MINIMUM_PANE_HEIGHT))return;const a=(e,t)=>e+t,l=o.reduce(a,0),c=s.map(e=>e.height).reduce(a,0);s.forEach((e,t)=>e.height=se(o[t]/l*c,4)),this.lastResizingOffset=t,e.recalculateLayout(),e.redraw()}startAxisScaling(e,t){this.resizingScale=!0,this.resizingScaleId=e.id,this.lastScaleResizingOffset=t}performAxisScaling(e,t,i){if(this.resizingScale&&this.resizingScaleId===t.id){const s=q()?4:5,n=function(e,t,i,s=1,n=-1){const r=(i.y-t.y)/10,o=e.yScale.rangeWithPadding().reverse();return[o[0]+r*s,o[1]+r*n].map(t=>e.yScale.yToPrice(t))}(t,this.lastScaleResizingOffset,i,s,-s);this.lastScaleResizingOffset=i,t.isCustomDomain=!0,t.yScale.domain(n),e.redraw()}}},jS=e=>QS(ZA,CS,1,e),KS=e=>QS(ZA,bA,1,e),qS={Default:()=>function(){return YS},Line:()=>QS(LA,sS,!1),DateRange:()=>QS(LA,IS,!1),PriceRange:()=>QS(LA,DS,!1),DatePriceRange:()=>QS(LA,OS,!1),GannBox:()=>QS(LA,wS,!1),GannSquare:()=>QS(_A,VS),Ray:()=>QS(LA,sS,!1),GannLine:()=>QS(MA,sS,!1),VerticalLine:()=>QS(ZA,nS,1),HorizontalLine:()=>QS(ZA,rS,1),LongPosition:()=>QS(ZA,_S,1,!0),ShortPosition:()=>QS(ZA,_S,1,!1),FiftyPercentLine:function(e,t){return ie(e)?QS(JA,oS,e.axis||t.mainAxis,e):QS(ZA,oS,2)},FibonacciRetracement:()=>QS(LA,lS,!1),TrendBasedFibExtension:()=>QS(LA,cS,!0),FibonacciFan:()=>QS(LA,dS,!1),FibonacciArcs:()=>QS(LA,gS,!1),FibonacciChannel:()=>QS(LA,BS,!0),GannFan:()=>QS(LA,yS,!1),SpeedResistanceFan:()=>QS(LA,AS,!1),SpeedResistanceArcs:()=>QS(LA,SS,!1),AndrewsPitchfork:()=>QS(ZA,TS,3),Rectangle:()=>QS(LA,zA,!1),Ellipse:()=>QS(LA,vS,!1),TrendChannel:()=>QS(LA,PS,!0),SymbolArrowUp:()=>jS("arrow_up"),SymbolArrowDown:()=>jS("arrow_down"),SymbolArrowRight:()=>jS("arrow_right"),SymbolArrowLeft:()=>jS("arrow_left"),SymbolArrowHorizontal:()=>jS("arrow_horizontal"),SymbolArrowVertical:()=>jS("arrow_vertical"),SymbolArcDown:()=>jS("arc_down"),SymbolArcUp:()=>jS("arc_up"),SymbolThumbsUp:()=>jS("thumbs_up"),SymbolThumbsDown:()=>jS("thumbs_down"),SymbolZero:()=>jS("zero"),SymbolOne:()=>jS("one"),SymbolTwo:()=>jS("two"),SymbolThree:()=>jS("three"),SymbolFour:()=>jS("four"),SymbolFive:()=>jS("five"),SymbolSix:()=>jS("six"),SymbolSeven:()=>jS("seven"),SymbolEight:()=>jS("eight"),SymbolNine:()=>jS("nine"),SymbolQuestion:()=>jS("question"),SymbolFishHook:()=>jS("fish_hook"),SymbolBuy:()=>jS("buy"),SymbolSell:()=>jS("sell"),FibonacciTimeZones:()=>QS(LA,bS,!1),Text:()=>QS(xA,CA,null),PickPoint:()=>function(){return new ES},ZoomIn:()=>function(){return new KA},ProfitLoss:KS,RewardRisk:KS,VolumeAtPrice:function(e){return QS(ZA,FS,2,e)},ZigZag:function(e){return QS(JA,WS,null,e)},ProbabilityCones:function(e){return QS(ZA,zS,2,e)},LinearRegressionChannel:function(e){return QS(JA,$S,null,e)}};function XS(e,t=!1,i=null,s=null,n=null){let r=qS[e];return r=r(s,n),r(e,t,i)}function ZS(e,t={}){e.enableTooltip(!0),e.resetActiveTool();const{axis:i,annotation:s,toolChange:n,annId:r}=t;ie(i)&&e.onAnnotationsUpdated(i),ie(s)&&e.onAnnotationModifiedByTool(s,n),[E.Cancelled,E.Executed,E.TextChanged].includes(n)&&e.onAnnotationDone(r,n)}function JS(e,t=!0,i=E.None){e.wasModifiedByTool();const s=e.axis,n={axis:s,annotation:e,toolChange:i};ZS(s.pane.presenter,t?n:void 0)}function QS(e,t,i,s){return function(n,r,o){const a=dA(n,t,s,o);return a.annName=n,r?a:new e(a,i)}}function eT(e){e.button===A.Right&&ZS(e.presenter)}function tT(e,t,i){const s={};s.source=Ka[e.source],s.inputs=fe(e.inputs);const n=void 0!==e.target,r=ie(i)?i:e.curves,o=n?[Ka[e.target]]:r.map(e=>e.fields).flat();return s.outFields=function(e){const t=[];for(const i of e)t.includes(i)||t.push(i);return t}(o),s.target=n?Ka[e.target]:s.outFields[0],s.aggregation=t,s}class iT extends Qy{model;basePlot;_hasEvents;_params;_shiftFmt;_title;range;shouldMaybePriceMap;annIndex;_canPriceMap;#e(e=3){let t=this.model.inputs||[];const i=t.length;if(0===i)return"";let s="";i>e&&(t=t.slice(0,3),s=", ...");const n="AVWAP"===this.model.study;return 0===t.length?"":`(${t.map(e=>n&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value).join(", ")}${s})`}get params(){return ie(this._params)||(this._params=this.#e()),this._params}get fullParams(){return this.#e(Number.MAX_VALUE)}get shiftFmt(){if(!("PC"!==this.model.study))return"";if(!ie(this._shiftFmt)){const e=this.curves.map(e=>Number(e.shift)).filter(e=>0!==e);this._shiftFmt=0===e.length?"":`[${e.join(", ")}]`}return this._shiftFmt}get title(){if(!ie(this._title)){const e=this.params,t=this.shiftFmt;this._title=`${this.model.study} ${e} ${t}`.trim()}return this._title}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(){const e=Ur(this.model.study),t=e.meta.decimals;this.metaData=void 0!==t?new Qs(t):this.basePlot.metaData,ie(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){const e=this.model?.study;return"VOL"===e&&this.axis?.pane.isMain?gs.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){const t=this.model.study;!0===Ur(t).meta.shiftable&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});const i=(e,t,i)=>this.curves[e].zones[t].value=this.model.levels[i].value;switch(t){case"ICHCLD":{const t=e.inputs.Displacement;this.curves[2].shift=-t,this.curves[3].shift=t,this.curves[4].shift=t,this.curves[5].shift=t;break}case"MARIB":{const t=Math.min(Math.max(0,e.inputs.Count),10);this.curves.forEach((e,i)=>e.visible=e.visible&&i<t);break}case"CRS":{const t="PercentChange"===e.inputs.Display;this.axis.comparison=t?d.Percent:d.None;break}case"PERF":{const t="VisibleStart"===e.inputs.Anchor;this.axis.comparison=t?d.Percent:d.None;break}case"JPI":case"CTTP":case"CTTI":{const t=Y(10,e=>.025*(e+1)),i=e=>t.map(t=>Cn(t)(e)),s=([e,t])=>[...i(e).reverse(),t,"#6a4a3a","#a000c8","#ffffff"];this.curves[0].colors=s(this.curves[0].colors),this.curves[1].colors=s(this.curves[1].colors);const n=this.curves[0].colors.length;this.curves[0].colors[n-1]=this.curves[1].colors[t.length],this.curves[1].colors[n-1]=this.curves[0].colors[t.length],this.shouldMaybePriceMap="Performance"===e.inputs.Height;break}case"RSI":case"RSIMOD":case"RSISTO":case"CCI":i(0,0,0),i(0,1,2);break;case"STC":i(0,0,0),i(0,1,1);break;case"RVOL":case"DPO":case"COPP":i(0,0,0);break;case"VOL":this.setCurveAttributes(0,e.inputs.BarColoring);break;case"MAVOL":this.setCurveAttributes(1,e.inputs.BarColoring);break;case"VOLAP":{this.notifyAboutPriceDomains=!0,this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=this.curves[1],i=this.curves[2],s=XS("VolumeAtPrice",!0,{[gs.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[gs.AT_FILL]:{color:this.curves[0].colors[0]},[gs.AT_FILL2]:{color:this.curves[0].colors[1]},[gs.AT_FILL3]:{color:this.curves[0].colors[2]},[gs.AT_FILL4]:{color:i.colors[0]},[gs.AT_FILL5]:{color:i.colors[1]},[gs.AT_FILL6]:{color:i.colors[2]}},this.id)(this.axis,!1);s.setOptions(e.inputs),this.annIndex=this.annotations.push(s)-1;break}case"PVACP":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=this.curves[1],i=this.curves[2],s=this.curves[3],n=XS("VolumeAtPrice",!0,{[gs.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[gs.AT_FILL]:{color:this.curves[0].colors[0]},[gs.AT_FILL2]:{color:this.curves[0].colors[1]},[gs.AT_FILL3]:{color:this.curves[0].colors[2]},[gs.AT_FILL4]:{color:i.colors[0]},[gs.AT_FILL5]:{color:i.colors[1]},[gs.AT_FILL6]:{color:i.colors[2]},[gs.AT_FILL7]:{color:s.colors[0]}},this.id)(this.axis,!1);n.setOptions(e.inputs),this.annIndex=this.annotations.push(n)-1;break}case"ZIGZAG":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=XS("ZigZag",!0,{[gs.AT_LINE]:{color:this.curves[0].colors[0],width:this.curves[0].lineWidth,dashStyle:this.curves[0].dashStyle??"Solid"}},this.id)(this.axis,!1);t.setOptions(e.inputs),this.annIndex=this.annotations.push(t)-1;break}case"LINRCHN":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const e=this.curves[0],t=this.curves[1],i=this.curves[2],s=this.curves[3],n=this.curves[4],r=XS("LinearRegressionChannel",!0,{[gs.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??"Solid"},[gs.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??"Solid"},[gs.AT_LINE_3]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle??"Solid"},[gs.AT_FILL]:{color:s.colors[0]},[gs.AT_FILL2]:{color:n.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(r)-1;break}case"IVRANK":{let t=Ka.ImplVolRank1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=Ka.ImplVolRank5D;break;case"1-Month":t=Ka.ImplVolRank1M;break;case"3-Month":t=Ka.ImplVolRank3M;break;case"6-Month":t=Ka.ImplVolRank6M;break;case"YTD":t=Ka.ImplVolRankYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"IVPCTL":{let t=Ka.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=Ka.ImplVolPerc5D;break;case"1-Month":t=Ka.ImplVolPerc1M;break;case"3-Month":t=Ka.ImplVolPerc3M;break;case"6-Month":t=Ka.ImplVolPerc6M;break;case"YTD":t=Ka.ImplVolPercYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"OPTIV":{let t=[Ka.WeighImplVolHigh,Ka.WeighImplVol,Ka.WeighImplVolLow];switch(e.inputs.TimeFrame){case"1-Day":default:break;case"5-Day":t=[Ka.WeighImplVolHigh5D,Ka.WeighImplVol5D,Ka.WeighImplVolLow5D];break;case"1-Month":t=[Ka.WeighImplVolHigh1M,Ka.WeighImplVol1M,Ka.WeighImplVolLow1M];break;case"3-Month":t=[Ka.WeighImplVolHigh3M,Ka.WeighImplVol3M,Ka.WeighImplVolLow3M];break;case"6-Month":t=[Ka.WeighImplVolHigh6M,Ka.WeighImplVol6M,Ka.WeighImplVolLow6M];break;case"1-Year":t=[Ka.WeighImplVolHigh1Y,Ka.WeighImplVol1Y,Ka.WeighImplVolLow1Y];break;case"YTD":t=[Ka.WeighImplVolHighYTD,Ka.WeighImplVolYTD,Ka.WeighImplVolLowYTD]}this.curves[0].fields[0]=t[0],this.curves[1].fields[0]=t[1],this.curves[2].fields[0]=t[2],e.outFields=[...t];break}case"PC":{const t=e.inputs.PeriodForecast-1;this.curves.forEach(e=>e.shift=t),ie(this.annotations)||(this.annotations=[]);const i=this.curves[11],s=this.curves[12],n=XS("ProbabilityCones",!0,{[gs.AT_LINE]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle},[gs.AT_LINE_2]:{color:s.colors[0],width:s.lineWidth,dashStyle:s.dashStyle}},this.id)(this.axis,!1);n.setOptions(e.inputs),this.annIndex=this.annotations.push(n)-1;break}}}getValueAt(e,t,i){if(!this.isVolAP)return super.getValueAt(e,t,i);return this.annotations[this.annIndex].getValueAt(e,t,i)}getColorOf(e){if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;const t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case Ka.UPVOL:return t[1];case Ka.DNVOL:return t[0];case Ka.TOTVOL:return t[2];case Ka.POC:case Ka.VAREA:case Ka.BARBACK:return gs.COLOR_TRANSPARENT;case Ka.LINRUP:return t[0];case Ka.LINRMID:return this.curves[1].colors[0];case Ka.LINRLOW:return this.curves[2].colors[0];default:throw new Error("Unexpected Volume At Price field")}}isEmpty(){return!(this.isVolAP||this.isZigZag||this.isLinRegChannel)&&super.isEmpty()}setCurveAttributes(e,t){const i=t=>this.curves[e].attributes=[r[t]];switch(t){case"LikeMain":{const t=this.axis.pane.presenter.mainPlot.curves[0].attributes,s=Gv().config.defaultVolumeBarColoring;if(ie(t))this.curves[e].attributes=[t[0]];else if(ie(s)){i("OpenToClose"===s?"OpenVsClose":"ChangeBased")}else i("OpenVsClose");break}case"OpenToClose":i("OpenVsClose");break;case"CloseToClose":i("ChangeBased");break;default:throw new Error(`Unexpected bar coloring choice: ${t}`)}}get hasEvents(){return this._hasEvents}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){const e=this.timeSeries.helpers;return e.includes(Ka.Buy)||e.includes(Ka.Sell)}getEventFor(e){switch(e){case Ka.Buy:return{show:!0,title:"B",color:"#03c03c"};case Ka.Sell:return{show:!0,title:"S",color:"#c23b22"};default:return null}}getEventFields(){return this.hasEvents?[Ka.Buy,Ka.Sell]:[]}async initialize(){if(this.model.basis!==gs.BASIS_MAIN)throw new Error("Studies can currently only be based on the main (symbol) plot");return ps.call(this,async()=>{this.basePlot=this.axis.pane.presenter.mainPlot,await this.basePlot.initialize(),this.getMetaData();const e=this.axis.pane.presenter.data.aggregation,t=tT(this.model,e,this.curves);this.applySpecifics(t);let i=this.basePlot.timeSeries;i instanceof dp&&(i=i.actual),this.timeSeries=ny(this.model.study,t,i),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;const s=this.title,n=this.basePlot.timeSeries instanceof bh;return this.timeSeries.ready().then(e=>{e||n||this.timeSeries.computedServerSide||Hv(`Unable to calculate study values for ${s}`,"error")}),!0})}get isJpi(){return["JPI","CTTP","CTTI"].includes(this.model.study)}get isVolAP(){return"VOLAP"===this.model.study||"PVACP"===this.model.study}get isZigZag(){return"ZIGZAG"===this.model.study}get isLinRegChannel(){return"LINRCHN"===this.model.study}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[this.annIndex].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations("PriceDomainsChanged")}shouldPriceMap(e){return this.isJpi?!!this.shouldMaybePriceMap&&(e.id===Ka.JPIB.id||e.id===Ka.JPIS.id):super.shouldPriceMap(e)}canPriceMap(e,t){if(!this.isJpi)return super.canPriceMap(e,t);this._canPriceMap=e>0}priceMap(e,t,i){if(!this.isJpi)return super.priceMap(e,t,i);if(t>this.visToIndex)return e;const s=(e,t)=>this.timeSeries.container.getData(e)[t],n=s(Ka.JPIB,t),r=s(Ka.JPIS,t);if(null===n&&i.id===Ka.JPIB.id||null===r&&i.id===Ka.JPIS.id)return null;let o=0,a=this.visFromIndex;const l=this.timeSeries.helpers[0],c=this.timeSeries.helpers[2];for(;a<=t;){o+=1===s(c,a)?0:s(l,a),a++}return o}}const sT=[Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Volume];class nT extends Qy{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){const e=ca(this._expression);if(this.exprModel=null,this.symbols=null,la(e))this.errorText=e.error;else{const{model:t,clean:i,symbols:s}=e;this.errorText=void 0,this.symbols=s,this.exprModel=t,this._expression=i}}get isValid(){return!ie(this.errorText)}#t(e){return{mapper:e=>e.query.symbol,loadMoreData:!0,recompute:i.Minimum,missing:t.UseNext,stretch:e=>!1,fieldMap:new Map(sT.map(e=>[e,e])),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:e}}getTimeSeries(){const e=this.getInnerSeries(),t=this.axis?.pane.presenter.data?.exprSkipLeadingEmpty??!1,i=new Vm(this.exprModel,e,this.#t(t));this.timeSeries=this.wrapIfAdvancedStyle(i);const s=this.title;this.timeSeries.ready().then(e=>{e||Hv(`Unable to calculate expression: ${s}`,"error")})}getInnerSeries(){const e=pa(this.exprModel),t=Gv().getTimeSeriesDataSource();return e.map(e=>{const i=this.makeQuery();return i.symbol=e,t.getTimeSeries(i)})}getRecord(){if(ie(this.errorText))return;const e=this.metaData.inner.map(e=>[e.symbol,e.resolved]);this.record=new hl(e,ue(this.exprModel)),this.record.ready().then(e=>e)}getMetaData(){this.isValid&&(this.metaData=new tn(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return ps.call(this,async()=>(await this.parseExpression(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}class rT extends Qy{suffix;_forward;offset;errorText;fwdModel=null;outField;roots=null;symbols=[];get title(){return`${this.forward}${this.suffix}`}get forward(){return this._forward}fromModel(e){super.fromModel(e);const t=e;this.offset=t.offset,this._forward=t.forward}async parseForward(){const e=ca(this.forward),t=la(e);if(t?(this.errorText=e.error,this.fwdModel=null,this._forward=e.text):(this.errorText=void 0,this.fwdModel=e.model,this._forward=e.clean),t)this.roots=null;else{this.offset>0?(this.suffix=` (${x(mu(this.offset),fu(gs.FMT_US_DATE_ONLY))(/* @__PURE__ */new Date)})`,this.outField=new Ga(`Close_${this.offset}`,c.Number,h.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix="",this.outField=Ka.Close);const t=e=>Fi(`${e}*1`),{yes:i,no:s}=V(e.symbols,t),n=(await Promise.all(i.map(e=>Xi(e)))).map(e=>e.map(e=>e.name));this.roots=i.reduce((e,t,i)=>(e[t]=n[i],e),{}),this.symbols=s}}get isValid(){return!ie(this.errorText)}getMetaData(){if(this.isValid){const e=Object.values(this.roots).flat();this.metaData=new tn(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}}getForwardPolicy(e){return{mapper:e=>e.query.root,loadMoreData:!1,recompute:i.Everything,missing:t.UseNext,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,this.outField]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1,valueProvider:e}}getTimeSeries(){const e=Gv().getTimeSeriesDataSource(),t=Object.keys(this.roots),i=0===this.offset?m.Forward:m.HistoricalForward,s=t.map(t=>{const s={seriesKind:i,root:t,offset:this.offset,symbols:this.roots[t],getHashKey:()=>`${i}|${t}|${this.offset}`};return e.getTimeSeries(s)}),n=this.symbols.length>0?new Ih(this.symbols):void 0;this.timeSeries=new Vm(this.fwdModel,s,this.getForwardPolicy(n)),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e)}})}async initialize(){return ps.call(this,async()=>(await this.parseForward(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}const oT=e=>e.substring(0,e.lastIndexOf("::"));class aT extends Qy{isAverage;hasComputation;offset;offsets;_seasonal;symbolToOffset;errorText;seaModel=null;isPlain=!1;isFutures=!1;suffix="";outField;symbols;coreModel;coreHasComputation;refSeasonal;get title(){if(this.isAverage){let e="YB ";return this.offset<-1&&(e=`${Math.abs(this.offset)}y `),`${e}Average`}return!this.hasComputation&&(this.symbols?.length??0)>0?this.outField.name:`${this.seasonal}${this.suffix}`}get seasonal(){return this._seasonal}fromModel(e){super.fromModel(e);const t=e;this.offset=t.offset,this.offsets=t.offsets,this.isAverage=t.offset<0,this._seasonal=this.refSeasonal=t.seasonal}constructSeasonal(e,t){return da(ma(e,e=>this.applyOffset(e,t)))}constructAverage(e,t=null){const i=null===t?null:t.map(e=>this.symbolToOffset[e]),s=null===i,n=this.offsets.filter(e=>!!s||i.includes(e)).map(t=>`(${this.constructSeasonal(e,t)})`);return`(${n.join("+")})/${n.length}`}prepareFields(){const e=this.isPlain?`${this.yearFromOffset(this.offset)}`:`${this.offset}Y`,t=this.isAverage?"Avg":e;this.suffix=0===this.offset?"":` (${t})`,this.outField=new Ga(`Close_${t}`,c.Number,h.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:es(e,-t)}::${t}`}createSymbolToOffsetMapping(e){this.symbolToOffset={},e.forEach(e=>{this.offsets.forEach(t=>{this.symbolToOffset[this.applyOffset(e,t)]=t})})}async parseSeasonal(){const e=ca(this.seasonal,!0),t=e=>(this.errorText=e,this.seaModel=null,null);if(la(e))return t(e.error);let{model:i,symbols:s}=e;this.prepareFields();const n=/* @__PURE__ */new Map;for(const h of s){const e=Yi(await Hi(h));n.set(h,e)}i=ma(i,e=>n.get(e)),s=Array.from(n.values());const r=s.every(e=>Fi(e)||Wi(e)),o=s.every(e=>$i(e)),a=s.every(e=>!Fi(e)&&!$i(e)&&!Wi(e));if(!r&&!o&&!a)return t("Mixed types of symbols aren't supported yet");this.isPlain=a,this.isFutures=r,this.createSymbolToOffsetMapping(s),this.coreModel=this.isAverage?i:null,this.coreHasComputation=fa(i);const l=this.isAverage?this.constructAverage(i):this.constructSeasonal(i,this.offset),{model:c,symbols:u}=ca(l,!0);this.seaModel=c,this.hasComputation=fa(c),this._seasonal=da(ma(c,oT)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!ie(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(oT))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){const e=oT(this.symbols[0]);if(this.isPlain)return`${e} ${/* @__PURE__ */(new Date).getFullYear()-this.offset}`;if(this.isFutures)return Yi(e,!0)}return this.title}getMetaData(){if(this.isValid){const e=this.getActualSymbols(),t=1===e.length&&!this.hasComputation&&!this.isAverage,i=Gv().getMetaDataSource();this.metaData=t?i.getMetaData(e[0]):new tn(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}}getNoDataApproach(){return this.isAverage&&!this.coreHasComputation?s.ModelTransformRequired:this.hasComputation?s.NoAction:s.IgnoreTimelineOnly}get seasonalPolicy(){return{mapper:e=>e.query.surrogate||e.query.symbol,loadMoreData:!1,recompute:i.Everything,missing:this.hasComputation?t.UsePrevious:t.UseNone,stretch:e=>this.shouldStretch(e),fieldMap:/* @__PURE__ */new Map([[Ka.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>{if(0===t.length)return this.seaModel;return ca(this.constructAverage(this.coreModel,e)).model},skipLeadingEmpty:!1}}shouldStretch(e){return 0===this.symbolToOffset[e]&&(this.isAverage&&this.symbols.length>1||this.offset>0)}shiftYears(e){return lt(/* @__PURE__ */new Date,-e)}yearFromOffset(e){return Pi(this.shiftYears(e))}getCmdtyRange(e){const t=this.shiftYears(e);return[Mt(t),Lt(t)]}getTimeSeries(){if(!this.isValid)return;const e=Gv().getTimeSeriesDataSource(),t=Object.keys(this.symbolToOffset).map(t=>{const i=this.makeQuery();return i.surrogate=t,i.symbol=oT(t),i.offset=this.symbolToOffset[t],i.cacheMe=!this.isPlain||0===i.offset,this.isPlain&&(i.range=this.getCmdtyRange(i.offset)),this.isFutures&&i.offset>0&&ie(...i.range)&&(i.range=i.range.map(e=>lt(e,-i.offset))),i.offset>0&&(i.disableStreamingUpdates=!0),e.getTimeSeries(i)});this.timeSeries=new Vm(this.seaModel,t,this.seasonalPolicy),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e)}})}async initialize(){return ps.call(this,async()=>(await this.parseSeasonal(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}const lT=["bottom","right","left"],cT={bottom:"center",right:"start",left:"end"};class uT{lineWidth;arrowLength;position;textAlign;fontSize;fontFamily;padding;strokeColor;textColor;backgroundColor;constructor(e){this.lineWidth=1,this.arrowLength=7,this.position="bottom",this.textAlign="center",this.fontSize=12,this.fontFamily="Arial",this.padding=4,this.strokeColor="white",this.textColor="white",this.backgroundColor="black",e&&this.configure(e)}configure(e){Object.assign(this,e)}draw(e,t,i,s,n,r){const o=ie(n);if(r=r||this.fontSize+this.padding+this.padding+(o?this.padding:0),!lT.includes(this.position.toLowerCase()))return void console.error(`Can not draw indicator in position [${this.position}]`);e.font=`bold ${this.fontSize}px ${this.fontFamily}`,e.textAlign=cT[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=Sn(this.backgroundColor),e.lineWidth=this.lineWidth;const a=[s,n??""].map(t=>e.measureText(t).width),l=Math.max(...a),c="bottom"!==this.position?this.arrowLength:0,u=Math.round(l+c+this.padding+this.padding),h=Math.round(u/2),d=Math.round(r/2);e.setLineDash([]);const p=t;e.beginPath(),e.moveTo(p,i);const f=i+d,m=i+2*d,g=i-d;if("right"===this.position){e.lineTo(p,f);const t=p+u;o&&(e.lineTo(p,m),e.lineTo(t,m)),e.lineTo(t,f),e.lineTo(t,g),e.lineTo(p,g)}else if("left"===this.position){e.lineTo(p,f);const t=p-u;o&&(e.lineTo(p,m),e.lineTo(t,m)),e.lineTo(t,f),e.lineTo(t,g),e.lineTo(p,i-d)}else if("bottom"===this.position){const t=p-h,s=p+h;e.lineTo(p,i),e.lineTo(s,i),e.lineTo(s,i+r),e.lineTo(t,i+r),e.lineTo(t,i),e.lineTo(p,i)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline="middle","bottom"===this.position)e.fillText(s,p,i+Rn(e,1));else if("right"===this.position){const t=p+this.arrowLength+this.padding;e.fillText(s,t,i),o&&e.fillText(n,t,i+this.padding+d)}else if("left"===this.position){const t=p-this.arrowLength-this.padding;e.fillText(s,t,i),o&&e.fillText(n,t,i+this.padding+d)}}}const hT=({y:e,halfHeight:t})=>e+t;const dT=({x:e,halfWidth:t})=>e-t-4,pT=({x:e,halfWidth:t})=>e+t+4,fT=(e,t)=>e-1-t-4,mT=(e,t)=>e+1+t+4;const gT=Array.from(Array(6),(e,t)=>++t).reverse();function yT(e){const t=e.plot.timeSeries.container;return null===t||t.size<1?null:e.getColor(t.size-1)}function AT(e){return e.curves.filter(t=>e.visible&&t.visible&&(e.type!==f.Study||t.style!==o.Ribbon)).map(t=>{const i=t.pickMainField(),[s,n]=function(e,t){const i=e.timeSeries.container;if(null===i||i.size<1)return[null,-1];let s=i.getLastDataPoint(t);const n=i.getData(t);let r=n.length-1;const o=e.type===f.Study&&["JPI","CTTP","CTTI"].includes(e.model.study);return null!=s||o||(r=H(n,e=>null!==e),s=-1!==r?n[r]:null),[s,r]}(e,i);return{value:s,color:yT(t),field:i,index:n}})}class ST{constructor(e){this.pane=e,this.id=Pe(),this.ticks=null,this.lastUsedOptions=null;const{chart:{fontSize:t},yAxis:{fontSize:i}}=this.pane.presenter.display,s=i||t||12;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:s},this.crosshairIndicator=new uT({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}annotations=[];id;isCustomDomain=!1;primary=!1;onTheRight=!0;viewBox;plots=[];comparison;scale;yScale;label="";crosshairIndicator;ticks;lastUsedOptions;config;_fullDomain;makePlot(e){let t=null;switch(f[e.type]){case f.Symbol:t=new eA;break;case f.Expression:t=new nT;break;case f.Study:t=new iT;break;case f.IncomeStatement:t=new tA(m.IncomeStatement);break;case f.BalanceSheet:t=new tA(m.BalanceSheet);break;case f.Forward:t=new rT;break;case f.Seasonal:t=new aT;break;default:throw new Error(`${e.type} isn't supported yet`)}return t.axis=this,t.fromModel(e),t}toPrice(e){const t=this.yScale.yToPrice(e);return this.comparison!==d.None?this.pane.presenter.mainPlot.priceMap(t,void 0,Ka.Close,!0):t}toTime(e){return this.pane.presenter.view.toTime(e)}toAnnotationPoint(e){const t=this.toPrice(e.y),i=this.toTime(e.x);return new aA(this,t,i||void 0)}toX(e){return this.pane.presenter.view.toX(e)}priceMap(e){return this.comparison!==d.None?this.pane.presenter.mainPlot.priceMap(e,void 0,Ka.Close):e}toY(e){const t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){const e=[];return this.plots.forEach(t=>{t.annotations&&e.push(...t.annotations)}),e}annTimeToX(e){return this.pane.presenter.view.xAxis?.annTimeToX(e)}snapTo(e){const t={x:this.annTimeToX(e.time),y:this.toY(e.price)},i=this.pane.presenter,s=i.activeTool,n=s.annotation;return s.alignPointsMode&&n&&n.alignPointsSupported&&n.points.includes(e)?this.alignPoints(n,e,t):!s.snapToSupported||!i.display.yAxis.snapAnnotationsToPrices||e.passive||e.moveDirection!==T.Both&&e.moveDirection!==T.Vertical||this.snapToPrices(e,t),t}snapToPrices(e,t){const i=this.plots.find(e=>e.main);if(i&&i.timeSeries&&i.timeSeries.hasData){const s=i.timeSeries.container,n=G(s.getTimeData(),+e.time,Number),r=Array().concat(...i.curves.map(e=>e.fields)).filter(e=>s.hasField(e)).map(e=>{const i=s.getData(e)[n],r=this.toY(i);return{priceSnap:i,ySnap:r,dist:Math.abs(r-t.y)}}).filter(e=>e.dist<=gs.SNAP_PROXIMITY_PIXELS).reduce((e,t)=>null===e||t.dist<e.dist?t:e,null);ie(r)&&(e.price=r.priceSnap,t.y=r.ySnap,e.time=s.getTimeData()[n],t.x=this.toX(e.time))}}alignPoints(e,t,i){const s=e.points.find(e=>e!==t);if(t!==s&&s&&s.point){const e=s.point,n=(360+180*-gn(e,i)/Math.PI)%360,r=22.5,o=n>90-r&&n<90+r||n>270-r&&n<270+r;if(n>360-r||n<r||n>180-r&&n<180+r)i.y=e.y,t.price=this.toPrice(i.y);else if(o)i.x=e.x,t.time=this.toTime(i.x);else{const s=Math.abs(i.x-e.x),n=e.y>i.y?-1:1;i.y=e.y+s*n,t.price=this.toPrice(i.y)}}}toPoint(e){if(ie(this.pane.presenter.view))return this.snapTo(e)}makeAnnotation(e,t=!0){const i=XS(e.id,!0,e.traits)(this,!1);t&&e.uid&&(i.uid=e.uid);const s=i.activePoints,n=e.points.length-s.length;return n>0&&i.addPoints(n),i.activePoints.forEach((t,i)=>{const s=e.points[i];ne(s.price)&&ne(s.time)&&t.update(s.price,s.time)}),i.visible=e.visible,i.locked=e.locked,i}expand(e){const t=[];switch(e.type){case"Forward":{const i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;for(let n=0;n<i.length;n++){const r=Object.assign({},e);r.curves=[i[n]],r.offset=s[n],t.push(r)}break}case"Seasonal":{const i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;const n=s.filter(e=>e>=0);for(let r=0;r<i.length;r++){const o=Object.assign({},e);o.curves=[i[r]],o.offset=s[r];const a=o.offset<0;if(a){const e=-1===o.offset;o.offsets=e?n:Y(Math.abs(o.offset),e=>e+1)}else o.offsets=[o.offset];(!a||o.offsets.length>1)&&t.push(o)}break}default:t.push(e)}return t}fromModel(e){this.comparison=d[e.comparison??"None"],this.scale=p[e.scale??"Linear"],this.yScale=new Yy(this.scale,this),this.label=e.label,this.plots=Array().concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e));const t=e.annotations||[];this.annotations=t.map(e=>this.makeAnnotation(e));const{chart:{fontFamily:i,backgroundColor:s},yAxis:{textColor:n,crosshair:{color:r},primaryOnTheLeft:o}}=this.pane.presenter.display,a=o??!1;this.onTheRight=this.primary&&!a||!this.primary&&a,this.crosshairIndicator.configure({position:this.onTheRight?"right":"left",fontFamily:i,strokeColor:r,textColor:n,backgroundColor:Cn(.15)(s)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){const t=this.makeAnnotation(e,!0);this.appendAnnotation(t),t.requestRedraw(),this.fireAnnotationsChanged()}appendAnnotation(e){-1===this.findIndex(e)&&this.annotations.push(e)}fireAnnotationsChanged(e=!1){this.pane.presenter.onAnnotationsUpdated(this,e)}deleteAnnotation(e,t=!0){e.isSelected&&this.pane.presenter.clearSelection();const i=this.findIndex(e);-1!==i&&this.annotations.splice(i,1),t&&this.fireAnnotationsChanged(!e.isSelected)}fliphorizontalAnnotation(e){e.flip(!0),this.fireAnnotationsChanged(!0)}flipverticalAnnotation(e){e.flip(!1),this.fireAnnotationsChanged(!0)}duplicateAnnotation(e){const t=e.axis,i=this.makeAnnotation(e.toModel(),!1);i.drawPoints(null,!0),i.offset({x:gs.ANN_DUPLICATE_OFFSET,y:gs.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(i),i.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&this.pane.presenter.clearSelection(),Co(e.name,t.traits),e.updateFrom(t.traits,t.extras,t.isUndoRedo?null:t.points,t.visible,t.locked),t.isUndoRedo&&ie(t.points)&&e.updateActivePoints(t.points),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(cA(e,E.Moved)),e.requestRedraw(),this.fireAnnotationsChanged()}setViewBox(e){this.viewBox=e;const{y:t,height:i}=this.viewBox;this.yScale.range([Math.floor(t),Math.floor(t+i)]),this.plots.forEach(t=>t.setViewBox(e))}get fullDomain(){return ie(this._fullDomain)||(this._fullDomain=this.getDataDomain().domain),this._fullDomain}updateFullDomain(e=null){if(null===e&&this.comparison!==d.None)return;const t=this.fullDomain;this._fullDomain=this.getDataDomain([e,e],t).domain}getPlotDataDomain(e,t,i){const s=e.timeSeries;if(!s.hasData)return{domain:null};const n=s.container,r=n.getTimeData(),a=e=>G(r,+e,Number),l=ie(t),c=l?a(t):0,u=ie(i),h=u?a(i):r.length-1,d=e.curves.map(e=>e.fields).flat().filter(e=>e.id!==Ka.Change.id),p=ie(e.targetFields);p&&d.push(...e.targetFields);const f={},m=t=>{const[i,s]=(t=>{const i=p?e.curves[0]:e.curves.find(e=>e.fields.includes(t));if(!ie(i)||0===i.shift)return[c,h];if(!ie(f[i.id])){const e=i.shiftedTimeDomain;if(!ie(e))return[c,h];f[i.id]=[a(e[0]),a(e[1])]}return f[i.id]})(t),r=n.getData(t),o=Math.max(i,0),l=Math.min(r.length-1,s);return r.slice(o,l+1).map((i,s)=>e.priceMapper(i,s,t))},g=[null,null],y=e=>e.id,A=new Set(F(n.fields,d,y).map(y));e.curves.filter(e=>e.visible).map(e=>{const t=e.fields.filter(e=>A.has(e.id));if(e.isStackedColumn){j(z(t.map(e=>m(e)).reduce((e,t)=>t.map((t,i)=>(e[i]||0)+(t||0)),[])),g)}else t.map(e=>{const t=(e=>z(m(e)))(e);j(t,g)})});let S=L.None;const T=[o.Column,o.MultiColumn,o.StackedColumn];if(l&&u&&!e.main&&e.curves.some(e=>T.includes(e.style))){const e=g[0]>0,t=g[1]<0;e?(S=L.Min,g[0]=0):t&&(S=L.Max,g[1]=0)}return{domain:g,clamped:S}}getDataDomain([e,t]=[null,null],i=[null,null]){const s=ue(i);let n=!1;for(const c of this.plots.filter(e=>!e.hasDetachedScale)){const{domain:i,clamped:r}=this.getPlotDataDomain(c,e,t);ie(i)&&(j(i,s),n=n||r!==L.None)}if(!ie(s))return{domain:null};const[r,o]=s;if(!ie(r,o))return{domain:null};const a=[Number(r),Number(o)];a[0]===a[1]&&(a[0]-=1,a[1]+=1);let l=L.None;return n&&(0===a[0]?l=L.Min:0===a[1]&&(l=L.Max)),{domain:a,clamped:l}}setDomain(){const e=this.pane.presenter,t=e.view.xAxis.xScale.domain();if(!ie(t))return;for(const n of this.plots.filter(e=>e.hasDetachedScale)){const{domain:e}=this.getPlotDataDomain(n,t[0],t[1]);ie(e)&&n.yScale.domain(e)}if(this.isCustomDomain)return;const{domain:i,clamped:s}=this.getDataDomain(t);if(this===e.mainAxis&&e.mainPlot?.showPrevious){const t=e.mainPlot.getPreviousValue(),s=ce(e.display,!1,"chart","previous","forceVisible");ie(t,i)&&s&&(i[0]=Math.min(i[0],t),i[1]=Math.max(i[1],t))}if(this.yScale.domain(i),ie(i)){const e=this.getPadding(s);ie(e)&&this.yScale.padding(e)}}getInitialPadding(){const e=is(this.pane.presenter.hostElement);let t=rs(`#${gs.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!ie(t)){t=us(e,"div"),os(t,{display:"none"}),as(t,{id:gs.HEADER_SIZE_PLACEHOLDER_ID,class:"bcharts-card bcharts-card-first"});const{lineHeight:i}=getComputedStyle(t);isNaN(Number.parseFloat(i))&&os(t,{lineHeight:"120%"})}const{paddingTop:i,paddingBottom:s,marginTop:n,lineHeight:r}=getComputedStyle(t),o=this.pane.isMain?n:"0";if("cards"!==this.pane.presenter.display.tooltip.mode)return Number.parseFloat(o);return[i,s,o,r].map(Number.parseFloat).reduce((e,t)=>e+t,0)+gs.CARDS_Y_OFFSET}getPadding(e){const t=this.pane.presenter,i=t.display,s=ce(i,null,"yAxis","minPaddingPercent"),n=ce(i,null,"yAxis","maxPaddingPercent"),r=ie(s),o=ie(n),a=r||o?0:this.getInitialPadding(),l=r?s:gs.PANE_CAP_MIN_PADDING_PERCENT,c=o?n:gs.PANE_CAP_MAX_PADDING_PERCENT,u=l*this.viewBox.height,h=[o?c*this.viewBox.height:Math.max(u,Math.min(c*this.viewBox.height,a)),u];e===L.Max?h[0]=gs.PANE_TINY_PADDING_PIXELS:e===L.Min&&(h[1]=gs.PANE_TINY_PADDING_PIXELS);const d=t.mainPlot;return d&&d.hasEvents&&(h[0]+=3*t.view.getEventRadius()),h}clearTicks(){this.ticks=null}getTicks(e,t=0){const{height:i}=this.viewBox,s=Rn(e,1.3),n={height:i,approxLineHeight:s,domain:this.yScale.domain()};if(ie(this.ticks)&&ie(n.domain)&&ie(this.lastUsedOptions)&&ie(this.lastUsedOptions.domain)&&n.height===this.lastUsedOptions.height&&n.approxLineHeight===this.lastUsedOptions.approxLineHeight&&n.domain[0]===this.lastUsedOptions.domain[0]&&n.domain[1]===this.lastUsedOptions.domain[1])return this.ticks;this.lastUsedOptions=n;const r=Math.floor((i+40)/(s+40));let o=this.yScale.getTicks(r);const a=ce(Gv().config,null,"overrides","yAxis","tickProvider");if(ie(a)&&"function"==typeof a&&n.height>0&&ie(n.domain)){const e=ue(n);e.autoTicks=ue(o),o=a(e)}const{innerTickSize:l,tickPadding:c,fontSize:u}=this.config;let h=null;const d=this.yScale?.checkTicks(),p=d?30:40;return this.ticks=o.map(i=>{const s=Math.round(this.yScale.priceToY(i)),n=Math.abs(s-(h??s));if(d&&null!==h&&n<p)return null;h=s;const r=nd(this,i),o=e.measureText(r).width,a={x1:0,x2:0,y1:s,y2:s,dy:0,label:r,labelX:0,labelY:s+.32*u};return this.onTheRight?(a.x1=t,a.x2=a.x1+l,a.labelX=a.x2+o+c):(a.x1=t-l,a.x2=a.x1+l,a.labelX=a.x1-c),a}).filter(e=>null!==e),this.ticks}widthNeeded(e){if(!ie(this.fullDomain))return gs.DEFAULT_PRICE_AXIS_WIDTH;e.save();const{fontWeight:t,fontSize:i}=this.config,{chart:{fontFamily:s}}=this.pane.presenter.display;e.font=`${t} ${i}px ${s}`;const n=Math.max(...this.fullDomain.map(t=>e.measureText(nd(this,t,!0)).width)),{innerTickSize:r,tickPadding:o}=this.config,a=n+r+2*o+(ie(this.label)?Rn(e,1.6):0);return e.restore(),a}draw(e){const{chart:{fontFamily:t},yAxis:{gridLines:i,textColor:s,visible:n}}=this.pane.presenter.display;if(!n||!this.viewBox)return;e.save();const{x:r,y:o,width:a,height:l}=this.viewBox,{fontWeight:c,fontSize:u}=this.config;if(_n(e,this.viewBox),e.font=`${c} ${u}px ${t}`,e.lineWidth=2,e.strokeStyle=i.color,e.textAlign="end",ie(this.label)){e.save();const t=Pn(.4);e.fillStyle=t(s),e.translate(0,0);const i=this.onTheRight?1:-1;e.rotate(i*Math.PI/2),e.textAlign="center";const n=Rn(e),c=i*(o+l/2);this.onTheRight?e.fillText(this.label,c,-(r+a-n)):e.fillText(this.label,c,r+n),e.restore()}const h=this.onTheRight?r:a;e.setLineDash([]),Un(e,h,o,o+l);const d=this.getTicks(e,h);this.drawTicks(e,d,s),this.drawPriceAdornments(e),e.restore()}drawTicks(e,t,i){t&&(e.fillStyle=i,t.forEach(t=>{e.fillText(t.label,t.labelX,t.labelY+t.dy)}))}drawCrosshairIndicator(e,t){if(0===this.plots.length||!this.pane.presenter.display.yAxis.crosshair.enabled)return;const i=this.onTheRight?this.viewBox.x:this.viewBox.width,s=nd(this,this.yScale.yToPrice(t));this.crosshairIndicator.draw(e,i,t,s)}get indicatorHeight(){return this.config.fontSize+this.config.indicatorPadding+this.config.indicatorPadding}drawPriceAdornments(e){const t=this.pane.presenter,{chart:{fontFamily:i,previous:s},yAxis:{showLastValue:n,preventLabelOverlap:r,includePercentChangeWithLastValue:o}}=t.display,a=t.view,l=[],c=(e,t,i,s,n,r)=>{if(null!=t){const a=t;let c;t=e.priceMapper(t,r,n);const u=e.is(f.Symbol)||e.is(f.Expression);if(o&&u){const t=e.axis.comparison===d.Percent?d.None:d.Percent;c=e.priceMapper(a,r,n,t)}const h=e.hasDetachedScale?e.metaData.format(t,n):void 0,p=ie(c)?1:2;l.push({y:e.priceToY(t),formattedValue:h,value:t,auxValue:c,color:i,halfHeight:Math.round(this.indicatorHeight/p),priority:s})}};this.plots.forEach(e=>{if(e.timeSeries&&e.timeSeries.hasData){if("All"===n||"Main"===n&&e.main){const t=e.main?1:3;AT(e).filter(e=>null!=e.value&&-1!==e.index).forEach(i=>c(e,i.value,i.color,t,i.field,i.index))}e.showPrevious&&c(e,e.getPreviousValue(),s.color,2,Ka.PreviousClose,void 0)}});this.annotations.concat(this.plotAnnotations).forEach(e=>{l.push(...e.getPriceScaleAdornments().map(e=>({y:this.toY(e.price),value:this.priceMap(e.price),color:e.color,halfHeight:Math.round(this.indicatorHeight/2),priority:4})))}),l.sort((e,t)=>e.y-t.y),r&&function(e,t){e.forEach((e,i,s)=>{if(0===i&&e.y-e.halfHeight<t.y)e.y=t.y+e.halfHeight+1;else if(i>0){const n=s[i-1],r=(({y:e,halfHeight:t})=>e-t)(e),o=hT(n);r<o&&(e.y=o+1+e.halfHeight),hT(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}(l,this.viewBox);const u=({y:t,value:s,formattedValue:n,color:r,auxValue:o})=>{const{leftOffset:l,rightOffset:c}=a,u=this.onTheRight?this.pane.viewBox.width-c:l,h=Ln(r),p=new uT({position:this.onTheRight?"right":"left",fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:i,textColor:h,strokeColor:r,backgroundColor:r}),f=n||nd(this,s);let m;const g=this.comparison===d.Percent;te(o)&&(m=g?sd(this,o):id(o)),p.draw(e,u,t,f,m)};r?l.forEach(u):gT.forEach(e=>l.filter(t=>t.priority===e).forEach(u))}}const TT=/* @__PURE__ */Symbol.for("__dloacip__");class vT{constructor(e){this.presenter=e,this.id=Pe()}id;axes=[];height=0;alignedToYear=null;viewBox;fromModel(e){this.height=e.height,!0===e.alignOnExpirations&&(this.alignedToYear=function(e){const t=e.map(e=>e.plots).flat().filter(e=>f[e.type]==f.Symbol).map(e=>e.symbol).map(e=>Ji(e)).filter(e=>null!==e).map(e=>e.getFullYear());return 0!=t.length?Math.max(...t):null}(e.axes)),this.axes=e.axes.map((e,t)=>{const i=new ST(this);return i.primary=0===t,i.fromModel(e),i},this)}getBounds(){return this.viewBox}setViewBox(e){this.viewBox=e}drawBackground(e){ie(this.viewBox)&&(this.drawAxes(e),e.save(),this.clipToNoScales(e),this.drawGrid(e),e.restore())}draw(e){ie(this.viewBox)&&(e.save(),this.clipToNoScales(e),this.drawPrevious(e),this.drawPlots(e),this.drawAnnotations(e),this.drawLogo(e),e.restore())}drawLogo(e){this.isMain&&!1!==this.presenter[TT]&&function(e,{x:t,y:i,height:s,width:n}){if(!te(GA))return;const{path:r,width:o,height:a,rect:l}=GA,c=n/8,u=Math.min(Math.max(50,c),o)/o;l.width=o*u,l.height=a*u,l.x=t+5,l.y=i+s-l.height-5,e.save();const h=getComputedStyle(e.canvas).getPropertyValue("--widget-logo-fill-color");e.fillStyle=0===h.length?"rgba(127, 127, 127, 0.6)":h,e.translate(l.x,l.y),e.scale(u,u),e.fill(r),e.restore()}(e,this.getBoundsWithoutScales())}drawAxes(e){for(const t of this.axes)t.draw(e)}drawPrevious(e){const t=this.presenter.mainPlot;if(t.showPrevious&&this.isMain){let i=t.getPreviousValue();if(i=t.priceMapper(i,void 0,Ka.PreviousClose),null!=i){const{leftOffset:s,rightOffset:n}=this.presenter.view,r=s,o=this.viewBox.width-n,a=t.axis.yScale.priceToY(i),{color:l,dashStyle:c,lineWidth:u}=this.presenter.display.chart.previous,h=An(c);e.save(),e.strokeStyle=l,e.lineWidth=u,e.setLineDash(h),$n(e,a,r,o),e.restore()}}}getBoundsWithoutScales(){const e=this.viewBox.duplicate(),t=this.presenter.view;return e.x=t.leftOffset,e.width-=t.leftOffset+t.rightOffset,e}clipToNoScales(e){_n(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();const{chart:{fontFamily:t},yAxis:{fontSize:i}}=this.presenter.display;e.font=`${i??12}px ${t}`;const s=t=>t.draw(e,!0);this.axes.forEach(e=>{e.annotations.forEach(s),e.plotAnnotations.forEach(s)}),e.restore()}drawGrid(e){const{chart:{fontFamily:t},yAxis:{gridLines:i,visible:s,minorGridLines:n}}=this.presenter.display;if(!s||!i.visible)return;const{lineWidth:r,color:o,dashStyle:a}=i;e.save();const l=0===this.axes[0].plots?.length&&this.axes.length>1,c=this.axes[l?1:0],{fontWeight:u,fontSize:h}=c.config;e.font=`${u} ${h}px ${t}`;const d=c.getTicks(e),{leftOffset:p,rightOffset:f}=this.presenter.view,m=p,g=this.viewBox.width-f,y=(t,i,s)=>{e.lineWidth=t,e.strokeStyle=i,e.setLineDash(An(s)),e.beginPath()};if(y(r,o,a),d.forEach(t=>{e.moveTo(m,t.y1),e.lineTo(g,t.y2)}),e.stroke(),n&&n.visible&&d.length>=2){const{lineWidth:t,color:i,dashStyle:s}=n,r=(d[0].y1-d[1].y1)/5;y(t,i,s),d.forEach(t=>{for(let i=1;i<5;i++){const s=Math.ceil(t.y1+i*r);e.moveTo(m,s),e.lineTo(g,s)}}),e.stroke()}e.restore()}drawYCrosshair(e,t){const{yAxis:{crosshair:{enabled:i,showValue:s,color:n,dashStyle:r}}}=this.presenter.display;if(!i)return;const o=An(r);e.strokeStyle=n,e.setLineDash(o);const a=this.presenter.view.leftOffset,l=this.viewBox.width-this.presenter.view.rightOffset,c=Kn();c.prolog(e),$n(e,c.adjust(t.y),c.adjust(a),c.adjust(l)),c.epilog(e),s&&this.axes.forEach(i=>{i.drawCrosshairIndicator(e,t.y)})}drawNoData(e){e.save(),e.font=`800 14px ${this.presenter.display.chart.fontFamily}`,e.fillStyle="#f00";Bn(e,Gv().config.noDataText||gs.NO_DATA_TEXT,{x:this.viewBox.centerX,y:this.viewBox.centerY},g.Center),e.restore()}get isMain(){const e=this.presenter.mainPlot;return this.axes.some(t=>t.plots.includes(e))}drawPlots(e){e.save();const t=this.presenter.mainPlot,i=this.presenter.display.chart.showNoDataText,s=!ie(i)||i,n=/* @__PURE__ */new Map;let r=!0;const o=i=>{for(const e of this.axes){for(const s of e.plots){const e=s.isEmpty();r=r&&s.main&&e,s===t||e||i(s)}e.plots.includes(t)&&!t.isEmpty()&&i(t)}s&&r&&this.drawNoData(e)};o(t=>t.draw(e)),o(t=>t.drawTopmost(e,n)),e.restore()}}function PT(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}class CT extends ky{constructor(e,t){super(),this.timeline=e,this.aggregation=t;const i=e.presenter.display;this.marginBars=i.xAxis.marginBars||0,this.bar=PT(ce(i,gs.DEFAULT_BAR_WIDTH,"chart","bar","width"),ce(i,gs.DEFAULT_BAR_SPACING,"chart","bar","spacing")),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}marginBars;bar;resetBar;wasZoomed;fitAllData;extent(e){return Fy.call(this,"_extent",e)}get presenter(){return this.timeline.presenter}get display(){return this.presenter.display}scaleBarToFit(){if(this.wasZoomed)return;if(this.fitAllData)return this._domain=null,this.scaleBarToFitDensity(this.timeline.withoutPrologEpilogLength);const e=this.display.xAxis.visibleRange;if(ie(e))return this.scaleBarToFitRange([e.from,e.to]);const t=this.display.density;if(Number.isFinite(t))return this.scaleBarToFitDensity(t);const i=this.display.period;return Number.isFinite(i)?this.scaleBarToFitPeriod(i):void 0}deriveExtentsFromBarWidth(e){if(!ie(this._range))return null;if(0===this.timeline.length)return null;const t=this._range[1]-this._range[0],i=t/e.totalWidth,s=Math.ceil(i);e.offset=t-s*e.totalWidth;let n=this.timeline.lastSeriesIndex+this.marginBars;const r=this._domain&&this._domain[1];r&&(n=G(this.timeline,+r,Number,ud));return[n-s+1,n]}adjustDomain(){if(!ie(this._range))return;this.scaleBarToFit();const e=this.deriveExtentsFromBarWidth(this.bar);ie(e)&&(this.extent(e),this.setDomainFromExtent())}xToTime(e){if(!this.ready)return null;const t=e-this._range[0]-this.bar.offset,i=Math.floor(t/this.bar.totalWidth),s=this._extent[0]+i;return this.timeline.at(s)}timeToIndex(e){return this.ready?(e="number"==typeof e?e:+e,G(this.timeline,e,Number,ud)):null}indexToX(e){const t=e-this._extent[0];return this.bar.width/2+this.range()[0]+this.bar.offset+t*this.bar.totalWidth}timeToX(e){if(!this.ready)return null;const t=this.timeToIndex(e);return this.indexToX(t)}zoom(e){const t=e,i=t*this.bar.width/100,s=this.bar.width-i,n=this.bar.spacing-t*this.bar.spacing/100;if(s>gs.MAXIMUM_BAR_WIDTH||s<gs.MINIMUM_BAR_WIDTH)return!1;const r=PT(s,n),o=this.deriveExtentsFromBarWidth(r);return!!this.isUsableExtent(o)&&(this.setBar(s,n),this.adjustDomain(),this.wasZoomed=!0,!0)}scaleBarToFitRange(e,t=!0){const i=(e,t,i,s)=>ie(e)?G(this.timeline,e,Number,ud,i,s):t,{from:s,to:n}=this.presenter.data.range||{},r=+e[0]===s&&+e[1]===n,{firstSeriesIndex:o,lastSeriesIndex:a}=this.timeline,l=r?o:void 0,c=r?a:void 0,u=[i(e[0],o,l,c),i(e[1],a,l,c)];this.timeline.at(u[1])>e[1]&&(u[1]=Math.max(0,u[1]-1)),this.extent(u),this.scaleBarToFitDensity(u[1]-u[0]+1,t)}scaleBarToFitDensity(e,t=!0){const i=Math.max(gs.MINIMUM_BARS_VISIBLE,e),s=t&&this.display.xAxis.marginBars||0,n=(this._range[1]-this._range[0])/(i+s);this.setBar(2/3*n,1/3*n,!1)}scaleBarToFitPeriod(e){const t=this.timeline.lastSeriesIndex,i=this.timeline.at(t);let s=i,n=t;const r=this.presenter.data.aggregation;if(r.isEndOfDay||r.isIntraday&&e>=gs.INTRA_THRESHOLD)for(;n>0&&ft(i,s)<e;)n--,s=this.timeline.at(n);else if(!r.isTick){let t=Math.floor(e/gs.ONE_DAY_MILLIS);const s=e=>yt(e,nt(e)),r=s(i);let o=i;for(;n>0;){const e=this.timeline.at(n),i=ut(e,o);if(0===t){if(s(e)<=r||!i)break}else i||(t--,o=e);n--}}this.scaleBarToFitDensity(t-n+1)}setBar(e,t,i=!0){const[s,n]=ve(e,t,gs.MINIMUM_BAR_WIDTH,gs.MAXIMUM_BAR_WIDTH);this.bar.width=s,this.bar.spacing=n,this.wasZoomed||(this.resetBar={width:s,spacing:n}),i&&(this.presenter.model.display.chart.bar={width:e,spacing:t})}resetZoom(){ie(this.resetBar)?(this.bar.width=this.resetBar.width,this.bar.spacing=this.resetBar.spacing):(this.bar.width=gs.DEFAULT_BAR_WIDTH,this.bar.spacing=gs.DEFAULT_BAR_SPACING),delete this.presenter.model.display.chart.bar,this.adjustDomain()}isUsableExtent(e){return ie(e)&&ie(e[0],e[1])&&e[0]>=0&&e[1]<this.timeline.withPrologEpilogLength&&e[1]-e[0]>=gs.MINIMUM_BARS_VISIBLE}shiftBars(e,t=null){if(!this._extent)return;const i=this._extent.map(t=>t+e);this.isUsableExtent(i)&&(ie(t)&&(this.bar.offset=t),this.extent(i),this.setDomainFromExtent())}setDomainFromExtent(){this.domain(this.extent().map(e=>this.timeline.at(e)))}pan(e){if(!Number.isFinite(e)||0===e)return;const t=e%this.bar.totalWidth;let i=this.bar.offset+t;const s=Math.sign(e);let n=-(e<0?Math.ceil:Math.floor)(e/this.bar.totalWidth);(i>this.bar.totalWidth||i<-this.bar.totalWidth)&&(n+=i>0?-1:1,i-=s*this.bar.totalWidth),this.shiftBars(n,i)}getSeriesThatCouldLoadMoreData(){const e=this.domain();if(!ie(e)||!ie(e[0]))return[];const t=e[0].getTime();return this.timeline.presenter.allPlots.map(e=>e.timeSeries).filter(e=>!(!ie(e)||!e.hasData||0===e.container.size||!0!==e.canLoadMoreData)&&t<=e.container.getTimeData()[0].getTime())}}function bT(e){return{date:e,priority:1,text:td(e)}}class ET{constructor(e){this.view=e,this.xScale=new CT(e.presenter.timeline,e.presenter.data.aggregation),this.ticks=null,this.lastUsedOptions=null,this.wasPanned=!1,this.panningXAxisAllowed=ce(e.presenter.display,!0,"xAxis","panning"),this.updateConfigFromModel();const t=e.presenter.renderTo.id,i=ce(Gv().config,null,"overrides","xAxis","tickProvider");ie(i)&&"function"==typeof i&&(this.overrideTickGetter=M(i,t));const s=ce(Gv().config,null,"overrides","xAxis","formatter");ie(s)&&"function"==typeof s&&(this.overrideFormatter=M(s,t))}xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;viewBox;overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;updateConfigFromModel(){const{chart:{fontFamily:e,backgroundColor:t,fontSize:i},xAxis:{textColor:s,visible:n,fontSize:r,crosshair:{color:o}}}=this.view.presenter.display,a=r||i||12;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:a},this.isVisible=n,this.crosshairIndicator=new uT({position:"bottom",fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:s,backgroundColor:Cn(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();const e=this.view.presenter.display.period===gs.FIFTY_YEARS_MILLIS;ie(this.xScale.extent())&&!e&&this.checkForMoreData()}zoom(e){const t=this.xScale.zoom(e);return this.checkForMoreData(),t}checkForMoreData(){this.xScale.getSeriesThatCouldLoadMoreData().forEach(e=>e.loadMoreData())}shouldScrollIntoView(e){const t=this.xScale.extent();return!!ie(t)&&(e-this.xScale.timeline.lastSeriesIndex>=0&&e-t[1]<=1)}pan(e){this.panningXAxisAllowed&&(this.xScale.pan(e),this.checkForMoreData(),this.view.setPriceAxesDomains(),this.wasPanned=!0)}get wasVisibleRangeChanged(){return this.wasPanned||this.xScale.wasZoomed}resetZoom(){this.xScale.resetZoom()}get barsToLast(){const e=this.xScale.timeline.lastSeriesIndex+this.getMaxCurveOffset(),t=this.xScale.extent();return e-(t?t[1]:e)}canGoToLast(){return this.barsToLast>0}getMaxCurveOffset(){return Math.max(...this.view.presenter.allCurves.map(e=>e.shift))}goToLatest(e=!1){if(this.canGoToLast()||e){const e=0!==this.barsToLast?this.barsToLast+this.xScale.marginBars+1:0;this.xScale.shiftBars(e),this.view.setPriceAxesDomains(),this.view.redraw()}}setViewBox(e){this.viewBox=e;const{x:t,width:i}=this.viewBox;this.xScale.range([t,t+i])}heightNeeded(e){if(!this.isVisible)return 0;const t=this.view.presenter.display.chart.fontFamily,{fontWeight:i,fontSize:s}=this.config;e.save(),e.font=`${i} ${s}px ${t}`;const{innerTickSize:n,tickPadding:r,indicatorPadding:o}=this.config,a=Rn(e,1)+n+r+o;return e.restore(),a}getTickGetter(e){if(this.overrideTickGetter)return this.overrideTickGetter;const t=this.view.presenter.display.xAxis.isOrdinal||!1,i=function(e){switch(e.agg.unit){case a.Tick:return new qh(e);case a.Intraday:return new Xh(e,e.agg.size);case a.Day:return new Zh(e);case a.Week:return new Jh(e);case a.Month:case a.Quarter:return new Qh(e);case a.Year:return new ed(e);default:throw new Error(`Aggregation unit ${a[e.agg.unit]} not supported.`)}}(e);return t?bT:e=>i.getTick(e)}getTicks(e){if(ie(this.lastUsedOptions)&&(t=e.agg,i=this.lastUsedOptions.agg,t.unit===i.unit&&t.size===i.size&&t.spec===i.spec)&&e.unitWidth===this.lastUsedOptions.unitWidth&&e.barWidth===this.lastUsedOptions.barWidth&&e.extent[0]===this.lastUsedOptions.extent[0]&&e.extent[1]===this.lastUsedOptions.extent[1]&&e.formatString===this.lastUsedOptions.formatString&&e.minTickInterval===this.lastUsedOptions.minTickInterval&&ie(this.ticks))return this.ticks;var t,i;this.lastUsedOptions=e;const s=this.getTickGetter(e),n=Math.max(0,e.extent[0]),r=Math.min(this.xScale.timeline.withPrologEpilogLength-1,e.extent[1]+1);return this.ticks=this.view.presenter.timeline.slice(n,r).map((e,t)=>{if(!ie(e)||Number.isNaN(e.getTime()))return null;const i=s(e);return ie(i)&&(i.index=n+t),i}).filter(e=>ie(e)),this.ticks}normalizeDuration(e){const t=function(){const e=Object.keys(Wh);return 1===Wh.Day.Multipliers[0]&&e.forEach(e=>{const t=Wh[e],i=Te(t.Period);t.One=1*i,t.Multipliers=t.Multipliers.map(e=>e*i)}),Wh}();let i=t.Year;const s=Object.keys(t);for(let a=0;a<s.length-1;++a){const n=t[s[a]].Multipliers,r=t[s[a+1]].Multipliers,o=(k(n)+W(r))/2;if(e<=o){i=t[s[a]];break}}const n=i.Multipliers,r=n.findIndex(t=>e<t);let o=-1===r?k(n):n[r];return"P1M"===i.Period?o*=.9:"P1W"===i.Period&&(o*=.84),o}draw(e){if(!this.isVisible)return;const{xAxis:{gridLines:t,textColor:i,minTickInterval:s,tickPixelInterval:n,format:r,forceTicksVisible:o},chart:{fontFamily:a}}=this.view.presenter.display,{fontWeight:l,fontSize:c,innerTickSize:u,tickPadding:h}=this.config,{x:d,y:p,width:f}=this.viewBox,{lineWidth:m,color:g,dashStyle:y}=t,A=An(y);e.textAlign="center",e.font=`${l} ${c}px ${a}`,e.lineWidth=1,e.strokeStyle=g,e.fillStyle=i,e.setLineDash([]),$n(e,p,d,d+f);const S=this.xScale.extent(),T=e=>!ie(e)||!ie(e[0],e[1]);if(T(S))return;const v=t=>e.measureText(t).width,P=n>0?n:120,C=this.xScale.domain();if(T(C))return;const b=(C[1].getTime()-C[0].getTime())*P*.6/f,E=this.normalizeDuration(b),L=this.view.presenter.data.aggregation.isEndOfDay,M=(e,t)=>{if(e.date.valueOf()===gs.ZERO_DATE.valueOf())return!0;if(i=e.date,n=t.date,(ie(i)?ft(n,i):gs.FIFTY_YEARS_MILLIS)<s)return!1;var i,n;const r=t.x-e.x,o=t.date.getTime()-e.date.getTime()>=E,a=r>P;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||!!L&&o)},_=d+f,x=({text:i,x:s,date:n,forced:r})=>{ie(n)&&(r||Un(e,s,p,p+u),e.fillText(i,s,p+u+h+.71*c),t.visible&&!r&&(e.save(),e.lineWidth=m,e.setLineDash(A),Un(e,s,0,p),e.restore()))},I={agg:this.view.presenter.data.aggregation,unitWidth:v("M"),barWidth:this.xScale.bar.width,extent:S,formatString:r,minTickInterval:s||0,duration:b},D=this.getTicks(I);let O={date:gs.ZERO_DATE,priority:999,x:-999,text:"",textWidth:0};D.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=v(e.text),(e=>{const{x:t,textWidth:i}=e;let s=t;if(o){const n=i/2;s=t-n<d?d+n:t,s=s+n>_?_-n:s,e.x=s,e.forced=t!==s}else e.forced=!1})(e),M(O,e)?(x(O),O=e):e.priority<O.priority&&(O=e)}),x(O),this.drawTimeTransitions(e),this.drawTimeAdornments(e)}drawTransitionsFor(e,t,i,s,n){const r=this.xScale.domain(),o=this.view.presenter?.mainPlot?.timeSeries.container;if(!te(o))return;const a=o.getTimeData(),l=null===t?a:o.getData(t);if(!ie(l))return;const c=G(a,+r[0],Number),u=G(a,+r[1],Number,$,c);if(c<u){const t=this.viewBox.y,r=this.view.leftOffset,o=this.viewBox.x+this.viewBox.width;if(s.save(),n){s.fillStyle=e.fillColor;let h=l[c],d=Math.max(r,this.xScale.timeToX(a[c]));for(let e=c+1;e<=u;++e){const r=e<l.length?l[e]:null;if(e===u||i(r,h)){const i=e<a.length?a[e]:null;let l=te(i)?this.xScale.timeToX(i):o;l=Math.min(l,o),n(h)%2==0&&s.fillRect(d,0,l-d,t),h=r,d=l}}}const h=Kn();h.prolog(s),s.strokeStyle=e.color,s.lineWidth=e.width,s.setLineDash(An(e.dashStyle));let d=null;for(let e=c;e<u;++e){const n=l[e];if(i(n,d)){const i=a[e],r=this.xScale.timeToX(i);ie(r,d)&&Un(s,r,0,t),d=n}}h.epilog(s),s.restore()}}drawTimeTransitions(e){const t=this.xScale.domain();if(!te(t)||!ie(t[0],t[1]))return;const i=this.view.presenter,{xAxis:{contractTransition:s,cycleTransition:n}}=i.display,r=(e,t)=>e!==t;if(s.enabled&&i?.data?.aggregation.isMultiContract){const t=i?.mainPlot?.timeSeries.container,n=t?.getData(Ka.Symbol);if(n&&n.length>0){const t=n[0];if(this.contractParityCacheKey!==t||!this.contractParityCache){const e=[...new Set(n)];e.sort((e,t)=>{const i=Ji(e),s=Ji(t);return(i?.getTime()??0)-(s?.getTime()??0)});let i=0;if(this.contractParityCache)for(let t=0;t<e.length;t++){const s=e[t],n=this.contractParityCache.get(s);if(void 0!==n){i=(n-t)%2==0?0:1;break}}this.contractParityCache=/* @__PURE__ */new Map,e.forEach((e,t)=>this.contractParityCache.set(e,t+i)),this.contractParityCacheKey=t}const i=e=>this.contractParityCache.get(e)??0;this.drawTransitionsFor(s,Ka.Symbol,r,e,i)}}if(n.enabled)if(i?.data?.aggregation.isIntraday)this.drawTransitionsFor(n,Ka.TradingDay,r,e,e=>e);else if(i?.data?.aggregation.unit===a.Day){const t=(e,t)=>!_i(e,t),i=e=>e.getMonth();this.drawTransitionsFor(n,null,t,e,i)}else if(i?.data?.aggregation.unit===a.Week){const t=(e,t)=>!Ii(e,t),i=e=>e.getFullYear();this.drawTransitionsFor(n,null,t,e,i)}}getAnnXScore(e,t){return[ut,Mi,_i,Ii].map((i,s)=>(4-s)*Number(i(e,t))).reduce((e,t)=>e+t,0)}annTimeToX(e){const t=this.xScale.timeToIndex(e);if(!te(t))return null;const i=this.xScale.timeline.at(t),s=this.xScale.timeToX(e);if(t>0&&i.valueOf()!==e.valueOf()){const n=t-1,r=this.xScale.timeline.at(n),o=this.xScale.indexToX(n),a=this.view.presenter.display?.xAxis?.isOrdinal;if(!a){if(r.valueOf()>e.valueOf())return s;const t=this.getAnnXScore(r,e),n=this.getAnnXScore(i,e);if(t>n)return o;if(n>t)return s;const a=this.view.presenter?.data?.aggregation?.isIntraday;return a?o:s}return o+(s-o)*((e.valueOf()-r.valueOf())/(i.valueOf()-r.valueOf()))}return s}drawTimeAdornments(e){e.save();const t=this.view.presenter,{chart:{fontFamily:i},xAxis:{preventLabelOverlap:s}}=t.display,n=[],r=t.mainPane?.getBoundsWithoutScales()??new xn(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).forEach(i=>{n.push(...i.getTimeScaleAdornments().map(i=>{const s=this.annTimeToX(i.time);if(s<r.x||s>r.x+r.width)return null;const n=!this.view.presenter?.display?.xAxis?.isOrdinal?this.xScale.xToTime(s):i.time,o=rd(t,n),a=e.measureText(o).width/2;return{x:s,value:o,color:i.color,halfWidth:a}}).filter(e=>null!=e))}),n.sort((e,t)=>e.x-t.x),s&&function(e,t){const i=e.length-1;e.forEach((e,s,n)=>{const r=0===s,o=r?null:n[s-1],a=dT(e),l=r?t.x:pT(o);if(e.x-e.halfWidth<t.x&&(e.x=mT(t.x,e.halfWidth)),a<l)e.x=mT(l,e.halfWidth+4);else{const t=pT(e),r=s<i?dT(n[s+1]):Number.MAX_SAFE_INTEGER;if(t>r){const i=fT(e.x,t-r),s=fT(e.x,e.halfWidth-2),n=mT(l,o?.halfWidth??0);e.x=Math.max(s,i,n)}}pT(e)>t.x+t.width&&(e.x=fT(t.x+t.width,e.halfWidth))})}(n,this.viewBox),n.forEach(t=>{const s=Ln(t.color);new uT({position:"bottom",fontSize:this.config.fontSize,fontFamily:i,padding:this.config.indicatorPadding,strokeColor:gs.COLOR_TRANSPARENT,textColor:s,backgroundColor:t.color,arrowLength:this.config.innerTickSize}).draw(e,t.x,this.viewBox.y+1,t.value)}),e.restore()}drawCrosshair(e,{x:t}){const i=this.view.presenter,s=i.display.xAxis,{enabled:n,showValue:r,color:o,dashStyle:a,format:l}=s.crosshair,c=this.xScale.xToTime(t);if(!(ie(c)&&ht(c)))return!1;if(!n)return!0;t=this.xScale.timeToX(c);const u=An(a);e.strokeStyle=o,e.setLineDash(u);const h=Kn();if(h.prolog(e),Un(e,h.adjust(t),0,h.adjust(this.viewBox.y)),h.epilog(e),!r||!s.visible)return!0;const d=ie(s.format)?l:void 0,p=rd(i,c,d);this.crosshairIndicator.draw(e,t,this.viewBox.y+1,p,void 0,this.viewBox.height-2);const{plotHover:f}=i.display.chart;return f&&i.allPlots.filter(e=>e.visible).forEach(i=>i.curves.forEach(i=>i.drawHover(e,c,t))),!0}}const LT={mousedown:"onMouseDown",mousemove:"onMouseMove",mouseup:"onMouseUp",dblclick:"onMouseDblClick",contextmenu:"onContextMenu",mouseover:"onMouseEnter",mouseout:"onMouseLeave",wheel:"onWheel",touchstart:"onMouseDown",touchmove:"onMouseMove",touchend:"onMouseUp",keydown:"onKeyDown"},MT={Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"};class _T{constructor(e){this.view=e}subscriptions=[];init(e){const t=q();Object.keys(LT).filter(e=>!(e=>e.startsWith("touch"))(e)||t).forEach(t=>{const i=e=>{const i=LT[t];!0===this.notifyActiveTool(i,e)&&e.preventDefault()};e.addEventListener(t,i),this.subscriptions.push(()=>{e.removeEventListener(t,i)})})}shutdown(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}notifyActiveTool(e,t){const i=this.view.presenter;if(void 0===i||null===i.activeTool)return!1;const s=this.getPayload(t,i),n=i.activeTool;let r=!1;return"function"==typeof n[e]&&(r=n[e](s)||!1),r}getPayload(e,t){const i=e instanceof MouseEvent,s=q()&&e instanceof TouchEvent;if(i||s){const n={x:0,y:0};if(s&&1===e.touches.length){const t=e.touches[0],{left:i,top:s}=e.target.getBoundingClientRect();n.x=t.clientX-i,n.y=t.clientY-s}else i&&(n.x=e.offsetX,n.y=e.offsetY);const r={button:i?e.which:A.Left,offset:n,view:t.view,presenter:t,originalEvent:e,getModifier:t=>e[MT[S[t]]]};if(e instanceof WheelEvent&&(r.delta=e.shiftKey?e.deltaX:e.deltaY),s&&2===e.touches.length){const t=e.touches[0],i=e.touches[1];r.pinchZoom=!0;const s=t.clientX-i.clientX,n=t.clientY-i.clientY;r.pinchDistance=Math.sqrt(s*s+n*n)}return this.view.splitters.forEach((e,t)=>{e.contains(n)&&(r.splitter=[t,t+1])}),t.panes.forEach(e=>{const t=e.getBounds();if(ie(t)&&t.contains(n)){const t=e.axes.find(e=>e.viewBox?.contains(n));if(t)r.priceAxis=t;else{const t=e.axes.find(e=>e.primary);r.point=t.toAnnotationPoint(n)}}}),r}if(e instanceof KeyboardEvent){return{key:e.key??e.keyIdentifier,code:e.keyCode||e.charCode,repeat:e.repeat,presenter:t,getModifier:t=>e.getModifierState(S[t])}}}}const xT=$u.concat(Ka.PercentChange);class IT{constructor(e){this.view=e,this.id=`bc-legend-${Pe()}`}id;isOptionsChart=!1;getLegendElem(){const e=this.view.el;return ls(this.id,e,"div")}update(){const e=this.getLegendElem(),t=Ed(this.presenter.mainPane);if(!ie(t))return;this.isOptionsChart=this.mainPlot.title.startsWith(gs.FAKE_SYMBOL_PREFIX);const{left:i,right:s,top:n,width:r}=t;FA(e,"row",i,s,n,r),cs(e,{"bcharts-card":!0,"bcharts-legend":!0});const o=this.mainPlot,a=o.isSeasonal||this.isOptionsChart?this.getFirstColorBadge(o):"",l=this.getPlotTitle(o),c=this.maybeGetQuote(),u=this.div(`${a} ${l} `)+this.div(`${c}`),h=this.maybeGetAdditionalPlots();e.innerHTML=`${u} ${h}`}remove(){ns(this.getLegendElem())}get presenter(){return this.view.presenter}get mainPlot(){return this.presenter.mainPlot}getAttributes(e){return Object.entries(e).map(([e,t])=>{if(null===t)return"";return`${e} = "${Array.isArray(t)?t.join(" "):t}" `}).join(" ")}span(e,t={}){return`<span ${this.getAttributes(t)}>${e}</span>`}div(e){return`<div class="plot" style="flex: 0 0 auto">${e}</div>`}get meta(){return this.mainPlot.metaData}isSingleSymbolSeasonal(e){return e.isSeasonal&&!e.hasComputation}format(e,t,i){return(i??this.meta).format(e,t)}spanAsName(e){return this.span(e,{class:"field-name"})}spanAsValue(e,t=null,i=null){return this.span(e,{class:["field-value",t],style:i})}getQuoteFromRecord(e){const t=xT.map(t=>e.getValue(t));if(R(t)){const e=t[4],i=`field-${e>0?"up":e<0?"down":"same"}-value`;return`${t.slice(0,-1).map((e,t)=>{const s=xT[t],n=this.format(e,s),r=xd(s);return`${this.spanAsName(r)}${this.spanAsValue(n,i)}`}).join(" ")} ${this.spanAsValue(`(${this.format(k(t),k(xT))})`,i)}`}return""}maybeGetQuote(){if(this.mainPlot.isSymbol&&this.mainPlot.timeSeries?.record?.isValid){const e=Gv().getRecordSource().getRecord(this.mainPlot.timeSeries.record.symbol);return this.getQuoteFromRecord(e)}if(this.mainPlot.isExpression&&this.mainPlot.record.isValid){const e=this.mainPlot.record;return e.evaluate(),this.getQuoteFromRecord(e)}return""}getTitle(e,t,i){const s=t?"value-main":null;return`${this.span(`${e.name} (${e.symbol})`,{"data-plot-id":i,class:["value-title",s]})}${t?` ${this.span(e.exchange,{class:"value-subtitle"})}`:""}`}getPlotTitle(e){if(e.isSymbol)return this.getTitle(e.metaData,e.main,e.id);if(this.isSingleSymbolSeasonal(e)&&0===e.offset&&(e.symbols?.length??0)>0){const t=Gv().getMetaDataSource().getMetaData(e.getActualSymbols()[0]);return this.getTitle(t,!0,e.id)}return this.span(e.title,{"data-plot-id":e.id,class:"value-title"})}getFirstColorBadge(e){return Ad("rectangle",e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?"":AT(e).filter(e=>ie(e.value)).map(t=>{const i=this.format(t.value,t.field,e.metaData);return this.spanAsValue(i,null,`color:${t.color}`)}).join(" ")}canBeDeleted(e){return e.isStudy||!e.main&&this.isOptionsChart}maybeGetAdditionalPlots(){const e=this.presenter.mainPane.axes.map(e=>e.plots).flat().filter((e,t)=>!e.main||e.isSeasonal&&t>0),t=this.presenter.display.yAxis.showLastValue;return e.length>0?e.map(e=>{const i=this.getFirstColorBadge(e),s=this.getPlotTitle(e),n=this.canBeDeleted(e)?Cd(e.id):"",r="All"!==t&&!e.isSeasonal?this.getLastValues(e):"";return this.div(`${n} ${i} ${s} ${r}`)}).join(" "):""}}class DT{presenter;splitters=[];canvasContainer=null;mouseCanvas=null;mainCanvas=null;mouseContext;mainContext;leftOffset=0;rightOffset=0;legend;notifyLayoutChanged;el=null;listeners=[];tooltip;width;height;customEventPopup=null;goToLatestButton=null;xAxis;eventCapture;resetZoomAndVisibleRange=!1;constructor(){this.legend=new IT(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=ee(qa.CH_CHTLAYOUTCHANGED,gs.LAYOUT_THROTTLE_DELAY)}get canShowLegend(){if(!this.presenter.hasLegend)return!1;const e=this.presenter.display.chart.showLegend;return!("boolean"==typeof e&&!e)}updateLegend(){this.canShowLegend&&this.legend.update()}removeLegend(){this.legend.remove()}findSvgParentWithClass(e,t){return[e,e.parentElement,e.parentElement.parentElement].find(e=>ie(e)&&e.className===t)}onNonToolHandledMouseDown(e){const t=this.presenter,i=e.target;if("string"==typeof i.className&&i.className.split(" ").includes("value-title"))t.onCardClicked(i);else{const s=this.findSvgParentWithClass(i,"move-pane");if(te(s))return void t.onMovePaneClicked(s);const n=this.findSvgParentWithClass(i,"delete-plot");if(te(n))return void t.deletePlotClicked(n);const r=this.findSvgParentWithClass(i,"show-hide-plot");if(te(r))return void t.showHidePlotClicked(r);const o=this.findSvgParentWithClass(i,"more-actions");if(te(o))return void t.plotMoreActionsClicked(o,e)}}initialize(e){this.presenter=e,this.el=this.presenter.hostElement;const t=new ResizeObserver(e=>{for(const t of e){const{width:e,height:i}=t.contentRect;this.setSize(e,i),ie(this.tooltip)&&this.tooltip.repositionAuto()}});t.observe(this.el.parentElement),this.listeners.push(()=>t.unobserve(this.el.parentElement));const i=e=>this.onNonToolHandledMouseDown(e);this.el.addEventListener("mousedown",i),this.listeners.push(()=>this.el.removeEventListener("mousedown",i)),os(this.el,{flex:1,display:"flex",position:"relative","flex-direction":"column","touch-action":"pan-x pan-y"}),this.tooltip=new VA(this);const s=Gv().config.getCustomEventPopup;this.customEventPopup=s?s(this):null;const{clientHeight:n,clientWidth:r}=this.el;this.width=r,this.height=n,this.canvasContainer=us(this.el,"div"),as(this.canvasContainer,{class:"chart-canvas-container"}),os(this.canvasContainer,{flex:1,display:"flex","flex-direction":"column",position:"relative",height:"100%"}),this.mainCanvas=us(this.canvasContainer,"canvas");const o={height:`${n}px`,width:`${r}px`,"z-index":2,position:"absolute",top:0,left:0};os(this.mainCanvas,o),this.mouseCanvas=us(this.canvasContainer,"canvas"),as(this.mouseCanvas,{tabIndex:0}),o["z-index"]=3,o.outline="none",os(this.mouseCanvas,o),this.goToLatestButton=us(this.el,"button"),ds(this.goToLatestButton,'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">\n <path d="M13.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0zM6.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0z"></path>\n </svg>'),os(this.goToLatestButton,{position:"absolute",right:0,bottom:0,"z-index":3}),as(this.goToLatestButton,{class:"go-to-latest"}),this.goToLatestButton.onclick=()=>{this.xAxis.goToLatest()},this.listeners.push(()=>{this.goToLatestButton.onclick=null}),this.mainContext=this.mainCanvas.getContext("2d"),this.mouseContext=this.mouseCanvas.getContext("2d"),this.splitters=[],this.xAxis=new ET(this),this.eventCapture=new _T(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(r,n);const a=is(this.el);ie(rs(`.${gs.SVG_ICONS_DOM_NODE}`,a))||function(e){const t=us(e,"div");as(t,{class:gs.SVG_ICONS_DOM_NODE});const i=Object.keys(dd).map(e=>`<symbol id="${yd(e)}" viewBox="0 0 1024 1024">${dd[e]}</symbol>`).join("");t.innerHTML=`<svg style="display:none" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>${i}</defs></svg>`}(a)}reinitialize(){this.el&&hs(".bcharts-card",this.el).forEach(e=>e.remove()),this.customEventPopup?.hide(),this.drawCrosshair({ap:void 0}),this.tooltip.hide(),this.tooltip.setMode(this.presenter.display.tooltip.mode),this.resetZoomAndVisibleRange?this.xAxis=new ET(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,i=!1){this.setChartSize(e,t),this.redraw(i)}setChartSize(e,t){const i={width:`${e}px`,height:`${t}px`};os(this.el,i),this.width=e,this.height=t;const s=globalThis.devicePixelRatio||1,n={height:this.height*s,width:this.width*s};[this.mainCanvas,this.mouseCanvas].forEach(e=>{as(e,n),os(e,i)}),this.mainContext.scale(s,s),this.mouseContext.scale(s,s),this.recalculateLayout(),this.presenter&&HA(this.presenter)}widthNeeded(e,t){const i=this.presenter.allAxes.filter(e=>e.onTheRight===t);return 0===i.length?0:Math.max(...i.map(t=>t.widthNeeded(e)))}recalculateLayout(){if(!this.isHostElementVisible)return;this.leftOffset=0,this.rightOffset=0,this.presenter.allAxes.forEach(e=>e.clearTicks()),this.splitters.length=0;const e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),i=this.widthNeeded(this.mainContext,!1),s=this.height-e,n=this.presenter.panes;let r=O(n.map(e=>e.height)),o=0;const a=gs.PANE_SPLITTER_PERCENT_HEIGHT/100,l=Math.floor(a*s);r*=1+(n.length-1)*a;const c=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;if(this.presenter.display.yAxis.visible){n.some(e=>e.axes.length>1)?(this.leftOffset=i,this.rightOffset=t):c?this.leftOffset=i:this.rightOffset=t}n.forEach((e,i,n)=>{const a=i===n.length-1,c=Math.floor(s*e.height/r),u=new xn(0,o,this.width,c);e.setViewBox(u);const h=new xn(this.width-this.rightOffset,o,t,c),d=new xn(0,o,this.leftOffset,c),p=e=>e.setViewBox(e.onTheRight?h:d);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),o+=c,!a){const e=new xn(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,l);this.splitters.push(e),o+=l}});const u=new xn(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,e);this.xAxis.setViewBox(u),os(this.goToLatestButton,{right:`${t+5}px`,bottom:`${e+5}px`}),this.updateLegend(),this.xAxis.setDomain(),this.setPriceAxesDomains(),this.notifyLayoutChanged({chart:this.presenter.accessor})}setPriceAxesDomains(){this.presenter.allAxes.forEach(e=>{e.setDomain(),e.updateFullDomain()}),this.presenter.priceDomainsUpdated()}draw(){this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext);for(const s of this.presenter.panes)s.drawBackground(this.mainContext);this.xAxis.draw(this.mainContext);for(const s of this.presenter.panes)s.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext);const e=Gv().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart,i=ie(e)?e:t;this.goToLatestButton.style.display=i&&this.xAxis.canGoToLast()?"block":"none",this.mainContext.restore()}get isHostElementVisible(){return ie(this.el)&&ie(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():Gv().redraw(this.presenter.hostElement))}drawBackground(e){const t=this.presenter.display.chart.backgroundColor;e.clearRect(0,0,this.width,this.height),e.fillStyle=t,e.fillRect(0,0,this.width,this.height)}drawCrosshair({ap:e,offset:t}){const i=this.mouseContext;if(i.clearRect(0,0,this.width,this.height),!e)return!1;return!!this.xAxis.drawCrosshair(i,t)&&(this.presenter.display.yAxis.visible&&e.axis.pane.drawYCrosshair(i,t),!0)}drawSplitters(e){const t=(e=>{const t=bn(e);return Mn(vn(function({r:e,g:t,b:i,a:s}){return{r:255-e,g:255-t,b:255-i,a:s}}(t),t,.7))})(this.presenter.display.chart.backgroundColor);e.strokeStyle=t,e.lineWidth=2,this.splitters.forEach(t=>{const{x:i,y:s,width:n,height:r}=t,o=s+r/2;e.beginPath(),e.moveTo(i,o),e.lineTo(i+n,o),e.stroke()})}toTime(e){return this.xAxis.xScale.xToTime(e)}toIndex(e){return this.xAxis.xScale.timeToIndex(e)}toX(e){return this.xAxis.xScale.timeToX(e)}setCursor(e){const t=function(e){switch(e){case y.Arrow:default:return"default";case y.Crosshair:return"crosshair";case y.Hand:return"pointer";case y.Move:return"move";case y.ResizeVertical:return"ns-resize";case y.Grabbing:return"grabbing";case y.ResizeHorizontal:return"ew-resize"}}(e);os(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&hs(".bcharts-card",this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){const e=this.xAxis.xScale.bar.width/2;return Math.max(e,gs.MIN_EVENT_RADIUS)}}class OT{view;popupElement;date;value;visible;_initialized;constructor(e){this.view=e,this.date=null,this.value=null,this.visible=!1,this._initialized=!1}initialize(){this.popupElement=us(this.view.el,"div"),as(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),os(this.popupElement,{visibility:"hidden",position:"absolute","z-index":30,top:"0px",left:"0px",padding:"5px 10px 10px 10px",display:"flex","flex-direction":"column",background:"var(--chartPopupElemBg, #999)","box-shadow":"0px 2px 10px rgba(0,0,0,.3)","border-radius":"4px",border:"1px solid var(--chartPopupElemBorderColor, #888)","max-height":"400px",overflow:"auto"});const e=us(this.popupElement,"a");as(e,{class:"custom-event-close-button"}),os(e,{position:"absolute",right:"10px",top:"5px",fill:"var(--text-color,#888)",cursor:"pointer"}),e.innerHTML='<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="12px" height="12px"><use xlink:href="#bchart-icon-delete"></use></svg>',e.addEventListener("click",e=>this.hide()),this._initialized=!0}showValue(){}show(e,t,i){this._initialized||this.initialize(),this.date=t,this.value!==i&&(this.value=i,this.showValue()),os(this.popupElement,{visibility:"visible",top:`${e.y}px`,left:`${e.x}px`,width:"310px"}),this.visible=!0}hideValue(){}hide(){this.visible&&(this.hideValue(),os(this.popupElement,{visibility:"hidden"}),this.visible=!1)}}function wT(e,t){if(!((i=e).annotations&&i.annotations.length>0))return;var i;let s=t.annotations||[];t.annotations=s.concat(e.annotations)}const RT='..axes{..plots{.type==="Study"}}';const NT={ok:!1,change:void 0,toApply:void 0};class VT{constructor(e){this.presenter=e,this.clear()}paused=null;undoStack=[];redoStack=[];initial=/* @__PURE__ */new Map;isPaused=!1;clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=/* @__PURE__ */new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,cA(e,E.Moved)))}done(e){this.isPaused?this.paused=e:(this.undoStack.push(e),this.redoStack.length=0)}undo(){this.undoRedo(this.undoStack,this.redoStack,!0)}pause(){this.isPaused=!0}resume(e){this.isPaused=!1,e&&te(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){const t={...e,id:"Delete"};this.presenter.handleAnnotationChange(t)}add(e){const t={annotation:e,id:"Add"};this.presenter.handleAnnotationChange(t)}apply(e,t,i){if(!ie(e))return!1;switch(t){case E.None:case E.Undo:case E.Redo:Hv(`Unexpected tool change ${E[t]} for undo/redo`,"warn");break;case E.Created:i?this.delete(e):this.add(e);break;case E.Deleted:i?this.add(e):this.delete(e);break;default:{const t={...e,id:"Update"};this.presenter.handleAnnotationChange(t);break}}const s=this.presenter.allAnnotations.find(t=>t.uid===e.uid),n=i?E.Undo:E.Redo;return ie(s)&&this.presenter.onAnnotationModifiedByTool(s,n),!0}can(e){const t=e?this.undoStack:this.redoStack;if(t.length<1)return NT;const i=k(t),s=i.toolChange;if(!(e&&s!==E.Deleted&&s!==E.Created))return{ok:!0,change:s,toApply:i};const n=U(t,e=>e.uid===i.uid,t.length-2),r=-1!==n?t[n]:null,o=null===r;return o&&!this.initial.has(i.uid)?NT:{ok:!0,change:s,toApply:o?this.initial.get(i.uid):r}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,i){const{ok:s,change:n,toApply:r}=this.can(i);if(!s)return;const o=e.pop();this.apply(r,n,i),t.push(o)}}class HT{constructor(e){this.presenter=e}text=null;align="center";verticalAlign="top";x=0;y=0;style={color:"#333",fontSize:18};update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;const{fontFamily:t}=this.presenter.display.chart,{fontSize:i,color:s,fontWeight:n}=this.style,{x:r,y:o,width:a,height:l}=this.presenter.mainPlot.axis.pane.getBounds(),c=r+this.presenter.view.leftOffset,u=r+a-this.presenter.view.rightOffset;let h=c;h="center"===this.align?a/2:"right"===this.align?u:c;let d=o+i;"middle"===this.verticalAlign?d=o+i+l/2:"bottom"===this.verticalAlign&&(d=o+l),h+=this.x,d+=this.y,e.save();const p=n||"normal";e.font=`${p} ${i}px ${t}`,e.textAlign=this.align,e.textBaseline="bottom",e.fillStyle=s,e.fillText(this.text,h,d),e.restore()}}function BT(e={}){const t=this.allPlots;if(!t.every(e=>ie(e.timeSeries)&&e.timeSeries.hasData))return"No data to export";const i=e.excludeHeader??!1,s=e.numDecimals??null,n=e.excludeFields??[],r=e=>{const t=/* @__PURE__ */new Map;return e.main&&(t.set(Ka.DateTime,0),this.data.aggregation.isMultiContract&&!e.isExpression&&t.set(Ka.Symbol,0)),e.curves.forEach(e=>{e.fields.forEach(i=>{n.includes(i.id)||t.set(i,e.shift)})}),Array.from(t)},o=this.data.aggregation.isEndOfDay?gs.FMT_ISO_DATE_ONLY:gs.FMT_EXPORT_ALL_BUT_MILLIS,a=(e,t)=>e===Ka.DateTime?Si(t,o):(e=>ie(s,e)?se(e,s):e)(t)?.toString()??"",l={},c=this.timeline.lastSeriesIndex,u=W(this.mainPlot.timeSeries.container.getTimeData()),h=G(this.timeline,+u,Number,ud),d=(e,t)=>{const i=this.timeline.at(e),s=t.timeSeries.container,n=s.getTimeData(),c=l[t.id]||0,u=G(n,+i,Number,$,c),h=+i===+n[u];return h&&(l[t.id]=u),r(t).map(([t,r])=>{if(0===r)return h?a(t,s.getData(t)[u]):t===Ka.DateTime?Si(i,o):"";{const i=this.timeline.at(e-r),o=G(n,+i,Number,$,0);return+i===+n[o]?a(t,s.getData(t)[o]):""}})},p=e=>{const i=t.map(e).flat();return i.slice(1).every(e=>0===e.length)?null:i.join(",")},m=[];if(!i){const e=e=>{const t=new Array(r(e).length).fill("");return t[0]=(e=>`"${f[e.type]}: ${e.title}"`)(e),t};m.push(p(e)),m.push(p(e=>r(e).map(([e,t])=>`"${e.name}"`)))}const g=[0,0];this.allCurves.forEach(e=>{e.fields.every(e=>n.includes(e.id))||(e.shift<0&&(g[0]=Math.min(g[0],e.shift)),e.shift>0&&(g[1]=Math.max(g[1],e.shift)))});for(let f=h+g[0];f<=c+g[1];f++){const e=p(M(d,f));null!==e&&m.push(e)}return m.join("\n")}function FT(e={}){const t=this.view.mainCanvas,{width:i,height:s}=t,{width:n,height:r,title:o}=e,a=(e,t)=>{const i=document.createElement("canvas");return i.width=e,i.height=t,i.getContext("2d")},l=a(i,s),c=globalThis.devicePixelRatio;if(l.drawImage(t,0,0),l.scale(c,c),te(o)){const e=new HT(this);e.update(o),e.draw(l)}const u=this.mainPlot?.timeSeries.container?.getLastDataPoint(Ka.DateTime);if(te(u)){const{fontFamily:e}=this.display.chart,{fontWeight:i,fontSize:s}=this.mainAxis.config;l.font=`${i} ${1.2*s}px ${e}`,l.textBaseline="top";const n=1.5*s,r=getComputedStyle(t),o=r.getPropertyValue("--app-hc-color"),a=r.getPropertyValue("--app-color-pl"),c={x:gs.CARDS_X_OFFSET,y:gs.CARDS_Y_OFFSET},h=bd(this,u,c,0,!1,0),d=`${h.date} ${h.time??""}`.trim(),[p,m]=[1,5],g=(e,t)=>l.measureText(e).width+t,y=(e,t,i,s,n)=>(l.fillStyle=s,l.fillText(e,t,i),g(e,n)),A=(e,t)=>e.type===f[t],S=e=>{let t=e.name;return e.isMain&&A(e,"Symbol")?t=`${e.description} (${e.name}) [${e.exchange}]`:A(e,"Study")&&(t=`${e.description} ${e.name.substring(e.name.indexOf(" "))}`),t};h.panes.forEach(e=>{const{top:t,left:i,width:s,right:r}=e.bounds,l=i+s-r-m;let u=i+c.x,h=t+c.y;e.plots.some(e=>e.isMain)&&(u+=y(d,u,h,o,m)),e.plots.forEach((e,t)=>{const s=S(e),r=!A(e,"Study")&&e.values.length>1;if(!e.isMain&&t>0){let t=u+g(s,m);e.values.forEach(e=>{r&&(t+=g(e.abbreviation,p)),t+=g(e.value,m)}),t>=l&&(u=i+c.x,h+=n)}u+=y(s,u,h,o,m),e.values.forEach(e=>{r&&(u+=y(e.abbreviation,u,h,a,p)),u+=y(e.value,u,h,e.color,m)})})})}const h=e=>({width:n??i,height:r??s,data:e.toDataURL("image/png")});if(te(n)&&te(r)){const e=a(n,r);return e.drawImage(l.canvas,0,0,n,r),h(e.canvas)}return h(l.canvas)}const kT=/* @__PURE__ */Symbol.for("__ias__");class WT{constructor(e){this.accessor=e,this.defaultTool=XS("Default"),this._activeTool=this.defaultTool,this.timeline=new hd(this),this.undoRedoManager=new VT(this),this.title=new HT(this),this.notifySelectionChanged=Q(qa.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Q(qa.CH_RECREATED),this.notifyDefinitionChanged=Q(qa.CH_DEFINITION_CHANGED)}view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken="";metaChangedToken="";streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;getModel(){return this.model}get isEmpty(){return!ie(this.model)}notifyHost(e,t){J(e,t)}async fromModel(e,t){if(this._isShutdown)return;ie(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearSelection(),this.model=e;const i=ue(e);this.data=i.data,this.data.aggregation=No(i.data.aggregation),this.display=i.display,ie(this.display.period)&&(this.display.period=Te(this.display.period)),this.panes=i.panes.map(e=>{const t=new vT(this);return t.fromModel(e),t},this);const s=this.allPlots.map(e=>e.initialize());await Promise.all(s),this._isShutdown||(this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),ie(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view)if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{const i=!t||function(e,t,i){const s={id:"Aggregation",context:{id:"Get"}},n=Ro(Pv(s,t,i)),r=Ro(Pv(s,e,i));if(GT(n,r))return!0;if(!UT(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!UT(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;const o=Sa(t),a=Sa(e);if(function(e,t){const i=e=>e.curves[0],s=i(e),n=i(t),r=$T.includes(s.style),o=$T.includes(n.style);if(r!==o)return!0;if(!o)return!1;if(s.style!==n.style)return!0;if(t.inputs){if(GT(fe(e.inputs),fe(t.inputs)))return!0}return!1}(o,a))return!0;const l=(e,t)=>e.type===t,c=e=>{const t=e.toLowerCase();return l(a,e)&&l(o,e)&&o[t]!==a[t]},u=o.type!==a.type,h=c("Forward"),d=c("Expression"),p=c("Symbol");return u||h||d||p}(e,t,this);this.view.resetZoomAndVisibleRange=i,i&&(this._maxOffset=0)}}closeView(){ie(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(ie(this.view)?this.view.reinitialize():(this.view=new DT,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e))}get activeTool(){return this._activeTool}set activeTool(e){ie(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,ie(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(qa.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){const e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){const e=[];return this.allPlots.forEach(t=>{t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){const e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){const e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){const e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}fixupDensityForForwards(){const e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;const i=t.series,s=e=>e.timeSeries===i||e.eventsSeries===i,n=this.allPlots.find(s);if(!ie(n))return;const r=ie(n)&&n.main;let o=!1,a=!1;if(e===qa.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}const l=ie(t.index)?i.container.getTimeData()[t.index]:null,c=e===qa.TS_EVENTSCHANGED,u=this.view.xAxis,h=u.xScale;if(e===qa.TS_MANYCHANGED||c){if(r&&this.data.checkRange){if(ie(this.display.xAxis.visibleRange)){const e={id:"Period",context:{range:this.display.xAxis.visibleRange}};return e[kT]=!0,void this.accessor.change(e)}delete this.data.checkRange}n.isForward&&this.fixupDensityForForwards();const e=this.view.xAxis?.getMaxCurveOffset()??0;if(n.isStudy){e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0));n.invalidateAssociatedAnnotations("NewChunkArrived")}if((n.isSeasonal&&!u.wasVisibleRangeChanged||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===P.Tail){const e=G(this.timeline,l,Number,ud);u.shouldScrollIntoView(e)&&h.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===qa.TS_DATAPOINTADDED){const e=this.timeline.mergeDateIntoTimeline(l);-1!=e&&u.shouldScrollIntoView(e)?(h.shiftBars(1),o=!0):a=!0,n.isStudy&&n.invalidateAssociatedAnnotations("DataPointAdded")}else e===qa.TS_DATAPOINTCHANGED&&(a=!0,n.isStudy&&n.invalidateAssociatedAnnotations("DataPointChanged"));if(!c&&s(this.mainPlot)&&i.hasData&&0===i.container.size&&this.notifyHost(qa.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),a){o&&Hv("Performance : redundant call to recompute price domains (layout recalculation took care of this)","warn");this.allAxes.filter(e=>e.plots.includes(n)).forEach(e=>{e.setDomain(),ie(l)&&e.updateFullDomain(l)})}if(!this.sentInitialLoadNotification&&e===qa.TS_MANYCHANGED){if(this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(qa.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),HA(this);const e=this.display.period===gs.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(h.fitAllData=!0,h.adjustDomain())}}this.view.redraw()}onMetaChanged(e,t){e===qa.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){const t=this.panes.indexOf(e.pane),i=e.pane.axes.indexOf(e),s={chart:this.accessor,paneIndex:t,axisIndex:i};this.notifyHost(qa.CH_AXISSCALECHANGED,s)}get previousMask(){return ie(this._previousMask)||(this._previousMask=Za(Ka.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return ie(this._hasLegend)||(this._hasLegend=Gv().config.mode===v[v.cmdtyView]),this._hasLegend}onStreamingUpdates(e){ie(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return ie(this._ohlcMask)||(this._ohlcMask=Za(Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.PreviousClose)),this._ohlcMask}updateMatches(e,t){if(0===(e&this.ohlcMask))return!1;const i=(e,t)=>te(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?i(this.mainPlot.timeSeries.record,t):!!this.mainPlot.isExpression&&i(this.mainPlot.record,t)}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return ie(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:rs(`#${e}`),!this._hostElement)throw new Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=ap.subscribe(qa.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=ap.subscribe(qa.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return ap.unsubscribe(this.seriesChangedToken),ap.unsubscribe(this.metaChangedToken),ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(qa.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor})}clearSelection(){ie(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(y.Arrow)}print(e={}){const t=us(document.body,"iframe");t.src="",t.style.display="none",t.onload=()=>{const{title:i}=e,s=FT.call(this,{title:i}),n=new Image;n.src=s.data,n.style.width="100%";var r;t.contentDocument.body.appendChild(n),(r=n,new Promise(e=>{const t=()=>{r&&void 0!==r.naturalWidth&&0!==r.naturalWidth&&r.complete?e():setTimeout(t,150)};t()})).then(()=>{const e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),ie(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;const t=this.display.tooltip.mode===gs.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){const t=this.display.tooltip,i=q();!e&&t.visible&&t.mode===gs.TOOLTIP_CARDS&&hs(".bcharts-card",this.hostElement).forEach(e=>{const t=e.classList.contains("bcharts-card-move");if(i&&t)return;e.classList.contains("bcharts-legend")||(e.style.display="none")})}handleAnnotationChange(e){const t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if("List"===e.id)return this.allAnnotations.map(t);if("Cache"===e.id){return ro(this.model,"..annCache{.annotations}").map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}))}if("Add"===e.id)return this.mainAxis.addAnnotation(e.annotation);const i=this.allAnnotations.find(t=>t.uid===e.uid);if(void 0!==i){const t=i.axis,s=t[`${e.id.toLowerCase()}Annotation`];if("function"==typeof s)return s.call(t,i,e),void("Delete"!==e.id||e.isUndoRedo||this.onAnnotationModifiedByTool(i,E.Deleted))}throw new Error(`Unknown sub-action ${e.id} for action ${gs.ANN_ACTION_ID}`)}getPlotInfoFromDomId(e){const t=e.attributes.getNamedItem("data-plot-id").value,i=this.allPlots,s=i.findIndex(e=>e.id===t);return{type:f[i[s].type],index:s}}getSimplePlot(e,t){return this.accessor.change({id:"Plot",context:{id:gs.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){const t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index),s={chart:this.accessor,plot:i};this.notifyHost(qa.CH_CARDPLOTCLICKED,s)}deletePlotClicked(e){const t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index);this.accessor.change({id:"Plot",context:{id:"Delete",type:t.type,index:t.index}});const s={chart:this.accessor,plot:i};this.notifyHost(qa.CH_CARDPLOTREMOVED,s)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);const t=this.getPlotInfoFromDomId(e),i="Show"===e.attributes.getNamedItem("data-act").value;this.accessor.change({id:"Plot",context:{id:"Update",type:t.type,index:t.index,visible:i}});const s=this.getSimplePlot(t.type,t.index),n={chart:this.accessor,plot:s,visible:i};this.notifyHost(qa.CH_CARDPLOTVISIBILITYCHANGED,n)}plotMoreActionsClicked(e,t){const i=this.getPlotInfoFromDomId(e),s=this.getSimplePlot(i.type,i.index),n={x:t.clientX,y:t.clientY},r={chart:this.accessor,plot:s,offset:n,originalEvent:t};this.notifyHost(qa.CH_PLOTNEEDSCONTEXTMENU,r)}onMovePaneClicked(e){const t=parseInt(e.attributes.getNamedItem("data-pane").value),i="Down"===e.attributes.getNamedItem("data-dir").value,s=t+(i?1:0),n=t-(i?0:1);setTimeout(()=>{this.accessor.change({id:"MovePane",context:{from:s,to:n}}),this.notifyHost(qa.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){const i=this.allAxes.indexOf(e),s=e.annotations.map(e=>e.toModel()),n=oo(this.model,`..axes[${(r={axisIndex:i,annotations:s}).axisIndex}]`,e=>(e.annotations=r.annotations,e));var r;try{this.model=Wa(n,gs.CHART_SCHEMA)}catch(o){Hv(`Cannot update annotation (corrupts definition), error is: ${o.message}`,"error")}t&&this.view.draw(),this.notifyHost(qa.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,i=!0){if(t!==E.None){if(i&&t!==E.Undo&&t!==E.Redo){const i=cA(e,t);this.undoRedoManager.done(i)}const s=uA(e);s.toolChange=E[t],this.notifyHost(qa.CH_ANNMODIFIEDBYTOOL,s)}}onAnnotationDone(e,t){const i={id:e,chart:this.accessor,toolChange:E[t]};this.notifyHost(qa.CH_ANNMODIFIEDBYTOOL,i)}onPaneHeightsUpdated(){const e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=function(e,t){let i=e;return t.paneHeights.forEach(e=>{i=oo(i,`..panes[${e.index}]`,t=>(t.height=e.relativeHeight,t))}),i}(this.model,{paneHeights:e}),this.notifyHost(qa.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){const e=this.mainPlot.timeSeries.container;if(!ie(e)||0===e.size)return null;const t=e.getTimeData();return{dataRange:{from:W(t).getTime(),to:k(t).getTime()},barCount:e.size}}}function UT(e,t){return e?.from===t?.from&&e?.to===t?.to}const $T=["Renko","Range","LineBreak","Kagi","PointAndFigure"];function GT(e,t){for(const i of Object.keys(e))if(e[i]!==t[i])return!0}const zT="MARKED_FOR_DELETION";function YT(e,t){if(0===t.plots.length)return e;let i=e;return t.plots.forEach(e=>{const t=qT(e.index),s=XT(i,t);ie(s)&&s.type===e.type&&(i=oo(i,t,e=>(e[zT]=!0,e)))}),i=oo(i,`..plots{.${zT} === true}`,e=>gs.NULL_OBJECT),Ua(i)}function jT(e,{main:t,type:i,index:s},n){const r="..plots{.main === true}",o=ro(e,"..panes").map((e,t)=>{const i=1===ro(e,r).length;return ro(e,"..axes").map((e,s)=>{const o=1===ro(e,r).length;return ro(e,"..plots").map(e=>{const r=function(e,t,i,s){const n=f[e.type],r={curves:ue(e.curves),type:e.type};r.precision=e.precision,r.visible=e.visible;const o=(e,t)=>{ie(e[t])?r[t]=e[t].map(e=>ue(e)):r[t]=[]},a=(e,t,i=!1)=>{!0===t.main&&(e.main=!0,e.showPrevious=t.showPrevious,i&&null!=t.events&&(e.events=ue(t.events)))},l=(e,t=e=>!0)=>{ie(s)&&(e.subtitles=s.allPlots.filter(e=>e.type===n).filter(t).map(e=>e.title))};switch(n){case f.Symbol:{const t=e;r.title=t.symbol;const i=t=>{o(e,"inputs"),0===r.inputs.length&&(r.inputs=ue(t))};switch(r.curves[0].style){case"Renko":i(gs.DEFAULT_RENKO_INPUTS);break;case"Kagi":i(gs.DEFAULT_KAGI_INPUTS);break;case"PointAndFigure":i(gs.DEFAULT_PNF_INPUTS);break;case"LineBreak":i(gs.DEFAULT_LINEBREAK_INPUTS);break;case"Baseline":i(gs.DEFAULT_BASELINE_INPUTS)}a(r,e,!0);break}case f.Study:{o(e,"inputs");const s=Ur(e.study),n=r.inputs,a="AVWAP"===e.study,l=e=>a&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value,c=0===n.length?"":` (${n.map(l).join(", ")})`,u=r.curves.map(e=>Number(e.shift)).filter(e=>e>0),h=0===u.length?"":` [${u.join(", ")}]`;r.title=`${s.id}${c}${h}`,r.studyId=s.id,o(e,"levels"),o(e,"bands"),r.placement=t?i?"overlay":"withMain":"standalone",r.detachedScale=e.detachedScale;break}case f.BalanceSheet:case f.IncomeStatement:{const t=Ka[e.curves[0].fields[0]];r.title=`${t.name} (${e.fundamental.substring(0,1)})`,r.fundamentalId=t.id,r.frequency=e.fundamental;break}case f.Expression:r.title=e.expression,a(r,e);break;case f.Forward:r.title=e.forward,o(e,"offsets"),l(r),a(r,e);break;case f.Seasonal:r.title=e.seasonal,l(r,e=>e.refSeasonal===r.title),o(e,"offsets"),a(r,e);break;default:throw new Error("Unexpected plot type")}return r}(e,i,o,n);return r.paneIndex=t,r.axisIndex=s,r})})}).flat(2).map((e,t)=>(e.index=t,e));if(t)return o.filter(e=>e.main);if(ie(i)){const e=o.filter(e=>e.type===i);return ie(s)?e.filter(e=>e.index===s):e}return o}function KT(e,t){"Study"===e.type&&t.curves?.forEach(e=>delete e.varyColorPerBar),function(e){const t=f[e.type];return t===f.Forward||t===f.Seasonal}(e)?ie(t.curves)&&(e.curves=t.curves):function(e,t){if(i=t,void 0!==i&&t.length===e.length)for(let s=0;s<e.length;++s){const i=t[s],n=e[s];de(n,i);const r=["shift","dashStyle","lineSmoothing","lineMarker"];for(const e of r){const t=i[e];ie(t)&&(n[e]=t)}}var i}(e.curves,t.curves);const i=f[t.type],s=e;if(ie(t.precision)?s.precision=t.precision:delete s.precision,i===f.Symbol)e.symbol=t.symbol;else if(i===f.Study)!function(e,t,i){const s=fe(e),n=fe(t);de(s,n);const r=(o=n,Object.keys(o).map(e=>({name:e,value:o[e]})));var o;r.length>0&&(i.inputs=r)}(e.inputs,t.inputs,e),["bands","levels","detachedScale"].forEach(i=>function(e,t,i){t[i]&&(e[i]=t[i])}(e,t,i));else if(i!==f.BalanceSheet&&i!==f.IncomeStatement||!t.frequency){if(i===f.Expression){const i=e;ie(t.expression)&&(i.expression=t.expression)}else if(i===f.Forward){const i=e;ie(t.offsets)&&(i.offsets=t.offsets),ie(t.forward)&&(i.forward=t.forward)}else if(i===f.Seasonal){const i=e;ie(t.offsets)&&(i.offsets=t.offsets),ie(t.seasonal)&&(i.seasonal=t.seasonal),ie(t.usesInAverage)&&(s.usesInAverage=t.usesInAverage),_o(i)}}else e.fundamental=t.frequency}const qT=e=>`..plots[${e}]`;function XT(e,t){const i=ro(e,t);return 1!==i.length?null:i[0]}const ZT=["withMain","overlay","standalone","clone"];function JT(e){return{axes:[{plots:[]}],height:e.display.chart.newPaneHeight??1}}function QT(e){const t=JT(e);return e.panes.push(t),t}function ev(e,t){const i=te(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:QT(e),s=i.axes[0];return t.oppositeScale??!1?hv(i,s):s}function tv(e,t,i){let s=null;const{mainPane:n,mainAxis:r}=Ta(e);switch(t){case"withMain":s=hv(n,r);break;case"overlay":s=r;break;case"standalone":s=QT(e).axes[0];break;case"clone":if("number"==typeof i){const t={main:!1,index:i,type:f[f.Study]},n=jT(e,t).find(e=>e.index===t.index);s=ro(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}}return s}const iv=[{fields:[Ka.Close.id],colors:["#888"],style:"Line",lineWidth:2,varyColorPerBar:!1,visible:!0}];function sv(e){return"Symbol"===e.type}const nv={attributes:["OpenVsClose"],colors:["#b63400","#007f3e","#1664db"],fields:["Open","High","Low","Close","Change"],style:"Candlestick",varyColorPerBar:!0,lineWidth:1};let rv=0;const ov=["#0d223a","#8abc21","#910000","#2f7ed8","#42ccdc","#bf95df","#860262","#e5daa3","#4682e8","#aaa9c1","#fcccdc","#f66b00","#d875be","#e84b46"],av="Symbol",lv="Expression";function cv(e,t){const i={curves:[{attributes:[],colors:ov.slice(rv,rv+1),fields:e?[Ka.Last.id]:[Ka.Close.id],style:"Line",dashStyle:"Solid",varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0}]};return delete t.oppositeScale,pe(i,t),ie(t.curves)&&de(i.curves,t.curves),rv=(rv+1)%ov.length,i}const uv='..plots{(.type === "Symbol" || .type === "Expression") && .main !== true}';function hv(e,t){let i=e.axes.find(e=>e!==t);return ie(i)||(i={plots:[]},e.axes.push(i)),i}const dv=()=>gs.NULL_OBJECT;function pv(e){return oo(e,"..axes.annotations",dv)}function fv(e){return Ua(oo(e,'..plots{.type === "Symbol" && .main !== true}',dv))}const mv=".display.chart.previous";function gv(e,t,i){const s=[],n=i.allPlots[t.index];if(n?.type!==f[t.type])return s;const r=i.panes.indexOf(n.axis.pane),o=0===r,a=r===i.panes.length-1,l=1===i.panes[r].axes.reduce((e,t)=>e+t.plots.length,0);return o||s.push("ExistingAbove"),l||s.push("NewAbove"),a||s.push("ExistingBelow"),l||s.push("NewBelow"),s}function yv(e,t,i){const s=[],n=i.allPlots[t.index];if(n?.type!==f[t.type])return s;const r=n.axis.pane,o=n.axis===r.axes[0],a=r.axes.some(e=>e.plots.some(e=>n!==e&&!e.hasDetachedScale)),l=n.hasDetachedScale;return(o||l)&&s.push("SecondaryAxis"),o&&!l||s.push("PrimaryAxis"),a&&s.push("NoAxis"),s}function Av(e,t){const i=e.panes[t],s=i.axes.map(e=>e.plots.reduce((e,t)=>e+(t.detachedScale?1:0),0)),n=i.axes.length;return i.axes.forEach((e,t)=>{const r=s[t],o=e.plots.length;if(!(0===r||r<o)&&r===o)if(n>1&&1===r){const r=(t+1)%n;if(s[r]<i.axes[r].plots.length){const t=e.plots.find(e=>e.detachedScale);t&&(i.axes[r].plots.push(t),e.plots=e.plots.filter(e=>!e.detachedScale),s[r]++)}}else{const t=e.plots.find(e=>e.detachedScale);t&&(t.detachedScale=!1)}}),e}function Sv(e,t){const i=e.allPlots[t],s=e.panes.indexOf(i.axis.pane),n=e.panes[s].axes.indexOf(i.axis);return{pane:s,axis:n,plot:e.panes[s].axes[n].plots.findIndex(e=>e===i)}}const Tv={MainPlot:Ma,Aggregation:{Update:Ia,Get:function(e,t,i){return ue(e.data.aggregation)}},Period:{Update:function(e,t,i){const s=ie(t.period),n=ie(t.range),r=ie(t.density),o=e=>e?1:0;if(o(s)+o(n)+o(r)>1)throw new Error("Cannot set more than one of: period, range, density.");if(s&&(e.display.period=t.period,$o(e),zo(e)),n)if(ie(e.display.period)&&!Da(e.display.period)||(e.display.xAxis.visibleRange=t.range),Go(e),zo(e),ie(i)){const s=function(e){const t=e.getDataStats();return null===t?null:t.dataRange}(i),n=No(e.data.aggregation),r=i.data.aggregation,o=(l=r,(a=n).unit!==l.unit||a.size!==l.size||a.spec!==l.spec||!ie(s)||e.data.checkRange);let c=o;if(!o){const{from:e,to:i}=s,{from:n,to:r}=t.range;c=n<e||n>i||r<e||r>i}c&&(e.data.range=t.range),delete e.data.checkRange}else e.data.checkRange=!0;var a,l;return r&&(e.display.density=t.density,$o(e),Go(e)),(s||n||r)&&(Uo(e),i&&(i.forceResetVisibleRange=!0)),e},Delete:function(e,t,i){return ie(t.period)&&t.period&&(delete e.display.period,_a(e),i&&(i.forceResetVisibleRange=!0)),e}},Crosshair:{Update:function(e,t){let[i,s]=re(t.crosshair);const{color:n,dashStyle:r}=t.horizontal||{},{color:o,dashStyle:a}=t.vertical||{},l=(e,t,i)=>{t&&(e.color=t),i&&(e.dashStyle=i)};let c=oo(e,".display.xAxis.crosshair",e=>(e.enabled=i,l(e,o,a),e));return c=oo(c,".display.yAxis.crosshair",e=>(e.enabled=s,l(e,n,r),e)),ie(t.haloTracking)&&"boolean"==typeof t.haloTracking&&(c=oo(c,".display.chart",e=>(e.plotHover=t.haloTracking,e))),c},Get:function(e,t,i){const s=t=>ro(e,t)[0],n=s(".display.chart"),r=s(".display.xAxis.crosshair"),o=s(".display.yAxis.crosshair");let a="none";return r.enabled&&o.enabled?a="both":r.enabled?a="vertical":o.enabled&&(a="horizontal"),{crosshair:a,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:r.color,dashStyle:r.dashStyle},haloTracking:n.plotHover}}},Tooltip:{Update:function(e,t){return oo(e,".display.tooltip",e=>(null!=t.visible&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),null!=t.showMainTitle&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))},Get:function(e,t,i){const s=ro(e,".display.tooltip")[0];return{visible:s.visible,mode:s.mode,showMainTitle:s.showMainTitle,mainTitle:s.mainTitle}}},Events:function(e,t){const i=ue(t);return Object.keys(t).forEach(e=>{gs.EVENTS.includes(e)||delete i[e];let s=t[e];"boolean"==typeof s?s={show:t[e]}:Object.keys(s).forEach(e=>{gs.EVENT_PROPERTIES.includes(e)||delete s[e]}),i[e]=s}),oo(e,Aa,e=>("Symbol"===e.type&&(e.events=e.events||{},Object.keys(i).forEach(t=>{e.events[t]=e.events[t]||{},he(e.events[t],i[t],!1)})),e))},Scale:{Update:function(e,t){let i=oo(e,"..panes[0]..axes",e=>(te(t.scale)&&(e.scale=t.scale),e));return i=oo(i,".display.xAxis",e=>(te(t.marginBars)&&(e.marginBars=t.marginBars),te(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),te(t.ordinalName)&&(e.ordinalName=t.ordinalName),te(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e)),i=oo(i,".display.yAxis",e=>{(ie(t.minPadding)||ie(t.maxPadding))&&Hv("The 'minPadding' and 'maxPadding' are deprecated (ignored)","warn");const i=te(t.preventLabelOverlap)&&!te(t.preventVerticalLabelOverlap);i&&Hv("The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'","warn");const s=i?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return te(s)&&(e.preventLabelOverlap=s),ie(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),ie(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),e}),ie(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{const{axis:t,text:s,index:n,paneIndex:r}=e;if(ie(t,s,n)&&"vertical"===t&&Number.isInteger(n)){i=oo(i,`..panes[${r??0}]..axes[${n}]`,e=>ie(e)?(e.label=s,e):gs.NULL_OBJECT)}}),te(t.contractTransition)&&(i=oo(i,".display.xAxis",e=>(de(e.contractTransition,t.contractTransition),e))),te(t.cycleTransition)&&(i=oo(i,".display.xAxis",e=>(de(e.cycleTransition,t.cycleTransition),e))),i},Get:function(e,t,i){const{mainAxis:s}=Ta(e),n=ro(e,".display.xAxis")[0],r=ro(e,".display.yAxis")[0];return{scale:s.scale,marginBars:n.marginBars??0,preventLabelOverlap:r.preventLabelOverlap,preventVerticalLabelOverlap:r.preventLabelOverlap,preventHorizontalLabelOverlap:n.preventLabelOverlap,snapAnnotationsToPrices:r.snapAnnotationsToPrices,nonEodLabelWithDate:n.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:r.includePercentChangeWithLastValue??!1,ordinalName:n.ordinalName??"",contractTransition:n.contractTransition,cycleTransition:n.cycleTransition}}},Other:{Update:function(e,t,i){let s=e;if(ie(t.comparisonMode)&&"string"==typeof t.comparisonMode&&le(d,t.comparisonMode)&&(s=oo(s,`..panes{${Aa}}.axes`,e=>(e.comparison=t.comparisonMode,e))),ie(t.gridLines)){const[e,i]=re(t.gridLines);s=oo(s,".display.xAxis.gridLines",t=>(t.visible=e,t)),s=oo(s,".display.yAxis.gridLines",e=>(e.visible=i,e))}if(ie(t.minorGridLines)){const[,e]=re(t.minorGridLines);s=oo(s,".display.yAxis.minorGridLines",t=>(t.visible=e,t))}ie(t.newPaneHeight)&&"number"==typeof t.newPaneHeight&&(s=oo(s,".display.chart{.newPaneHeight > 0}",e=>(e.newPaneHeight=t.newPaneHeight,e))),ie(t.showNavigator)&&"boolean"==typeof t.showNavigator&&(s=oo(s,".display.scrollbar",e=>(e.visible=t.showNavigator,e))),ie(t.plotHover)&&"boolean"==typeof t.plotHover&&(s=oo(s,".display.chart",e=>(e.plotHover=t.plotHover,e))),ie(t.showLastValue)&&"string"==typeof t.showLastValue&&(s=oo(s,".display.yAxis",e=>(e.showLastValue=t.showLastValue,e))),ie(t.showMinMaxArc)&&"boolean"==typeof t.showMinMaxArc&&(s=oo(s,".display.chart",e=>(e.showMinMaxArc=t.showMinMaxArc,e))),ie(t.showGoToLatest)&&"boolean"==typeof t.showGoToLatest&&(s=oo(s,".display.chart",e=>(e.showGoToLatest=t.showGoToLatest,e))),ie(t.showLegend)&&"boolean"==typeof t.showLegend&&(s=oo(s,".display.chart",e=>(e.showLegend=t.showLegend,e)),t.showLegend||i.view.removeLegend()),ie(t.allAnnotationsLocked)&&"boolean"==typeof t.allAnnotationsLocked&&(s=oo(s,".display",e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),ie(t.exprSkipLeadingEmpty)&&"boolean"==typeof t.exprSkipLeadingEmpty&&(s=oo(s,".data",e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));const n=[];if(ie(t.extendedHours)&&"boolean"==typeof t.extendedHours&&(s=oo(s,".data",e=>(e.extendedHours=t.extendedHours,e))),ie(t.realTimeCboeBzx)&&"boolean"==typeof t.realTimeCboeBzx&&(s=oo(s,".data",e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&n.push("realTimeCboeBzx"),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),ie(t.buildContinuation)&&"boolean"==typeof t.buildContinuation&&(s=oo(s,".data",e=>(e.buildContinuation=t.buildContinuation,e))),n.length>0){const e={chart:i.accessor,hostPropsChanged:n};i.notifyHost(qa.CH_HOST_PROPS_CHANGED,e)}return s},Get:function(e,t,i){const s=ro(e,`..panes{${Aa}}.axes.comparison`)[0],n=e.display,r=(e,t)=>ce(e,!1,t,"visible"),o=e=>function(e,t){const i=e=>ie(e)&&"boolean"==typeof e&&e,s=i(e),n=i(t);return s&&n?"both":s?"vertical":n?"horizontal":"none"}(r(n.xAxis,e),r(n.yAxis,e)),a=ce(n.chart,!0,"showLegend");return{comparison:s,gridLines:o("gridLines"),minorGridLines:o("minorGridLines"),newPaneHeight:n.chart.newPaneHeight,showLastValue:n.yAxis.showLastValue,showLegend:a,showMinMaxArc:n.chart.showMinMaxArc,allAnnotationsLocked:n.allAnnotationsLocked,exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}},Plot:{Add:function(e,t){switch(t.type){case"Study":return function(e,t){const i=Ur(t.studyId);if(!te(i))return Hv(`Unknown or unavailable study with the id '${t.studyId}'`,"error"),e;const s=Sa(e),n=Yr(i);if(s.type===f[f.Expression]&&n)return Hv(`Cannot add study "${i.meta.title}" because it cannot be based on an expression (current main plot); study needs more than "OHLCV" fields to be calculated.`,"error"),e;const r=t.placement||(i.meta.overlay?"overlay":"standalone"),o={type:"Study",study:t.studyId,visible:!0};"overlay"===r&&"VOL"===t.studyId&&(o.detachedScale=!0),void 0!==t.curves&&(o.curves=i.defaults.curves),KT(o,t);const a=tv(e,r,t.cloneIndex);ie(a)&&a.plots.push(o);const l=e.data.aggregation;return xa(e,"Tick"===l.unit&&"None"===l.spec)}(e,t);case"IncomeStatement":case"BalanceSheet":return function(e,t){const i=Sa(e);if(i.type!==f[f.Symbol])throw new Error("Cannot add fundamental to the chart whose main plot is not a Symbol plot.");const s=i.symbol,n={curves:[{fields:[t.fundamentalId],lineWidth:2,style:"Line",varyColorPerBar:!1,visible:!0,colors:["#888"]}],fundamental:"Quarter",symbol:s,type:h[Ka[t.fundamentalId].category],visible:!0};return KT(n,t),function(e,t){e.panes.push({axes:[{plots:[t]}]})}(e,n),e}(e,t);case"Expression":return function(e,t){const i=Sa(e),s={curves:ue(sv(i)?i.curves:iv),expression:"",type:"Expression",visible:!0};return KT(s,t),ev(e,t).plots.push(s),e}(e,t);case"Symbol":return function(e,t){const i=Sa(e),s=Gv().getDefaultMultiFieldCurve(),n=ie(s)?s:nv,r=i.curves?.length,o={curves:r===t.curves.length&&1===r?ue(sv(i)?i.curves:[n]):t.curves,symbol:"",type:"Symbol",visible:!0};return KT(o,t),ev(e,t).plots.push(o),e}(e,t);case"Seasonal":return function(e,t){const i={curves:ue(iv),offsets:[0],seasonal:"",type:"Seasonal",visible:!0,main:!1};return KT(i,t),t.paneIndex=t.paneIndex??0,ev(e,t).plots.push(i),e}(e,t);default:throw new Error("Unexpected plot type '${type}', not supported currently")}},Get:jT,Delete:YT,Update:function(e,t,i){if(ie(t.placement)&&!ZT.includes(t.placement))throw new Error(`Unknown placement: ${t.placement}`);const s=t.main?Aa:qT(t.index),n=XT(e,s);if(!te(n)||te(t.type)&&n.type!==t.type)return e;if(te(t.visible))return n.visible=t.visible,e;if(n.main&&function(e){const t=f[e.type];return t===f.Symbol||t===f.Expression}(n)){if(t.curves){const i=e=>e.curves[0].style===o[o.Range],[s,r]=[i(n),i(t)],a=!s&&r;s&&!r?e=Ia(e,{unit:"Day",size:1,spec:"None"}):a&&(e=Ia(e,{unit:"Intraday",size:100,spec:"PerRange"}))}t.type||(t.type=n.type);const i=n;return ie(t.precision)?i.precision=t.precision:delete i.precision,ie(t.showPrevious)&&(e=oo(e,Aa,e=>(e.showPrevious=t.showPrevious,e))),t.curves?Xo(e,t):e}{let n=oo(e,s,e=>(KT(e,t),e));const r=jT(n,t,i).find(e=>e.index===t.index);if(!ie(r))return e;if(!(t.type===f[f.Study]&&ie(t.placement)&&t.placement!==r.placement))return n;const o=XT(n,s);n=YT(n,{plots:[{index:t.index,type:t.type}]});const a=tv(n,t.placement);return null!==a&&a.plots.push(o),n}}},Compare:{Update:function(e,t){const i=function(e){return ie(e.symbols)&&(Hv("Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types","warn"),e.plots=e.symbols.map(e=>(e.type=av,e))),e.plots?.some(e=>ie(e.leftScale))?(Hv("Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'","warn"),e.plots.map(e=>{const t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}(t),{yes:s,no:n}=V(i,e=>e.oppositeScale??!1),{mainPane:r,mainAxis:o}=Ta(e);r.alignOnExpirations=t.alignOnExpirations||!1;const a=hv(r,o),l=e=>![av,lv].includes(e.type);a.plots=a.plots.filter(l);const c=o.plots.filter(e=>e.main||l(e)),u="Tick"===e.data.aggregation.unit;rv=0;const h=M(cv,u);return o.plots=c.concat(n.map(h)),s.length>0&&(a.plots.push(...s.map(h)),a.comparison=o.comparison,a.scale=o.scale),Ua(e)},Get:function(e,t){const i=ro(e,uv),{mainPane:s,mainAxis:n}=Ta(e),r=[];for(const o of i){const e=n.plots.includes(o),t=o.type.toLowerCase(),i={curves:ue(o.curves),type:o.type,[t]:o[t],leftScale:!e};r.push(i)}return{plots:r,alignOnExpirations:s.alignOnExpirations}}},Annotation:{Get:function(e,t,i){const s=ro(e,"..panes").map((e,t)=>ro(e,"..axes").map((e,i)=>ro(e,".annotations").map(e=>({...e,paneIndex:t,axisIndex:i})))).flat(2).map((e,t)=>({...e,index:t}));return ie(t.index)&&Number.isFinite(t.index)?t.index<s.length?[s[t.index]]:gs.EMPTY_ARRAY:s}},MovePane:function(e,t){let i=e.panes;return i.splice(t.to,0,i.splice(t.from,1)[0]),e},Template:function(e,t){let i=ue(e);if(t.strip.main){const e=Sa(i),t=e.type.toLowerCase();e[t]=gs.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(i=pv(i)),t.strip.compare&&(i=fv(i)),i=oo(i,".data",e=>(e.range&&(delete e.range,e.checkRange=!0),e)),i},Outline:function(e,t,i){const s=jT(e,{main:!0},i)[0],n=s.title===gs.PLACEHOLDER_SYMBOL_NAME,r="Symbol"===s.type,o="Expression"===s.type,a=ca(s.title);let l=[];return o&&!la(a)?l=a.symbols:n||(l=[s.title]),{isTemplate:n,isDefinition:!n,main:{isSymbol:r,isExpression:o,symbols:l,title:n?null:s.title},compare:ro(e,uv).map(e=>e.symbol),annotations:ro(e,"..annotations").map(e=>e.id),studies:jT(e,{type:"Study"},i).map(e=>e.title)}},Theme:{Update:function(e,t){let i=e;const{backgroundColor:s,axis:{gridLinesColor:n,textColor:r,crosshairColor:o,gridLinesStyle:a},fontSize:l}=t,{chart:c,xAxis:u,yAxis:h}=l||{};if((s||c)&&(i=oo(e,".display.chart",e=>(s&&(e.backgroundColor=s),c&&(e.fontSize=c),e))),n){const e=e=>(e.color=n,e);i=oo(i,".display.xAxis.gridLines",e),i=oo(i,".display.yAxis.gridLines",e),i=oo(i,".display.yAxis.minorGridLines",e)}if(a){const e=e=>(e.dashStyle=a,e);i=oo(i,".display.xAxis.gridLines",e),i=oo(i,".display.yAxis.gridLines",e),i=oo(i,".display.yAxis.minorGridLines",e)}if(r){const e=e=>(e.textColor=r,e);i=oo(i,".display.xAxis",e),i=oo(i,".display.yAxis",e)}if(o){const e=e=>(e.color=o,e);i=oo(i,".display.xAxis.crosshair",e),i=oo(i,".display.yAxis.crosshair",e)}if(u||h){const e=e=>t=>(t.fontSize=e,t);u&&(i=oo(i,".display.xAxis",e(u))),h&&(i=oo(i,".display.yAxis",e(h)))}return i},Get:function(e,t,i){const{chart:s,xAxis:n,yAxis:r}=e.display||{},{fontSize:o,backgroundColor:a}=s||{},{fontSize:l,gridLines:c,textColor:u,crosshair:h}=n||{},{color:d,dashStyle:p}=c||{},{fontSize:f}=r||{},{color:m}=h||{};return{backgroundColor:a,axis:{gridLinesColor:d,textColor:u,crosshairColor:m,gridLinesStyle:p},fontSize:{chart:o,xAxis:l,yAxis:f}}}},Clear:function(e,t,i){const{paneIndex:s,annotations:n,studies:r}=t||{},o=`..panes${Number.isInteger(s)?`[${s}]`:""}`;let a=e;const l=e=>gs.NULL_OBJECT;if(!0===n){const e=e=>i.onAnnotationModifiedByTool(e,E.Deleted,!1);i.allAnnotations.forEach(e),a=oo(a,`${o}..annotations`,l)}return!0===r&&(a=oo(a,`${o}..plots{.type=="Study"}`,l)),a=Ua(a),a},Previous:{Update:function(e,t,i){return oo(e,mv,e=>(de(e,t),e))},Get:function(e,t,i){return ro(e,mv)[0]}},MovePlot:{Update:function(e,t,i){if(!gv(0,t,i).includes(t.targetPane))return e;const s=Sv(i,t.index),n=XT(e,qT(t.index));e.panes[s.pane].axes[s.axis].plots.splice(s.plot,1);let r=s.pane,o=!0;switch(t.targetPane){case"ExistingAbove":r--;break;case"NewAbove":e.panes.splice(r,0,JT(e)),o=!1;break;case"ExistingBelow":r++;break;case"NewBelow":r++,o=!1,e.panes.splice(r,0,JT(e))}o&&i.panes[r].isMain&&"Study"===n?.type&&"VOL"===n.study&&(n.detachedScale=!0);const a=e.panes[r];a.axes.length<2&&a.axes[0].plots.length>0&&a.axes.push({plots:[]});const l=a.axes.findIndex(e=>0===e.plots.length),c=-1===l?a.axes.length-1:l;a.axes[c].plots.push(n);let u=Av(e,s.pane);return u=Av(u,r),Ua(u)},Get:gv},PinPlot:{Update:function(e,t,i){if(!yv(0,t,i).includes(t.targetAxis))return e;const s=Sv(i,t.index),n=e.panes[s.pane],r=XT(e,qT(t.index));let o=-1;switch(t.targetAxis){case"PrimaryAxis":o=0;break;case"SecondaryAxis":o=1;break;case"NoAxis":r.detachedScale=!0}if(-1!==o)if(o!==s.axis)delete r.detachedScale,n.axes.length<2&&o>0&&n.axes.push({plots:[]}),n.axes[o].plots.push(r),n.axes[0===o?1:0].plots.splice(s.plot,1);else{delete n.axes[s.axis].plots[s.plot].detachedScale}return Ua(Av(e,s.pane))},Get:yv}};function vv(e){return"function"==typeof e}function Pv(e,t,i){return function(e,t){const i=Tv[e];if(vv(i))return i;{let e=void 0!==t?i[t]:void 0;if(!vv(e)&&(e=i[gs.DEFAULT_ACCESSOR_SUBACTION],!vv(e)))throw new Error("Invalid accesor id and/or sub id");return e}}(e.id,e.context.id)(t,e.context,i)}function Cv(e){return{id:"MainPlot",context:e}}const bv={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},Ev=/* @__PURE__ */Symbol.for("__ias__");class Lv{constructor(e=!1){this.headless=e,this.presenter=e?null:new WT(this)}presenter;_model;get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless)console.error("You cannot initialize a headless chart.");else if(this.presenter.initialize(e),te(t)){const e="string"==typeof t;e?Hv("Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.","warn"):(t.template&&this.load(t.template),delete t.template);const i=e?{symbol:t}:t;this.change(Cv(i))}}shutdown(){if(!this.headless){const e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,i=null){if(!this.headless)if(ie(e)){bo(e,t),Co(e,t);const s=XS(e,!1,t,i,this.presenter);s.isDrawingAnnotation&&this.presenter.view.setCursor(y.Crosshair),this.presenter.activeTool=s,q()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}zoom(e){this.headless||"boolean"!=typeof e||(e?this.annotate("ZoomIn"):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return zv()}get model(){return(this.headless?this._model:this.presenter.getModel())||zv()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:gs.ACTION_TEMPLATE,context:{strip:e}})}change(...e){const t={chart:this,actions:e.filter(e=>!e[Ev])};t.actions.length>0&&this.presenter?.notifyHost(qa.CH_API_ACTIONS_RECEIVED,t);const i=Gv().config.validateInput,s=e.map(e=>i?Wa(e,gs.ACCESSOR_SCHEMA):e);if(1===s.length){const e=s[0];if(e.id===gs.ACTION_TEMPLATE||e.context.id===gs.ACTION_GET)return Pv(e,this.model,this.presenter);if(!this.headless&&e.id===gs.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}const{yes:n,no:r}=V(s,e=>e.id===gs.ACTION_PLOT&&ie(e.context)&&e.context.id===gs.ACTION_DELETE),o=ue(this.model);let a=ue(this.model);const l=r;n.length>0&&l.push({id:gs.ACTION_PLOT,context:{id:gs.ACTION_DELETE,plots:n.map(e=>e.context)}}),l.forEach(e=>{if(a=Pv(e,a,this.presenter),!ie(a))throw new Error("Forgot to return model from accessor")}),this.fromModel(a,o)}async fromModel(e,t){const i=Wa(e,gs.CHART_SCHEMA);this.headless?this._model=i:await(this.presenter?.fromModel(i,t))}async load(e,t){const i={...bv,...t};let s=Wa(JSON.parse(e),gs.CHART_SCHEMA);const n=this.model,r=ue(n);if(ie(n)){if(s=function(e,t,i){const s=Sa(t),n=s.type.toLowerCase();if(s[n]===gs.PLACEHOLDER_SYMBOL_NAME){const s=Sa(e),{mainAxis:n}=Ta(t),r=n.annotations,o=Ma(t,s);if(i){const{mainAxis:e}=Ta(o);e.annotations=r}return o}return t}(n,s,i.keepNewAnnotations),i.keepNewAnnotations||(s=pv(s)),i.keepOldAnnotations&&(s=function(e,t){const{mainAxis:i}=Ta(e),{mainAxis:s}=Ta(t);wT(i,s);const n=e=>ro(e,'..plots{.type==="Study"}.study')[0],r=ro(e,RT).filter(e=>e!==i),o=ro(t,RT).filter(e=>e!==s);return r.forEach(e=>{const t=n(e),i=o.find(e=>t===n(e));ie(i)&&wT(e,i)}),t}(n,s)),i.keepNewCompare||(s=fv(s)),i.keepOldCompare&&(s=function(e,t){const i=ro(e,uv),s=ro(t,uv),n=Math.max(0,4-s.length);if(0===n)return t;const r=i.filter(e=>!s.find(t=>e.symbol===t.symbol)).slice(0,n);if(0===r.length)return t;const{mainPane:o,mainAxis:a}=Ta(t),{mainAxis:l}=Ta(e);return r.forEach(e=>{l.plots.includes(e)?a.plots.push(e):hv(o,a).plots.push(e)}),t}(n,s)),i.keepOldAggregation){const e={id:gs.ACTION_AGGREGATION,context:n.data.aggregation},t=s.display.density;s=Pv(e,s,this.presenter),i.keepNewBarWidth&&ie(t)&&(s.display.density=t)}await this.fromModel(s,r),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){this.headless||this.presenter.undoRedoManager.clear(!0)}reset(e=!0){const t=zv();if(this.headless)this._model=t;else if(this.presenter.getModel()){const i=this.presenter.mainPlot;let s=null;const n=i;if(i.isSymbol?s={symbol:n.symbol}:i.isExpression?s={expression:n.expression}:i.isForward?s={forward:n.forward}:i.isSeasonal&&(s={seasonal:n.seasonal}),ie(s)){const i=Pv({id:"Theme",context:{id:"Get"}},this.model,this.presenter);let n=Pv(Cv(s),t,this.presenter);e&&(n=Pv({id:"Theme",context:i},n,this.presenter)),this.presenter?.fromModel(n)}}this.clearUndoRedo(),this.presenter?.notifyHost(qa.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){Hv("Obsolete: please use 'exportImage' method instead.","warn")}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}exportData(e={}){return this.headless?null:BT.call(this.presenter,e)}exportImage(e={}){return this.headless?null:FT.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&this.presenter.undoRedoManager.canUndo}get canRedo(){return!this.headless&&this.presenter.undoRedoManager.canRedo}undo(){this.canUndo&&this.presenter.undoRedoManager.undo()}redo(){this.canRedo&&this.presenter.undoRedoManager.redo()}pauseUndoRedo(){this.headless||this.presenter.undoRedoManager.pause()}resumeUndoRedo(e){this.headless||this.presenter.undoRedoManager.resume(e)}priceToY(e,t=0,i=0){const s=this.presenter;if(this.headless||t<0||i<0||t>s.panes.length)return null;const n=s.panes[t];if(i>n.axes.length)return null;return n.axes[i].toY(e)}yToPrices(e){const t=this.presenter;if(this.headless)return null;for(const[i,s]of t.panes.entries()){const t=s.getBounds();if(ie(t)&&e>=t.y&&e<=t.y+t.height)return{pane:i,prices:s.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(qa.CH_DIDBECOMEACTIVE,{chart:this})}}function Mv(){const e=globalThis.parent?.location?.hostname||"";return["","localhost","127.0.0.1"].includes(e)||function(e){const t=e.split(".");if(!t||4!==t.length)return!1;const i=t.map(Number);if(!i.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;const[s,n]=i;return 10===s||172===s&&n>=16&&n<=31||192===s&&168===n}(e)}function _v(){let e=document.domain;const t=e.split("."),i="__tld"+/* @__PURE__ */(new Date).getTime();let s=0;for(;s<t.length-1&&-1===document.cookie.indexOf(`${i}=${i}`);)e=t.slice(-1-++s).join("."),document.cookie=`${i}=${i};domain=${e};`;return document.cookie=`${i}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function xv(e,t){var i;i=t,Object.keys(i).forEach(e=>!ie(i[e])&&delete i[e]);return`${e}/?${new URLSearchParams(t).toString()}`}function Iv(e,t=""){return xv(atob("aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ=="),{module:atob("YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy"),secret:t,referer:e})}function Dv(e,t){return e+Math.random()*(t-e)}const Ov=new Function(atob("Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg")),wv=new Function("f",atob("Zi5yZW1vdmVBbGxDaGFydHMoKTsg")),Rv=new Function("m",atob("cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw=="));async function Nv(e,t){if(t&&!Rv(e.mode))return;let i=!1,s=0,n=25;for(;!i&&s<5;){const t=Mv()||"FreeWidget"===e.mode,r=t?e.apiKey:"";try{const n=Iv(t?"":_v(),r),o=await fetch(n);if(o.ok){const t=await o.json(),s=t[atob("YXV0aG9yaXplZA==")];e.knownSite=s,s?(e.dataEndpoint=(t[atob("ZGF0YS1lbmRwb2ludA==")]||"").replace(/\/$/g,""),e.allowCredentials=t[atob("YWxsb3dDcmVkZW50aWFscw==")]):(e.dataEndpoint="",e.allowCredentials=!1),i=!0;break}s++}catch{}s++,n*=2,await new Promise(e=>setTimeout(e,n))}i&&e.knownSite||(setTimeout(Ov,Dv(2e3,3e3)),setTimeout(()=>wv(Gv()),Dv(4e3,5e3)))}const Vv={major:2,minor:366,patch:0};function Hv(e,t="info",i=""){const s=globalThis.console;s[void 0!==s[t]?t:"log"](e,i)}const Bv={environment:"Browser",validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${gs.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:"wheel+shift",bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:"Auto",tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:"Unspecified",hostingModel:"Page",overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,baseUrl:{instruments:"/proxies/instruments",futures:"/proxies/futures",timeseries:"/proxies/timeseries",timeseriesNew:"/proxies/new-timeseries",ondemand:"/proxies/ondemand",options:"/proxies/core-api"},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){const i=this.baseUrl[e];let s=`${i}${t}`;if(Rv(this.mode)&&this.knownSite){const{username:n,password:r}=this.credentials||{},o=ie(n,r),a=("timeseries"===e||"timeseriesNew"===e)&&o&&this.allowCredentials?`&username=${n}&password=${r}`:"";s=`https://${this.dataEndpoint}${i}${t}${a}`}const n=await fetch(s);return await n.text()},getCustomEventPopup:e=>null};async function Fv(e,t){const i=Gv()?.config;if(!i||!i.fetch)throw new Error("You should call initFeed first");let s=t;return"timeseries"===e?s=`/historical${t}`:"options"===e&&(s=`/options-historical${t}`),await i.fetch.call(i,e,s)}let kv=!1,Wv=null;function Uv(e){const t=e.extensions?.studyProvider;if(!ie(t))return;const i=t.getFields(),s=t.getStudies(),n=ue(Rr(gs.CHART_SCHEMA)),r=n.definitions,o=r.studyField.enum,a=r.study.enum;for(const u of i)if(o.includes(u.id))throw new Error(`Field with id ${u.id} already exists`);for(const u of s)if(a.includes(u.id))throw new Error(`Study with id ${u.id} already exists`);var l,c;o.push(...i.map(e=>e.id)),a.push(...s.map(e=>e.id)),l=gs.CHART_SCHEMA,c=n,ka.addSchema(l,c),ja(i),Fr(s)}function $v(e,t={}){if(kv)throw new Error("You should only call initFeed once during page's lifetime");kv=!0;const i=Object.assign(Bv);return de(i,t),te(i.logo)&&function(e,t){const i=(new DOMParser).parseFromString(e,"image/svg+xml"),s=i.querySelector("svg")?.getAttribute("viewBox"),n=i.querySelector("path")?.getAttribute("d");if(te(s)&&te(n)){const e=s.split(" ").map(Number);4===e.length&&e.every(Number.isFinite)&&(GA={path:new Path2D(n),width:e[2],height:e[3],rect:new xn(0,0,0,0),logoClickable:t})}}(i.logo,i.logoClickable??!1),Uv(i),Wv=new e(i),Wv.version=`${Vv.major}.${Vv.minor}.${Vv.patch}`,Hv(`%cBarchart Chart version ${Wv.version}`,"info","font-size: larger"),Wv.cachesData&&(Wv.subject?.subscribe(Wv.onPerformInternalGc.bind(Wv)),ap.subscribe(qa.CH_ALL,Wv.onChartChanged.bind(Wv))),Wv}function Gv(){return Wv}function zv(){return ue(Gv()?.template)}function Yv(){te(Wv)&&(Wv.shutdown(),kv=!1,Wv=null)}function jv(){return new Lv(!0)}function Kv(e){const t=jv();return t.load(e),t.change({id:"Outline",context:{id:"Get"}})}function qv(e,t,i,s=null){return new Proxy(e,{get:function(e,n,r){return n===t?function(t){const r=s?t[s]:t;return(i.handlesRequestsFor(r)?i:e)[n](t)}:Reflect.get(e,n,r)}})}class Xv{constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=/* @__PURE__ */new Map,this.pendingRedraw=/* @__PURE__ */new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=Pe()}version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;get subject(){return this.isAuxiliary||te(this._subject)||(this._subject=(new ql).pipe(fc(gs.INTERNAL_GC_MILLIS),pc(e=>e.length>0))),this._subject}get isAuxiliary(){return null!==window.opener}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=qv(this.timeSeriesSource,"getTimeSeries",e,"symbol"),this.metaDataSource=qv(this.metaDataSource,"getMetaData",e),this.recordSource=qv(this.recordSource,"getRecord",e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!te(this.timeSeriesSource))throw new Error("No time series source defined");return this.timeSeriesSource}getMetaDataSource(){if(!te(this.metaDataSource))throw new Error("No metadata source defined");return this.metaDataSource}getRecordSource(){if(!te(this.recordSource))throw new Error("No record source defined");return this.recordSource}async ready(){return ps.call(this,async()=>{const e=this instanceof tP||this instanceof Zv||this instanceof nP;await Nv(this.config,e);let t=this.config.defaultTemplate;if(!t)throw new Error("Must provide a default template");if("string"==typeof t){const e=await fetch(t);t=await e.json()}return this.template=Wa(t,gs.CHART_SCHEMA),!0})}getHeadlessChart(){return jv()}fixupRenderTo(e){if(!te(e))return null;if(e instanceof HTMLElement)return e;const t=rs(`#${e}`);if(te(t))return t;const i=[...this.charts.keys()].find(t=>t.id===e);return te(i)?i:null}checkChart(e,t){const i=this.fixupRenderTo(e),s=te(i)&&this.charts.has(i);return te(t)&&t!==s&&Hv(`There is ${t?"no":"already a"} chart inside the element ${e}`,"error"),i}addChart(e,t=null){const i=this.checkChart(e,!1),s=new Lv;return this.charts.set(i,s),s.initialize(e,t),s}removeChart(e){const t=this.checkChart(e,!0);if(!te(t))return;this.charts.get(t).shutdown(),this.charts.delete(t)}removeAllCharts(){for(const e of this.charts.keys())this.removeChart(e)}getChart(e){const t=this.checkChart(e);return te(t)?this.charts.get(t):null}redraw(e){const t=this.checkChart(e,!0);te(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),te(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{const t=this.getChart(e);if(!te(t?.presenter?.view))return;const i=t.presenter.view;i.isHostElementVisible&&i.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:/* @__PURE__ */new Set,records:/* @__PURE__ */new Set,timeSeries:/* @__PURE__ */new Set}}getAllCacheableEntities(e){for(const t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){const e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{te(t)&&(te(t.record)&&e.records.add(t.record),te(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){this.getTimeSeriesDataSource().refresh(),J(qa.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){const e=this.getCacheableEntities();this.evictUnused(e)}triggerGc(){this.subject?.next()}onChartChanged(e,t){e!==qa.CH_RECREATED&&e!==qa.CH_SHUTDOWN||(this.isAuxiliary?this._mainFeed?.triggerGc():this.triggerGc())}getDefaultMultiFieldCurve(){if(!te(this.template))return null;if(!this.knowDefaultCurve){const e=Sa(this.template);1===e.curves.length&&function(e){switch(o[e]){case o.OHLC:case o.HLC:case o.Candlestick:case o.HollowCandles:case o.HeikinAshi:case o.ElderImpulseSystem:case o.Range:case o.MultiColumn:return!0;default:return!1}}(e.curves[0].style)?this.defaultOhlcCurve=ue(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=ue(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}}class Zv extends Xv{constructor(e){super(e),this.timeSeriesSource=new Rh(!1),this.metaDataSource=new nn,this.recordSource=new iu}}class Jv extends Xv{constructor(e){super(e),this.timeSeriesSource=new Rh(!0),this.metaDataSource=new nn,this.recordSource=new su}}class Qv extends Xv{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new Rh(!0),this.metaDataSource=new nn,this.recordSource=new iu}}const eP=["drazen.dotlic@barchart.com","princec","b.hebert24@barchart.com"];class tP extends Xv{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new Rh(!0),this.metaDataSource=new rn,this.recordSource=new nu,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,te(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){te(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug("need to refresh caches"),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on("events",this.onEvents),this.connection.on("timestamp",this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&eP.includes(this.connection._username)&&Hv(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===gs.BC_EVENT_DISCONNECTED||e===gs.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):e!==gs.BC_EVENT_LOGGED_IN&&e!==gs.BC_EVENT_FEED_RESUMED||(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),te(this._connection)&&(this.connection.off("timestamp",this.onTimestamp),this.connection.off("events",this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}}function iP(e,t){return new sP(e,t)}class sP{_client;_subscriptions=/* @__PURE__ */new Map;_listeners=/* @__PURE__ */new Set;constructor(e,t){this._client=e;const i=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{const s=e.marketSnapshot;if(te(s)){const e=i(t);null!==e&&this._listeners.forEach(t=>t.onSnapshot?.(s,e))}const n=e.marketUpdate;if(te(n)){const e=i(t);null!==e&&this._listeners.forEach(t=>t.onUpdate?.(n,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return te(await this._client.connection)}shutdown(){te(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!te(this._client))return;const t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!te(this._client))return;const t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){const t=await this._client.connection;return await(t?.getInstrument(e))??[]}}class nP extends Xv{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new Rh(!0),this.metaDataSource=new on,this.recordSource=new ru,ap.subscribe(qa.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(const i of this._auxFeeds)i.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&J(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw new Error("Cannot set adapter on auxiliary feed");this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){const e=await(this._mainFeed?.ready())??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await(this._adapter?.ready())??!1}subscribe(e){this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){const t=this._auxFeeds.findIndex(t=>t.id==e.id);-1!==t&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc())}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(const t of this._auxFeeds)t.getAllCacheableEntities(e)}}const rP=ap;export{Wo as Aggregation,l as AggregationSpec,a as AggregationUnit,Zv as BarchartSiteDataFeed,Xv as BaseDataFeed,tu as BaseRecordSource,P as ChunkPart,Eh as ContainerWrapperTimeSeries,OT as CustomEventPopup,tl as EmptyRecord,t as ExpressionMissingBar,s as ExpressionNoDataApproach,i as ExpressionRecompute,Vm as ExpressionSeries,Ga as Field,h as FieldCategory,u as FieldFormat,c as FieldValueType,Ka as Fields,tP as MarketDataFeed,Qv as MiniWidgetDataFeed,Eu as OHLCDataPointBuilder,nP as OpenFeed,rP as PubSub,m as SeriesKind,Jv as SnapshotDataFeed,up as StudySeries,Mu as TimeSeriesContainer,ip as TimeSeriesQuery,qa as Topics,iP as adaptOpenFeedClient,us as appendDOMElement,ps as asyncReady,Cy as convertSeries,fa as doesExpressionHaveComputation,zr as doesStudyExist,ua as evaluateExpression,da as formatExpression,zs as formatPriceWithDecimals,Pe as generateUid,$r as getAnnotationTraits,Kv as getChartOutline,Ys as getCombinedMetaData,pa as getExpressionSymbols,Gv as getFeed,En as getLightness,tT as getStudyOptions,Zr as getTaxonomies,Ki as hasOpenInterest,$v as initFeed,Py as linReg,Nm as makeExpression,cp as makeHelperField,ny as makeStudy,by as mapSeries,ay as movAvg,ly as movExp,hy as movHul,cy as movSmo,uy as movWei,Tu as optionValueToDate,ca as parseExpression,ma as replaceExpressionSymbols,Ay as roc,as as setAttributesDOMElement,Yv as shutdownFeed,vy as stdDev,os as styleDOMElement,my as trueRange,yy as typical};
|
|
9
|
+
return new Date(NaN)}function kc(e,t,i){t=t||0,i=i||0;var s=/* @__PURE__ */new Date(0);s.setUTCFullYear(e,0,4);var n=7*t+i+1-(s.getUTCDay()||7);return s.setUTCDate(s.getUTCDate()+n),s}var Wc=[31,28,31,30,31,30,31,31,30,31,30,31],Uc=[31,29,31,30,31,30,31,31,30,31,30,31];function $c(e){return e%400==0||e%4==0&&e%100!=0}function Gc(e,t,i){if(t<0||t>11)return!1;if(null!=i){if(i<1)return!1;var s=$c(e);if(s&&i>Uc[t])return!1;if(!s&&i>Wc[t])return!1}return!0}function zc(e,t,i){return!(t<0||t>52)&&(null==i||!(i<0||i>6))}function Yc(e,t,i){return(null==e||!(e<0||e>=25))&&((null==t||!(t<0||t>=60))&&(null==i||!(i<0||i>=60)))}var jc,Kc,qc={exports:{}},Xc={exports:{}};function Zc(){return jc||(jc=1,function(e,t){Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t){if(null==e)throw new TypeError("assign requires that input parameter not be null or undefined");for(var i in t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},e.exports=t.default}(Xc,Xc.exports)),Xc.exports}function Jc(){return Kc||(Kc=1,function(e,t){var i=(mc||(mc=1,function(e){e.exports=function(e){return e&&e.__esModule?e:{default:e}},e.exports.__esModule=!0,e.exports.default=e.exports}(gc)),gc.exports).default;Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return(0,s.default)({},e)};var s=i(/* @__PURE__ */Zc());e.exports=t.default}(qc,qc.exports)),qc.exports}const Qc=/* @__PURE__ */He(/* @__PURE__ */Jc());const eu=[Ka.Open,Ka.High,Ka.Low,Ka.Last,Ka.Close,Ka.TradingDay,Ka.PreviousClose,Ka.PreviousHigh,Ka.PreviousLow,Ka.PreviousOpen,Ka.Volume,Ka.Change,Ka.PercentChange,Ka.YearHigh,Ka.YearLow,Ka.WeekPreviousClose,Ka.WeekPreviousHigh,Ka.WeekPreviousLow,Ka.MonthPreviousClose,Ka.MonthPreviousHigh,Ka.MonthPreviousLow];class tu{recordCache;translateSymbolBack;_subject;constructor(){this.recordCache=/* @__PURE__ */new Map,this.translateSymbolBack=/* @__PURE__ */new Map}get subject(){if(!ie(this._subject)){const t=dc(Math.max(gs.MINIMUM_THROTTLE,Gv().config.throttleMillis||0)),i=dc(gs.BACKGROUND_TAB_THROTTLE),s=()=>globalThis.document?.hidden?i:t;this._subject=(new ql).pipe((e=s,zl(function(t,i){var s=null,n=null,r=function(){null==n||n.unsubscribe();var t=s;s=[],t&&i.next(t),ac(e()).subscribe(n=Yl(i,r,Rl))};r(),t.subscribe(Yl(i,function(e){return null==s?void 0:s.push(e)},function(){s&&i.next(s),i.complete()},void 0,function(){return s=n=null}))})),pc(e=>e.length>0))}var e;return this._subject}addRecordForSymbol(e,t){const i=Ws(e);i!==e&&this.translateSymbolBack.set(i,e),this.recordCache.set(e,t)}removeRecordForSymbol(e){this.recordCache.delete(e);const t=Ws(e);this.translateSymbolBack.has(t)&&this.translateSymbolBack.delete(t)}findRecordForSymbol(e){const t=this.translateSymbolBack.has(e)?this.translateSymbolBack.get(e):e;return this.recordCache.get(t)}getSupportedFields(){return eu}makeAndCacheRecord(e,t){if(e===gs.PLACEHOLDER_SYMBOL_NAME)return new el(gs.PLACEHOLDER_SYMBOL_NAME);if(this.recordCache.has(e))return this.recordCache.get(e);const i=t(e),s=this.getSupportedFields();return i.addFields(...s),this.addRecordForSymbol(e,i),i.ready().then(e=>{this.postInit(e,i)}),i}evictUnused(e,t){for(const[i,s]of this.recordCache)e.has(s)||(t(s),this.removeRecordForSymbol(i))}postInit(e,t){}}class iu extends tu{getRecord(e){return this.makeAndCacheRecord(e,()=>new cl(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}}class su extends tu{getRecord(e){return this.makeAndCacheRecord(e,()=>new ll(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}}class nu extends tu{constructor(){super(),this.onMarketUpdate=this.onMarketUpdate.bind(this)}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),Gv().connection.off("marketUpdate",this.onMarketUpdate,e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new al(e))}postInit(e,t){e&&Gv().connection.on("marketUpdate",this.onMarketUpdate,t.translated)}onMarketUpdate(e){if(e.type===gs.REALTIME_INITIAL_QUOTE){const t=this.updateFromQuote(e,!0);this.subject.next({topic:qa.RT_QUOTE,data:e,updated:t})}else if(e.type===gs.REALTIME_TRADE){const t=Gv().connection.getMarketState().getQuote(e.symbol),i=this.updateFromQuote(t);this.subject.next({topic:qa.RT_TRADE,data:e,updated:i}),e.symbol===gs.DEBUG_SYMBOL&&console.log(`Trade\nSymbol: ${e.symbol} \t%cPrice: ${e.tradePrice} \t%cSize: ${e.tradeSize} \t%cTime: ${Si(e.time,gs.DEBUG_TIME_FORMAT)} \t%cSession: ${e.session}`,"color:#0f0","color:#a7a","color:#f96","color:#bee")}else if(e.type===gs.REALTIME_VOLUME){const t=this.updateFromVolume(e);0!==t&&(this.subject.next({topic:qa.RT_VOLUME,data:e,updated:t}),e.symbol===gs.DEBUG_SYMBOL&&console.log(`Volume\n Symbol: ${e.symbol} \t%cValue: ${e.value} \t%cSession: ${e.session}`,"color:#a7a","color:#bee"))}}updateFromQuote(e,t=!1){const i=this.findRecordForSymbol(e.symbol);i.resetUpdated(),i.update(Ka.Open,e.openPrice),i.update(Ka.High,e.highPrice),i.update(Ka.Low,e.lowPrice),i.update(Ka.Last,e.lastPrice),i.update(Ka.Close,e.lastPrice);const s=(e,t)=>{ie(t)&&i.update(e,t)};return s(Ka.Volume,e.volume),i.update(Ka.PreviousClose,e.previousPrice),t&&(s(Ka.PreviousOpen,e.previousOpenPrice),s(Ka.PreviousHigh,e.previousHighPrice),s(Ka.PreviousLow,e.previousLowPrice)),i.computeWellKnown(),i.updated}updateFromVolume(e){const t=this.findRecordForSymbol(e.symbol);return t.resetUpdated(),t.update(Ka.Volume,e.value),t.updated}}class ru extends tu{localTimeZone;constructor(){super(),this.localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone}get feed(){return Gv()}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),this.feed.unsubscribe(e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new al(e))}postInit(e,t){e&&this.feed.subscribe(t.translated)}onSnapshot(e,t){const i=this.findRecordForSymbol(t),s=Gv().metaDataSource.getMetaData(t);if(!s.isReady)return;const n=(e,t)=>{if(te(t)){const n=s.asPrice(t);return i.update(e,n),n}};i.resetUpdated();const r=n(Ka.Open,e.open?.price),o=n(Ka.High,e.high?.price),a=n(Ka.Low,e.low?.price),l=n(Ka.Last,e.last?.price);if(te(n(Ka.Close,e.close?.price))||te(n(Ka.Close,e.settlement?.price))||n(Ka.Close,e.last?.price),te(e.instrumentStatus?.tradeDate)){const t=e.instrumentStatus.tradeDate%100;i.update(Ka.TradingDay,t)}te(e.volume?.volume)&&i.update(Ka.Volume,s.asQuantity(e.volume.volume));const c=this.toExchangeTime(e.transactionTime,s.timeZone);te(n(Ka.PreviousClose,e.prevClose?.price))||n(Ka.PreviousClose,e.previousSession?.settlement?.price),n(Ka.PreviousOpen,e.previousSession?.open?.price),n(Ka.PreviousHigh,e.previousSession?.high?.price),n(Ka.PreviousLow,e.previousSession?.low?.price),n(Ka.YearHigh,e.yearHigh?.price),n(Ka.YearLow,e.yearLow?.price),i.computeWellKnown();const u={topic:"rt.quote",data:{symbol:t,openPrice:r,highPrice:o,lowPrice:a,lastPrice:l,tradeTime:c},updated:i.updated};this.subject.next(u)}skip(e){return void 0===e||e.blockTrade||e.doesNotUpdateLast||e.doesNotUpdateVolume}asDate(e){return!te(e)||e.isZero()?null:new Date(e.div(1e6).toNumber())}toExchangeTime(e,t){const i=this.asDate(e);if(null===i)return null;const s=function(e,t,i){if("string"==typeof e&&!e.match(Nc)){var s=Qc(i);return s.timeZone=t,Fc(e,s)}var n=Fc(e,i),r=Lc(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()).getTime(),o=xc(t,new Date(r));return new Date(r+o)}(i,this.localTimeZone);return function(e,t,i){var s=Fc(e,i),n=xc(t,s,!0),r=new Date(s.getTime()-n),o=/* @__PURE__ */new Date(0);return o.setFullYear(r.getUTCFullYear(),r.getUTCMonth(),r.getUTCDate()),o.setHours(r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds()),o}(s,t)}onUpdate(e,t){if(!this.recordCache.has(t))return void Hv(`[OpenFeed] update for unsubscribed symbol: ${t}`,"warn");const i=Gv().metaDataSource.getMetaData(t);if(!i.isReady)return;const s=this.toExchangeTime(e.transactionTime,i.timeZone);if(e.trades?.trades)for(const{trade:n}of e.trades.trades){if(this.skip(n))continue;const e=i.asPrice(n.price);if(null===e)continue;const r=i.asQuantity(n.quantity),o=this.toExchangeTime(n.transactionTime,i.timeZone),a=this.findRecordForSymbol(t),l=["High","Low","Volume","TradingDay"].map(e=>Ka[e]),[c,u,h,d]=l.map(e=>a.getValue(e));(!te(u)||e<u)&&a.update(Ka.Low,e),(!te(c)||e>c)&&a.update(Ka.High,e),a.update(Ka.Last,e),a.update(Ka.Close,e),a.update(Ka.Volume,(te(h)?h:0)+r),a.computeWellKnown();const p={data:{symbol:t,tradePrice:e,tradeSize:r,session:n.session,time:o??s,tradingDay:d},topic:"rt.trade",updated:a.updated};this.subject.next(p)}}}function ou(e,t){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[];return i.length>=t?e.apply(null,i.slice(0,t).reverse()):function(){for(var s=arguments.length,n=new Array(s),r=0;r<s;r++)n[r]=arguments[r];return ou(e,t,i.concat(n))}}const au=ou(Xe,2),lu=ou(ot,2),cu=ou(Ze,2),uu=ou(function(e,t){return Ke(2,arguments),Ze(e,3*je(t))},2),hu=ou(at,2),du=ou(function(e,t){return Ke(2,arguments),Xe(e,7*je(t))},2),pu=ou(lt,2),fu=ou(Si,2),mu=ou(Di,2);function gu(e,t){switch(e){case a.Tick:return hu(t);case a.Intraday:return lu(t);case a.Day:return au(t);case a.Week:return du(t);case a.Month:return cu(t);case a.Quarter:return uu(t);case a.Year:return pu(t);default:throw new Error(`Unexpected aggregation unit ${a[e]}`)}}function yu(e,t){return t.getFullYear()-1-(t.getFullYear()-1)%e}function Au(e){return yu(10,e)}function Su(e,t){return yu(100,e)===Au(t)}function Tu(e){return new Date(e*gs.OPTIONS_DATA_INCREMENT+gs.OPTIONS_DATA_BASE)}function vu(e,t=gs.ZERO_DATE){const i=/* @__PURE__ */new Date(`${e}T00:00:00`);return ht(i)?i:t}function Pu(e){return e.size-1}class Cu{container;supportsChunks=!0;retryCountForChunk=1;constructor(){this.container=null}get base(){return this.container}ready(){return Promise.resolve()}processRetrieved(){}getFirstDate(e){return this.base.getTimeData()[0]}getLastDate(){return this.base.getLastDataPoint(Ka.DateTime)}prepend(e){this.base.prepend(e),this.processRetrieved()}append(e){this.base.append(e),this.processRetrieved()}}class bu extends Cu{constructor(e){super(),this.container=e,this.retryCountForChunk=gs.FETCH_TICK_CHUNK_RETRY_COUNT}getFirstDate(e){const t=super.getFirstDate(0);return e>0&&e<this.retryCountForChunk?At(Di(t,e)):t}process(e){const t=this.container,i=t.size>0?t.getLastDataPoint(Ka.Last):null,s=t.getLastDataPoint(Ka.DateTime);let n=e.time;return void 0!==s&&n<=s&&(n=Qe(s,1)),t.addDataPoint(Ka.DateTime,n),t.addDataPoint(Ka.Last,e.tradePrice),t.addDataPoint(Ka.TradeSize,e.tradeSize),t.addDataPoint(Ka.Change,ie(i)?e.tradePrice-i:null),t.hasField(Ka.TradingDay)&&t.addDataPoint(Ka.TradingDay,e.tradingDay),{isUpdate:!1,time:n.getTime(),index:Pu(t)}}}class Eu extends Cu{agg;durationAdd;constructor(e,t){super(),this.agg=t,this.container=e,this.durationAdd=function(e){switch(e.unit){case a.Tick:case a.Intraday:case a.Day:return gu(e.unit,e.size);case a.Week:case a.Month:case a.Quarter:case a.Year:return gu(e.unit,1);default:throw new Error(`Unexpected aggregation unit ${a[e.unit]}`)}}(t)}isSameBar(e,t){switch(this.agg.unit){case a.Tick:case a.Intraday:case a.Day:return bi(t,this.durationAdd(e));case a.Week:return Mi(e,t);case a.Month:return _i(e,t);case a.Quarter:return xi(e,t);case a.Year:return Ii(e,t);default:throw new Error(`Unexpected aggregation unit ${a[this.agg.unit]}`)}}fixupTimeBasedAggregationTimestamp(e){return e}isCorrection(e,t){const i=bi(t,e);return i&&Hv("Currently not handling data corrections (updates of the past historical data)","error"),i}computeNextStamp(e,t){if(this.isCorrection(e,t))return null;let i=e;for(;!this.isSameBar(i,t);)i=this.durationAdd(i);return i}isUpdate(e,t,i,s){return function(e,t){Ke(2,arguments);var i=qe(e),s=qe(t);return i.getTime()===s.getTime()}(i,e)}getPosition(e){if(0===this.container.size){const t=this.fixupTimeBasedAggregationTimestamp(e.time);return{lastTimestamp:null,newTimestamp:t,nextTimestamp:t,isUpdate:!1}}const t=this.container.getLastDataPoint(Ka.DateTime),i=e.time,s=this.computeNextStamp(t,i);if(null===s)return null;const n=this.isUpdate(t,i,s,e);return null===n?null:{lastTimestamp:t,newTimestamp:i,nextTimestamp:s,isUpdate:n}}createBar(e,t,i,s,n,r,o){const a=this.container,l=a.size>0?a.getLastDataPoint(Ka.Close):null;a.addDataPoint(Ka.DateTime,r),a.addDataPoint(Ka.Open,e),a.addDataPoint(Ka.High,t),a.addDataPoint(Ka.Low,i),a.addDataPoint(Ka.Close,s),a.addDataPoint(Ka.Change,ie(l)?s-l:null),a.addDataPoint(Ka.Volume,n),a.hasField(Ka.OpenInterest)&&a.addDataPoint(Ka.OpenInterest,null),a.hasField(Ka.TradingDay)&&a.addDataPoint(Ka.TradingDay,o??null)}addBar(e,t){const{nextTimestamp:i}=t,{tradePrice:s,tradingDay:n}=e;return this.createBar(s,s,s,s,e.tradeSize,i,n),{isUpdate:!1,time:i.getTime(),index:Pu(this.container)}}updateLastBar(e,t,i,s){const n=this.container,r=e=>n.getLastDataPoint(e);if(ie(e)&&e>r(Ka.High)&&n.setLastDataPoint(Ka.High,e),ie(t)&&t<r(Ka.Low)&&n.setLastDataPoint(Ka.Low,t),ie(i)){n.setLastDataPoint(Ka.Close,i);const e=n.getData(Ka.Close)[n.size-2];n.setLastDataPoint(Ka.Change,i-e)}if(ie(s)){const e=n.getLastDataPoint(Ka.Volume)+s;n.setLastDataPoint(Ka.Volume,e)}}changeLastBar(e,t){const{lastTimestamp:i}=t,s=e.tradePrice;return this.updateLastBar(s,s,s,e.tradeSize),{isUpdate:!0,time:i.getTime(),index:Pu(this.container)}}process(e){const t=this.getPosition(e);if(null===t)return null;const i=fu(gs.DEBUG_TIME_FORMAT);return t.isUpdate?(e.symbol===gs.DEBUG_SYMBOL&&console.log(`Adding ${this.agg.describe()} Bar\nBars %cnot same %c${i(t.lastTimestamp)} < ${i(t.newTimestamp)} %cnext is %c${i(t.nextTimestamp)}`,"color:#f00","color:#f96","","color:#fff"),this.changeLastBar(e,t)):ie(e.tradePrice)?(e.symbol===gs.DEBUG_SYMBOL&&console.log(`Updating ${this.agg.describe()} Bar\nBars %csame %c${i(t.lastTimestamp)} == ${i(t.newTimestamp)}`,"color:#0f0","color:#f96"),this.addBar(e,t)):null}alignToQuote(e){if(ie(e.lastPrice,e.time))return this.updateLastBar(e.highPrice,e.lowPrice,e.lastPrice,void 0),{isUpdate:!0,time:e.time.getTime(),index:Pu(this.container)}}}class Lu extends Eu{innerBuilder;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.processRetrieved()}get base(){return this.innerBuilder.container}fixupTimeBasedAggregationTimestamp(e){return Di(e,pt(e,gs.START_OF_LAST_CENTURY)%this.agg.size)}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:0,tradePrice:0,tradingDay:0};[Ka.Open,Ka.High,Ka.Low].forEach(i=>{t.tradePrice=this.base.getData(i)[e],super.process(t)}),t.tradePrice=this.base.getData(Ka.Close)[e],t.tradeSize=this.base.getData(Ka.Volume)[e],super.process(t)}}process(e){return this.innerBuilder.process(e),super.process(e)}}class Mu{fields;storage={};constructor(e){this.fields=e,this.clear()}clear(){this.storage={},this.fields.forEach(e=>{this.storage[e.id]=[]})}fixupTransition(e,t){if(e!==Ka.Change||!this.hasField(Ka.Close)||t<1)return;const i=this.storage[e.id],s=this.storage[Ka.Close.id];i[t]=s[t]-s[t-1]}concat(e,t,i){this.storage[e.id]=t.concat(i),this.fixupTransition(e,t.length)}prependData(e,t){this.checkField(e),this.concat(e,t,this.getData(e))}prepend(e){const t=e.getLastDataPoint(Ka.DateTime).getTime()===this.getTimeData()[0].getTime(),i=e.size;e.fields.forEach(s=>{t&&e.getData(s).splice(i-1,1),this.prependData(s,e.getData(s))})}appendData(e,t){this.checkField(e),this.concat(e,this.getData(e),t)}append(e){const t=e.getTimeData()[0].getTime()===this.getLastDataPoint(Ka.DateTime).getTime(),i=this.size;return e.fields.forEach(s=>{t&&this.getData(s).splice(i-1,1),this.appendData(s,e.getData(s))}),e.size-(t?1:0)}getTimeData(){return this.getData(Ka.DateTime)}getData(e){return this.storage[e.id]}setData(e,t){this.checkField(e),this.storage[e.id]=t}hasField(e){return-1!==this.fields.findIndex(t=>t.id===e.id)}get size(){return 0===this.fields.length?0:this.getData(this.fields[0]).length}get isEmpty(){return 0===this.size}checkField(e){if(!this.hasField(e))throw new Error(`This container does not store values for field ${e.id}`)}addDataPoint(e,t){this.checkField(e);this.getData(e).push(t)}getLastDataPoint(e){this.checkField(e);return k(this.getData(e))}setLastDataPoint(e,t){this.checkField(e);const i=this.getData(e);i[i.length-1]=t}keepOnlyLast(e){if(this.size<=e)return;const t=this.size-e;this.fields.forEach(e=>this.getData(e).splice(0,t))}}class _u extends Mu{constructor(){super([])}get size(){return 0}}class xu extends Mu{wrapper;constructor(e,t){super(e),this.wrapper=t}isWrapped(e){return le(this.wrapper,e.id)}hasField(e){return this.isWrapped(e)||super.hasField(e)}getData(e){return this.isWrapped(e)?this.wrapper[e.id]():super.getData(e)}}const Iu=gs.RENKO_KAGI_NAMES;function Du(e){const{Method:t,Period:i,Source:s,BrickSize:n}=fe(e);return{method:oe(t,[Iu.ATR,Iu.TRD,Iu.PCT],Iu.ATR),period:Number.isFinite(i)?i:14,source:oe(s,[Iu.CLS,Iu.HL],Iu.CLS),brickSize:Number.isFinite(n)?n:10}}function Ou(e,t,i){return e.getData(t)[i]}function wu(e,t){const[i,s]=[Ka.High,Ka.Low].map(i=>Ou(e,i,t)),n=Ou(e,Ka.Close,t-1);return Math.max(i-s,Math.abs(i-n),Math.abs(s-n))}function Ru(e,t){if(e.size<t)return null;const i=t-1,s=[];s.push(Ou(e,Ka.High,0)-Ou(e,Ka.Low,0));for(let r=1;r<t;++r)s.push(wu(e,r));let n=w(s);for(let r=t;r<e.size;++r){n=(n*i+wu(e,r))/t}return n}const Nu=e=>Ka[e],Vu=["DateTime","Open","High","Low","Close","Volume"].map(Nu),Hu=Vu.concat(["Change","Projection","BarIndex"].map(Nu));class Bu extends Cu{innerBuilder;inputs;brickSize;lastFinalBrick;projectionCount;refPrices;constructor(e,t){super(),this.supportsChunks=!1,this.innerBuilder=e,this.inputs=ue(t.inputs),this.brickSize=null,this.container=new Mu(Hu),this.processRetrieved()}get base(){return this.innerBuilder.container}baseVal(e,t){return this.base.getData(e)[t]}isLastBase(e){return e===this.base.size-1}getValuesAt(e,t){const[i,s,n,r,o,a]=Vu.map(i=>t.getData(i)[e]);return{date:i,open:s,high:n,low:r,close:o,volume:a}}getBrickAt(e){return this.getValuesAt(e,this.container)}getBarAt(e){return this.getValuesAt(e,this.base)}getBricksCount(e){return Math.floor(e/this.brickSize)}getMove(e,t,i){const[s,n]=this.refPrices(t.close,t.high,t.low),r=s-e.high,o=e.low-n;return{climbing:(i&&r>0||r>=this.brickSize)&&r>=o,falling:(i&&o>0||o>=this.brickSize)&&o>r,moveUp:r,moveDown:o}}initFirstBrick(e,t){const i=Math.max(this.brickSize,se(t.close-t.close%this.brickSize,4));e.open=e.high=e.low=e.close=i,e.date=t.date,e.volume=e.change=0}findSafeStartIndex(){let e=0,t=this.base.size-1;const i=2*gs.RENKO_MAX_BARS;for(;t>0&&e<i;){const i=wu(this.base,t);e+=Math.floor(i/this.brickSize),t--}return t}processRetrieved(){const e=Du(this.inputs),{method:t,period:i,source:s}=e;if(this.brickSize=e.brickSize,t===Iu.ATR)this.brickSize=Ru(this.base,i);else if(t===Iu.PCT)if((this.base?.size??0)>0){const e=this.base.getLastDataPoint(Ka.Close);this.brickSize=e*this.brickSize/100}else this.brickSize=null;if(!ie(this.brickSize))return;this.refPrices=s===Iu.HL?(e,t,i)=>[t,i]:(e,t,i)=>[e,e];const n={},r=this.findSafeStartIndex();for(let o=r;o<this.base.size;o++){const e=this.getBarAt(o);if(o===r){this.initFirstBrick(n,e);continue}const t=this.isLastBase(o),{climbing:i,falling:s,moveUp:a,moveDown:l}=this.getMove(n,e,t);if(!i&&!s){n.volume+=e.volume;continue}n.proj=Number(t),n.barIndex=o;const c=e.date.getTime();if(i){const e=this.getBricksCount(a);for(let t=0;t<e;++t)this.constructClimbing(n,c,t,this.brickSize);t&&(this.constructClimbing(n,c,e,a%this.brickSize),this.projectionCount=e+1)}else if(s){const e=this.getBricksCount(l);for(let t=0;t<e;++t)this.constructFalling(n,c,t,this.brickSize);t&&(this.constructFalling(n,c,e,l%this.brickSize),this.projectionCount=e+1)}t||(this.lastFinalBrick=this.container.size-1,n.volume=0)}this.container.keepOnlyLast(gs.RENKO_MAX_BARS)}constructClimbing(e,t,i,s,n=!0){const r=e.high,o=e.close;e.open=e.low=r,e.high=e.close=r+s,e.date=new Date(t+i),e.change=e.close-o,n?this.addToContainer(e):this.updateLastDataPoint(e)}constructFalling(e,t,i,s,n=!0){const r=e.low,o=e.close;e.open=e.high=r,e.low=e.close=r-s,e.date=new Date(t+i),e.change=e.close-o,n?this.addToContainer(e):this.updateLastDataPoint(e)}process(e){const t=this.innerBuilder.process(e);return this.processUpdate(t)}alignToQuote(e){const t=this.innerBuilder.alignToQuote(e);return this.processUpdate(t)}rebuild(){return this.container.clear(),this.processRetrieved(),{isUpdate:!1,time:0,index:-1}}processUpdate(e){if(!Number.isFinite(this.lastFinalBrick))return null;const t=this.base.size-1,i=this.getBarAt(t),s=this.getBrickAt(this.lastFinalBrick),{climbing:n,falling:r,moveUp:o,moveDown:a}=this.getMove(s,i,!0),l=1===this.container.getLastDataPoint(Ka.Projection);if(!n&&!r)return l?this.rebuild():null;const c=n?o:a,u=this.getBricksCount(c)+1;if(l&&this.projectionCount===u){const e=this.getBrickAt(this.container.size-1),s=this.getBrickAt(Math.min(this.container.size-2,0));return e.proj=1,e.barIndex=t,e.open===e.high?e.low=e.close=i.close:e.open===e.low&&(e.high=e.close=i.close),e.change=e.close-s.close,this.updateLastDataPoint(e),{isUpdate:!0,time:e.date.getTime(),index:this.container.size-1}}return this.rebuild()}addToContainer(e){const t=this.container;t.addDataPoint(Ka.DateTime,e.date),t.addDataPoint(Ka.Open,e.open),t.addDataPoint(Ka.Close,e.close),t.addDataPoint(Ka.High,e.high),t.addDataPoint(Ka.Low,e.low),t.addDataPoint(Ka.Change,e.change),t.addDataPoint(Ka.Volume,e.volume),t.addDataPoint(Ka.Projection,e.proj),t.addDataPoint(Ka.BarIndex,e.barIndex)}updateLastDataPoint(e){const t=this.container;t.setLastDataPoint(Ka.DateTime,e.date),t.setLastDataPoint(Ka.Open,e.open),t.setLastDataPoint(Ka.Close,e.close),t.setLastDataPoint(Ka.High,e.high),t.setLastDataPoint(Ka.Low,e.low),t.setLastDataPoint(Ka.Change,e.change),t.setLastDataPoint(Ka.Volume,e.volume),t.setLastDataPoint(Ka.Projection,e.proj),t.setLastDataPoint(Ka.BarIndex,e.barIndex)}}const Fu=[Ka.DateTime,Ka.TradingDay,Ka.Last,Ka.TradeSize,Ka.Change],ku=[Ka.DateTime,Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Volume,Ka.Change],Wu=[...ku,Ka.OpenInterest],Uu=[...Wu,Ka.Symbol],$u=[Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Change];function Gu(e,t){const i=Ki(e);if(t.isTick)return Fu;{let e=ku;return t.isMultiContract?e=Uu:(i||t.isEndOfDay)&&(e=Wu),t.isIntraday?[...e,Ka.TradingDay]:e}}class zu{symbol;aggregation;offset;container;previousTime;timeZone;isFuture;needsResolution;hasOpenInterest;padded;constructor(e,t,i=0,s=!1){this.symbol=e,this.aggregation=t,this.offset=i||0,this.previousTime=/* @__PURE__ */new Date(0),this.timeZone=this.getTimeZone(),this.isFuture=Fi(e),this.padded=s,this.needsResolution=ji(e),this.hasOpenInterest=Ki(e)}makeContainer(){return new Mu(Gu(this.symbol,this.aggregation))}parse(e){this.container=this.makeContainer();const t=e.split("\n"),i=this.getParseFunc();if(null!==i){const e=i.bind(this);t.forEach(t=>{const i=t.trim();if(i){const t=i.split(",");e(t)}})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){const t=e.length-5;0!==t&&1!==t||(this.container.addDataPoint(Ka.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(Ka.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(Ka.Last,parseFloat(e[3+t])),this.container.addDataPoint(Ka.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(Ka.Change,this.calculateChange(Ka.Last)))}nullify(e){return null==e||0===e?null:e}parseMinutes(e){const t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,i=t?1:0;e.length===7+i&&(this.container.hasField(Ka.Symbol)&&this.container.addDataPoint(Ka.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(Ka.DateTime,this.parseDate(e[0+i])),this.container.addDataPoint(Ka.TradingDay,parseInt(e[1+i])),this.container.addDataPoint(Ka.Open,parseFloat(e[2+i])),this.container.addDataPoint(Ka.High,parseFloat(e[3+i])),this.container.addDataPoint(Ka.Low,parseFloat(e[4+i])),this.container.addDataPoint(Ka.Close,parseFloat(e[5+i])),this.container.addDataPoint(Ka.Volume,this.nullify(parseInt(e[6+i]))),this.container.addDataPoint(Ka.Change,this.calculateChange()))}parseFloatOrNull(e){const t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){const t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){const t=this.aggregation.isMultiContract,i=7+(this.hasOpenInterest?1:0);e.length===i&&(t&&this.container.addDataPoint(Ka.Symbol,e[0]),this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(Ka.High,parseFloat(e[3])),this.container.addDataPoint(Ka.Low,parseFloat(e[4])),this.container.addDataPoint(Ka.Close,parseFloat(e[5])),this.container.addDataPoint(Ka.Volume,this.nullify(this.parseIntOrNull(e[6]))),this.hasOpenInterest&&this.container.addDataPoint(Ka.OpenInterest,this.nullify(this.parseIntOrNull(e[7]))),this.container.addDataPoint(Ka.Change,this.calculateChange()))}calculateChange(e=Ka.Close){const t=this.container.size;if(t>1){const i=this.container.getData(e);return i[t-1]-i[t-2]}return 0}parseTimestamp(e){switch(this.aggregation.unit){case a.Tick:case a.Intraday:return function(e,t=gs.ZERO_DATE){const i=new Date(e.replace(" ","T"));return ht(i)?i:t}(e);default:return vu(e)}}parseDate(e){const t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?lt(t,this.offset):(!function(e,t){Ke(2,arguments);var i=qe(e),s=qe(t);return i.getTime()>s.getTime()}(t,this.previousTime)?this.previousTime=Qe(this.previousTime,1):this.previousTime=t,this.previousTime)}getTimeZone(){return qi(this.symbol)}}const{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:Yu,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:ju}=gs;class Ku{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case a.Tick:return gs.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case a.Intraday:return t&&e.spec===l.Nearest?Yu:ju;case a.Day:case a.Week:case a.Month:case a.Quarter:case a.Year:return gs.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return""}}addExtraParams(e){}makeUrl(e){const t={},i=Ws(e.symbol);t.symbol=i;const s=e.aggregation,n=this.getDataParam(s);if(n.length>0&&(t.data=n),s.size>1&&s.unit===a.Intraday){const e=s.spec===l.PerRange?1:s.size;t.interval=e.toString()}const[r,o]=e.range,c=null!==r,u=null!==o;if(c&&(t.start=this.toHistoricalFeedDate(r,s)),!c||e.alwaysUseBarsToFetch){let i=e.barsToFetch||gs.DEFAULT_MAX_RECORDS;s.unit===a.Tick&&s.spec!==l.None&&(i*=gs.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=i.toString()}u&&(t.end=this.toHistoricalFeedDate(o,s)),t.volume=s.isContractVolume?"contract":"total",t.order="asc",t.dividends=s.dividendsAdjust.toString(),t.backadjust=s.backAdjust.toString(),t.daystoexpiration=s.daysToExpiration.toString(),t.contractroll=s.contractRoll,s.isTick&&(t.type="T",t.skipOldEmulation="true"),!0===e.extendedHours&&(t.formt="true"),t.splits=(e?.splits??!0).toString(),t.padded=(e.padded??!1).toString(),this.addExtraParams(t);const h=ge(t),d=Fi(i);return`/${this.getPageNameFor(s,d)}?${h}`}toHistoricalFeedDate(e,t){return Si(e,t.isTick||t.isIntraday?gs.FMT_HIST_FEED_PARAM_DATE_TIME:gs.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t="";const i=this.getSpecPart(e);switch(e.unit){case a.Tick:case a.Intraday:break;case a.Day:t=`daily${i}`;break;case a.Week:t=`weekly${i}`;break;case a.Month:t=`monthly${i}`;break;case a.Quarter:t=`quarterly${i}`;break;case a.Year:t=`yearly${i}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===l.Continue?"continue":"nearest":""}getParser(e){const t=Ws(e.symbol);return new zu(t,e.aggregation,e.offset,e.padded)}async retrieve(e){const t=this.makeUrl(e),i=e.aggregation.unit===a.Tick?"timeseriesNew":"timeseries",s=await Fv(i,t);return this.getParser(e).parse(s)}}class qu{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){const t=Ws(e.symbol),i=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==a.Day)return i;const s={symbol:t};this.addExtraParams(s);const n=`/${this.getPageName()}.json?${ge(s)}`,r=await Fv("ondemand",n);try{const e=JSON.parse(r);if(200===e.status.code){const t=e.results;if(this.iterateForward)for(let e=0;e<t.length;e++)this.processRow(t[e],e,i);else for(let e=t.length-1;e>=0;e--)this.processRow(t[e],e,i);return i}}catch(o){Hv(`Failed parsing the JSON result from OnDemand, error is ${o.message}`)}return i}}class Xu extends qu{emptyContainer(e,t){return new Mu(Gu(e,t))}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){const s=i.hasField(Ka.Symbol),n=t>0?i.getLastDataPoint(Ka.Close):null;i.addDataPoint(Ka.DateTime,vu(e.date)),s&&i.addDataPoint(Ka.Symbol,e.symbol),i.addDataPoint(Ka.Open,e.open),i.addDataPoint(Ka.High,e.high),i.addDataPoint(Ka.Low,e.low),i.addDataPoint(Ka.Close,e.close),i.addDataPoint(Ka.Volume,e.volume),i.addDataPoint(Ka.OpenInterest,e.openInterest);const r=null===n?null:se(e.close-n,2);i.addDataPoint(Ka.Change,r)}}const Zu={WeighImplVolHigh:"weightedImpliedVolatility",WeighImplVolLow:"weightedImpliedVolatility",WeighImplVol:"weightedImpliedVolatility",WeighImplVolHigh5D:"weightedImpliedVolatilityHigh5d",WeighImplVolLow5D:"weightedImpliedVolatilityLow5d",WeighImplVol5D:"weightedImpliedVolatility5d",WeighImplVolHigh1M:"weightedImpliedVolatilityHigh1m",WeighImplVolLow1M:"weightedImpliedVolatilityLow1m",WeighImplVol1M:"weightedImpliedVolatility1m",WeighImplVolHigh3M:"weightedImpliedVolatilityHigh3m",WeighImplVolLow3M:"weightedImpliedVolatilityLow3m",WeighImplVol3M:"weightedImpliedVolatility3m",WeighImplVolHigh6M:"weightedImpliedVolatilityHigh6m",WeighImplVolLow6M:"weightedImpliedVolatilityLow6m",WeighImplVol6M:"weightedImpliedVolatility6m",WeighImplVolHigh1Y:"weightedImpliedVolatilityHigh1y",WeighImplVolLow1Y:"weightedImpliedVolatilityLow1y",WeighImplVol1Y:"weightedImpliedVolatility1y",WeighImplVolHighYTD:"weightedImpliedVolatilityHighYtd",WeighImplVolLowYTD:"weightedImpliedVolatilityLowYtd",WeighImplVolYTD:"weightedImpliedVolatilityYtd",WeighImplVolChg:"weightedImpliedVolatilityChange",ImplVolRank5D:"impliedVolatilityRank5d",ImplVolRank1M:"impliedVolatilityRank1m",ImplVolRank3M:"impliedVolatilityRank3m",ImplVolRank6M:"impliedVolatilityRank6m",ImplVolRank1Y:"impliedVolatilityRank1y",ImplVolRankYTD:"impliedVolatilityRankYtd",ImplVolPerc5D:"impliedVolatilityPercentile5d",ImplVolPerc1M:"impliedVolatilityPercentile1m",ImplVolPerc3M:"impliedVolatilityPercentile3m",ImplVolPerc6M:"impliedVolatilityPercentile6m",ImplVolPerc1Y:"impliedVolatilityPercentile1y",ImplVolPercYTD:"impliedVolatilityPercentileYtd",OptTotVol:"totalVolume",OptCallVol:"callVolume",OptPutVol:"putVolume",PutCallVolRatio:"putCallVolumeRatio",TotalOpenInt:"totalOpenInterest",CallOpenInt:"callOpenInterest",PutOpenInt:"putOpenInterest",PutCallOIRatio:"putCallOpenInterestRatio",DateTime:"date"};class Ju{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){const t=Ws(e.symbol).replace(/\.bz$/i,""),i=e.fields.concat(Ka.DateTime),s=()=>new Mu(i);if(e.aggregation.unit!==a.Day)return s();const n=`/get?${ge({symbol:t,apiKey:"default",fields:i.map(e=>Zu[e.id]).join(",")})}`,r=await Fv("options",n);try{const e=JSON.parse(r).data,t=s(),n=e=>Number.parseFloat(e.replace(/,/g,""));return e.forEach(e=>{i.forEach(i=>{i===Ka.DateTime?t.addDataPoint(Ka.DateTime,vu(e.date)):t.addDataPoint(i,n(e[Zu[i.id]]))})}),t}catch(o){Hv(`Failed parsing options JSON historical data result, error is ${o.message}`)}return s()}}class Qu extends Eu{innerBuilder;isBuildingBars;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=gs.FETCH_TICK_CHUNK_RETRY_COUNT,this.processRetrieved()}get base(){return this.innerBuilder.container}getFirstDate(e){return this.innerBuilder.getFirstDate(e)}get startFromIndex(){return 0}processRetrieved(){this.container.clear(),this.isBuildingBars=!0;const e=[Ka.DateTime,Ka.TradeSize,Ka.Last,Ka.TradingDay],[t,i,s,n]=e.map(e=>this.base.getData(e));for(let r=this.startFromIndex;r<this.base.size;r++){const e={isTrade:!0,time:t[r],tradeSize:i[r],tradePrice:s[r],tradingDay:n[r]};super.process(e)}this.isBuildingBars=!1}process(e){const t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}}class eh extends Qu{constructor(e,t,i){super(e,t,i)}fixupTimeBasedAggregationTimestamp(e){return function(e,t){return Ke(2,arguments),at(e,-je(t))}(e,vt(e,Et(Oi(e,1)))%this.agg.size)}}class th extends Qu{series;constructor(e,t,i,s){super(e,i,s),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}}const ih=new Ga("_TICK_COUNT");class sh extends th{anchorTimestamp=null;constructor(e,t,i,s){super(e,t,i,s)}get startFromIndex(){let e=0;const t=this.base.getTimeData();if(ie(this.anchorTimestamp))e=U(t,e=>e===this.anchorTimestamp);else{const i=this.base.size;if(i>2)for(let s=i-2;s>2;--s){const i=t[s].valueOf();if(i-t[s-1].valueOf()>1&&t[s+1].valueOf()-i>1){e=s;break}}this.anchorTimestamp=t[e]}return e>this.agg.size&&(e%=this.agg.size),Math.max(e,0)}addBar(e,t){const i=super.addBar(e,t);return this.container.addDataPoint(ih,1),i}changeLastBar(e,t){const i=super.changeLastBar(e,t),s=this.container.getLastDataPoint(ih);return this.container.setLastDataPoint(ih,s+1),i}isUpdate(e,t,i,s){return this.container.getLastDataPoint(ih)<this.agg.size}}const nh=new Ga("_VOLUME_TALLY");class rh extends th{constructor(e,t,i,s){super(e,t,i,s)}addBar(e,t){const i=this.container,s=(i.getLastDataPoint(nh)||0)+e.tradeSize,n=Math.floor(s/this.agg.size),r=s%this.agg.size,o=s<this.agg.size;i.size>0&&(i.setLastDataPoint(Ka.Volume,o?1:n),i.setLastDataPoint(nh,s));const a=super.addBar(e,t);return i.setLastDataPoint(Ka.Volume,1),i.addDataPoint(nh,o?0:r),a}changeLastBar(e,t){const i=this.container,s=super.changeLastBar(e,t);i.setLastDataPoint(Ka.Volume,1);const n=i.getLastDataPoint(nh)??0;return i.setLastDataPoint(nh,n+e.tradeSize),s}isUpdate(e,t,i,s){if(!ut(e,t))return!1;const n=this.container.getLastDataPoint(nh)??0;return s.tradeSize+n<this.agg.size}}class oh extends Eu{innerBuilder;metadata;range;step;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.range=i.size,this.step=1;const n=Gv().getMetaDataSource();this.metadata=n.getMetaData(s)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return ps.call(this,async()=>{const e=await this.metadata.ready();return e&&(this.step=this.metadata.minMovement,this.processRetrieved()),e})}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){const t=this.base.getData(Ka.Volume)[e],i=this.useHighOrLow(e);if(!ie(i)){this.updateLastBar(void 0,void 0,void 0,t);continue}const s={isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:t,tradePrice:i,tradingDay:0};super.process(s)}}useHighOrLow(e){const t=this.base.getData(Ka.Close)[e];if(0==this.container.size)return t;const i=this.container.getLastDataPoint(Ka.High),s=this.container.getLastDataPoint(Ka.High),n=this.base.getData(Ka.High)[e],r=this.base.getData(Ka.Low)[e],o=n>i,a=r<s;return o&&a?n-t<t-r?n:r:o?n:a?r:void 0}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}isUpdate(e,t,i,s){return!0}process(e){return this.innerBuilder.process(e),super.process(e)}changeLastBar(e,t){const i=e.tradePrice,s=this.container.getLastDataPoint(Ka.Low)+this.priceRange;if(i>s)return this.changeAndAddBar(s,e,t);const n=this.container.getLastDataPoint(Ka.High)-this.priceRange;return i<n?this.changeAndAddBar(n,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,i){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(Ka.Projection,0),this.addBar(t,i)}addBar(e,t){return this.container.addDataPoint(Ka.Projection,1),super.addBar(e,t)}}const ah=[Ka.Open,Ka.High,Ka.Low,Ka.Close],lh=[Ka.BARCOLIX,Ka.High,Ka.Low],ch=gs.RENKO_KAGI_NAMES;function uh(e){const{BoxSizeMethod:t,Period:i,ReversalAmount:s}=fe(e);return{method:oe(t,[ch.ATR,ch.TRD],ch.ATR),period:Number.isFinite(i)?i:14,reversal:Number.isFinite(s)?s:30}}class hh extends Eu{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ue(i.inputs),this.reversal=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,i){return e.getData(t)[i]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}addBar(e,t){if(super.addBar(e,t),this.container.addDataPoint(Ka.BARCOLIX,null),this.container.size>1){const e=this.dataAt(Ka.Close,this.container.size-2);this.setLast(Ka.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,i,s){const n=s.tradePrice,r=e=>e>=0,o=n-this.getLast(Ka.Close),a=r(o),l=Math.abs(o)>=this.reversal,[c,u,h,d]=ah.map(e=>this.getLast(e)),p=d-c,f=r(p)!==a||0===p;return f&&!l||!f&&(a?n<u:n>h)?null:Math.abs(p)<this.reversal||!f||!l}computeBarColor(){const e=e=>this.dataAt(Ka.Close,e)>this.dataAt(Ka.Open,e),t=this.container.size;if(t>1){const i=e(t-1),[s,n,r]=lh.map(e=>this.dataAt(e,t-2)),[,o,a]=lh.map(e=>this.dataAt(e,t-1));let l=s;0===s&&i&&o>n?l=1:1===s&&!i&&a<r&&(l=0),this.setLast(Ka.BARCOLIX,l)}else this.setLast(Ka.BARCOLIX,e(0)?1:0)}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);const t=super.process(e);return this.computeBarColor(),t}processRetrieved(){const e=uh(this.inputs),{method:t,period:i,reversal:s}=e;if(this.reversal=s,t===ch.ATR&&(this.reversal=Ru(this.base,i)),ie(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.baseAt(Ka.DateTime,e),tradePrice:this.baseAt(Ka.Close,e),tradeSize:this.baseAt(Ka.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}function dh(e){const{LineCount:t}=fe(e);return{lineBreak:Number.isFinite(t)?t:3}}class ph extends Eu{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.inputs=ue(s.inputs);const n=dh(this.inputs);this.lineBreak=n.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(Ka.DateTime)[e],tradeSize:this.base.getData(Ka.Volume)[e],tradePrice:this.base.getData(Ka.Close)[e],tradingDay:0}}processRetrieved(){if(this.container.clear(),!(this.base.size<2)){this.startLine(this.readTrade(1));for(let e=1;e<this.base.size-1;e++){const t=this.readTrade(e);this.insertBar(t,t.time)}super.process(this.readTrade(this.base.size-1))}}process(e){return this.innerBuilder.process(e),super.process(e)}updateLastBar(e,t,i,s){const n=this.findOpen(i,0,1);this.currentVolume+=s,null!==n?(super.updateLastBar(void 0,void 0,i,void 0),this.container.setLastDataPoint(Ka.Open,n),this.container.setLastDataPoint(Ka.Low,Math.min(n,i)),this.container.setLastDataPoint(Ka.High,Math.max(n,i))):this.resetProjection()}resetProjection(){const e=this.container;e.setLastDataPoint(Ka.High,null),e.setLastDataPoint(Ka.Low,null),e.setLastDataPoint(Ka.Open,null),e.setLastDataPoint(Ka.Close,null),e.setLastDataPoint(Ka.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(Ka.DateTime,t.nextTimestamp);const i=this.changeLastBar(e,t);return i.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},i}addBar(e,t){const i=this.container,{nextTimestamp:s}=t;if(1===i.getLastDataPoint(Ka.Projection)){const s=i.getLastDataPoint(Ka.Close);if(null===this.findOpen(s,this.lineBreak,1))return this.updateProjection(e,t);i.setLastDataPoint(Ka.Projection,0),i.setLastDataPoint(Ka.Volume,this.currentVolume),this.currentVolume=0}return!this.isProjection(s)&&this.insertBar(e,s)||this.addProjection(e,s)?{isUpdate:!1,time:s.getTime(),index:this.container.size-1}:null}insertBar(e,t){this.currentVolume+=e.tradeSize;const i=e.tradePrice,s=this.findOpen(i,this.lineBreak);return null!==s&&(this.createBar(s,Math.max(s,i),Math.min(s,i),i,this.currentVolume,t),this.container.addDataPoint(Ka.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;const i=e.tradePrice,s=this.findOpen(i,0);return null!==s&&(this.createBar(s,Math.max(s,i),Math.min(s,i),i,0,t),this.container.addDataPoint(Ka.Projection,1),!0)}findOpen(e,t,i=0){if(!ie(e))return null;const s=this.container,n=s.size-1-i,r=s.getData(Ka.Close)[n],o=s.getData(Ka.Open)[n];if(r>o){if(e<=r){if(e>=o)return null;for(let i=0;i<Math.min(s.size,t);i++){if(e>=s.getData(Ka.Low)[n-i])return null}return o}return r}if(e>=r){if(e<=o)return null;for(let i=0;i<Math.min(s.size,t);i++){if(e<=s.getData(Ka.High)[n-i])return null}return o}return r}startLine(e){this.container.addDataPoint(Ka.Projection,0);const t=this.readTrade(0);this.createBar(t.tradePrice,Math.max(t.tradePrice,e.tradePrice),Math.min(t.tradePrice,e.tradePrice),e.tradePrice,e.tradeSize+t.tradeSize,e.time)}}const fh=gs.RENKO_KAGI_NAMES,mh=1,gh=2,yh=3;function Ah(e){switch(e){case gs.BARKIND_O:case gs.BARKIND_XO:return!0;default:return!1}}function Sh(e){switch(e){case gs.BARKIND_X:case gs.BARKIND_OX:return!0;default:return!1}}function Th(e){const t=fe(e),{Source:i,BoxSizeMethod:s,Period:n}=t,{ReversalAmount:r,BoxSize:o,OneStepBack:a}=t,l=oe(i,[fh.CLS,fh.HL],fh.CLS),c=oe(s,[fh.ATR,fh.TRD],fh.ATR),u=Number.isFinite(n)?o:14,h=Number.isFinite(r)?r:3;return{method:c,period:u,source:l,boxSize:Number.isFinite(o)?o:20,reversal:h,oneStepBack:"Yes"===a}}class vh extends Eu{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ue(i.inputs),this.boxSize=this.reversal=this.source=this.firstTrend=this.oneStepBack=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,i){return e.getData(t)[i]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}roundToBox(e){return e-e%this.boxSize}roundedDiff(e,t,i){const s=Math.abs(t-e);return e+i*this.roundToBox(s)}get closeBased(){return this.source===fh.CLS}get currentKind(){return this.getLast(Ka.BARKIND)}getTrendField(e){return this.closeBased?Ka.Close:e?Ka.Low:Ka.High}getTrendPrice(e,t){if(this.closeBased)return e.tradePrice;const i=e;return t?i._lowPrice:i._highPrice}changeLastBar(e,t){const i=Ah(this.currentKind),s=i?-1:1,n=this.getLast(this.getTrendField(i)),r=this.getTrendPrice(e,i);return e.tradePrice=this.roundedDiff(n,r,s),super.changeLastBar(e,t),null}addBar(e,t){const i=0===this.container.size,s=Ah(this.currentKind),n=s?1:-1,r=i?null:this.getLast(Ka.Close),o=this.getTrendPrice(e,!s),a=i?this.roundToBox(this.baseAt(Ka.Open,0)):r;if(e.tradePrice=a+n*(i?0:this.boxSize),super.addBar(e,t),!i){const e=this.roundedDiff(r,o,n);this.updateLastBar(e,e,e)}return this.container.addDataPoint(Ka.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){const e=Ah(this.currentKind)?gs.BARKIND_OX:gs.BARKIND_XO;this.setLast(Ka.BARKIND,e)}canInplaceReverse(){return!function(e){switch(e){case gs.BARKIND_OX:case gs.BARKIND_XO:return!0;default:return!1}}(this.currentKind)&&this.getLast(Ka.High)===this.getLast(Ka.Low)}isUpdate(e,t,i,s){const n=Ah(this.currentKind),r=this.getTrendPrice(s,n),o=this.getTrendPrice(s,!n),a=e=>e>=0,l=r-this.getLast(Ka.Close),c=a(l),u=Math.abs(l)>=this.boxSize,h=o-this.getLast(Ka.Close),d=a(h),p=Math.abs(h)>=this.reversal*this.boxSize;return n?!(c||!u)||(d&&p?!(!this.oneStepBack||!this.canInplaceReverse())&&(this.inplaceReverse(),!0):null):!(!c||!u)||(!d&&p?!(!this.oneStepBack||!this.canInplaceReverse())&&(this.inplaceReverse(),!0):null)}findFirstDiffLargerThanBox(e,t){const i=this.baseAt(Ka.Open,0),s=this.innerBuilder.container.size;for(let n=1;n<s;++n){const s=this.baseAt(e,n)-i;if(Math.abs(s)>this.boxSize){if(t===mh&&s>0)return[n,gs.BARKIND_X];if(t===gh&&s<0)return[n,gs.BARKIND_O];if(t===yh)return[n,s>0?gs.BARKIND_X:gs.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){const[,e]=this.findFirstDiffLargerThanBox(Ka.Close,yh);return e}{const[e,t]=this.findFirstDiffLargerThanBox(Ka.High,mh),[i,s]=this.findFirstDiffLargerThanBox(Ka.Low,gh);return null===t&&null===s?null:null===s?t:null===t?s:e<i?t:s}}computeBarColor(){const e=this.container.size;let t=this.firstTrend;if(e>1){t=Ah(this.dataAt(Ka.BARKIND,e-2))?gs.BARKIND_X:gs.BARKIND_O}this.setLast(Ka.BARKIND,t)}process(e){return this.isProcessingRetrieved||this.innerBuilder.process(e),null===this.firstTrend?null:super.process(e)}processRetrieved(){const e=Th(this.inputs),{method:t,period:i,reversal:s,source:n,boxSize:r,oneStepBack:o}=e;if(this.reversal=s,this.source=n,t===fh.ATR?this.boxSize=Ru(this.base,i):this.boxSize=r,ie(this.reversal,this.boxSize)&&(this.oneStepBack=o&&1===this.reversal,this.container.clear(),this.firstTrend=this.findFirstBarTrend(),null!==this.firstTrend)){this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){const t={isTrade:!0,time:this.baseAt(Ka.DateTime,e),tradePrice:this.baseAt(Ka.Close,e),_highPrice:this.baseAt(Ka.High,e),_lowPrice:this.baseAt(Ka.Low,e),tradeSize:this.baseAt(Ka.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}const Ph=new Wo(a.Intraday,0);class Ch{constructor(e){this.query=e,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new el(e.symbol)}container;canLoadMoreData=!0;alignToQuote=!1;record;isLoading=!1;serverComputedSeries;builder;retriever;streamingSubscription;records;get isTotalVolumeMode(){const e=this.query.symbol,t=this.query.aggregation;return Fi(e)&&!t.isContractVolume&&t.isEndOfDay}getHasVisible(e){return null!=this.query.visibleRange&&null!=this.query.visibleRange[e]}get hasVisibleFrom(){return this.getHasVisible("from")}get hasVisibleTo(){return this.getHasVisible("to")}refresh(){this.query.aggregation.isEndOfDay?this.alignToQuote=!0:this.loadMoreData(!1)}makeInnerBuilder(e){const t=this.query.aggregation;if(!t.isTick)return new Eu(e,t);switch(t.spec){case l.None:case l.PerSeconds:case l.PerCount:case l.PerVolume:return new bu(e);default:throw new Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}}makeBuilder(e){const t=this.makeInnerBuilder(e),i=this.query.aggregation,s=(e,t=[])=>new Mu(Gu(this.query.symbol,e).concat(t)),n=t;switch(this.query.curveStyle){case o.Renko:return new Bu(n,this.query);case o.Kagi:{const e=s(Ph,[Ka.BARCOLIX]);return new hh(n,e,this.query)}case o.PointAndFigure:{const e=s(Ph,[Ka.BARKIND]);return new vh(n,e,this.query)}case o.LineBreak:{const e=s(i,[Ka.Projection]);return new ph(n,e,i,this.query)}}if(i.isIntraday&&i.spec===l.PerRange){const e=s(Ph,[Ka.Projection]);return new oh(n,e,i,this.query.symbol)}const r=t;if(i.isTick)switch(i.spec){case l.PerSeconds:return new eh(r,s(Ph),i);case l.PerCount:{const e=s(Ph,[ih]);return new sh(r,this,e,i)}case l.PerVolume:{const e=s(Ph,[nh]);return new rh(r,this,e,i)}}return i.unit===a.Day&&i.size>1?new Lu(n,s(i),i):t}onStreamingUpdates(e){if(this.isLoading)return;e.map(e=>{if("isTrade"in e)return this.builder.process(e);if("isQuote"in e&&(J(qa.TS_QUOTEMARKER,{series:this}),this.alignToQuote)){const t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>ie(e)).filter((e,t,i)=>{if(0===t)return!0;const s=i[t-1];return s.isUpdate!==e.isUpdate||s.time!==e.time||e.timeCorrection}).forEach(e=>{if(-1===e.index)J(qa.TS_MANYCHANGED,{series:this,part:P.Unspecified});else{const t={series:this,index:e.index};J(e.isUpdate?qa.TS_DATAPOINTCHANGED:qa.TS_DATAPOINTADDED,t)}e.timeCorrection&&J(qa.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return null!==this.container}getRetriever(){return Gi(this.query.symbol)&&this.query.aggregation.isEndOfDay?new Xu:new Ku}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>{const t=this.query.aggregation.isEndOfDay,i=dl(qa.RT_TRADE,this.record.symbol),s=e.filter(i).filter(e=>ie(e.data.time)).filter(e=>"T"!==e.data.session||this.query.extendedHours&&!t).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay}));if(this.isTotalVolumeMode&&this.records){const t=this.getSiblingVolume(e);if(t>0&&s.length>0)s[0].tradeSize+=t;else if(t>0&&0===s.length){const e=this.record.getValue(Ka.Last)??this.record.getValue(Ka.Close);if(ie(e)){const i=/* @__PURE__ */new Date;s.push({isTrade:!0,tradePrice:e,tradeSize:t,time:i,tradingDay:this.record.getValue(Ka.TradingDay)})}}}const n=s.reduce((e,t)=>{const i=k(e);var s;return ie(i)&&ie(i.tradePrice)&&ie(t.tradePrice)&&i.tradePrice===t.tradePrice&&i.time.getTime()===t.time.getTime()&&i.tradingDay===t.tradingDay?i.tradeSize+=t.tradeSize:e.push((s=t,Object.assign({},s))),e},[]),r=dl(qa.RT_QUOTE,this.record.symbol);return n.concat(e.filter(r).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}getSiblingVolume(e){if(!this.records)return 0;return e.filter(e=>e.topic===qa.RT_TRADE&&e.data.symbol in this.records).filter(e=>ie(e.data.time)).filter(e=>"T"!==e.data.session).reduce((e,t)=>e+t.data.tradeSize,0)}async loadMoreData(e=!0){if(this.isLoading||!this.builder.supportsChunks||!this.retriever.supportsChunks||!this.canLoadMoreData)return Promise.resolve();this.isLoading=!0,e?await this.loadHeadChunk():await this.loadTailChunk(),this.isLoading=!1}async loadTailChunk(){const e=this.query.duplicate();let t=this.builder.getLastDate();ie(e.offset)&&0!==e.offset&&(t=lt(t,-e.offset)),e.range=[t,null];const i=await this.retriever.retrieve(e),s=this.container.size;this.builder.append(i);const n=this.container.size-s;J(qa.TS_MANYCHANGED,{series:this,part:P.Tail,count:n,index:s})}async loadHeadChunk(){let e=!1,t=null;for(let i=0;i<this.builder.retryCountForChunk&&!e;++i){const s=this.query.duplicate();let n=this.builder.getFirstDate(i);ie(s.offset)&&0!==s.offset&&(n=lt(n,-s.offset)),s.range=[null,n],t=await this.retriever.retrieve(s),e=t.size>1}this.canLoadMoreData=e,e&&null!==t&&(this.builder.prepend(t),J(qa.TS_MANYCHANGED,{series:this,part:P.Head}))}async applyNearbyFixup(e){const t=this.query.aggregation,i=t.spec===l.Nearest,s=this.query.symbol,n=Fi(s);return!n||!t.isMultiContract||!i||e.size<1||this.serverComputedSeries?n&&ji(s)?await Hi(s):s:e.getLastDataPoint(Ka.Symbol)}async ready(){return ps.call(this,async()=>{this.retriever=this.getRetriever();const e=await this.retriever.retrieve(this.query),t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=Gv().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.isTotalVolumeMode&&await this.setupTotalVolumeSubscriptions(),this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0})}async setupTotalVolumeSubscriptions(){const e=Zi(this.query.symbol);if(e)try{const t=(await Xi(e)).map(e=>e.name).filter(e=>e!==this.record.symbol),i=Gv().getRecordSource();this.records={};for(const e of t)this.records[e]=i.getRecord(e);await Promise.all(Object.values(this.records).map(e=>e.ready()))}catch(t){this.records=void 0}}getCacheableEntities(e){e.add(this)}shutdown(){ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.records=void 0}}class bh{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new _u}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}}class Eh{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return null!==this.container}loadMoreData(e){throw new Error("Should not be called.")}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}}class Lh{constructor(e){this.query=e,this.container=null,this.supplyCustomDemoData="DemoSite"===Gv().config.mode}container;supplyCustomDemoData;canLoadMoreData=!0;isLoading=!0;refresh(){}loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return null!==this.container}shutdown(){}parseEvents(e){const t=new Mu([Ka.DateTime,Ka.Dividends,Ka.Earnings,Ka.Splits,Ka.Custom]),i=e.split("\n"),s=(e,i,s,n)=>{const r=i===s?n:null;t.addDataPoint(e,r)};return i.forEach(e=>{if(""===e.trim())return;const i=e.split(",");if(4!==i.length)return;const n=vu(i[1]);t.addDataPoint(Ka.DateTime,n),s(Ka.Dividends,"Dividend",i[2],i[3]),s(Ka.Earnings,"Earnings",i[2],i[3]),s(Ka.Splits,"Split",i[2],i[3]),this.supplyCustomDemoData?s(Ka.Custom,"Custom","Custom",gs.FAKE_CUSTOM_EVENT):s(Ka.Custom,"Custom",i[2],i[3])}),t}makeUrl(){const e={};e.symbols=this.query.symbol,e.start="19700102",e.end="20501230",gs.EVENTS_BUILT_IN.forEach(t=>e[t]=this.query[t]);return`/queryevents.ashx?${ge(e)}`}async retrieve(){const e=this.makeUrl(),t=await Fv("timeseries",e);return this.parseEvents(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),this.isLoading=this.canLoadMoreData=!1,!0))}getCacheableEntities(e){e.add(this)}}class Mh{constructor(e){this.query=e,this.query=e,this.container=null}container;canLoadMoreData=!1;isLoading=!0;get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}shutdown(){}parseFundamental(e){const t=JSON.parse(e),i=t.status.code,s=204===i;if(200!==i&&!s)return null;const n=new Mu(this.query.fields.concat(Ka.DateTime));if(s)return n;const r=this.query.fields[0],o=r.id.substring(0,1).toLowerCase()+r.id.substring(1);return t.results.reverse().forEach(e=>{n.addDataPoint(Ka.DateTime,vu(e.date)),n.addDataPoint(r,parseFloat(e[o]))}),this.isLoading=!1,n}makeUrl(){const e={count:0,rawData:1};e.symbols=this.query.symbol,e.frequency=this.query.aggregation.unit===a.Quarter?"Quarter":"Annual";const t=ge(e);return`/${this.query.seriesKind===m.BalanceSheet?"getBalanceSheets":"getIncomeStatements"}.json?${t}`}async retrieve(){const e=this.makeUrl(),t=await Fv("ondemand",e);return this.parseFundamental(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}function _h(e,t){const i=e.findIndex(e=>e>t);return Math.max(i<0?e.length:i,0)}class xh{records;streamingSubscription;setSymbols(e){const t=Gv().getRecordSource();this.records=e.reduce((e,i)=>{const s=t.getRecord(i);return this.addFieldsToRecord(s,i),e[i]=s,e},{})}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}onStreamingUpdates(e){e.forEach(e=>{const t=e.data,i=this.records[t.symbol];ie(i)&&this.process(i)}),this.notifyAboutUpdates()}async retrieve(){const e=Object.values(this.records);return(await Promise.all(e.map(e=>e.ready()))).every(I)&&(this.onRecordsReady(),e.forEach(e=>this.process(e)),this.streamingSubscription=this.getStreamingSubscription()),this.hasData}async ready(){return ps.call(this,async()=>await this.retrieve())}shutdown(){ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class Ih extends xh{symbols=[];constructor(e){super(),this.symbols=e,this.setSymbols(e)}addFieldsToRecord(e,t){e.addFields(Ka.Symbol),e.update(Ka.Symbol,t)}notifyAboutUpdates(){J(qa.RT_QUOTEGROUP,{source:this})}process(e){}onRecordsReady(){}get hasData(){return!0}getValue(e){const t=this.records[e];return void 0===t?null:t.getValue(Ka.Close)}}class Dh extends xh{query;dataPoints;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){super(),this.query=e,this.setSymbols(e.symbols),this.dataPoints=e.symbols.length,this.container=null,this.fields=[Ka.DateTime,Ka.Close,Ka.Symbol]}addFieldsToRecord(e,t){e.addFields(Ka.DateTime,Ka.Symbol),e.update(Ka.DateTime,Ji(t)),e.update(Ka.Symbol,t)}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}get hasData(){return null!==this.container&&this.container.size===this.dataPoints}notifyAboutUpdates(){J(qa.TS_MANYCHANGED,{series:this,part:P.Unspecified})}onRecordsReady(){this.container=new Mu(this.fields)}findOrAddIndex(e){let t=this.container.getData(Ka.Symbol).indexOf(e.symbol);if(t<0){const i=this.container.getData(Ka.DateTime),s=Ji(e.symbol);t=_h(i,s),this.fields.forEach(e=>this.container.getData(e).splice(t,0,null))}return t}process(e){const t=this.fields.map(t=>{const i=e.getValue(t);if("Close"!==t.id)return i;return e.getValue(Ka.Last)??i});if(!R(t))return;const i=this.findOrAddIndex(e);this.fields.forEach((e,s)=>this.container.getData(e)[i]=t[s])}getCacheableEntities(e){e.add(this)}}class Oh{query;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){this.query=e,this.fields=[Ka.DateTime,Ka.Close,Ka.Symbol],this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw new Error("Should not be called.")}shutdown(){}insertValues(e,t,i){const s=(t,i,s)=>e.getData(i).splice(t,0,s),n=e.getData(Ka.DateTime),r=Ji(t),o=_h(n,r);s(o,Ka.DateTime,r),s(o,Ka.Close,i),s(o,Ka.Symbol,t)}parseHistoricalForward(e){const t=new Mu(this.fields);return e.split("\n").filter(e=>e.trim().length>0).forEach(e=>{const i=e.split(","),s=i[0];this.insertValues(t,s,parseFloat(i[5]))}),t}makeUrl(){const e={};e.symbols=this.query.symbols.join(","),e.maxrecords=1,e.data="daily",e.end=x(mu(this.query.offset),fu(gs.FMT_HIST_FEED_PARAM_DATE_ONLY))(/* @__PURE__ */new Date);return`/querylatesteod.ashx?${ge(e)}`}async retrieve(){const e=this.makeUrl(),t=await Fv("timeseries",e);return this.parseHistoricalForward(t)}async ready(){return ps.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}class wh extends Ch{constructor(e){super(e)}getRetriever(){return new Ju}onStreamingUpdates(e){}}class Rh{cacheSeries;seriesCache;constructor(e=!1){this.cacheSeries=e,this.seriesCache=/* @__PURE__ */new Map}getTimeSeries(e){return ie(e.symbol)&&e.symbol===gs.PLACEHOLDER_SYMBOL_NAME?new bh(e):this.getSeries(e)}evictUnused(e){for(const[t,i]of this.seriesCache)!e.has(i)&&i.isCached&&(i.isCached=!1,i.shutdown(),this.seriesCache.delete(t))}refresh(){for(const e of this.seriesCache.values())"function"==typeof e.refresh&&e.refresh()}getSeries(e){const t=(e.cacheMe||this.cacheSeries)&&!e?.alwaysUseBarsToFetch,i=e.getHashKey();if(t&&this.seriesCache.has(i))return this.seriesCache.get(i);{const s=this.makeSeries(e);return s.isCached=t,t&&this.seriesCache.set(i,s),s}}makeSeries(e){switch(e.seriesKind){case m.Normal:return new Ch(e);case m.BalanceSheet:case m.IncomeStatement:return new Mh(e);case m.Events:return new Lh(e);case m.Forward:return new Dh(e);case m.HistoricalForward:return new Oh(e);default:case m.Options:return new wh(e);case m.Study:throw new Error(`The series kind '${m[e.seriesKind]}' is not supported yet.`)}}}var Nh={lessThanXSeconds:{one:"moins d’une seconde",other:"moins de {{count}} secondes"},xSeconds:{one:"1 seconde",other:"{{count}} secondes"},halfAMinute:"30 secondes",lessThanXMinutes:{one:"moins d’une minute",other:"moins de {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"environ 1 heure",other:"environ {{count}} heures"},xHours:{one:"1 heure",other:"{{count}} heures"},xDays:{one:"1 jour",other:"{{count}} jours"},aboutXWeeks:{one:"environ 1 semaine",other:"environ {{count}} semaines"},xWeeks:{one:"1 semaine",other:"{{count}} semaines"},aboutXMonths:{one:"environ 1 mois",other:"environ {{count}} mois"},xMonths:{one:"1 mois",other:"{{count}} mois"},aboutXYears:{one:"environ 1 an",other:"environ {{count}} ans"},xYears:{one:"1 an",other:"{{count}} ans"},overXYears:{one:"plus d’un an",other:"plus de {{count}} ans"},almostXYears:{one:"presqu’un an",other:"presque {{count}} ans"}},Vh={date:ai({formats:{full:"EEEE d MMMM y",long:"d MMMM y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:ai({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:ai({formats:{full:"{{date}} 'à' {{time}}",long:"{{date}} 'à' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},Hh={lastWeek:"eeee 'dernier à' p",yesterday:"'hier à' p",today:"'aujourd’hui à' p",tomorrow:"'demain à' p'",nextWeek:"eeee 'prochain à' p",other:"P"},Bh={code:"fr",formatDistance:function(e,t,i){var s,n=Nh[e];return s="string"==typeof n?n:1===t?n.one:n.other.replace("{{count}}",String(t)),null!=i&&i.addSuffix?i.comparison&&i.comparison>0?"dans "+s:"il y a "+s:s},formatLong:Vh,formatRelative:function(e,t,i,s){return Hh[e]},localize:{ordinalNumber:function(e,t){var i=Number(e),s=null==t?void 0:t.unit;if(0===i)return"0";return i+(1===i?s&&["year","week","hour","minute","second"].includes(s)?"ère":"er":"ème")},era:ui({values:{narrow:["av. J.-C","ap. J.-C"],abbreviated:["av. J.-C","ap. J.-C"],wide:["avant Jésus-Christ","après Jésus-Christ"]},defaultWidth:"wide"}),quarter:ui({values:{narrow:["T1","T2","T3","T4"],abbreviated:["1er trim.","2ème trim.","3ème trim.","4ème trim."],wide:["1er trimestre","2ème trimestre","3ème trimestre","4ème trimestre"]},defaultWidth:"wide",argumentCallback:function(e){return e-1}}),month:ui({values:{narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["janv.","févr.","mars","avr.","mai","juin","juil.","août","sept.","oct.","nov.","déc."],wide:["janvier","février","mars","avril","mai","juin","juillet","août","septembre","octobre","novembre","décembre"]},defaultWidth:"wide"}),day:ui({values:{narrow:["D","L","M","M","J","V","S"],short:["di","lu","ma","me","je","ve","sa"],abbreviated:["dim.","lun.","mar.","mer.","jeu.","ven.","sam."],wide:["dimanche","lundi","mardi","mercredi","jeudi","vendredi","samedi"]},defaultWidth:"wide"}),dayPeriod:ui({values:{narrow:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"mat.",afternoon:"ap.m.",evening:"soir",night:"mat."},abbreviated:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"matin",afternoon:"après-midi",evening:"soir",night:"matin"},wide:{am:"AM",pm:"PM",midnight:"minuit",noon:"midi",morning:"du matin",afternoon:"de l’après-midi",evening:"du soir",night:"du matin"}},defaultWidth:"wide"})},match:{ordinalNumber:di({matchPattern:/^(\d+)(ième|ère|ème|er|e)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e)}}),era:hi({matchPatterns:{narrow:/^(av\.J\.C|ap\.J\.C|ap\.J\.-C)/i,abbreviated:/^(av\.J\.-C|av\.J-C|apr\.J\.-C|apr\.J-C|ap\.J-C)/i,wide:/^(avant Jésus-Christ|après Jésus-Christ)/i},defaultMatchWidth:"wide",parsePatterns:{any:[/^av/i,/^ap/i]},defaultParseWidth:"any"}),quarter:hi({matchPatterns:{narrow:/^T?[1234]/i,abbreviated:/^[1234](er|ème|e)? trim\.?/i,wide:/^[1234](er|ème|e)? trimestre/i},defaultMatchWidth:"wide",parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:"any",valueCallback:function(e){return e+1}}),month:hi({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(janv|févr|mars|avr|mai|juin|juill|juil|août|sept|oct|nov|déc)\.?/i,wide:/^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^av/i,/^ma/i,/^juin/i,/^juil/i,/^ao/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:"any"}),day:hi({matchPatterns:{narrow:/^[lmjvsd]/i,short:/^(di|lu|ma|me|je|ve|sa)/i,abbreviated:/^(dim|lun|mar|mer|jeu|ven|sam)\.?/i,wide:/^(dimanche|lundi|mardi|mercredi|jeudi|vendredi|samedi)/i},defaultMatchWidth:"wide",parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^di/i,/^lu/i,/^ma/i,/^me/i,/^je/i,/^ve/i,/^sa/i]},defaultParseWidth:"any"}),dayPeriod:hi({matchPatterns:{narrow:/^(a|p|minuit|midi|mat\.?|ap\.?m\.?|soir|nuit)/i,any:/^([ap]\.?\s?m\.?|du matin|de l'après[-\s]midi|du soir|de la nuit)/i},defaultMatchWidth:"any",parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^min/i,noon:/^mid/i,morning:/mat/i,afternoon:/ap/i,evening:/soir/i,night:/nuit/i}},defaultParseWidth:"any"})},options:{weekStartsOn:1,firstWeekContainsDate:4}};const Fh=/{value:([^}]+)}/,kh=/%([aAdewbBmyYHkIlMpPSL])+/g,Wh={Second:{Period:"PT1S",Multipliers:[.01,.02,.05,.1,.2,.5,1,2,5,10,15,30]},Minute:{Period:"PT1M",Multipliers:[1,2,5,10,15,30]},Hour:{Period:"PT1H",Multipliers:[1,2,3,4,6,8,12]},Day:{Period:"P1D",Multipliers:[1,2]},Week:{Period:"P1W",Multipliers:[1,2]},Month:{Period:"P1M",Multipliers:[1,2,3,4,6]},Year:{Period:"P1Y",Multipliers:[1,2,5,10,25,50,100,250]}};const Uh=/* @__PURE__ */new Map;function $h(e){if(!ie(e))return null;if(!Uh.has(e)){const i=ie(t=e)?t.replace(Fh,(e,t)=>t.replace(kh,(e,t)=>gs.PHP_TO_UNICODE_TS_35_MAP[t])):t;Uh.set(e,i)}var t;return Uh.get(e)}class Gh{barWidth;unitWidth;minTickInterval;duration;format;prevDate;size;constructor({barWidth:e,unitWidth:t,formatString:i,minTickInterval:s,duration:n},r){this.size=r,this.barWidth=e,this.unitWidth=t,this.minTickInterval=s,this.duration=n,this.format=$h(i),this.prevDate=null}get noPrevDate(){return!ie(this.prevDate)}formatDate(e,t){return ad(e,this.format||t)}asTick(e,t,i){return this.prevDate=e,{date:e,priority:t,text:this.formatDate(e,i)}}checkPrev(e){return!!this.noPrevDate&&(this.prevDate=e,!0)}}const zh="yyyy",Yh="LLL ''yy",jh=()=>function(){if("fr"===od())return!0;return!1}()?"d LLL":"LLL d",Kh="HH:mm";class qh extends Gh{repeatEach;repeatCounter;constructor(e){super(e),this.repeatEach=gs.TIME_SCALE_MAX_SPACE_NO_TICKS/this.barWidth,this.repeatCounter=0}asTick(e,t,i){return this.repeatCounter=0,super.asTick(e,t,i)}getTick(e){if(!ut(this.prevDate,e))return this.asTick(e,1,"EEE");if(!Li(this.prevDate,e))return this.asTick(e,2,Kh);this.repeatCounter++;const t=this.repeatCounter===this.repeatEach;return!function(e,t){Ke(2,arguments);var i=Ct(e),s=Ct(t);return i.getTime()===s.getTime()}(this.prevDate,e)||t?this.asTick(e,t?4:3,Kh):null}}class Xh extends Gh{getTick(e){const t=this.checkPrev(e),i=0===this.minTickInterval||0==(e=>vt(e,nt(e)))(e)%(this.minTickInterval/1e3),s=!ut(this.prevDate,e),n=function(e){return Ke(1,arguments),qe(e).getMinutes()}(e),r=!Li(this.prevDate,e)||t&&0===n;if(i){if(s)return this.asTick(e,1,jh());if(r)return this.asTick(e,2,Kh);if(0==n%30&&this.size<15)return this.asTick(e,3,Kh);if(0==n%15&&this.size<=5)return this.asTick(e,4,Kh)}return null}}class Zh extends Gh{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<22*Wh.Day.One,this.monthYear=this.duration>22*Wh.Day.One&&this.duration<7*Wh.Month.One,this.year=this.duration>7*Wh.Month.One}useTuesday(e){return!!this.noPrevDate||2===vi(e)&&ft(e,this.prevDate)>1728e5}getTick(e){this.checkPrev(e);const t=!_i(e,this.prevDate),i=!Ii(e,this.prevDate);return this.monthDay?1===vi(e)||this.useTuesday(e)?this.asTick(e,1,jh()):null:this.monthYear?t?this.asTick(e,1,Yh):null:this.year&&i?this.asTick(e,1,zh):null}}class Jh extends Gh{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<4*Wh.Week.One,this.monthYear=this.duration>4*Wh.Week.One&&this.duration<6*Wh.Month.One,this.year=this.duration>6*Wh.Month.One}getTick(e){this.checkPrev(e);const t=!_i(e,this.prevDate),i=!Ii(e,this.prevDate);return this.monthDay?this.asTick(e,1,jh()):this.monthYear?t?this.asTick(e,1,Yh):null:this.year&&i?this.asTick(e,1,zh):null}}class Qh extends Gh{showMonths;constructor(e){super(e),this.showMonths=this.duration<7*Wh.Month.One}getTick(e){this.checkPrev(e);const t=!Ii(e,this.prevDate);return this.showMonths?this.asTick(e,1,Yh):t?this.asTick(e,1,zh):null}}class ed extends Gh{constructor(e){super(e)}getTick(e){this.checkPrev(e);return!Ii(e,this.prevDate)?this.asTick(e,1,zh):null}}function td(e){const t=function(e){return(e.valueOf()-gs.OPTIONS_DATA_BASE)/gs.OPTIONS_DATA_INCREMENT}(e);return t.toString()}function id(e){return ie(e)?`${e.toFixed(2)}%`:""}function sd(e,t,i=!1){const s=e.plots[0],n=s.curves[0],r=ie(n)&&n.fields.length>0?n.fields[0]:null;if(!ie(r))return"";const o={range:e.fullDomain,allDigits:!1,forceTrailingZeros:i};return Md(s,e.pane.presenter,o),s.metaData.format(t,r,o)}function nd(e,t,i=!1){return e.comparison===d.Percent?id(t):sd(e,t,i)}function rd(e,t,i){const s=e.view?.xAxis?.overrideFormatter;if(s)return s(t);if(ie(e.display.xAxis.isOrdinal))return td(t);const n=i||e.display.xAxis.format;if(ie(n)){return ad(t,$h(n))}const r=e.data.aggregation,o=e.display?.xAxis?.nonEodLabelWithDate??!1;return r.isEndOfDay?ld(r,t):cd(r,t,o)}function od(){const e=ce(Gv().config,null,"overrides","xAxis","getLocaleName");if(ie(e)&&"function"==typeof e)try{return e()}catch(t){Hv(`Failed retrieving the locale name, error is ${t.message}`,"warn")}}function ad(e,t){return Si(e,t,function(){if("fr"===od())return{locale:Bh}}())}function ld(e,t){if(!ht(t))return"";switch(e.unit){case a.Tick:case a.Intraday:case a.Day:case a.Week:default:return ad(t,"P");case a.Month:return ad(t,"LLL yyyy");case a.Quarter:return ad(t,"qqq yyyy");case a.Year:return ad(t,"yyyy")}}function cd(e,t,i){if(!ht(t))return"";return ad(t,`${i?"P ":""} ${e.isTick?"pp":"p"}`)}const ud=(e,t)=>e.at(t);class hd{constructor(e){this.presenter=e,this._dates=[],this.invalidate()}_dates=[];pendingRebuild=!1;checkRebuild(){this.pendingRebuild&&this.rebuild()}get withPrologLength(){return this.checkRebuild(),this._dates.length+gs.TIMELINE_PROLOG_PADDING_BARS}get withPrologEpilogLength(){return this.withPrologLength+gs.TIMELINE_EPILOG_PADDING_BARS}get firstSeriesIndex(){return gs.TIMELINE_PROLOG_PADDING_BARS}get lastSeriesIndex(){return this.checkRebuild(),0===this._dates.length?0:this.withPrologLength-1}get withoutPrologEpilogLength(){return this.checkRebuild(),this._dates.length}at(e){if(this.checkRebuild(),e<0||e>=this.withPrologEpilogLength)return null;if(e<gs.TIMELINE_PROLOG_PADDING_BARS){const t=W(this._dates),i=e-gs.TIMELINE_PROLOG_PADDING_BARS;return this.applyDateShift(t,i)}if(e>=this.withPrologLength){const t=k(this._dates),i=e-this.withPrologLength+1;return this.applyDateShift(t,i)}return this._dates[e-gs.TIMELINE_PROLOG_PADDING_BARS]}get length(){return this.checkRebuild(),this._dates.length>0?this.withPrologEpilogLength:0}slice(e,t){this.checkRebuild();const i=[];for(let s=e;s<t;++s)i.push(this.at(s));return i}tryToCorrectLastBar(e,t,i=!0){i&&this.checkRebuild();const s=+e,n=G(this._dates,s,Number),r=+this._dates[n];return n===this._dates.length-1&&r===s&&(this._dates[n]=t,!0)}mergeDateIntoTimeline(e,t=!0){t&&this.checkRebuild();const i=+e,s=G(this._dates,i,Number),n=+this._dates[s];if(n!==i){const t=s+(i>n?1:0);return this._dates.splice(t,0,e),t+this.firstSeriesIndex}return-1}invalidate(){this._dates.length=0,this.pendingRebuild=!0}rebuild(){if(this.presenter.isEmpty)return;const e=this.presenter.mainPlot.timeSeries;if(!e.hasData)return;const t=e.container.getTimeData();for(let i=t.length-1;i>=0;i--)this._dates[i]=t[i];this.presenter.allPlots.forEach(t=>{if(t.timeSeries===e)return;if(!t.timeSeries.hasData)return;t.timeSeries.container.getTimeData().forEach(e=>this.mergeDateIntoTimeline(e,!1))}),this.pendingRebuild=!1}applyDateShift(e,t){const{unit:i,size:s}=this.presenter.data.aggregation;switch(i){case a.Year:return Ze(e,12*t);case a.Quarter:return Ze(e,3*t);case a.Month:return Ze(e,t);case a.Week:return Xe(e,7*t);case a.Day:return this.addTradingDays(e,t);case a.Intraday:return Qe(e,s*t*gs.ONE_MINUTE_MILLIS);case a.Tick:return Qe(e,1e3*t)}}addTradingDays(e,t){const i=this.presenter.display?.xAxis?.isOrdinal;if(i)return Xe(e,t);if(!e||!Number.isFinite(t)||!Number.isInteger(t))return Xe(e,t);const s=t>0?1:-1;if(0===t){const t=e.getDay();return 0===t?Xe(e,1):6===t?Xe(e,2):e}let n=Math.abs(t),r=e,o=r.getDay();if(s>0?0===o?(r=Xe(r,1),n--):6===o&&(r=Xe(r,2),n--):0===o?(r=Xe(r,-2),n--):6===o&&(r=Xe(r,-1),n--),n<=0)return r;const a=Math.trunc(n/5);a>0&&(r=Xe(r,7*a*s),n-=5*a);let l=14;for(;n>0;){if(--l<0)return Xe(e,t);r=Xe(r,s),o=r.getDay(),0!==o&&6!==o&&n--}return r}}const dd={delete:'<path d="M225.8 286.2l225.8 225.8-225.8 225.8c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3l-225.8-225.8 225.8-225.8c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>',circle:'<circle cx="512" cy="512" r="512"/>',rectangle:'<rect width="1024" height="1024"/>',chevronUp:'<path d="M798.2 609.8l-256.0-256.0c-16.7-16.7-43.7-16.7-60.3 0.0l-256.0 256.0c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3z"></path>',chevronDown:'<path d="M225.8 414.2l256.0 256.0c16.7 16.7 43.7 16.7 60.3 0.0l256.0-256.0c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>',eye:'<path d="M950.9 411.4q-86.9 134.9-217.7 201.7 34.9-59.4 34.9-128.6 0.0-105.7-75.1-180.9t-180.9-75.1-180.9 75.1-75.1 180.9q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 76.0-117.1 190.6-186.6t248.3-69.4 248.3 69.4 190.6 186.6zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM1024.0 411.4q0.0-19.4-11.4-39.4-80.0-131.4-215.1-210.6t-285.4-79.1-285.4 79.4-215.1 210.3q-11.4 20.0-11.4 39.4t11.4 39.4q80.0 130.9 215.1 210.3t285.4 79.4 285.4-79.4 215.1-210.3q11.4-20.0 11.4-39.4z"></path>',eyeSlash:'<path d="M317.1 197.1l44.6 80.6q-49.7 36.0-77.7 90.9t-28.0 116.0q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 95.4-147.4 244.0-214.3zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM746.9 740.0q0.0-4.0-0.6-5.1-60.0-107.4-180.0-323.4t-180.6-324.0l-28.0-50.9q-5.7-9.1-16.0-9.1-6.9 0.0-76.6 40.0-9.1 5.7-9.1 16.0 0.0 6.9 25.1 49.7-81.7 37.1-150.6 98.9t-119.1 140.0q-11.4 17.7-11.4 39.4t11.4 39.4q87.4 134.3 217.1 212.0t283.4 77.7q50.9 0.0 102.9-9.7l30.9 55.4q5.7 9.1 16.0 9.1 2.9 0.0 10.3-3.4t17.7-8.9 18.9-10.6 18.0-10.6 11.1-6.6q9.1-5.7 9.1-15.4zM768.0 484.6q0.0-79.4-45.1-144.9t-119.4-94.0l160.0 286.9q4.6-25.7 4.6-48.0zM1024.0 411.4q0.0-20.0-11.4-39.4-22.3-36.6-62.3-82.9-85.7-98.3-198.6-152.6t-239.7-54.3l42.3 75.4q121.1 10.3 224.3 78.3t172.3 175.4q-65.7 102.3-161.1 168.0l36.0 64.0q54.3-36.6 104.3-87.4t82.6-105.1q11.4-19.4 11.4-39.4z"></path>',moreActions:'<path d="M597.3 512a85.3 85.3 0 1 0-170.6 0 85.3 85.3 0 0 0 170.6 0zm298.7 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0zm-597.3 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0z"></path>'};function pd(e){return!0===Gv().config.useAllFieldsForComparison&&e.mainPlot.mainCurve.isOhlc&&e.mainAxis.comparison===d.None&&e.mainPane.axes.map(e=>e.plots).flat().reduce((e,t)=>e+(t.isSymbol?1:0),0)>1}const fd=new Wo;function md({plots:e,isMultiSymbol:t,isMultiContract:i,date:s,time:n,dateFieldName:r,hideSymbols:o,revealingClose:a}){const l=o&&a,c=[Td(r,s,null,"heading"),n?Td("Time",n,null,"heading"):""],u=e.map(e=>{if(0===e.values.length)return null;const s=(e=>{const s=e.name.startsWith(gs.FAKE_SYMBOL_PREFIX);switch(e.type){case f.Expression:return!0;case f.Symbol:return!(!t&&!i||s)||!o;default:return!1}})(e)?vd(f[e.type],e.name,e.values[0].color):"",n=e.values.map(t=>Td(t.id===Ka.Close.id&&l?e.description:t.longName,t.value,t.color));if(e.events&&e.events.length){const t=e.events.map(e=>vd(`${e.field.name} (${ld(fd,e.date)})`,e.value,e.color));n.push(...t)}return n.unshift(s),ie(e.unalignedDate)&&n.unshift(Td("Date",e.unalignedDate,e.values[0].color,"heading")),n}).filter(e=>null!=e).flat();return`<table class="values-table">${c.concat(u).filter(e=>""!==e).join("")}</table>`}function gd(e,{panes:t,date:i,time:s,isMultiSymbol:n},r=!1,o=!1,a=!1,l=!1,c=!1,u=!1){return t.map((h,d)=>{const p=r?h.plots:h.plots.filter(e=>!e.isMain),m=e.mainPlot.axis.pane.id===h.id,g=a&&m?`<span class="field-name" style="padding-right:5px">${i} ${s||""}</span>`:"",y=p.map(t=>function(e,t,i,s,n,r,o,a){const{id:l,name:c,type:u,error:h,description:d,values:p,events:m,isMain:g}=e,y=a.display.tooltip,A=h||d,S="value-title"+(g?" value-main":""),T=f[u],v=["Study","BalanceSheet","IncomeStatement"].includes(T)||"Expression"===T&&!i,P=!v||a.hasLegend&&i?"":Cd(l),C=function(e,t){const i=Ad(t?"eye":"eyeSlash"),s=t?"Hide":"Show",n=`${s} plot`;return`<a class="show-hide-plot" data-plot-id="${e}" data-act="${s}" title="${n}">${i}</a>`}(l,e.visible),b=o?function(e){const t=Ad("moreActions");return`<a class="more-actions" data-plot-id="${e}" data-act="Menu" title="Actions">${t}</a>`}(l):"",E=pd(a)&&e.type===f.Symbol,L=(g||E)&&(!s||e.values.length>1),M=e=>L?e.abbreviation:"Close"===e.id&&r?d+" ":null,_=t?p.map(e=>Pd(M(e),e.value,e.color)).join(" ")+function(e){if(e&&e.length){return`Event ${e.map(e=>Pd(`${e.field.name} (${ld(fd,e.date)})`,e.value,e.color)).join(" ")}`}return""}(m):"",x=e=>`<div class="box" style="background-color:${e.color}"></div>`,I=!g&&"Expression"!==T,D=p.slice(0,I?p.length:1).map(x).join(""),O=t?"":D,w="Name"===y.mainTitle?c:d,R=n?e.visible&&t?"":`${d}`:`${w}`;let N=s&&E?`${d} (${R})`:R;y.showMainTitle||(N="");const V=()=>{const e=a.data?.aggregation.toShortString(),t=a.data?.aggregation.describe();return`<span class="value-main" title="${t}">·${e}·</span>`},H=e.isMain?V():"";return`\n <div class="plot">\n ${P} ${C} ${b} ${O}\n <a class="${S}" ${A?`title="${A}" `:""}data-plot-id="${l}">${N}</a>\n ${H} ${_}\n </div>\n `.trim()}(t,o,m,n,l,c,u,e)),A=`${g}${y.join("")}`,S=function(e,t){const i=e>0,s=e<t-1;return[`${i?Sd(!0,e):""}`,`${s?Sd(!1,e):""}`].join(" ").trim()}(d,t.length);return{id:`bc-tip-${h.id.substring(0,8)}`,isMainPane:m,content:A,moveContent:S,bounds:h.bounds}})}function yd(e){return`bchart-icon-${e}`}function Ad(e,t=null,i=10){return`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="${i}px" height="${i}px" ${ie(t)?`style="fill:${t}"`:""}><use xlink:href="#${yd(e)}"></use></svg>`}function Sd(e,t){const i=e?"Up":"Down";return`<span data-pane="${t}" data-dir="${i}" title="Move ${i}" class="move-pane">${Ad(`chevron${i}`)}</span>`}function Td(e,t,i=null,s=[]){"string"==typeof s&&(s=s.split(" "));const n="string"==typeof i?` style="color: ${i}"`:"";return`\n <tr class="${["value-row",...s].join(" ")}">\n <td class="field-name">${e}</td>\n <td${n} class="field-value">${t}</td>\n </tr>\n `}function vd(e,t,i=null){return Td(e,t,i,"value-title")}function Pd(e,t,i){const s="string"==typeof i?` style="color: ${i}"`:"";return`${ie(e)?`<span class="field-name">${e}</span>`:""}<span${s} class="field-value">${t}</span>`}function Cd(e){return`<a class="delete-plot" data-plot-id="${e}" title="Delete plot">${Ad("delete")}</a>`}function bd(e,t,i,s,n,r){const a=function(e,t){const i=e.data.aggregation,s=e.display.xAxis,n=s.isOrdinal,r=te(n)&&n,o=r?s.ordinalName??"Value":"Date";return{date:r?td(t):ld(i,t),time:i.isEndOfDay||r?null:cd(i,t,!1),isMultiSymbol:_d(e),isMultiContract:i.isMultiContract,dateFieldName:o}}(e,t);a.offset=i,a.lastBarRefresh=!1,a.chartId=e.elementId;const l=i=>i.axes.map(e=>e.plots).flat().filter(t=>!n||t===e.mainPlot).map(i=>function(e,t,i,{isMultiContract:s},n){const r=n.isStudy;if(!n.timeSeries.hasData)return null;const a=n.timeSeries.container;n.type,f.Expression;const l=n.axis.comparison!==d.None,c=n.axis.comparison===d.Percent,u=(e,s)=>n.customPlotValues&&s!==Ka.DateTime?[n.getValueAt(s,t,i),0]:Ld(e,s,t,l),h=n,p=r?`${Gr(h.model.study).meta.title} ${h.fullParams}`:n.metaData.name||"",m={isMain:n.main,type:n.type,typeName:f[n.type],name:n.title,description:p,exchange:n.metaData.exchange||"",error:h.errorText,id:n.id,visible:n.visible};if(ie(h.yearOffset)&&0!=h.yearOffset){const i=e.data.aggregation,s=function(e,t){return Ke(2,arguments),lt(e,-je(t))}(t,h.yearOffset);m.unalignedDate=ld(i,s)}const g=n.curves[0];s&&n.type===f.Symbol&&a.hasField(Ka.Symbol)&&(t.valueOf()===gs.ZERO_DATE.valueOf()?m.name=n.timeSeries.container?.getLastDataPoint(Ka.Symbol):m.name=u(g,Ka.Symbol)[0]);const y={},A={range:n.axis.yScale.domain(),allDigits:!0};Md(n,e,A);const S=(e,t)=>{const i=(t===Ka.Change||t===Ka.PercentChange)&&e>0?"+":"";return c?i+id(e):i+n.metaData.format(e,t,A)},T=pd(e),v=/* @__PURE__ */new Set;return m.values=n.curves.filter(e=>e.visible).map(e=>(!n.main&&n.isSymbol&&T?$u:e.fields).map(t=>{if(v.has(t))return null;v.add(t);const[i,s]=u(e,t),a=n.axis.yScale.priceToY(i);y[t.id]=!0;const l=n.customPlotValues?h.getColorOf(t):e.getColor(s,e.style!==o.HollowCandles,t);let c=S(i,t).trim();if(ie(i)&&t===Ka.Change){const[t]=u(e,Ka.PercentChange);ie(t)&&(c+=` (${S(t,Ka.PercentChange)})`)}return{abbreviation:xd(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${r?h.params:""}`.trim(),color:Sn(l),val:i,y:a,value:c}}).filter(e=>null!==e)).flat(),m.events=n.findEvents(u(g,Ka.DateTime)).filter(e=>e.field!==Ka.Custom),m}(e,t,r,a,i)).filter(e=>null!==e);return a.panes=e.panes.map(e=>({bounds:Ed(e),id:e.id,plots:l(e)})),a}function Ed(e){const t=e.getBounds();if(!ie(t))return;const{x:i,y:s,width:n,height:r}=t,{leftOffset:o,rightOffset:a}=e.presenter.view;return{top:s,left:i+o,right:a,bottom:s+r,width:n,height:r}}function Ld(e,t,i,s=!1){const n=e.plot,r=n.timeSeries.container,o=n.axis.pane.presenter.timeline,a=G(o,+i,Number,ud),l=o.at(a-e.shift);if(null===l)return[null,0];const c=r.getTimeData(),u=G(c,+l,Number);return[!c[u]||c[u].getTime()!==l.getTime()?null:e.dataAt(t,u,!s),u]}function Md(e,t,i){ie(e.precision)?i.overridePrecision=e.precision:e.isStudy&&ie(t.mainPlot?.precision)&&!ie(Gr(e.model.study).meta.decimals)&&(i.overridePrecision=t.mainPlot.precision)}function _d(e){const t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===f.Symbol&&e.symbol!==t)}function xd(e){return e.id===Ka.Change.id?"Δ":e.id.substring(0,1)}class Id{plot;id;fields=[];colors=[];style=o.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle="Solid";varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=Pe(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=ie(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(Ka.Close)}get name(){return this.isOhlc?"":this.fields[0].name}get isHeikinAshiStyle(){return this.style===o.HeikinAshi}get isCandle(){return this.style===o.Candlestick||this.style===o.HollowCandles||this.style===o.HeikinAshi}get isHollowCandles(){return this.style===o.HollowCandles}get isElderImpulseSystemStyle(){return this.style===o.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===o.PercentChange}get isOhlcStyle(){return this.style===o.OHLC}get isHlcStyle(){return this.style===o.HLC}get isRangeStyle(){return this.style===o.Range}get isRenko(){return this.style===o.Renko}get isKagi(){return this.style===o.Kagi}get isPointAndFigure(){return this.style===o.PointAndFigure}get isLineBreak(){return this.style===o.LineBreak}get isBaseline(){return this.style===o.Baseline}get isLineLike(){return[o.Line,o.Area,o.Baseline,o.PercentChange].includes(this.style)}get isColumn(){return this.style===o.Column}get isMultiColumn(){return this.style===o.MultiColumn}get isStackedColumn(){return this.style===o.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>r[e])),this.colors=e.colors,this.fields=e.fields.map(e=>Ka[e]),this.style=o[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,i=!0){const s=!this.plot.isComparison(d.None),n=e===Ka.PercentChange,r=e===Ka.Change,o=n||(!i||s)&&r,a=this.timeSeries.container.hasField(Ka.Last)?Ka.Last:Ka.Close,l=o?a:e,u=(e,t)=>{const i=this.timeSeries.container.getData(e)[t];return e.type!==c.Number?i:this.plot.priceMapper(i,t,e)},h=u(l,t);if(!o)return h;if(t<=1)return 0;const p=u(l,t-1),f=h-p;return n?0===p?0:f/p:f}timeSeriesAt(e){const t=this.timeSeries.container.getTimeData(),i=t.length;return e<0||e>i-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){const e=this.view.xAxis.xScale;if(!ie(e.extent()))return null;return 0!==this.shift?e.extent().map(t=>e.timeline.at(t-this.shift)):e.domain()}get yScale(){return this.plot?.yScale??this.axis.yScale}getCore(){const e=this.timeSeries;if(!e.hasData||!this.visible)return null;const t=this.view.xAxis.xScale.extent();if(!ie(t))return null;const i=this.yScale.domain();if(!ie(i))return null;return{ts:e,extent:t,domain:i,range:this.yScale.range()}}drawHover(e,t,i){if(!this.isLineLike)return;if(null===this.getCore())return;const[s,n]=Ld(this,this.pickMainField(),t);if(!ie(s))return;e.save(),_n(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=Sn(this.getColor(n)),e.beginPath();Yd(e,i,this.priceToY(s),this.lineMarker??"Circle",1.3333),e.fill(),e.restore()}draw(e){const t=this.getCore();if(null===t)return;const{ts:i,extent:s,domain:n,range:r}=t;e.save(),e.setLineDash([]);const a=i.container.getTimeData(),l=this.shiftedTimeDomain[0],c={bar:this.view.xAxis.xScale.bar,domain:n,range:r,slice:s,start:G(a,+l,Number)||0},u=ie(this.zones);this.isOhlc?Gd.call(this,e,c):this.isRenko||this.isLineBreak?Bd.call(this,e,c):this.style===o.Ribbon?this.varyColorPerBar?ep.call(this,e,c):Qd.call(this,e,c,this.colors[0]):this.style===o.Area?u?Nd.call(this,e,c,Od,!0):Od.call(this,e,c,this.colors,!0):this.isColumn||this.isMultiColumn?u?Nd.call(this,e,c,kd,!0):kd.call(this,e,{...c,range:[null,null]}):this.isStackedColumn?Fd.call(this,e,c):this.isBaseline?Hd.call(this,e,c):this.style===o.Step?u?Nd.call(this,e,c,Ud):Ud.call(this,e,c,this.colors[0]):this.isKagi?Zd.call(this,e,c):this.isPointAndFigure?Jd.call(this,e,c):this.style===o.Dots?Wd.call(this,e,c):this.style===o.Line||this.isPercentChangeStyle?u?Nd.call(this,e,c,jd):this.varyColorPerBar?qd.call(this,e,c):jd.call(this,e,c):Hv(`Drawing of the curve style '${this.style}' is not implemented yet`,"error"),e.restore()}pickMainField(){return 1===this.fields.length?this.fields[0]:this.fields.includes(Ka.Last)?Ka.Last:this.fields.includes(Ka.Close)?Ka.Close:this.fields[0]}get zoneColors(){if(!ie(this._zoneColors)){const e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return-1===t&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?Sn(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(Ka.BARCOLIX))return null;const t=this.dataAt(Ka.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,i=null){if(this.varyColorPerBar){const i={};if(this.isOhlc||this.isRenko||this.isLineBreak){const t=this.dataAt(Ka.Open,e),s=this.dataAt(Ka.High,e),n=this.dataAt(Ka.Low,e),r=this.dataAt(Ka.Close,e),o=this.dataAt(Ka.Change,e);i.open=t,i.high=s,i.low=n,i.close=r,i.change=o}else if(this.plot.isStudy&&!["VOL","MAVOL"].includes(this.plot.model.study)){const t=this.pickMainField(),s=this.dataAt(t,e-1),n=this.dataAt(t,e),r=ie(s),o=ie(n);i.change=r?o?n-s:-1:o?1:0}else{const t=this.plot.axis.pane.presenter.data.aggregation;t.isTick&&t.spec===l.None||(i.open=this.dataAt(Ka.Open,e),i.close=this.dataAt(Ka.Close,e)),i.change=this.dataAt(Ka.Change,e)}let s;const n=function(e,{open:t,close:i,change:s},n){const r=n.length>2&&e!==o.HLC,a=ie(t,i),l=a&&i>t,c=a&&i===t,u=s>0,h=0===s;return{useSame:r,isUp:l,isSame:c,isUpPrev:u,isSamePrev:h,isDown:!l&&!c,isDownPrev:!u&&!h}}(this.style,i,this.colors),a=this.getComputedColor(e);switch(this.style){case o.Candlestick:case o.Renko:case o.LineBreak:case o.Range:case o.HeikinAshi:case o.OHLC:case o.HLC:case o.Column:{if(ie(a)){s=a;break}let t=n.useSame?n.isUp:n.isUp||n.isSame,i=n.isSame;const o=this.attributes||[],l=this.plot.isStudy&&!["HASMO","VOL","MAVOL"].includes(this.plot.model.study);if((o.includes(r.ChangeBased)||l)&&(t=n.useSame?n.isUpPrev:n.isUpPrev||n.isSamePrev,i=n.isSamePrev),s=this.colors[t?1:0],n.useSame&&i&&(s=this.colors[2]),this.isRenko||this.isLineBreak||this.isRangeStyle){1===this.dataAt(Ka.Projection,e)&&(s=Pn(.5,!0)(s))}break}case o.ElderImpulseSystem:s=this.colors[this.dataAt(Ka.BREL,e)];break;case o.HollowCandles:{const e=this.colors[n.isUpPrev||n.isSamePrev?1:0];s=t&&(n.isUp||n.isSame)?gs.COLOR_TRANSPARENT:e;break}case o.Line:case o.PercentChange:case o.Ribbon:case o.Kagi:if(ie(a)){s=a;break}s=this.colors[0];break;case o.PointAndFigure:{const t=Sh(this.dataAt(Ka.BARKIND,e))?1:0;s=this.colors[t];break}default:throw new Error(`Unexpected style ${o[this.style]} for a curve with varying colors`)}return ie(s)||(s=this.colors[0]),s}if(this.zones){const t=this.pickMainField(),i=this.dataAt(t,e),s=this.getColorsFromZone(i);return this.style===o.Area?this.pickAreaStroke(s):s.length>0?s[0]:this.colors[0]}{const e=e=>e===i;return(this.isMultiColumn||this.isStackedColumn)&&ie(i)?this.colors[function(e,t){return Math.min(Math.max(t,0),e.length-1)}(this.colors,this.fields.findIndex(e))]:this.colors[0]}}}function Dd([e,t],i,s){let n=i;const r=this.timeSeries.container.size;for(let o=e;o<=t;o++){for(;this.timeSeriesAt(n)<this.timelineAt(o-this.shift)&&n<r;)++n;if(n===r)break;const e=this.timeSeriesAt(n)>this.timelineAt(o-this.shift);s.call(this,n,e)}}function Od(e,t,i,s=!1){jd.call(this,e,t,this.pickAreaStroke(i)),tp.call(this,e,t,i[0],s)}function wd(e,t){const i=ie(e),s=ie(t);let n,r;const o=this.pane.getBounds();if(i)if(s){const i=this.priceToY(e),s=this.priceToY(t);n=(i+s)/2,r=new xn(o.x,s,o.width,i-s)}else n=this.priceToY(e),r=new xn(o.x,o.y,o.width,n-o.y);else n=this.priceToY(t),r=new xn(o.x,n,o.width,o.y+o.height-n);return[n,r]}const Rd=(e,t)=>{const i=Pn(.6)(e),s=Cn(.6)(e),n="linLighten"===t;return[n?s:i,e,n?i:s]};function Nd(e,t,i,s=!1,n){let r;this.zones.forEach((o,a)=>{const l=o.value,[c,u]=wd.call(this,r,l);e.save(),_n(e,u),s&&(t.range=[null,c]);let h=this.zoneColors[a];if(o.gradient){const t=Rd(h,o.gradient),i=e.createLinearGradient(0,u.y,0,u.y+u.height);i.addColorStop(0,t[0]),i.addColorStop(.5,t[1]),i.addColorStop(1,t[2]),h=i}else ie(n)&&(h=n(a,h));i.call(this,e,t,h),e.restore(),r=l})}function Vd(e,t){const{x:i,width:s}=this.pane.getBoundsWithoutScales();e.save(),e.lineWidth=1,e.strokeStyle="#888",e.setLineDash(An("dot")),$n(e,t,i,i+s),e.restore()}function Hd(e,t){const[i,s]=t.range,{baseLevel:n}=function(e){const{BaseLevel:t}=fe(e);return{baseLevel:Number.isFinite(t)?Ce(0,100,t):50}}(this.plot.inputs),r=(i-s)*n/100+s;this.zones[0].value=this.yToPrice(r),Vd.call(this,e,r);Nd.call(this,e,t,Od,!0,(t,n)=>{const o=1===t,a=Tn(n,0),l=e.createLinearGradient(0,o?i:s,0,r);return l.addColorStop(0,n),l.addColorStop(1,a),[l,Tn(n,1)]})}function Bd(e,{bar:t,slice:i,start:s}){let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;Dd.call(this,i,s,(i,s)=>{if(!s){const[s,r]=[Ka.Open,Ka.Close].map(e=>this.dataAt(e,i)).map(this.priceToY,this),o=Math.floor(t.totalWidth/2);e.fillStyle=this.getColor(i),e.beginPath(),e.rect(n-o,s,t.totalWidth,r-s),e.fill()}n+=t.totalWidth})}function Fd(e,{bar:t,slice:i,start:s}){if(!this.isFirstVisibleOfStyle())return!1;let n=this.view.xAxis.xScale.range()[0]+t.offset;const r=Kn();r.prolog(e);const o=this.plot.curves.filter(e=>e.isStackedColumn);Dd.call(this,i,s,(i,s)=>{if(!s){let s=this.priceToY(0),a=0;o.forEach(o=>{if(!o.visible)return;const l=o.fields[0];if(a+=this.dataAt(l,i),ie(a)){const c=this.priceToY(a);e.fillStyle=o.getColor(i,!1,l),e.beginPath(),e.rect(r.adjust(n),r.adjust(c),r.adjust(t.width),r.adjust(s-c)),e.fill(),s=c}})}n+=t.totalWidth}),r.epilog(e)}function kd(e,{bar:t,slice:i,start:s,range:[n,r]}){let o=this.view.xAxis.xScale.range()[0]+t.offset;const a=this.isMultiColumn,l=a?this.fields:[this.pickMainField()],c=t.width/(a?l.length:1),u=Kn();u.prolog(e),Dd.call(this,i,s,(i,s)=>{s||l.forEach((t,s)=>{const n=this.dataAt(t,i);if(ie(n)){ie(r)||(r=this.priceToY(0));const a=this.priceToY(n);e.fillStyle=this.getColor(i,!1,t),e.beginPath(),e.rect(u.adjust(o+s*c),u.adjust(a),u.adjust(c),u.adjust(r-a)),e.fill()}}),o+=t.totalWidth}),u.epilog(e)}function Wd(e,{bar:t,slice:i,start:s}){let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;e.fillStyle=this.getColor(0);const r=Math.max(1,this.lineWidth||gs.CURVE_STYLE_DOTS_RADIUS),o=2*Math.PI;e.beginPath(),Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const t=this.priceToY(s);e.moveTo(n+r,t),e.arc(n,t,r,0,o)}}n+=t.totalWidth}),e.fill()}function Ud(e,{bar:t,slice:i,start:s},n){let r=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const o=Kn();o.prolog(e),e.strokeStyle=n,e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(An(this.dashStyle)),e.beginPath();let a=!1,l=null;Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const n=this.priceToY(s);if(a)e.lineTo(r,l),e.lineTo(r,n);else{const s=this.dataAt(t,i-1);if(ie(s)){const t=this.priceToY(s);e.moveTo(-1,t),e.lineTo(r,t),e.lineTo(r,n)}else e.moveTo(r,n);a=!0}l=n}}r+=t.totalWidth}),e.stroke(),o.epilog(e)}const $d=[Ka.Open,Ka.High,Ka.Low,Ka.Close];function Gd(e,{bar:t,slice:i,start:s}){const n=this.presenter.display.chart.showMinMaxArc;let r=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const o=Kn();o.prolog(e);let a=null,l=null,c=null,u=null;const h=t=>{this.isCandle?(this.isHollowCandles?t.outlineColor=this.getColor(t.ix,!1):(this.colors.length>3&&(t.outlineColor=this.colors[3]),this.colors.length>4&&(t.wickColor=this.colors[4])),function(e,{x:t,adjust:i,width:s,y:[n,r,o,a],color:l,outlineColor:c,wickColor:u,isMin:h,isMax:d},p){const f=s/2;e.lineWidth=p,e.fillStyle=l,e.strokeStyle=c||l,e.beginPath(),e.rect(i(t-f),n,s,i(a-n)),e.fill(),e.stroke(),e.strokeStyle=u||c||l,e.beginPath(),e.moveTo(t,Math.min(a,n)),e.lineTo(t,r),e.moveTo(t,Math.max(a,n)),e.lineTo(t,o),e.stroke();const m=0===bn(l).a;e.strokeStyle=m?c:l,zd(e,h,d,t,o,r,f)}(e,t,this.lineWidth)):(this.isOhlcStyle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&function(e,{x:t,adjust:i,width:s,y:[n,r,o,a],color:l,isMin:c,isMax:u},h,d){const p=s/2;e.lineWidth=h,e.strokeStyle=l,e.beginPath(),e.moveTo(t,o),e.lineTo(t,r),d&&(e.moveTo(i(t-p),n),e.lineTo(t,n));e.moveTo(i(t+p),a),e.lineTo(t,a),e.stroke(),zd(e,c,u,t,o,r,p)}(e,t,this.lineWidth,!this.isHlcStyle)};Dd.call(this,i,s,(e,i)=>{if(!i){const i=$d.map(t=>this.dataAt(t,e)),[s,n,d,p]=i;if(ie(s,n,d,p)){const f={x:o.adjust(r),adjust:o.adjust,width:t.width,y:[s,n,d,p].map(this.priceToY,this).map(o.adjust),isMin:!1,isMax:!1,ix:e,color:this.getColor(e)},m=Math.min(...i),g=Math.max(...i);(!ie(a)||m<a)&&(a=m,c=f),(!ie(l)||g>l)&&(l=g,u=f),h(f)}}r+=t.totalWidth}),n&&(ie(c)&&(c.isMin=!0,h(c)),ie(u)&&(u.isMax=!0,h(u))),o.epilog(e)}function zd(e,t,i,s,n,r,o,a=3){t&&kn(e,{x:s,y:n+a},o,0,Math.PI),i&&kn(e,{x:s,y:r-a},o,0,Math.PI,!0)}function Yd(e,t,i,s,n=1){const r=gs.MARKER_SIZE*n,o=1.25*r;switch(s){case"Circle":e.moveTo(t+r,i),e.arc(t,i,r,0,2*Math.PI);break;case"Square":e.rect(t-r,i-r,2*r,2*r);break;case"TriangleUp":e.moveTo(t-o,i+o),e.lineTo(t+o,i+o),e.lineTo(t,i-o),e.lineTo(t-o,i+o);break;case"TriangleDown":e.moveTo(t-o,i-o),e.lineTo(t+o,i-o),e.lineTo(t,i+o),e.lineTo(t-o,i-o);break;case"Diamond":e.moveTo(t,i-o),e.lineTo(t+o,i),e.lineTo(t,i+o),e.lineTo(t-o,i),e.lineTo(t,i-o)}}function jd(e,{bar:t,slice:i,start:s},n=null){const r=n||this.getColor(0),o=te(this.lineMarker);o&&(e.fillStyle=r,e.beginPath());let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const l=[],c=this.pickMainField();Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.dataAt(c,i);if(ie(t)){const i=this.priceToY(t);o&&Yd(e,a,i,this.lineMarker),l.push({x:a,y:i})}}a+=t.totalWidth}),o&&e.fill(),e.lineWidth=this.lineWidth,this.dashStyle&&e.setLineDash(An(this.dashStyle)),te(this.lineSmoothing)?function(e,t,i,s){if(t.length<2)return;const n=function(e,t){const i=[];for(let s=0;s<e.length-1;s++){const n=e[s-1]||e[s],r=e[s],o=e[s+1],a=e[s+2]||o,l=r.x+(o.x-n.x)/t,c=r.y+(o.y-n.y)/t,u=o.x-(a.x-r.x)/t,h=o.y-(a.y-r.y)/t;i.push({cp1x:l,cp1y:c,cp2x:u,cp2y:h,x:o.x,y:o.y})}return i}(t,s);e.beginPath(),e.strokeStyle=i,e.moveTo(t[0].x,t[0].y);for(const r of n)e.bezierCurveTo(r.cp1x,r.cp1y,r.cp2x,r.cp2y,r.x,r.y);e.stroke()}(e,l,r,this.lineSmoothing):Kd(e,l,r)}function Kd(e,t,i){if(t.length>1){e.beginPath(),e.strokeStyle=i;const s=t[0];e.moveTo(s.x,s.y);for(let i=1;i<t.length;i++){const s=t[i];e.lineTo(s.x,s.y)}e.stroke()}}function qd(e,{bar:t,slice:i,start:s}){e.lineWidth=this.lineWidth,e.lineCap="square",this.dashStyle&&e.setLineDash(An(this.dashStyle));let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,r=null,o=null,a=[];Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.pickMainField(),s=this.dataAt(t,i);if(ie(s)){const t=this.priceToY(s);o=this.getColor(i),r!==o&&(Kd(e,a,r),a.length>0&&(a=[a.pop()]),r=o),a.push({x:n,y:t})}}n+=t.totalWidth}),Kd(e,a,o)}const Xd=[null,null,null,null];function Zd(e,{bar:t,slice:i,start:s}){e.lineWidth=Math.max(1,.5*t.width),e.lineJoin="miter",e.miterLimit=1.5;let n=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const r=Kn();r.prolog(e);let o=null,a=null,l=[];Dd.call(this,i,s,(i,s)=>{if(!s){const s=e=>$d.map(t=>this.dataAt(t,e)),[c,u,h,d]=s(i),[,p,f]=i<0?Xd:s(i-1);if(ie(c,u,h,d)){const s=r.adjust(n),m=r.adjust(n-t.totalWidth),g=[c,u,h,d].map(this.priceToY,this).map(r.adjust),y=r.adjust(this.priceToY(u>p?p:f));a=this.getColor(i);const A=ie(o)&&o!==a,S=c===u?1:2,T=c===u?2:1;l.push({x:m,y:g[0]}),l.push({x:s,y:g[S]}),A&&(l.push({x:s,y:y}),Kd(e,l,o),l=[]),A&&l.push({x:s,y:y}),l.push({x:s,y:g[T]}),o=a}}n+=t.totalWidth}),Kd(e,l,a),r.epilog(e)}function Jd(e,{bar:t,slice:i,start:s}){const n=this.view.xAxis.xScale.range()[0],r=t.totalWidth/2;let o=n+t.offset+t.width/2;const a=Kn();a.prolog(e);const l=this.plot.timeSeries.builder.boxSize,c=l/2;Dd.call(this,i,s,(i,s)=>{if(!s){const[t,s]=[Ka.High,Ka.Low].map(e=>this.dataAt(e,i)),n=this.colors[0],u=this.colors[1],h=this.dataAt(Ka.BARKIND,i),d=Sh(h),p=h===gs.BARKIND_XO,f=h===gs.BARKIND_OX;if(ie(t,s))for(let i=t;i>=s;i-=l){const l=a.adjust(o),[h,m]=[l-r,l+r],[g,y,A]=[i,i-c,i+c].map(e=>this.priceToY(e)),S=i===t&&p||i===s&&f?!d:d;e.beginPath(),S?(e.strokeStyle=u,e.moveTo(h,y),e.lineTo(m,A),e.moveTo(h,A),e.lineTo(m,y)):(e.strokeStyle=n,e.ellipse(l,g,r,y-g,0,0,2*Math.PI)),e.stroke()}}o+=t.totalWidth}),a.epilog(e)}function Qd(e,{bar:t,slice:i,start:s},n){e.fillStyle=n;const[r,o]=this.fields;let a=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2;const l=[];if(Dd.call(this,i,s,(e,i)=>{if(!i){const t=this.dataAt(r,e),i=this.dataAt(o,e);ie(t,i)&&l.push({x:a,upY:this.priceToY(t),downY:this.priceToY(i)})}a+=t.totalWidth}),l.length>0){e.beginPath(),e.moveTo(l[0].x,l[0].upY);for(let i=1;i<l.length;++i)e.lineTo(l[i].x,l[i].upY);const t=l.length-1;e.lineTo(l[t].x,l[t].downY);for(let i=t-1;i>=0;--i)e.lineTo(l[i].x,l[i].downY);e.closePath(),e.fill()}}function ep(e,{bar:t,slice:i,start:s}){const[n,r]=this.fields;let o=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,a=[];const l=t=>{if(a.length>1){e.beginPath(),e.fillStyle=t,e.moveTo(a[0].x,a[0].upY);for(let t=1;t<a.length;++t)e.lineTo(a[t].x,a[t].upY);const i=a.length-1;e.lineTo(a[i].x,a[i].downY);for(let t=i-1;t>=0;--t)e.lineTo(a[t].x,a[t].downY);e.closePath(),e.fill()}};let c=null,u=null;Dd.call(this,i,s,(e,i)=>{if(!i){const t=this.dataAt(n,e),i=this.dataAt(r,e);if(ie(t,i)){const s=this.priceToY(t),n=this.priceToY(i);u=this.getColor(e),c!==u&&(l(c),a.length>0&&(a=[a.pop()]),c=u),a.push({x:o,upY:s,downY:n})}}o+=t.totalWidth}),l(u)}function tp(e,{bar:t,slice:i,start:s,range:[n,r]},o,a){if(a){const t=e.createLinearGradient(0,n,0,r);t.addColorStop(0,o),t.addColorStop(1,Tn(o,0)),e.fillStyle=t}else e.fillStyle=o;e.beginPath();let l=null;const c=this.pickMainField();let u=this.view.xAxis.xScale.range()[0]+t.offset+t.width/2,h=!1,d=null;Dd.call(this,i,s,(i,s)=>{if(!s){const t=this.dataAt(c,i);if(ie(t)){const i=this.priceToY(t);h?e.lineTo(u,i):(e.moveTo(l=u,i),h=!0),d=u}}u+=t.totalWidth}),e.lineTo(d,r),e.lineTo(l,r),e.closePath(),e.fill()}class ip{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,i=m.Normal,s=[null,null]){this.symbol=e,this.aggregation=t,this.range=s,this.seriesKind=i,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(!ie(this.curveStyle)||!gs.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return"Standard";switch(this.curveStyle){case o.Renko:{const{method:e,period:t,source:i,brickSize:s}=Du(this.inputs);return`Renko;${"ATR"===e?`ATR;${t}`:`${e};${s}`};${i}`}case o.Kagi:{const{method:e,period:t,reversal:i}=uh(this.inputs);return`Kagi;${"ATR"===e?`ATR;${t}`:`User;${i}`}`}case o.PointAndFigure:{const e=Th(this.inputs),{method:t,period:i,reversal:s,boxSize:n,source:r,oneStepBack:o}=e;return`PointAndFigure;${"ATR"===t?`ATR;${i}`:`User;${n}`};${r};${s};${o}`}case o.LineBreak:{const{lineBreak:e}=dh(this.inputs);return`LineBreak;${e}`}default:return o[this.curveStyle]}}get needsExtraKey(){return[m.Options,m.BalanceSheet,m.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(";")}`:""}getHashKey(){const e=this.aggregation.getHashKey(),t=this.getBuilderKey(),i=this.getExtraKey(),s=this.extendedHours??!1;return`${this.symbol}|${e}|${s}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${i}`}duplicate(){const e=new ip(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return e.cacheMe=this.cacheMe,e.barsToFetch=this.barsToFetch,e.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,e.offset=this.offset,e.chartId=this.chartId,e.curveStyle=this.curveStyle,e.extendedHours=this.extendedHours,e.fields=ue(this.fields),e.splits=this.splits,e.padded=this.padded,e}}var sp,np={exports:{}},rp=np.exports;var op=(sp||(sp=1,function(e,t){var i,s;i="object"==typeof window&&window||rp||Ve,s={},i.PubSub?(s=i.PubSub,console.warn("PubSub already loaded, using existing version")):(i.PubSub=s,function(e){var t={},i=-1,s="*";function n(e){var t;for(t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function r(e){return function(){throw e}}function o(e,t,i){try{e(t,i)}catch(s){setTimeout(r(s),0)}}function a(e,t,i){e(t,i)}function l(e,i,s,n){var r,l=t[i],c=n?a:o;if(Object.prototype.hasOwnProperty.call(t,i))for(r in l)Object.prototype.hasOwnProperty.call(l,r)&&c(l[r],e,s)}function c(e,t,i){return function(){var n=String(e),r=n.lastIndexOf(".");for(l(e,e,t,i);-1!==r;)r=(n=n.substr(0,r)).lastIndexOf("."),l(e,n,t,i);l(e,s,t,i)}}function u(e){var i=String(e);return Boolean(Object.prototype.hasOwnProperty.call(t,i)&&n(t[i]))}function h(e){for(var t=String(e),i=u(t)||u(s),n=t.lastIndexOf(".");!i&&-1!==n;)n=(t=t.substr(0,n)).lastIndexOf("."),i=u(t);return i}function d(e,t,i,s){var n=c(e="symbol"==typeof e?e.toString():e,t,s);return!!h(e)&&(!0===i?n():setTimeout(n,0),!0)}e.publish=function(t,i){return d(t,i,!1,e.immediateExceptions)},e.publishSync=function(t,i){return d(t,i,!0,e.immediateExceptions)},e.subscribe=function(e,s){if("function"!=typeof s)return!1;e="symbol"==typeof e?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var n="uid_"+String(++i);return t[e][n]=s,n},e.subscribeAll=function(t){return e.subscribe(s,t)},e.subscribeOnce=function(t,i){var s=e.subscribe(t,function(){e.unsubscribe(s),i.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){var i;for(i in t)Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)&&delete t[i]},e.countSubscriptions=function(e){var i,s,n=0;for(i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)){for(s in t[i])n++;break}return n},e.getSubscriptions=function(e){var i,s=[];for(i in t)Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e)&&s.push(i);return s},e.unsubscribe=function(i){var s,n,r,o=function(e){var i;for(i in t)if(Object.prototype.hasOwnProperty.call(t,i)&&0===i.indexOf(e))return!0;return!1},a="string"==typeof i&&(Object.prototype.hasOwnProperty.call(t,i)||o(i)),l=!a&&"string"==typeof i,c="function"==typeof i,u=!1;if(!a){for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(n=t[s],l&&n[i]){delete n[i],u=i;break}if(c)for(r in n)Object.prototype.hasOwnProperty.call(n,r)&&n[r]===i&&(delete n[r],u=!0)}return u}e.clearSubscriptions(i)}}(s)),void 0!==e&&e.exports&&(t=e.exports=s),t.PubSub=s,e.exports=t=s}(np,np.exports)),np.exports);const ap=/* @__PURE__ */He(op);function lp(e,t){const i=e.query?.duplicate();if(ie(i)&&i.symbol!==gs.PLACEHOLDER_SYMBOL_NAME&&"Standard"===i.getBuilderKey()){0!==i.barsToFetch&&(i.barsToFetch=i.barsToFetch*gs.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);const e=t(i);return e.serverComputedSeries=!0,e}return new bh}function cp(e){return new Ga(e,c.Number,h.Study,e)}class up{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=/* @__PURE__ */new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=Pe(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw new Error("Should not be called.")}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(const t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){pe(this,e);const t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return gs.EMPTY_ARRAY}get hasData(){return null!==this.container}get source(){if(ie(this._source))return this._source;const e=ie(this.inputs)?this.inputs[gs.INPUT_SOURCE]:null;return ie(e)?Ka[e]:null}set source(e){this._source=e}async ready(){return ps.call(this,async()=>{this.basisChangedToken=this.useNotifications?ap.subscribe(qa.TS_ALL,this.onBasisChanged.bind(this)):null;const e={tag:Pe(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(I);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===qa.TS_EVENTSCHANGED||e===qa.TS_LOADING||this.innerSeries.some(e=>!e.hasData))return;if(!this.shouldTriggerOurRecalc(t.series)||null===this.base||this===t.series)return;const i={tag:Pe(),src:t.series};switch(e){case qa.TS_MANYCHANGED:this.calculate(i);break;case qa.TS_DATAPOINTCHANGED:case qa.TS_DATAPOINTADDED:{const s=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(i,s,e===qa.TS_DATAPOINTADDED);break}case qa.TS_TIMELINECORRECTION:case qa.TS_QUOTEMARKER:break;default:throw new Error("Unknown time series message, likely forgot to handle it")}}shutdown(){this.useNotifications&&this.basisChangedToken&&ap.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){const i=this.calculateAt(e);if(null!==i){Object.keys(i).forEach(e=>{const s=i[e],n=this.studyFields[e];t?this.container.addDataPoint(n,s):this.container.setLastDataPoint(n,s)})}}notify(e,t){J(e,{series:this,index:t})}calculateCommon(e,t=null,i=-1,s=!0){const n=-1===i,r=n?t=>{!ie(e.src)&&ie(t.calcCtx)||t.calculate(e)}:t=>t.recalculateAt(e,i,s);if(null===this.base)return;if(this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)return;this.calcCtx=e;if(this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>r(e)),n&&(this.container=this.makeContainer()),void 0!==this.calculateAt)if(n){const e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}else this.calculateDataPoint(i,s);t&&(ie(e.src)||this.initialNotification)&&this.notify(t,i)}calculate(e){this.calculateCommon(e,qa.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,i){this.computedServerSide||(!i&&te(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED,t,i))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,i){const s=this.innCont(e),n=s.size;return i<0||i>n-1?null:s.getData(t)[i]}innHasData(e){const t=this.innCont(e);return ie(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(Ka.DateTime,Ka.Symbol)}makeContainer(){const e=this.defaultWrappers.concat(this.getWrappers()),t=Object.keys(this.studyFields).map(e=>this.studyFields[e],this);return new xu(t,this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,i,s=this.base){return s.getData(i).slice(e-t+1,e+1)}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}}class hp extends up{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}}class dp extends hp{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){const[t,i,s,n]=[Ka.Open,Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e),this);let r=null,o=null,a=null,l=null;const c=w([t,i,s,n]);if(e<1)r=w([t,n]),o=i,a=s,l=0;else{const[t,n]=[Ka.Open,Ka.Close].map(t=>this.container.getData(t)[e-1],this);r=w([t,n]),o=Math.max(i,r,c),a=Math.min(s,r,c),l=c-n}return{[Ka.Open.id]:r,[Ka.High.id]:o,[Ka.Low.id]:a,[Ka.Close.id]:c,[Ka.Change.id]:l}}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}class pp extends up{constructor(e,t){super(e,t),My(this)}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)&&s.hasField(this.source)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=w(n.filter(D)):R(n)&&(t=w(n))}return{[this.target.id]:t}}getWrappers(){return this.source===Ka.Volume?this.wrapBaseFields(Ka.Volume,Ka.TradeSize,Ka.Change,Ka.Open,Ka.Close):[]}}class fp extends up{multiplier;constructor(e,t,i){super(e,t),this.multiplier=i(this.period),My(this)}calculateAt(e){let t=null;const[i,s]=_y(this);if(this.atLeast(e,2)&&s.hasField(this.source)){const n=this.container.getData(this.target)[e-1];if(null!==n){t=(this.innVal(i,this.source,e)-n)*this.multiplier+n}else{const i=this.period;if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=w(n.filter(D)):R(n)&&(t=w(n))}}}return{[this.target.id]:t}}}class mp extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=Ka.OpenInterest;return this.base.hasField(i)&&(t=this.baseVal(i,e)),{[i.id]:t}}}const gp={inField:Ka.MA,outFields:[Ka.ENVU,Ka.ENVD],func:ay},yp={inField:Ka.EMA,outFields:[Ka.ENVEXPU,Ka.ENVEXPD],func:ly},Ap={inField:Ka.SMA,outFields:[Ka.ENVSMOU,Ka.ENVSMOD],func:cy};class Sp extends up{kind;perc;constructor(e,t,i){super(e,i),this.kind=t,this.perc=this.inputs.Percent/100;const s=t.func(i,this.inputs.Period,e.source);this.addInner(s)}calculateAt(e){let t=null,i=null;const s=this.innVal(1,this.kind.inField,e);if(null!==s){const e=s*this.perc;t=s+e,i=s-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:i}}}class Tp extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period1,this.source),s=ay(t,this.inputs.Period2,this.source),n=by(this.target,(e,t,i)=>t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}}const vp={fields:[Ka.MACD,Ka.MACDS,Ka.MACDH],avgFunc:ay,mapFunc:Ey,histogramVaryColor:!0},Pp={fields:[Ka.MACD,Ka.MACDS,Ka.MACDH],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!0},Cp={fields:[Ka.MACD,Ka.CTLTM,Ka.CTM],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!1},bp={fields:[Ka.MACD,Ka.CTLTMF,Ka.CPMI],avgFunc:ly,mapFunc:Ey,histogramVaryColor:!1},Ep={fields:[Ka.PPO,Ka.PPOS,Ka.PPOH],avgFunc:ly,mapFunc:Ly,histogramVaryColor:!0},Lp={fields:[Ka.PVO,Ka.PVOS,Ka.PVOH],avgFunc:ly,mapFunc:Ly,histogramVaryColor:!1};class Mp extends up{histogramVaryColor=!1;histogramField;get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){const i=this.container.getData(this.histogramField)[e],s=this.container.getData(this.histogramField)[e-1];if(ie(i,s)){const n=i<=0;t=n?1:3,e>0&&(n&&i>s&&(t=0),!n&&i<s&&(t=2))}}return{[Ka.BARCOLIX.id]:t}}}class _p extends Mp{fields;constructor(e,t,i){super(e,i),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];const s=t.avgFunc(i,e.inputs.Period1,e.source,void 0),n=t.avgFunc(i,e.inputs.Period2,e.source,void 0),r=by(this.fields[0],t.mapFunc,s,n),o=t.avgFunc(r,e.inputs.Period3,r.target,this.fields[1]),a=by(this.fields[2],Ey,r,o);this.addInner(r,o,a)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}}const xp=cp("_AVG_GAIN"),Ip=cp("_AVG_LOSS");class Dp extends up{constructor(e,t,i){super(e,i);const s=Sy(i,this.inputs.Period,this.source,Ka.RSI,t),n=Oy(e,"MA","Average")(s,this.inputs.PeriodAvg,Ka.RSI,Ka.RSIAVG);this.addInner(s,n)}getWrappers(){return[this.wrapInner(Ka.RSI,1),this.wrapInner(Ka.RSIAVG,2)]}}class Op extends up{highest;index;constructor(e,t,i,s){super(e,s),this.highest=t,this.index=i}calculateAt(e){let t=null;const i=this.inputs.Period;if(this.atLeast(e,i)){const s=this.past(e,i,this.source);R(s)&&(t=this.highest?Math.max(...s):Math.min(...s),this.index&&(t=i-s.indexOf(t)-1))}return{[this.target.id]:t}}}class wp extends up{toHighest;field;highField;lowField;constructor(e,t,i){super(e,i),this.toHighest=t;const s=ie(e.source),n=e.source,r=s?n:Ka.Close;this.field=r;const o=s?n:Ka.High;this.highField=o;const a=s?n:Ka.Low;this.lowField=a;const l=dy(i,e.inputs.Period,this.highField,Ka.HH,!0),c=dy(i,e.inputs.Period,this.lowField,Ka.LL,!1);this.addInner(l,c)}calculateAt(e){let t=null;const i=this.baseVal(this.field,e),s=this.innVal(1,Ka.HH,e),n=this.innVal(2,Ka.LL,e);if(R([i,s,n])){const e=this.toHighest?s:n,r=s-n;0!==r&&(t=(i-e)/r*100)}return{[this.target.id]:t}}}const Rp=cp("RawPercK");class Np extends up{kField;constructor(e,t,i,s){super(e,s);const n=py(s,this.inputs.Period1,t?Rp:i,!1),r=Oy(e,"MA"),o=r(n,this.inputs.Period2,n.target,t?i:Ka.PercD),a=t?r(o,this.inputs.Period3,o.target,Ka.PercD):o;this.kField=i,t?this.addInner(o,a):this.addInner(n,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(Ka.PercD,2)]}}function Vp(e,t,i,s,n){if(null===n)return null;const r=e*n,o=s+r,a=s-r;switch(t){case Ka.BOLLBU:return o;case Ka.BOLLBL:return a;case Ka.BOLLBW:return(o-a)/s*100;default:return null}}class Hp extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=this.inputs.Period,n=this.source,r=ay(i,s,n,Ka.BOLLBM),o="Modified"===t,a=vy(o?function(e,t,i=Ka.PCTCHG){return ny("PCTCHG",{source:t,target:i,inputs:fy},e)}(i,n):i,s,o?Ka.PCTCHG:n),l=this.inputs.Width,c=e=>_(Vp,l,e),u=by(Ka.BOLLBU,c(Ka.BOLLBU),r,a),h=by(Ka.BOLLBL,c(Ka.BOLLBL),r,a),d=by(Ka.BOLLBW,c(Ka.BOLLBW),r,a),p=Oy(e,"MA","Average")(d,this.inputs.PeriodAvg,Ka.BOLLBW,Ka.BOLLBWA);this.addInner(r,a,u,h,d,p)}calculateAt(e){const t=this.innVal(3,Ka.BOLLBU,e),i=this.innVal(4,Ka.BOLLBL,e),s=this.innVal(1,Ka.BOLLBM,e),n=this.innVal(5,Ka.BOLLBW,e),r=this.innVal(6,Ka.BOLLBWA,e);let o=null;switch(ie(t,i)&&(o=(this.baseVal(Ka.Close,e)-i)/(t-i)),this.kind){case"Regular":return{[Ka.BOLLBU.id]:t,[Ka.BOLLBL.id]:i,[Ka.BOLLBM.id]:s};case"Width":return{[Ka.BOLLW.id]:t-i};case"Percent":return{[Ka.BOLLP.id]:o};case"BandWidth":return{[Ka.BOLLBW.id]:n,[Ka.BOLLBWA.id]:r};case"Modified":{let t=null,i=null,n=null,r=null;const o=this.innVal(2,Ka.MSD,e);if(ie(o)){const e=this.inputs.MultInside,a=this.inputs.MultOutside;t=s+e*o,n=s-e*o,i=s+a*o,r=s-a*o}return{[Ka.MBBUI.id]:t,[Ka.MBBLI.id]:n,[Ka.MBBUO.id]:i,[Ka.MBBLO.id]:r,[Ka.MBBM.id]:s}}default:return null}}}const Bp=cp("_ABS_CHG"),Fp=cp("_MA_ABS_CHG"),kp=cp("_CHG");const Wp=cp("_PDM"),Up=cp("_MDM"),$p=cp("_TRS"),Gp=cp("_PDS"),zp=cp("_MDS"),Yp=cp("_DX");class jp extends up{useEma;adxField;multiplier;constructor(e,t,i,s){super(e,s),this.useEma=t,this.adxField=i,this.multiplier=2/(this.inputs.AdxSmoothing+1);const n=my(s,Ka.TR);this.addInner(n)}get helpers(){return[Wp,Up,$p,Gp,zp,Yp]}sum(e,t,i,s){let n=null;if(this.atLeast(e-1,s-1)){let r=this.past(e-1,s-1,t,this.container);r.push(i),R(r)&&(n=r.reduce((e,t,i)=>e+t,0))}return n}smooth1(e,t,i,s){let n=null;const r=this.inputs.DiLength,o=this.container.getData(i)[e-1];return n=null!==o?o-o/r+s:this.sum(e,t,s,r),n}smooth2(e,t,i,s){const n=this.container.getData(i)[e-1],r=this.inputs.AdxSmoothing;if(null!==n)return this.useEma?(s-n)*this.multiplier+n:(n*(r-1)+s)/r;{const i=this.sum(e,t,s,r);if(null!==i)return i/r}return null}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null,l=null,c=null;if(e>0){const u=this.past(e,2,Ka.High),h=this.past(e,2,Ka.Low),d=Math.max(u[1]-u[0],0),p=Math.max(h[0]-h[1],0);t=d>p?d:0,i=p>d?p:0;const f=this.container.getData(Ka.TR)[e];n=this.smooth1(e,Wp,Gp,t),r=this.smooth1(e,Up,zp,i),s=this.smooth1(e,Ka.TR,$p,f),(n>0||r>0)&&0!==s&&(o=n/s*100,a=r/s*100,l=100*Math.abs(o-a)/(o+a),c=this.smooth2(e,Yp,this.adxField,l))}return{[Wp.id]:t,[Up.id]:i,[$p.id]:s,[Gp.id]:n,[zp.id]:r,[Ka.PDI.id]:o,[Ka.MDI.id]:a,[Yp.id]:l,[this.adxField.id]:c}}getWrappers(){return[this.wrapInner(Ka.TR,1)]}}class Kp extends up{calculateAtFunc;constructor(e,t,...i){super(e,...i),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,i)=>{const s=t;let n=s.target;if(!ie(n)){n=s.container.hasField(Ka.Close)?Ka.Close:s.container.fields[0]}return this.innVal(i,n,e)}),i=null;return R(t)&&(i=this.calculateAtFunc(e,...t)),{[this.target.id]:i}}}function qp(e,t){const i=this.baseVal(Ka.High,t),s=this.baseVal(Ka.Low,t);return{[e.id]:(i+s)/2}}function Xp(e,t){const i=this.baseVal(Ka.High,t),s=this.baseVal(Ka.Low,t);return{[e.id]:i-s}}class Zp extends up{calculateAtFunc;constructor(e,t,i){super(e,i),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}}const Jp=cp("_RANGE"),Qp=cp("_MOV_RANGE"),ef={fields:[Ka.KCUP,Ka.KCLOW,Ka.KCMID],midSeries:e=>yy(e,Ka.TP),midTarget:Ka.TP,rangeSeries:e=>Cy(Jp,M(Xp,Jp),e),rangeTarget:Jp,func:"MA",useMultiplier:!1},tf={fields:[Ka.KBUP,Ka.KBLOW,Ka.KBMID],midSeries:e=>e,midTarget:Ka.Close,rangeSeries:e=>my(e,Ka.TR),rangeTarget:Ka.TR,func:"EMA",useMultiplier:!0};class sf extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=t.midSeries(i),n=Oy(e,t.func,"Average"),r=n(s,this.inputs.Period,t.midTarget,t.fields[2]),o=n(t.rangeSeries(i),this.inputs.Period,t.rangeTarget,Qp);this.addInner(r,o)}calculateAt(e){const t=this.innVal(1,this.kind.fields[2],e),i=this.innVal(2,Qp,e),s=null!==t&&null!==i,n=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:s?t+i*n:null,[this.kind.fields[1].id]:s?t-i*n:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}}class nf extends up{isWidth;constructor(e,t,i){super(e,i),this.isWidth=t;const s=dy(i,this.inputs.Period,Ka.High,Ka.DONUP,!0),n=dy(i,this.inputs.Period,Ka.Low,Ka.DONLOW,!1);this.addInner(s,n)}calculateAt(e){const t=this.innVal(1,Ka.DONUP,e),i=this.innVal(2,Ka.DONLOW,e),s=null===t&&null===i;return this.isWidth?{[Ka.DONW.id]:s?null:t-i}:{[Ka.DONMID.id]:s?null:(t+i)/2}}getWrappers(){return[this.wrapInner(Ka.DONUP,1),this.wrapInner(Ka.DONLOW,2)]}}const rf=cp("_HIND"),of=cp("_LIND");class af extends up{constructor(e,t,i){super(e,i),this.justWidth=t,this.justWidth=t;const s=this.inputs.Period,n=dy(i,s,Ka.High,rf,!0,!0),r=dy(i,s,Ka.Low,of,!1,!0);this.addInner(n,r)}calculateAt(e){let t=null,i=null,s=null;const n=this.innVal(1,rf,e),r=this.innVal(2,of,e);if(null!==n&&null!==r){const e=this.period;t=(e-n)/e*100,i=(e-r)/e*100,s=t-i}return this.justWidth?{[Ka.ARNOSC.id]:s}:{[Ka.ARNUP.id]:t,[Ka.ARNLOW.id]:i}}}const lf=cp("_MIDPOINT");const cf=cp("_MIDPOINT");class uf extends up{multiplyVol;constructor(e,t,i){super(e,i),this.multiplyVol=t}calculateAt(e){const t=[Ka.High,Ka.Low,Ka.Close,Ka.Volume],[i,s,n,r]=t.map(t=>this.baseVal(t,e));let o=i===s?0:(n-s-(i-n))/(i-s);return this.multiplyVol&&(o*=r),{[this.target.id]:o}}}const hf=cp("_RANGE");const df=cp("_MATP");class pf extends up{isBull;constructor(e,t,i){super(e,i),this.isBull=t;const s=ly(i,this.inputs.Period,this.source);this.addInner(s)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.EMA,e);return null!==i&&(t=this.isBull?this.baseVal(Ka.High,e)-i:this.baseVal(Ka.Low,e)-i),{[this.isBull?Ka.ERBLPOW.id:Ka.ERBRPOW.id]:t}}}const ff=cp("_FORCE");const mf=cp("_RANGE"),gf=cp("_EMA1"),yf=cp("_EMA2"),Af=cp("_RATIO");const Sf={isNegative:!1,fields:[Ka.PVI,Ka.PVIEMA]},Tf={isNegative:!0,fields:[Ka.NVI,Ka.NVIEMA]};class vf extends up{kind;constructor(e,t,i){super(e,i),this.kind=t;const s=Cy(this.kind.fields[0],M(function(e,t){let i=1e3;if(t>0){const s=[Ka.Close,Ka.Volume],[n,r]=s.map(e=>this.baseVal(e,t)),[o,a]=s.map(e=>this.baseVal(e,t-1)),l=this.container.getData(this.target)[t-1];if(e?r<a:r>a){i=l*((n-o)/o+1)}else i=l}return{[this.target.id]:i}},this.kind.isNegative),i),n=ly(s,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(s,n)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}}const Pf=cp("_LOGPC");const Cf=cp("_SWING_INDEX");const bf=cp("_MIN_CLOSE"),Ef=cp("_MAX_CLOSE");const Lf=cp("_EP"),Mf=cp("_AF"),_f=cp("_POS");const xf=cp("_IDY"),If=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],Df=e=>Array(e).fill(0);function Of(e,t,i){let s=e[i-1];return 0===t&&(s=e[i]),t<0&&(s=e[i+1]),s}function wf(e,t,i,s,n){const r=n[18];let o=s+1,a=0;for(let l=0;l<r;++l){let i=0,s=0;for(let n=1;n<6;++n){if(o--,e[o]<=0)continue;const r=e[o]-t[o];1==n&&(i=s=r),r>i&&(i=r),r<s&&(s=r)}a=a+i-s}return a=a/r*function(e,t){return Of(e,t,4)}(n,i[s]),a}function Rf(e,t,i,s,n){let r=s;const o=function(e,t){return Of(e,t,7)}(n,i[s]);let a=0;do{r--,e[r]>0&&a++}while(a<o&&r>0);return t[s]-t[r]}function Nf(e,t,i,s,n,r,o,a,l,c){const u=function(e,t){return Of(e,t,10)}(n,i[s]),h=function(e,t){return Of(e,t,13)}(n,i[s]),d=function(e,t){return Of(e,t,16)}(n,i[s]),p=l+c+t[s]-e[s];let f=100;n[20]>0&&(f=n[20]);let m=u*a/f;a>h&&(m=u*h/f);const g=2*c,y=e[s]+(p-g)-(p-g)*m,A=e[s]+(p-p*m),S=[r,o];return(1===a||1!==d||y>r)&&(S[0]=y),(1===a||1!==d||A<o)&&(S[1]=A),S}function Vf(e,t,i){let s=0,n=-1,r=0,o=1;for(let a=0;a<i;++a){if(t[a]=0,null==e[a])continue;if(s++,21==s&&(o=2),31==s&&(o=3),r+=e[a]*o,s<40)continue;t[a]=r/70;let l=0;for(let t=n+1;t<i&&(null==e[t]||(l++,1==l&&(n=t),1!=l&&21!=l&&31!=l||(r-=e[t]),31!=l));++t);}}const Hf=1,Bf=2,Ff=3,kf={[Hf]:{param:"cot",func:"parseCotLineChart",fields:[Ka.DateTime,Ka.COTLCCMSP,Ka.COTLCLGSP,Ka.COTLCSMSP]},[Bf]:{param:"cotadv",func:"parseDisaggregated",fields:[Ka.DateTime,Ka.COTDAGPRO,Ka.COTDAGSPD,Ka.COTDAGMNM,Ka.COTDAGOTH]},[Ff]:{param:"cotfin",func:"parseFinancialTradersReport",fields:[Ka.DateTime,Ka.COTFTRDLI,Ka.COTFTRASM,Ka.COTFTRLVF,Ka.COTFTROTH]}};class Wf extends up{wrappers;constructor(e,t,i){super(e,lp(i,e=>new Uf(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=kf[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}}class Uf extends Ch{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new $f(this.kind)}onStreamingUpdates(e){}}class $f extends Ku{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[kf[this.kind].param]="y"}getParser(e){return new Gf(e.symbol,e.aggregation,this.kind)}}class Gf extends zu{kind;constructor(e,t,i){super(e,t,0),this.kind=i}makeContainer(){return new Mu(kf[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[kf[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(Ka.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(Ka.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(Ka.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(Ka.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(Ka.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(Ka.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(Ka.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(Ka.COTFTROTH,parseInt(e[5]))}}class zf extends Wf{constructor(e,t){super(e,1,t)}}const Yf={Day:[Ka.PreviousHigh,Ka.PreviousLow,Ka.PreviousClose],Week:[Ka.WeekPreviousHigh,Ka.WeekPreviousLow,Ka.WeekPreviousClose],Month:[Ka.MonthPreviousHigh,Ka.MonthPreviousLow,Ka.MonthPreviousClose]};class jf extends up{disabled;record;streamingSubscription;constructor(e,t,i){if(super(e,i),this.disabled=!ie(i.query)||!ie(i.query.symbol),!this.disabled){let e=i.query.symbol;e.endsWith(".BZ")&&(e=e.slice(0,-3)),this.record=Gv().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>{const t=dl(qa.RT_QUOTE,this.record.symbol);return e.filter(t)}),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return ps.call(this,async()=>ie(this.record)?await this.record.ready()&&await super.ready():await super.ready(),"asyncReadyWork2")}onStreamingUpdates(e){if(this.record){const e={tag:Pe(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return Yf[e].map(e=>this.record.getValue(e))}}class Kf extends Ch{constructor(e){super(e)}getRetriever(){return Bi(this.query.symbol)?new Jf:new qf}onStreamingUpdates(e){}}class qf extends Ku{addExtraParams(e){e.impl="y"}getParser(e){return new Zf(e.symbol,e.aggregation)}}function Xf(){return new Mu([Ka.DateTime,Ka.IMPVOL])}class Zf extends zu{constructor(e,t){super(e,t)}makeContainer(){return Xf()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(Ka.DateTime,this.parseDate(e[1])),this.container.addDataPoint(Ka.IMPVOL,parseFloat(e[8])))}}class Jf extends qu{emptyContainer(e,t){return Xf()}get iterateForward(){return!1}getPageName(){return"getFuturesOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date.substring(0,10)));const s=te(e.impliedVolatility);i.addDataPoint(Ka.IMPVOL,s?100*e.impliedVolatility:null)}}const Qf=cp("_ABS_CHG"),em=cp("_DS1_EMA1"),tm=cp("_DS1_EMA2"),im=cp("_DS2_EMA1"),sm=cp("_DS2_EMA2");const nm=cp("_DIFF");const rm=cp("_SUM");const om=cp("_ABS_CHG"),am=cp("_HH_LL"),lm=cp("_MULMA");class cm extends hp{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){const i=(e,t)=>this.baseVal(e,t),s=[Ka.Open,Ka.High,Ka.Low,Ka.Close],n=s.map(t=>i(t,e));if(R(n)){const r=s.map(t=>i(t,e-1));if(R(r)){t=n.map((e,t)=>100*(e-r[t])/r[t]);const[i,s]=z(t);if(t[1]=s,t[2]=i,e>1){const i=this.container.getData(Ka.Close)[e-1];t[4]=t[3]-i}}}}return{[Ka.Open.id]:t[0],[Ka.High.id]:t[1],[Ka.Low.id]:t[2],[Ka.Close.id]:t[3],[Ka.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}const um=cp("_DIST"),hm=cp("_EMA_DIST1"),dm=cp("_EMA_DIST2"),pm=cp("_DIFF"),fm=cp("_EMA_DIFF1"),mm=cp("_EMA_DIFF2");const gm=cp("_CHG"),ym=cp("_M1"),Am=cp("_M2");class Sm extends up{constructor(e,t){super(e,t);const i=Cy(gm,function(e){const t=Ka.Close,i=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[gm.id]:i}},t),s=by(ym,(e,t)=>t>=0?t:0,i),n=by(Am,(e,t)=>t>=0?0:-t,i);this.addInner(s,n)}perc(e,t){return 100*e/t}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i+1)){const s=this.past(e,i,ym,this.innCont(1)),n=this.past(e,i,Am,this.innCont(2));if(R(s)&&R(n)){const e=O(s),i=O(n);t=this.perc(e-i,e+i)}}return{[Ka.CHDMOMOSC.id]:t}}}const Tm=cp("_MAX"),vm=cp("_MIN"),Pm=cp("_ISUPTREND");const Cm=cp("_TRENDUP"),bm=cp("_TRENDDOWN"),Em=cp("_TREND");const Lm=cp("_CUM_PRICE"),Mm=cp("_CUM_VOL"),_m=cp("_PER_CHG");class xm extends up{constructor(e,t){super(e,t);const i=this.source,s=Cy(i,M(xy,i),t);this.addInner(s)}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}}const Im=cp("_DIFF"),Dm=[Im,Ka.Buy,Ka.Sell];function Om(e,t,i,s){let n=null,r=null,o=null;ie(i,s)&&(o=i-s);const a=t>0?e.getData(Im)[t-1]:null;return ie(o,a)&&(n=o>0&&a<=0?1:null,r=o<0&&a>=0?-1:null),{[Im.id]:o,[Ka.Buy.id]:n,[Ka.Sell.id]:r}}const wm=cp("_PVM"),Rm=cp("_NVM");function Nm(e,t,i){return new Vm(e,t,i)}class Vm{constructor(e,t,i){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[i.mapper(t)]=t,e),{}),this.policy=i,this.exprSymbols=pa(e),this.valueSymbols=this.exprSymbols.filter(e=>void 0===this.innerLookup[e]),this.onlyForTimeline=B(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;const t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!ie(this.exprModel)}get hasData(){return null!==this.container}get sourceFields(){return this._sourceFields||(this._sourceFields=Array.from(this.policy.fieldMap.keys())),this._sourceFields}get targetFields(){return this._targetFields||(this._targetFields=Array.from(this.policy.fieldMap.values())),this._targetFields}async ready(){return ps.call(this,async()=>{this.basisChangedToken=ap.subscribe(qa.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=ap.subscribe(qa.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));const e=this.innerSeries.map(e=>e.ready());void 0!==this.policy.valueProvider&&e.push(this.policy.valueProvider.ready());const t=(await Promise.all(e)).every(I);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>ie(e.container))&&this.calculateCommon(qa.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===i.Manual)return;if(e===qa.TS_EVENTSCHANGED||e===qa.TS_LOADING)return;if(!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!ie(e.container)))return;const s=this.policy.mapper(t.series);if(e===qa.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(s))return;switch(this.policy.recompute===i.Everything?qa.TS_MANYCHANGED:e){case qa.TS_MANYCHANGED:this.calculate();break;case qa.TS_DATAPOINTCHANGED:case qa.TS_DATAPOINTADDED:this.recalculate(e===qa.TS_DATAPOINTADDED);break;case qa.TS_TIMELINECORRECTION:case qa.TS_QUOTEMARKER:break;default:throw new Error("Unknown time series message, likely forgot to handle it")}}shutdown(){this.basisChangedToken&&ap.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(ap.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,i)=>{if(t===Ka.Volume)return O(this.exprSymbols.map(t=>e.inn[t].values[i]??0));return ua(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[i]??null)})}pickMainField(){let e=null;for(const t of this.policy.fieldMap.values())if(null==e)e=t;else if(t===Ka.Close){e=t;break}return e}calculateLastChange(){const e=this.container,t=e.size;if(t<=1)return;const i=this.pickMainField(),s=e.getData(i)[t-2],n=e.getData(i)[t-1];ie(s,n)&&e.setLastDataPoint(Ka.Change,n-s)}calculateDataPoint(e,t){const i=this.calculateAt(e);if(null===i)return;e.atLeastOne=!0;const[s,n]=z(i,0,3);i[1]=n,i[2]=s,this.targetFields.forEach((e,s)=>{const n=i[s];t?this.container.addDataPoint(e,n):this.container.setLastDataPoint(e,n)}),t&&(this.container.addDataPoint(Ka.Change,null),this.container.addDataPoint(Ka.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){J(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,i){const s=this.innerLookup[e].container.getData(i);return t<0||t>=s.length?null:s[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,Ka.DateTime)}timeline(e){return e.container.getData(Ka.DateTime)}getRangeHelper(){switch(this.policy.missing){case t.UseNext:case t.UseNone:return Math.min;case t.UsePrevious:return Math.max;default:throw new Error("Unknow missing bar policy, likely forgot to implement it.")}}getRange(){const e=this.getRangeHelper();return{begin:new Date(e(...this.symbols.map(e=>W(this.timeline(this.innerLookup[e]))))),end:new Date(e(...this.symbols.map(e=>k(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,i){const s=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case t.UseNext:case t.UseNone:return s.findIndex(e=>e.valueOf()>=i.valueOf());case t.UsePrevious:return U(s,e=>e.valueOf()<=i.valueOf());default:throw new Error("Unknow missing bar policy, likely forgot to implement it.")}}checkPos(e){const t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!(ie(e.timeStamp)||this.policy.stretch(e.symbol)&&1!==t))}fillPosSymbolAt(e,i,s){e.index=i,e.timeStamp=this.timeStampAt(e.symbol,i);const n=(this.policy.missing===t.UseNone||this.policy.skipLeadingEmpty&&!s.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==s.timeStamp.valueOf();return e.values=this.sourceFields.map(t=>n?null:this.fieldValueAt(e.symbol,i,t)),e}skippable(e){return!!this.innerLookup[e].container.isEmpty&&(this.policy.noDataApproach===s.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===s.ModelTransformRequired)}get symbols(){const e=Object.keys(this.innerLookup);return ie(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){const t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return 0===this.symbols.length||(this.symbols.forEach(i=>{const s=this.findIndex(i,e),n={symbol:i,index:-1,timeStamp:/* @__PURE__ */new Date(0),values:[]};t.inn[i]=this.fillPosSymbolAt(n,s,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t)),t}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;ie(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>null!==e.timeStamp).map(e=>e.timeStamp.valueOf()))),this.policy.missing===t.UsePrevious?this.getInner(e).forEach(t=>{const i=ie(t.timeStamp);(i&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!i&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===t.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){return this.container.getLastDataPoint(Ka.DateTime).valueOf()<e.timeStamp.valueOf()}calculateCommon(e=null,t=null,i=!0){try{if(t)this.calculateDataPoint(t,i);else if(this.container=this.makeContainer(),!this.isExprInError){const e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(s){this.crashedComputationReported||(Hv(s,"error"),this.crashedComputationReported=!0)}}calculate(){const{yes:e,no:t}=V(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===s.ModelTransformRequired){const i=e=>e.map(this.policy.mapper),s=this.policy.modelTransform(i(e),i(t));null!==s&&(this.exprModel=s)}this.calculateCommon(qa.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;const t=this.getLastPos(),i=this.shouldAdd(t);this.calculateCommon(i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED,t,i)}recalculateAt(e,t,i){return this.recalculate(i)}makeContainer(){const e=[Ka.DateTime,Ka.Change].concat(this.targetFields);return new Mu(e)}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}}const Hm=cp("_AVG");const Bm=cp("_HAO"),Fm=cp("_HAH"),km=cp("_HAL"),Wm=cp("_HAC");const Um=cp("_DELTA");const $m=cp("_DIFF"),Gm=cp("_RANK"),zm=cp("_CHG"),Ym=cp("_AVG"),jm=cp("_HBRAKE_CHG"),Km=cp("_HEIGHT_DELTA"),qm=cp("_ACTION"),Xm=cp("_REVERSAL"),Zm=10,Jm=e=>[e>0,e<0],Qm=[null,null,null],eg=0,tg=1,ig=2;function sg([e,t],i){let s=null;if(i>0){const t=this.baseVal(e,i-1);ie(t)&&(s=this.baseVal(e,i)-t)}return{[t.id]:s}}class ng extends up{useHandbrake;constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,Ce(1,999,this.inputs.FastPeriod),Ka.Close),n=Ce(0,999,this.inputs.SlowPeriod),r=n>0,o=r?i(t,n,Ka.Close):t,a=by($m,r?(e,t,i)=>t-i:(e,t,i)=>i-t,s,o),l=Cy(zm,M(sg,[Ka.Close,zm]),t),c=Cy(Gm,function(e){const t=Math.abs(this.baseVal($m,e));let i=null,s=0,n=0;for(let r=e-1;r>=0&&s<200;--r){s++,Math.abs(this.baseVal($m,r))<t&&n++}return s>0&&(i=Math.floor(n/s*Zm)),i===Zm&&i--,{[Gm.id]:i}},a),u=Ce(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;const h=i(t,u,Ka.Close,Ym),d=Cy(jm,M(sg,[Ym,jm]),h);this.addInner(l,a,c,d)}get helpers(){return[Km,Ka.BARCOLIX,qm,Xm]}getStateAt(e){const t=this.innVal(2,$m,e);return ie(t)?Jm(t):Qm}findPreviousKnownState(e){for(let t=e-1;t>0;t--){const e=this.getStateAt(t);if(e===Qm)return Qm;const[i,s]=e;if(i||s)return e}return Qm}getBuySell(e){const t=this.getStateAt(e);if(t===Qm)return Qm;const[i,s]=t,n=this.findPreviousKnownState(e),[r,o]=n;if(!i&&!s)return n===Qm?Qm:[r,o,!1];const a=i!==r||s!==o;return a?[r,o,a]:[i,s,a]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,i=null,s=0,n=-1,r=eg;const[o,a,l]=this.getBuySell(e),[c,u]=[Xm,qm].map(t=>this.getPrev(t,e)),[h,d]=[0,-1].map(t=>this.innVal(4,jm,e+t));if(n=l?Zm:this.innVal(3,Gm,e),this.useHandbrake&&ie(h,d)){const t=!o&&h>0||!a&&h<0;l?(n=t?Zm:12,r=u):!0!==c&&u!==tg||(o&&d>0||a&&d<0?(n=this.innVal(3,Gm,e),r=ig):(n=t?11:13,r=tg))}if(ie(this.innVal(2,$m,e))){const t=this.innVal(1,zm,e),[i,n]=Jm(t),r=Math.abs(t);(o&&i||a&&n)&&(s=r),(o&&n||a&&i)&&(s=-r)}return o?t=1:a&&(i=1),{[Ka.JPIB.id]:t,[Ka.JPIS.id]:i,[Ka.BARCOLIX.id]:n,[Km.id]:s,[qm.id]:r,[Xm.id]:l}}}const rg={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:"EMA",Height:"Fixed"};const og=cp("_SMTH_ROC"),ag=cp("_TEN_SMTH_ROC");function lg(e,t,i,s,n){return new fp({source:s,target:n,outFields:[n],aggregation:i,inputs:ty(t)},e,e=>2/e)}const cg=cp("_VOL_AVG");const ug=(()=>{const e=(t=51,se(Math.pow(.5,1/t),6));var t;const i=Y(52,t=>Math.pow(e,t)),s=52/O(i);return i.map(e=>e*s)})(),hg=["Renko","Kagi","PointAndFigure","LineBreak"];function dg(e){return e===l.Continue||e===l.Nearest}class pg extends up{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,i){super(e,i,lp(i,e=>{if(!jr(v[Gv()?.config.mode??"Unspecified"]))return i;const t=e.duplicate(),s=e.aggregation;if(s.hasSpec)return dg(s.spec)?i:new bh(t,!0);const n=s.unit===a.Intraday&&s.size<=5,r=function(e,t){switch(e){case a.Intraday:return t>=240?3:t>=120?2:1;case a.Day:default:return 5;case a.Week:return 15;case a.Month:return 60;case a.Quarter:case a.Year:return 240}}(s.unit,s.size);t.aggregation=n?new Wo(a.Tick,s.size,l.PerSeconds):new Wo(a.Intraday,r);const o=n?1:3;t.barsToFetch=Math.min(gs.MAX_INTRADAY_BARS,o*e.barsToFetch);return new Ch(t)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof bh,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){const e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<20&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,i){if(e.src!==this.innerSeries[0])return;const s=i?qa.TS_DATAPOINTADDED:qa.TS_DATAPOINTCHANGED;this.notify(s,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(Ka.Change,1),this.wrapInner(Ka.Open,1),this.wrapInner(Ka.Close,1)]}}const fg=cp("_DR");class mg extends up{constructor(e,t,i){super(e,i);const s=Cy(fg,e=>{const t=this.baseVal(Ka.High,e),i=this.baseVal(Ka.Low,e);return{[fg.id]:ie(t,i)?t-i:null}},i),n=Oy(e,"MA")(s,this.inputs.Period,fg,Ka.ADR);if(t){const e=(e,t,i)=>ie(t,i)&&0!==i?t/i*100:null,t=by(this.target,e,n,i);this.addInner(t)}else this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}}const gg=cp("_EMA1"),yg=cp("_EMA2"),Ag=cp("_MACD"),Sg=cp("_PCTK"),Tg=cp("_PCTD"),vg=cp("_PCTK2");const Pg=cp("_EMA1"),Cg=cp("_EMA2"),bg=cp("_CORE");class Eg extends up{isEmpty=!1;constructor(e,t){if(super(e,t),Hy(t)&&e.aggregation?.isEndOfDay){let i=["$ADVT","$DECT"];switch(this.inputs.Source){case"TotalStocks":default:break;case"NYSEStocks":i=["$ADVN","$DECN"];break;case"NasdaqStocks":i=["$AVDQ","$DECQ"]}const s=this.getSeries(t.query,i[0]),n=this.getSeries(t.query,i[1]),r=this.getTargetSeries(e,s,n);this.addInner(s,n,r),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;const e=Cy(Ka.Close,(e,t)=>null,t),i=Cy(Ka.Close,(e,t)=>null,t),s=Cy(this.target,(e,t)=>null,t);this.addInner(e,i,s),this.canLoadMoreData=!1}}get baseIndex(){return this.isEmpty?0:1}getSeries(e,t){const i=e.duplicate();i.symbol=t;return Gv().getTimeSeriesDataSource().getTimeSeries(i)}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e!==this.innerSeries[0]&&((e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2))}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}}const Lg=cp("_INN_HL_ACC_IX"),Mg=new Wo;class _g extends up{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof bh)this.canLoadMoreData=!1;else{const r="PriceIndex"===this.inputs.Source?"$MADX":"$FADX",o=this.getSeries(t.query,r);if(this.addInner(o),this.isWeekly=e.aggregation.unit===a.Week,this.isWeekly){const e=this.getSeries(t.query,r,Mg),o=(i=e,s=this.inputs,new _g({aggregation:Mg,source:null,target:n=Lg,outFields:[n],inputs:{...s}},i));this.addInner(o)}this.canLoadMoreData=!0,this.initialNotification=!0}var i,s,n}getSeries(e,t,i){const s=e.duplicate();s.symbol=t,i&&(s.aggregation=i,s.barsToFetch=15*gs.US_TRADING_DAYS_PER_YEAR);return Gv().getTimeSeriesDataSource().getTimeSeries(s)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null;const i=this.period;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.Close);R(s)&&(t=O(s))}return{[this.target.id]:t}}calculateAtWeekly(e){const t=this.container?.size??-1;let i=null;const s=this.innCont(2);if(t>0&&e===t-1)i=s.getLastDataPoint(Lg);else{const t=this.container.getTimeData()[e],n=s.getTimeData();let r=G(n,t),o=n[r],a=null;for(;r<s.size&&Mi(t,o);)a=r,r+=1,o=n[r];null!==a&&(i=s.getData(Lg)[a])}return{[this.target.id]:i}}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e!==this.innerSeries[0]&&(e===this.innerSeries[1]&&this.innHasData(1))}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}}const xg=cp("_RSI1"),Ig=cp("_RSI1_MOM"),Dg=cp("_RSI2"),Og=cp("_RSI2_MA");const wg=cp("_MUL_ATR");class Rg extends up{constructor(e,t){super(e,lp(t,t=>{const i=Gv().getTimeSeriesDataSource();return t.seriesKind=m.Options,t.fields=e.outFields,i.getTimeSeries(t)})),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}}const Ng=cp("_CORE");class Vg extends Ch{constructor(e){super(e)}getRetriever(){return Bi(this.query.symbol)?new Fg:Gi(this.query.symbol)?new kg:new Bg}}function Hg(){const e=[Ka.DateTime,Ka.Delta,Ka.Gamma,Ka.Theta,Ka.Vega];return new Mu(e)}class Bg{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return Hg()}}class Fg extends qu{emptyContainer(e,t){return Hg()}get iterateForward(){return!1}getPageName(){return"getFuturesOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date.substring(0,10))),i.addDataPoint(Ka.Delta,e.delta),i.addDataPoint(Ka.Gamma,e.gamma),i.addDataPoint(Ka.Theta,e.theta),i.addDataPoint(Ka.Vega,e.vega)}}class kg extends qu{emptyContainer(e,t){return Hg()}addExtraParams(e){e.fields="delta,gamma,theta,vega"}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){i.addDataPoint(Ka.DateTime,vu(e.date)),i.addDataPoint(Ka.Delta,e.delta),i.addDataPoint(Ka.Gamma,e.gamma),i.addDataPoint(Ka.Theta,e.theta),i.addDataPoint(Ka.Vega,e.vega)}}const Wg=cp("_RSI1"),Ug=cp("_RSI2");const $g=cp("_ANCHR");const Gg=cp("_HH_N"),zg=cp("_LL_N"),Yg=cp("_HH_H1"),jg=cp("_LL_H1"),Kg=cp("_HH_H2"),qg=cp("_LL_H2");const Xg=cp("_MIDPOINT"),Zg=cp("_VALUE");class Jg extends up{constructor(e,t){super(e,t),My(this)}computeMidranks(e){const t=e.length,i=e.map((e,t)=>({v:e,i:t}));i.sort((e,t)=>e.v-t.v);const s=new Array(t);let n=0;for(;n<t;){let e=n;const r=i[n].v;for(;e+1<t&&i[e+1].v===r;)e++;const o=(n+1+(e+1))/2;for(let t=n;t<=e;t++)s[i[t].i]=o;n=e+1}return s}pearsonCorrelation(e){const t=e.length;if(t<2)return null;const i=(t+1)/2;let s=0;for(let c=0;c<t;c++)s+=e[c];const n=s/t;let r=0,o=0,a=0;for(let c=0;c<t;c++){const t=c+1-i,s=e[c]-n;r+=t*s,o+=t*t,a+=s*s}const l=Math.sqrt(o*a);return 0===l?null:r/l}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);if(n.every(e=>null!==e)){const e=this.computeMidranks(n),i=this.pearsonCorrelation(e);null!==i&&(t=100*i)}}return{[Ka.RCI.id]:t}}}const Qg=cp("_ATR");const ey={_TR:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=this.baseVal(Ka.High,e),s=this.baseVal(Ka.Low,e);if(e>0){const n=this.baseVal(Ka.Close,e-1);t=Math.max(i-s,Math.abs(i-n),Math.abs(s-n))}else t=i-s;return{[this.target.id]:t}}},_RSI:class extends up{isModified;constructor(e,t){super(e,t);const i=e.inputs.Modified;this.isModified=i}get helpers(){return[xp,Ip]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,i=null,s=null;const n=this.period;if(this.atLeast(e,n+1)){if(null===this.container.getData(this.target)[e-1]||this.isModified){const t=this.past(e,n+1,this.source);if(R(t)){const e=N(1,n),r=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));i=w(r),s=w(o)}}else{const t=this.container.getData(xp)[e-1],r=this.container.getData(Ip)[e-1],o=this.past(e,2,this.source);i=(t*(n-1)+this.gain(1,o))/n,s=(r*(n-1)+this.loss(1,o))/n}null!==i&&null!==s&&(t=100-100/(1+i/s))}return{[xp.id]:i,[Ip.id]:s,[this.target.id]:t}}},MA:pp,MAEXP:class extends fp{constructor(e,t){super(e,t,e=>2/(e+1))}},MAHLC:class extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period1,Ka.High,Ka.MAHI),s=ay(t,this.inputs.Period2,Ka.Low,Ka.MALO);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.MAHI,1),this.wrapInner(Ka.MALO,2)]}},VOL:class extends mp{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(Ka.Volume,Ka.TradeSize,Ka.Change,Ka.Open,Ka.Close)}},MAENV:class extends Sp{constructor(e,t){super(e,gp,t)}},MAENVEXP:class extends Sp{constructor(e,t){super(e,yp,t)}},MAENVSMO:class extends Sp{constructor(e,t){super(e,Ap,t)}},MATRI:class extends up{constructor(e,t){super(e,t);const i=ay(t,this.inputs.Period,this.source),s=ay(i,this.inputs.Period,Ka.MA,Ka.TMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.TMA,2)]}},MAWEI:class extends up{triangle;constructor(e,t){super(e,t);const i=this.period;this.triangle=i*(i+1)/2,My(this)}weightedAverage(e){const t=e.length;if(0===t)return null;const i=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,i)=>e+t*(i+1),0)/i}calculateAt(e){let t=null;const i=this.period,[,s]=_y(this);if(this.atLeast(e,i)){const n=this.past(e,i,this.source,s);this.allowEmptyValues?t=this.weightedAverage(n.filter(D)):R(n)&&(t=this.weightedAverage(n))}return{[this.target.id]:t}}},MAVOL:pp,MASMO:class extends fp{constructor(e,t){super(e,t,e=>1/e)}},MACD:class extends _p{constructor(e,t){super(e,vp,t)}},MACDEXP:class extends _p{constructor(e,t){super(e,Pp,t)}},MACDV:class extends Mp{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=Ka.MACDVH;const i=Oy(e,"EMA","Average"),s=i(t,e.inputs.Period1,e.source,void 0),n=i(t,e.inputs.Period2,e.source,void 0),r=gy(t,e.inputs.Period2,e.inputs.Average),o=by(Ka.MACDV,(e,t,i,s)=>(t-i)/s*100,s,n,r),a=i(o,e.inputs.Period3,o.target,Ka.MACDVS),l=by(Ka.MACDVH,Ey,o,a);this.addInner(o,a,l)}getWrappers(){return[this.wrapInner(Ka.MACDV,1),this.wrapInner(Ka.MACDVS,2),this.wrapInner(Ka.MACDVH,3)]}},GMMA:class extends up{constructor(e,t){super(e,t);for(let i=1;i<=12;++i){const s=Vy(e.inputs,i);this.addInner(ly(t,s,Ka.Close,e.outFields[i-1]))}}getWrappers(){return N(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},OSCI:Tp,OSCIVOL:Tp,RSI:class extends Dp{constructor(e,t){super(e,!1,t)}},RSIMOD:class extends Dp{constructor(e,t){super(e,!0,t)}},RSISTO:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period,this.source),s=this.inputs.Range,n=Cy(Ka.STORSI,function(e){let t=null;if(this.atLeast(e,s)){const i=this.past(e,s,Ka.RSI,this.base),n=z(i),r=n[0],o=n[1];t=(k(i)-r)/(o-r)}return{[Ka.STORSI.id]:t}},i),r=Oy(e,"MA","Average")(n,this.inputs.PeriodAvg,Ka.STORSI,Ka.STORSIAVG);this.addInner(n,r)}getWrappers(){return[this.wrapInner(Ka.STORSI,1),this.wrapInner(Ka.STORSIAVG,2)]}},RSA:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period1,this.source,Wg),s=Sy(t,this.inputs.Period2,this.source,Ug),n=by(Ka.RSA,(e,t,i)=>(t+i)/2,i,s),r=Oy(e,"MA","Average")(n,this.inputs.PeriodAvg,Ka.RSA,Ka.RSAAVG);this.addInner(n,r)}getWrappers(){return[this.wrapInner(Ka.RSA,1),this.wrapInner(Ka.RSAAVG,2)]}},WPERCR:class extends wp{constructor(e,t){super(e,!0,t)}},HHLL:class extends up{constructor(e,t){super(e,t);const i=dy(t,this.inputs.Period1,Ka.High,Ka.HH,!0),s=dy(t,this.inputs.Period2,Ka.Low,Ka.LL,!1);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.HH,1),this.wrapInner(Ka.LL,2)]}},WGCL:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=[Ka.Close,Ka.High,Ka.Low],[s,n,r]=i.map(t=>this.baseVal(t,e));return t=(2*s+n+r)/4,{[this.target.id]:t}}},STOCHF:class extends Np{constructor(e,t){super(e,!1,Ka.PercK,t)}},STOCHS:class extends Np{constructor(e,t){super(e,!0,Ka.PercK,t)}},BBANDS:class extends Hp{constructor(e,t){super(e,"Regular",t)}},BWIDTH:class extends Hp{constructor(e,t){super(e,"Width",t)}},BPERC:class extends Hp{constructor(e,t){super(e,"Percent",t)}},OBVOL:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.OBVOL,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e),n=this.baseVal(Ka.Close,e-1);let r=this.container.getData(this.target)[e-1];ie(r)||(r=0),t=i>n?r+s:i<n?r-s:r}return{[this.target.id]:t}},t),s=Oy(e,"MA","Average")(i,this.period,Ka.OBVOL,Ka.OBVOLAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.OBVOL,1),this.wrapInner(Ka.OBVOLAVG,2)]}},ATR:class extends up{constructor(e,t){super(e,t);const i=my(t,Ka.TR),s=Oy(e,"SMA")(i,this.inputs.Period,Ka.TR,this.target),n=ay(s,this.inputs.Period2,Ka.ATR,Ka.ATRMA);this.addInner(s,n)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(Ka.ATRMA,2)]}},ADR:class extends mg{constructor(e,t){super(e,!1,t)}},ATRP:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.ATR,e),s=this.baseVal(Ka.Close,e);return ie(i,s)&&s>0&&(t=i/s*100),{[Ka.ATRP.id]:t}}},ADRP:class extends mg{constructor(e,t){super(e,!0,t)}},ADX:class extends jp{constructor(e,t){super(e,!1,Ka.ADX,t)}},ADXMOD:class extends jp{constructor(e,t){super(e,!0,Ka.ADXM,t)}},ADL:class extends up{constructor(e,t){super(e,t);const i=Ty(t);this.addInner(i)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,Ka.MFMUL,e),{[this.target.id]:t}}},ADWM:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.ADWM,function(e){let t=null,i=null;if(e>0){const s=this.baseVal(Ka.Close,e-1),n=Math.max(s,this.baseVal(Ka.High,e)),r=Math.min(s,this.baseVal(Ka.Low,e)),o=this.baseVal(Ka.Close,e);if(t=o>s?o-r:o<s?o-n:0,e>1){i=(e>2?this.container.getData(Ka.ADWM)[e-1]:0)+t}}return{[Ka.ADWM.id]:i}},t),s=ay(i,this.inputs.Period,Ka.ADWM,Ka.ADWMMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.ADWM,1),this.wrapInner(Ka.ADWMMA,2)]}},CHAOSC:class extends up{constructor(e,t){super(e,t);const i=Ka.ADL;let s=function(e,t=Ka.ADL){return ny("ADL",sy(t),e)}(t,i),n=ly(s,3,i),r=ly(s,10,i),o=by(e.target,(e,t,i)=>t-i,n,r);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},TP:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=w([Ka.Close,Ka.High,Ka.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},KELCHN:class extends sf{constructor(e,t){super(e,ef,t)}},KELBND:class extends sf{constructor(e,t){super(e,tf,t)}},DONCHN:class extends nf{constructor(e,t){super(e,!1,t)}},DONWIDTH:class extends nf{constructor(e,t){super(e,!0,t)}},PVT:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e),n=this.baseVal(Ka.Close,e-1);let r=this.container.getData(this.target)[e-1];ie(r)||(r=0);t=r+(i-n)/n*s}return{[this.target.id]:t}}},ROC:class extends up{constructor(e,t){super(e,t)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i+1)){const s=this.baseVal(this.source,e-i);if(null!==s&&0!==s){t=(this.baseVal(this.source,e)-s)/s*100}}return{[this.target.id]:t}}},TRIX:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=ly(s,this.inputs.Period,s.target),r=Ay(n,1,n.target,this.target);this.addInner(r)}getWrappers(){return[this.wrapInner(this.target,1)]}},PPMOV:class extends up{constructor(e,t){super(e,t);const i=yy(t,Ka.PVPT);this.addInner(i)}calculateAt(e){const t=this.innVal(1,Ka.PVPT,e),i=this.baseVal(Ka.High,e),s=this.baseVal(Ka.Low,e);return{[Ka.PVPTR.id]:t+i-s,[Ka.PVPTS.id]:t-i+s}}getWrappers(){return[this.wrapInner(Ka.PVPT,1)]}},PIVPTS:class extends jf{constructor(e,t){super(e,Yf[e.inputs.Previous],t)}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null;if(!this.disabled){const e=this.getValues(this.inputs.Previous);if(R(e)){const[l,c,u]=e;t=(l+c+u)/3;const h=2*t;i=h-c,s=h-l;const d=l-c;n=t+d,r=t-d,o=l+2*(t-c),a=c-2*(l-t)}}return{[Ka.PPTPIV.id]:t,[Ka.PPTR1.id]:i,[Ka.PPTR2.id]:n,[Ka.PPTR3.id]:o,[Ka.PPTS1.id]:s,[Ka.PPTS2.id]:r,[Ka.PPTS3.id]:a}}},CPP:class extends jf{constructor(e,t){super(e,Yf.Day,t)}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=null,l=null;if(!this.disabled){const e=this.getValues("Day");if(R(e)){const[c,u,h]=e,d=c-u,[p,f,m,g]=[2,4,6,12].map(e=>1.1/e*d);a=h+p,r=h+f,s=h+m,t=h+g,i=h-g,n=h-m,o=h-f,l=h-p}}return{[Ka.CPPH4.id]:a,[Ka.CPPH3.id]:r,[Ka.CPPH2.id]:s,[Ka.CPPH1.id]:t,[Ka.CPPL1.id]:i,[Ka.CPPL2.id]:n,[Ka.CPPL3.id]:o,[Ka.CPPL4.id]:l}}},ARNUPDW:class extends af{constructor(e,t){super(e,!1,t)}},ARNOSC:class extends af{constructor(e,t){super(e,!0,t)}},TCHN:class extends up{constructor(e,t){super(e,t);const i="Close"===e.inputs.Range,s=Ny(t);if(!i&&s){const e=Cy(Ka.TCHNUP,(e,t)=>null,t),i=Cy(Ka.TCHNLOW,(e,t)=>null,t);this.addInner(e,i)}else{let s=dy(t,e.inputs.PeriodUpper,i?Ka.Close:Ka.High,Ka.TCHNUP,!0),n=dy(t,e.inputs.PeriodLower,i?Ka.Close:Ka.Low,Ka.TCHNLOW,!1);this.addInner(s,n)}}getWrappers(){return[this.wrapInner(Ka.TCHNUP,1),this.wrapInner(Ka.TCHNLOW,2)]}},TCHRE:class extends up{constructor(e,t){super(e,t);const i=function(e,t,i){const s="TCHN",n={PeriodUpper:t,PeriodLower:t,Range:i},r=ry(s);return ny(s,{inputs:n,outFields:r,source:null},e)}(t,e.inputs.Period,e.inputs.Range);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(1,Ka.TCHNUP,e),s=this.innVal(1,Ka.TCHNLOW,e),n=this.inputs.Adjustment,r=this.inputs.Retracement;return"Long"===r?t=ie(i)?i-n:null:"Short"===r&&(t=ie(s)?s+n:null),{[this.target.id]:t}}},ALLG:class extends up{constructor(e,t){super(e,t);const i=Cy(lf,M(qp,lf),t),s=cy(i,e.inputs.Period1,lf,Ka.ALJAW),n=cy(i,e.inputs.Period2,lf,Ka.ALTEETH),r=cy(i,e.inputs.Period3,lf,Ka.ALLIPS);this.addInner(s,n,r)}calculateAt(e){return{[Ka.ALJAW.id]:this.innVal(1,Ka.ALJAW,e),[Ka.ALTEETH.id]:this.innVal(2,Ka.ALTEETH,e),[Ka.ALLIPS.id]:this.innVal(3,Ka.ALLIPS,e)}}},PLTLN:class extends up{constructor(e,t){super(e,t)}calculateAt(e){return{[Ka.PLTLN.id]:this.inputs.Position}}},AWEOSC:class extends up{constructor(e,t){super(e,t);const i=Cy(cf,M(qp,cf),t),s=ay(i,this.inputs.Period1,cf),n=ay(i,this.inputs.Period2,cf),r=by(Ka.AWOS,(e,t,i)=>t-i,s,n),o=ay(r,this.inputs.Period3,r.target,Ka.AWOSMA);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.AWOS,1),this.wrapInner(Ka.AWOSMA,2)]}},MFV:class extends uf{constructor(e,t){super(e,!0,t)}},CLV:class extends uf{constructor(e,t){super(e,!1,t)}},CHAMF:class extends up{constructor(e,t){super(e,t);const i=Ty(t);this.addInner(i)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.Volume),n=this.past(e,i,Ka.MFMUL,this.innCont(1));if(R(s)&&R(n)){const e=O(s);0!==e&&(t=O(n)/e)}}return{[this.target.id]:t}}},CHAVOL:class extends up{constructor(e,t){super(e,t);const i=Ay(ly(Cy(hf,M(Xp,hf),t),this.inputs.Period1,hf),this.inputs.Period2,Ka.EMA,this.target);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},DPO:class extends up{shift;constructor(e,t){super(e,t);const i=this.inputs.Period;this.shift=Math.floor(i/2)+1;const s=ay(t,i,e.source);this.addInner(s)}calculateAt(e){let t=null;const i=this.shift,s=this.innVal(1,Ka.MA,e-i);return null!==s&&(t=this.baseVal(this.source,e)-s),{[this.target.id]:t}}},CCI:class extends up{constructor(e,t){super(e,t);const i=yy(t),s=ay(i,this.inputs.Period,i.target,df);this.addInner(i,s)}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){let s=this.past(e,i,Ka.TP,this.innCont(1));if(R(s)){const i=this.innVal(2,df,e);if(null!==i){const n=s.reduce((e,t,s)=>e+Math.abs(i-t),0)/this.period;t=(this.innVal(1,Ka.TP,e)-i)/(.015*n)}}}return{[this.target.id]:t}}},EMV:class extends up{constructor(e,t){super(e,t);const i=Cy(Ka.EMV,function(e){let t=null;if(e>0){const i=[Ka.High,Ka.Low,Ka.Volume],[s,n,r]=i.map(t=>this.baseVal(t,e)),o=[Ka.High,Ka.Low],[a,l]=o.map(t=>this.baseVal(t,e-1));t=((s+n)/2-(a+l)/2)/(r/1e6/(s-n))}return{[this.target.id]:t}},t),s=ay(i,this.inputs.Period,Ka.EMV,Ka.EMVMA);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.EMV,1),this.wrapInner(Ka.EMVMA,2)]}},ERBRPOW:class extends pf{constructor(e,t){super(e,!1,t)}},ERBLPOW:class extends pf{constructor(e,t){super(e,!0,t)}},FI:class extends up{constructor(e,t){super(e,t);const i=ly(Cy(ff,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Volume,e);t=(i-this.baseVal(Ka.Close,e-1))*s}return{[this.target.id]:t}},t),this.inputs.Period,ff,Ka.FI);this.addInner(i)}getWrappers(){return[this.wrapInner(Ka.FI,1)]}},MI:class extends up{constructor(e,t){super(e,t);const i=ly(Cy(mf,M(Xp,mf),t),9,mf,gf),s=ly(i,9,gf,yf),n=by(Af,(e,t,i)=>t/i,i,s);this.addInner(n)}calculateAt(e){let t=null;if(this.atLeast(e,25)){const i=this.past(e,25,Af,this.innCont(1));R(i)&&(t=O(i))}return{[this.target.id]:t}}},MOM:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=Cy(Ka.MOM,_(Iy,i,Ka.Close),t),n=ay(s,this.inputs.Movement,Ka.MOM,Ka.MOMMA);this.addInner(s,n)}getWrappers(){return[this.wrapInner(Ka.MOM,1),this.wrapInner(Ka.MOMMA,2)]}},MFI:class extends up{constructor(e,t){super(e,t);const i=yy(t);this.addInner(i)}calculateAt(e){let t=null;const i=this.period+1;if(this.atLeast(e,i)){const s=this.past(e,i,Ka.TP,this.innCont(1)),n=this.past(e,i,Ka.Volume).map(e=>null!=e?e:0);if(R(s)&&R(n)){let e=0,r=0;for(let t=1;t<i;++t){const i=s[t]*n[t];s[t]>s[t-1]?e+=i:r+=i}t=100-100/(1+e/r)}}return{[this.target.id]:t}}},MSD:class extends up{constructor(e,t){super(e,t),My(this);const i=ay(t,this.inputs.Period,this.source);this.addInner(i)}calculateAt(e){let t=null;const[i,s]=_y(this),n=this.innVal(i+1,Ka.MA,e);if(null!==n){const i=this.inputs.Period;let r=this.past(e,i,this.source,s);r=r.map(e=>(e-n)*(e-n)),t=Math.sqrt(w(r))}return{[this.target.id]:t}}getWrappers(){const[e]=_y(this);return[this.wrapInner(Ka.MA,e+1)]}},NVI:class extends vf{constructor(e,t){super(e,Tf,t)}},PVI:class extends vf{constructor(e,t){super(e,Sf,t)}},PPO:class extends _p{constructor(e,t){super(e,Ep,t)}},PVO:class extends _p{constructor(e,t){super(e,Lp,t)}},HV:class extends up{constructor(e,t){super(e,t);const i=Math.sqrt(Ry(e.aggregation));if(0===i){const e=Cy(this.target,(e,t)=>null,t);this.addInner(e)}else{const s=function(e,t){let i=null;const s=this.baseVal(Ka.MSD,t);return null!==s&&(i=100*s*e),{[Ka.HV.id]:i}},n=vy(Cy(Pf,M(function(e,t){let i=null;if(t>0){const s=this.baseVal(e,t),n=this.baseVal(e,t-1);null!==s&&null!==n&&(i=Math.log(s/n))}return{[Pf.id]:i}},Ka.Close),t),e.inputs.Period,Pf,Ka.MSD),r=Cy(Ka.HV,M(s,i),n);this.addInner(r)}}getWrappers(){return[this.wrapInner(this.target,1)]}},PERF:class extends up{noOp;constructor(e,t){super(e,t);const i="VisibleStart"===this.inputs.Anchor;this.noOp=i}calculateAt(e){let t=null;const i=this.baseVal(this.source,0),s=this.baseVal(this.source,e);return this.noOp?t=s:null!==i&&null!==s&&(t=(s-i)/i*100),{[this.target.id]:t}}},WASI:class extends up{constructor(e,t){super(e,t)}get helpers(){return[Cf]}ohlcVals(e){return[Ka.Open,Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,i,s){const n=Math.abs(e-s),r=Math.abs(t-s),o=Math.abs(e-t),a=Math.max(n,r,o),l=.25*Math.abs(s-i);return a===n?n-.5*r+l:a===r?r-.5*n+l:o+l}calculateAt(e){let t=null,i=null;if(e>0){let s=this.container.getData(Cf)[e-1];ie(s)||(s=0);const[n,r,o,a]=this.ohlcVals(e),[l,c,u,h]=this.ohlcVals(e-1);if(R([n,r,o,a,l,h])){const e=Math.max(Math.abs(r-h),Math.abs(o-h)),c=this.inputs.Limit;t=(a-h+.5*(a-n)+.25*(h-l))/this.obtainR(r,o,l,h)*50*(e/c),i=s+t}}return{[Cf.id]:t,[this.target.id]:i}}},WWVOL:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Ef,bf]}calculateAt(e){let t=null,i=null,s=null,n=null,r=this.innVal(1,Ka.ATR,e);if(null!==r){const o=this.baseVal(Ka.Close,e),a=this.baseVal(Ka.Close,e-1),l=this.period;s=Math.max(...this.past(e,l,Ka.Close)),n=Math.min(...this.past(e,l,Ka.Close));const c=r*this.inputs.Constant;if(null===this.innVal(1,Ka.ATR,e-1)){o>a?t=s-c:i=n+c}else{const r=[Ka.WWVSARU,Ka.WWVSARD,Ef,bf],[a,l,u,h]=r.map(t=>this.container.getData(t)[e-1]);s=u,n=h;null!==a?o<a?(n=o,i=o+c):(s=Math.max(o,s),t=s-c):o>l?(s=o,t=o-c):(n=Math.min(o,n),i=n+c)}}return{[Ef.id]:s,[bf.id]:n,[Ka.WWVSARU.id]:t,[Ka.WWVSARD.id]:i}}},PARTP:class extends up{constructor(e,t){super(e,t)}get helpers(){return[Lf,Mf,_f]}hlcVals(e){return[Ka.High,Ka.Low,Ka.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null;if(e>0){const[a,l,c]=this.hlcVals(e),[u,h,d]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),f=this.reciprocal(this.inputs.Limit);if(1===e){r=c>d?1:-1;const e=1===r;o=e?h:u,s=e?Math.max(a,u):Math.min(l,h),n=p,e?t=o:i=o}else{const c=[_f,Ka.PARSARS,Ka.PARSARL,Lf,Mf],[d,m,g,y,A]=c.map(t=>this.me(t,e-1)),S=1===d,T=S?g:m,v=A*Math.abs(y-T);r=S?T+v>l?-1:1:T-v<a?1:-1;const P=d===r;if(o=P?S?Math.min(T+v,h,this.baseVal(Ka.Low,e-2)):Math.max(T-v,u,this.baseVal(Ka.High,e-2)):y,s=P?S?Math.max(a,y):Math.min(l,y):1===r?a:l,n=A,P){(S?s>y:s<y)&&A<f&&(n=A+p)}else n=p;1===r?t=o:i=o}}return{[Lf.id]:s,[Mf.id]:n,[_f.id]:r,[Ka.PARSARS.id]:i,[Ka.PARSARL.id]:t}}},MOVLR:class extends up{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);const i=this.period;this.xSum=i*(i+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=i*(i+1)*(2*i+1)/6}calculateAt(e){let t=null;const i=this.period;if(this.atLeast(e,i)){let s=this.past(e,i,this.source);if(R(s)){const e=O(s),n=(i*O(s.map((e,t)=>e*(t+1)))-this.xSum*e)/(i*this.x2Sum-this.xSum2);t=(e-n*this.xSum)/i+n*i}}return{[this.target.id]:t}}},TRSP:class extends up{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];const i=["VelocityUpTrend","VelocitySideTrend","VelocityDownTrend"].map(t=>e.inputs[t]||"3").map(Number);If.splice(6,3,...i)}get helpers(){return[xf]}prepareComputation(){const e=this.base.getData(Ka.Close);let t=0,i=0;const s=e.length;for(;i<72&&t<s;)null!=e[t]&&i++,t++;this.haveEnoughData=t<s,this.firstUsefulIndex=t,this.s3=Df(s),this.itr=Df(s),this.haveEnoughData&&Vf(e,this.s3,s)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,i){const s=this.base.getData(Ka.Close),n=s.length;this.haveEnoughData&&Vf(s,this.s3,n),super.recalculateAt(e,t,i)}calculateAt(e){let t=null,i=null,s=null;const n=t=>this.us(t,e-1);if(0===e)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&null!==this.baseVal(Ka.Close,e)){let r=n(Ka.TRSP1),o=n(Ka.TRSP2);s=n(xf),null===r&&null===o&&(r=o=this.baseVal(Ka.Close,this.firstUsefulIndex)),null===s&&(s=1);const a=this.base.getData(Ka.Close);s=function(e,t,i,s,n,r){let o=i;do{o--}while(e[o]<=0);return t[i]=t[o],e[i]>n&&t[o]<=0&&(t[i]=t[o]+1),e[i]<s&&t[o]>=0&&(t[i]=t[o]-1),r++,t[i]!==t[o]&&(r=1),r}(a,this.itr,e,r,o,s);const l=Rf(a,this.s3,this.itr,e,If),c=wf(a,this.s3,this.itr,e,If);[r,o]=Nf(a,this.s3,this.itr,e,If,r,o,s,l,c),this.itr[e]>=0&&(t=r),this.itr[e]<=0&&(i=o)}return{[xf.id]:s,[Ka.TRSP1.id]:t,[Ka.TRSP2.id]:i}}},COTLC:zf,COTDAG:class extends Wf{constructor(e,t){super(e,2,t)}},COTFTR:class extends Wf{constructor(e,t){super(e,3,t)}},IMPVOL:class extends up{constructor(e,t){super(e,lp(t,e=>new Kf(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(Ka.IMPVOL,0)]}},CTM:class extends _p{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,Cp,t)}},CPMI:class extends _p{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,bp,t)}},DEMA:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=by(Ka.DEMA,(e,t,i)=>2*t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.DEMA,1)]}},EOSC:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period1,this.source),s=ly(t,this.inputs.Period2,this.source),n=by(Ka.EOSC,(e,t,i)=>t-i,i,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.EOSC,1)]}},TEMA:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,this.source),s=ly(i,this.inputs.Period,i.target),n=ly(s,this.inputs.Period,s.target),r=by(Ka.TEMA,(e,t,i,s)=>3*(t-i)+s,i,s,n);this.addInner(r)}getWrappers(){return[this.wrapInner(Ka.TEMA,1)]}},TSI:class extends up{constructor(e,t){super(e,t);const i=(e,t,i,s,n,r)=>{const o=ly(e,t,i,s);return ly(o,n,s,r)},s=Cy(Qf,M((e,t)=>({[e.id]:Math.abs(this.baseVal(Ka.Change,t))}),Qf),t),n=i(t,e.inputs.Period1,Ka.Change,em,e.inputs.Period2,tm),r=i(s,e.inputs.Period1,Qf,im,e.inputs.Period2,sm),o=by(Ka.TSI,(e,t,i)=>100*t/i,n,r),a=ly(o,e.inputs.Period3,Ka.TSI,Ka.TSISIG);this.addInner(o,a)}getWrappers(){return[this.wrapInner(Ka.TSI,1),this.wrapInner(Ka.TSISIG,2)]}},ADJATR:class extends up{constructor(e,t){super(e,t);const i=Cy(Bp,M((e,t)=>{let i=0;return t>0&&(i=this.baseVal(e,t)-this.baseVal(e,t-1)),{[Bp.id]:Math.abs(i)}},this.source),t),s=Oy(e,"MA")(i,this.inputs.Period,Bp,Fp),n=by(Ka.ADJATR,(e,t)=>2*t,s);this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.ADJATR,1)]}},COTR:class extends up{constructor(e,t){super(e,t);const i=Cy(kp,e=>{let t=0;return e>0&&(t=this.baseVal(Ka.Close,e)-this.baseVal(Ka.Close,e-1)),{[kp.id]:t}},t),s=function(e){const t=e.inputs.TypeOfATR.toLowerCase();return wy[t]}(e),n=s(t,this.inputs.Period,this.inputs.Smoothing),r=by(this.target,(e,t,i)=>ie(t)&&ie(i)?t/i:null,i,n);this.addInner(r)}getWrappers(){return[this.wrapInner(this.target,1)]}},MCGD:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.Period,Ka.Close);this.addInner(i)}calculateAt(e){let t=null;const i=e>0?this.container.getData(this.target)[e-1]:null,s=this.innVal(1,Ka.EMA,e);if(te(i)){const n=this.baseVal(this.source,e),r=Math.pow(n/i,4);t=i+(n-i)/(.6*this.period*r);const o=e=>Math.log10(Math.abs(e-t))>1,a=o(i)||o(s);Number.isFinite(t)&&!a||(t=null)}else t=s;return{[this.target.id]:t}}},HMA:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=Math.floor(i/2),n=this.allowEmptyValues,r=uy(t,s,this.source,Ka.WMA,n),o=uy(t,i,this.source,Ka.WMA,n),a=uy(by(nm,(e,t,i)=>2*t-i,r,o),Math.floor(Math.sqrt(i)),nm,this.target,n);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},COPP:class extends up{constructor(e,t){super(e,t);const i=Ay(t,this.inputs.PeriodRocLong),s=Ay(t,this.inputs.PeriodRocShort),n=uy(by(rm,(e,t,i)=>t+i,i,s),this.inputs.PeriodWma,rm,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},REATRS:class extends up{constructor(e,t){super(e,t);const i="Close"===e.inputs.TurtleChnField,s="Long"===e.inputs.Direction,n=Ny(t);if(!i&&n){const e=Cy(this.target,(e,t)=>null,t);this.addInner(e)}else{const e=ay(Cy(om,M((e,t)=>({[om.id]:t>0?e*Math.abs(this.baseVal(Ka.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,om,Ka.MA),n=s?Ka.High:Ka.Low,r=dy(t,this.inputs.PeriodTurtleChn,i?Ka.Close:n,am,s),o=by(lm,(e,t)=>this.inputs.FactorAdjATR*t,e),a=s?-1:1,l=(e,t,i)=>t+a*i,c=by(this.target,l,r,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},LINRCHN:class extends up{state;constructor(e,t){super(e,t),this.resetState()}resetState(){const e=this.inputs.ExtendLines??"None";this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:"Left"===e||"Both"===e,extendRight:"Right"===e||"Both"===e}}calculateAt(e){const t=this.inputs.Period,i=this.inputs.Width;if(e===this.base.size-1&&this.base.size>=t){this.resetState();const e=t*(t+1)/2,s=e*e,n=t*(t+1)*(2*t+1)/6;let r=0,o=0,a=1;const l=this.base.size-t;for(let i=0;i<t;++i){const e=this.baseVal(Ka.Close,l+i);r+=e,o+=a*e,a+=1}const c=(t*o-e*r)/(t*n-s),u=r/t-c*e/t;let h=0;for(let i=0;i<t;++i){const e=this.baseVal(Ka.Close,l+i)-(u+c*(i+1));h+=e*e}const d=Math.sqrt(h/t);this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=c,this.state.intercept=u,this.state.stdDevWidth=ie(d)?i*d:null}return{}}getCurrentState(){return this.state}},CSHO:class extends up{computeDone;constructor(e,t){super(e,t,lp(t,e=>{const t=ue(e);var i;t.symbol=Fi(i=e.symbol)?`${Zi(i)}Y00`:null;return ie(t.symbol)?new Ch(t):new bh(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){const e=this.innCont(0);if(!ie(e)||0===e.size)return;const t=this.innCont(1),i=e.getTimeData(),s=t.getTimeData(),n=t.getData(Ka.Close),r=Array(i.length).fill(null);if(!(this.innerSeries[1]instanceof bh)){let o=0;const a=e.size,l=t.size;for(let e=0;e<a;++e){for(;o<l&&s[o].getTime()<i[e].getTime();)o++;o<l&&s[o].getTime()===i[e].getTime()&&(r[e]=n[o])}}this.container.setData(this.target,r)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(qa.TS_MANYCHANGED,-1))}},CSHB:class extends up{constructor(e,t){super(e,t,function(e,t=Ka.CSHO){return ny("CSHO",sy(t),e)}(t))}shouldTriggerOurRecalc(e){return!!super.shouldTriggerOurRecalc(e)||e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){const t=(t,i)=>ie(this.innCont(t))?this.innVal(t,i,e):null,i=t(0,Ka.Close),s=t(1,Ka.CSHO);return{[this.target.id]:ie(s)&&ie(i)?s-i:null}}},MKTCAP:class extends up{computeDone;constructor(e,t){super(e,t,lp(t,e=>{const t=new ip(e.symbol,new Wo(e.aggregation.unit===a.Year?a.Year:a.Quarter,1),m.BalanceSheet);return t.fields=[Ka.SharesOutstanding],t.cacheMe=!0,new Mh(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){const e=this.innCont(0);if(!ie(e)||0===e.size)return;const t=this.innCont(1);if(!ie(t)||0===t.size)return;const i=e.getTimeData(),s=t.getTimeData(),n=t.getData(Ka.SharesOutstanding),r=e.getData(Ka.Close),o=Array(i.length);let a=0;const l=e.size,c=t.size;for(let u=0;u<l;++u){const e=i[u].getTime();for(;a<c-1&&s[a+1].getTime()<=e;)a++;if(a<c&&s[a].getTime()<=e){const e=n[a],t=r[u];o[u]=ie(e,t)?e*t:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(qa.TS_MANYCHANGED,-1))}},CTPI:class extends Np{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,Ka.CTPI,t)}},PCTCHG:class extends up{constructor(e,t){super(e,t),My(this)}calculateAt(e){let t=null;const[i]=_y(this);if(e>0){const s=this.innVal(i,this.source,e-1);if(null!==s){t=100*(this.innVal(i,this.source,e)-s)/s}}return{[this.target.id]:t}}},OPINT:class extends mp{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(Ka.TradeSize,Ka.Change)}},STOMOMIX:class extends up{constructor(e,t){super(e,t);const i=dy(t,e.inputs.Period1,Ka.High,Ka.HH,!0),s=dy(t,e.inputs.Period1,Ka.Low,Ka.LL,!1),n=ly(by(um,(e,t,i)=>this.baseVal(Ka.Close,e)-(t+i)/2,i,s),e.inputs.Period2,um,hm),r=ly(n,e.inputs.Period2,hm,dm),o=ly(by(pm,(e,t,i)=>t-i,i,s),e.inputs.Period2,pm,fm),a=ly(o,e.inputs.Period2,fm,mm),l=by(Ka.STOMOMIX,(e,t,i)=>100*t/i,r,a);this.addInner(l)}getWrappers(){return[this.wrapInner(this.target,1)]}},CHDMOMOSC:class extends up{constructor(e,t){super(e,t);const i=new Sm(e,t),s=Oy(e,"MA","Average")(i,this.inputs.PeriodAvg,Ka.CHDMOMOSC,Ka.CHDMOMOSCAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(Ka.CHDMOMOSC,1),this.wrapInner(Ka.CHDMOMOSCAVG,2)]}},VSTOP:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Tm,vm,Pm]}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null,a=1;const l=this.baseVal(Ka.Close,e),c=e=>((e,t)=>ie(e)?e:t)(e,0),u=(e,t)=>this.container.getData(e)[t];e>0&&(s=Math.max(c(u(Tm,e-1)),l),r=Math.min(c(u(vm,e-1)),l),a=u(Pm,e-1));const h=this.inputs.Multiplier,d=this.innVal(1,Ka.ATR,e);if(ie(d)){const c=1===a,p=c?s-h*d:r+h*d;let f=u(c?Ka.VSTOPUP:Ka.VSTOPLOW,e-1);ie(f)||(f=0);const m=c?Math.max(f,p):Math.min(f,p);o=l-m>=0?1:0;const g=o!=a;i=g?l:s,n=g?l:r,t=g?1===o?i-h*d:n+h*d:m}return{[Ka.VSTOPUP.id]:1===o?t:null,[Ka.VSTOPLOW.id]:1===o?null:t,[Tm.id]:i,[vm.id]:n,[Pm.id]:o}}},SUPTR:class extends up{constructor(e,t){super(e,t);const i=gy(t,e.inputs.Period);this.addInner(i)}get helpers(){return[Cm,bm,Em,Ka.BARCOLIX]}calculateAt(e){let t=0,i=0,s=0,n=null,r=0;const o=this.innVal(1,Ka.ATR,e);if(ie(o)){const a=(e,t)=>ie(e)?e:t,l=[Ka.Close,Ka.High,Ka.Low],[c,u,h]=l.map(t=>this.baseVal(t,e)),d=(u+h)/2,p=this.baseVal(Ka.Close,e-1),f=this.inputs.Multiplier,m=d-f*o,g=d+f*o,y=[Cm,bm,Em],[A,S,T]=y.map(t=>this.container.getData(t)[e-1]);t=p>A?Math.max(m,A):m,i=p<S?Math.min(g,S):g,s=c>S?1:c<A?-1:a(T,1);const v=1===s;n=v?t:i,r=v?1:0}return{[Cm.id]:t,[bm.id]:i,[Em.id]:s,[Ka.SUPTR.id]:n,[Ka.BARCOLIX.id]:r}}},ICHCLD:class extends up{constructor(e,t){super(e,t);const i=(e,t,i)=>by(i,(e,t,i)=>(t+i)/2,e,t),s=(e,s)=>i((e=>dy(t,e,Ka.Low,Ka.LL,!1))(e),(e=>dy(t,e,Ka.High,Ka.HH,!0))(e),s),n=s(e.inputs.PeriodConversionLine,Ka.CONVLN),r=s(e.inputs.PeriodBaseLine,Ka.BASELN),o=i(n,r,Ka.LEADSP1),a=s(e.inputs.PeriodLaggingSpan2,Ka.LEADSP2);this.addInner(n,r,o,a)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){const t=this.innVal(3,Ka.LEADSP1,e)>this.innVal(4,Ka.LEADSP2,e)?1:0;return{[Ka.LAGGSP.id]:this.baseVal(Ka.Close,e),[Ka.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(Ka.CONVLN,1),this.wrapInner(Ka.BASELN,2),this.wrapInner(Ka.LEADSP1,3),this.wrapInner(Ka.LEADSP2,4)]}},VWAP:class extends xm{constructor(e,t){super(e,t)}get helpers(){return[Lm,Mm,_m]}isSame(e,t){switch(this.inputs.AnchorPeriod){case"Session":default:return ut(e,t);case"Week":return Mi(e,t);case"Month":return _i(e,t);case"Quarter":return xi(e,t);case"Year":return Ii(e,t);case"Decade":return function(e,t){return Au(e)===Au(t)}(e,t);case"Century":return Su(e,t)}}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(1===this.valueAt(_m,t))return t;return 0}calculateAt(e){let t=null,i=null,s=null,n=null,r=null;const o=e>0,a=o?this.dateAt(e-1):gs.ZERO_DATE,l=this.dateAt(e),c=o&&this.isSame(a,l),u=c?this.valueAt(Lm,e-1):0,h=c?this.valueAt(Mm,e-1):0,d=this.innVal(0,Ka.Volume,e),p=u+this.innVal(1,this.source,e)*d,f=h+d;if(t=p/f,c){const o=this.findPrevPeriodChange(e-1),a=this.container.getData(Ka.VWAP).slice(o,e);a.push(t);const l=w(a),c=a.map(e=>(e-l)*(e-l)),u=Math.sqrt(w(c)),h=this.inputs.Stdev1stMultiplier*u;i=t+h,s=t-h;const d=this.inputs.Stdev2ndMultiplier*u;n=t+d,r=t-d}else i=t,s=t,n=t,r=t;return{[Lm.id]:p,[Mm.id]:f,[_m.id]:c?0:1,[Ka.VWAP.id]:t,[Ka.VWAPSD1U.id]:i,[Ka.VWAPSD1L.id]:s,[Ka.VWAPSD2U.id]:n,[Ka.VWAPSD2L.id]:r}}},MACROSS:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,e.inputs.Period1,this.source,Ka.MAS),n=i(t,e.inputs.Period2,this.source,Ka.MAL);this.addInner(s,n)}get helpers(){return Dm}calculateAt(e){const t=this.innVal(1,Ka.MAS,e),i=this.innVal(2,Ka.MAL,e);return Om(this.container,e,t,i)}getWrappers(){return[this.wrapInner(Ka.MAS,1),this.wrapInner(Ka.MAL,2)]}},PACROSS:class extends up{_maIndex;_maTarget;constructor(e,t){super(e,t),My(this);const i=Oy(e,"MA","Average")(t,e.inputs.Period,this.source);this.addInner(i);const[s]=_y(this);this._maIndex=s+1,this._maTarget=i.target}get helpers(){return Dm}calculateAt(e){const t=this.innVal(this._maIndex,this._maTarget,e),[,i]=_y(this),s=i.getData(this.source)[e],n=Om(this.container,e,s,t);return n[this.target.id]=t,n}},VOIN:class extends up{constructor(e,t){super(e,t);const i=Cy(wm,function(e){return{[wm.id]:e>0?Math.abs(this.baseVal(Ka.High,e)-this.baseVal(Ka.Low,e-1)):null}},t),s=Cy(Rm,function(e){return{[Rm.id]:e>0?Math.abs(this.baseVal(Ka.Low,e)-this.baseVal(Ka.High,e-1)):null}},t),n=my(t,Ka.TR);this.addInner(i,s,n)}calculateAt(e){let t=null,i=null;const s=this.period;if(this.atLeast(e,s)){const n=this.past(e,s,wm,this.innCont(1)),r=this.past(e,s,Rm,this.innCont(2)),o=this.past(e,s,Ka.TR,this.innCont(3));if(R(n)&&R(r)&&R(o)){const e=O(n),s=O(r),a=O(o);t=e/a,i=s/a}}return{[Ka.PLVI.id]:t,[Ka.MNVI.id]:i}}},DIFA:class extends up{isPercent;constructor(e,t){super(e,t);const i=Oy(e,"MA","Average")(t,this.period,this.source,Hm);this.isPercent="Percentage"===e.inputs.Distance,this.addInner(i)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null,i=null;const s=this.innVal(1,Hm,e),n=this.baseVal(this.source,e);if(null!=s&&0!==s){t=n-s,this.isPercent&&(t=100*t/s);const r=t<=0;if(i=r?1:3,e>0){const s=this.container.getData(this.target)[e-1];null!==s&&(r&&t>s&&(i=0),!r&&t<s&&(i=2))}}return{[this.target.id]:t,[Ka.BARCOLIX.id]:i}}},DOSC:class extends up{constructor(e,t){super(e,t);const i=ly(Sy(t,this.inputs.PeriodRsi,this.source,Ka.RSI),this.inputs.PeriodEma1,Ka.RSI,Ka.EMA),s=ly(i,this.inputs.PeriodEma2,Ka.EMA,Ka.EMA),n=ay(s,this.inputs.PeriodMa,Ka.EMA,Ka.MA);const r=by(Ka.DOSCH,(e,t,i)=>t-i,s,n),o=ay(r,this.inputs.PeriodSig,Ka.DOSCH,Ka.DOSCS);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.DOSCH,1),this.wrapInner(Ka.DOSCS,2)]}},BBANDW:class extends Hp{constructor(e,t){super(e,"BandWidth",t)}},MARIB:class extends up{constructor(e,t){super(e,t);const i=this.inputs.Period,s=this.inputs.Increment,n=Math.min(Math.max(0,this.inputs.Count),10);for(let r=0;r<n;++r){const e=ay(t,i+r*s,this.source,this.outFields[r]);this.addInner(e)}}getWrappers(){const e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},HASMO:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"EMA","Smoothing1"),s=e.inputs.Period1,n=i(t,s,Ka.Open),r=i(t,s,Ka.High),o=i(t,s,Ka.Low),a=i(t,s,Ka.Close),l=by(Wm,(e,t,i,s,n)=>(t+i+s+n)/4,n,r,o,a);const c=by(Bm,function(e,t,i,s){let n=null;if(e>0){const s=this.container.getData(Bm)[e-1],r=this.innVal(2,Wm,e-1);ie(s,r)?n=(s+r)/2:ie(t,i)&&(n=(t+i)/2)}return n},n,a,l),u=by(Fm,(e,t,i,s)=>ie(t,i,s)?Math.max(t,Math.max(i,s)):null,r,c,l),h=by(km,(e,t,i,s)=>ie(t,i,s)?Math.min(t,Math.min(i,s)):null,o,c,l),d=Oy(e,"EMA","Smoothing2"),p=e.inputs.Period2,f=d(c,p,Bm,Ka.Open),m=d(u,p,Fm,Ka.High),g=d(h,p,km,Ka.Low),y=d(l,p,Wm,Ka.Close),A=Cy(Ka.Change,function(e){let t=null;if(e>0){const i=this.baseVal(Ka.Close,e),s=this.baseVal(Ka.Close,e-1);ie(i,s)?t=i-s:ie(i)&&!ie(s)&&(t=0)}return{[Ka.Change.id]:t}},y);this.addInner(f,m,g,y,A)}getWrappers(){return[this.wrapInner(Ka.Open,1),this.wrapInner(Ka.High,2),this.wrapInner(Ka.Low,3),this.wrapInner(Ka.Close,4),this.wrapInner(Ka.Change,5)]}},TTMSQZ:class extends up{constructor(e,t){super(e,t);const i=e.inputs,s=ly(t,i.PeriodEmaKeltner,Ka.Close),n=gy(t,i.PeriodAtrKeltner);function r(e,t,i,s){return ie(i,s)?i+e*s:null}const o=i.MultiplierKeltner,a=by(Ka.KCUP,M(r,o),s,n),l=by(Ka.KCLOW,M(r,-o),s,n),c=function(e,t,i,s=Ka.Close){const n="BBANDS",r=ry(n),o={[gs.INPUT_PERIOD]:t,[gs.INPUT_WIDTH]:i};return ny(n,{source:s,inputs:o,outFields:r},e)}(t,i.PeriodBollinger,i.WidthBollinger),u=function(e,t){const i="DONCHN",s=ry(i);return ny(i,{inputs:ty(t),outFields:s,source:null},e)}(t,i.PeriodMomentum),h=ay(t,i.PeriodMomentum,Ka.Close);const d=Py(by(Um,function(e,t,i,s){let n=null;const r=this.innVal(1,Ka.DONMID,e);return ie(r,s)&&(n=t-(r+s)/2),n},t,u,h),i.PeriodMomentum,Um,Ka.TTMSQZOSC);this.addInner(a,l,c,d)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null,i=null,s=-1;const n=this.innVal(1,Ka.KCUP,e),r=this.innVal(2,Ka.KCLOW,e),[o,a]=[Ka.BOLLBU,Ka.BOLLBL].map(t=>this.innVal(3,t,e));o<n&&a>r?t=0:i=0;const l=this.innVal(4,Ka.TTMSQZOSC,e),c=e>0?this.innVal(4,Ka.TTMSQZOSC,e-1):null;if(ie(l))if(ie(c)){const e=c<l;s=l>=0?e?3:2:e?1:0}else s=2;return{[Ka.TTMSQZON.id]:t,[Ka.TTMSQZOFF.id]:i,[Ka.BARCOLIX.id]:s}}getWrappers(){return[this.wrapInner(Ka.TTMSQZOSC,4)]}},CRS:class extends up{constructor(e,n){if(super(e,n),Hy(n)){const r=Gv().getTimeSeriesDataSource(),o=n.query.duplicate();o.symbol=this.inputs.Symbol.toUpperCase();const l=r.getTimeSeries(o),c=e=>e.query?.symbol,u=(e,t)=>`{${c(e)}} / {${c(t)}}`,{model:h}=ca(u(n,l),!1),d=(e=>{const n=e.unit===a.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:i.Manual,missing:n?t.UseNext:t.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,Ka.CRS]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}})(e.aggregation),p=new Vm(h,[n,l],d),f=Oy(e,"MA","Average")(p,this.period,Ka.CRS,Ka.CRSAVG);this.addInner(l,p,f),this.canLoadMoreData=!0,this.initialNotification=!0}else{const e=Cy(Ka.Close,(e,t)=>null,n),t=Cy(Ka.CRS,(e,t)=>null,n),i=Cy(Ka.CRSAVG,(e,t)=>null,n);this.addInner(e,t,i),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(Ka.CRS,2),this.wrapInner(Ka.CRSAVG,3)]}},JPI:ng,CTTP:class extends ng{constructor(e,t){const i=Ur("JPI");e.inputs=fe(i.defaults.inputs.filter(e=>"HandbrakePeriod"!==e.name)),super(e,t)}},CTTI:class extends ng{constructor(e,t){e.inputs=structuredClone(rg),super(e,t)}},DRS:class extends up{get indexSymbol(){return this.inputs[gs.INPUT_SYMBOL]}constructor(e,n){if(super(e,n),Hy(n)){const r=Gv().getTimeSeriesDataSource(),o=n.query.duplicate();o.symbol=this.indexSymbol;const l=r.getTimeSeries(o),c=`{${n.query.symbol}} / {${l.query.symbol}} * 100`,{model:u}=ca(c,!1),h=(e=>{const n=e.unit===a.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:i.Manual,missing:n?t.UseNext:t.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,Ka.DRS]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}})(e.aggregation),d=new Vm(u,[n,l],h);this.addInner(l,d),this.canLoadMoreData=!0,this.initialNotification=!0}else{const e=Cy(Ka.Close,(e,t)=>null,n),t=Cy(Ka.DRS,(e,t)=>null,n);this.addInner(e,t),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(Ka.DRS,2)]}},MRS:class extends up{get indexSymbol(){return this.inputs[gs.INPUT_SYMBOL]}constructor(e,t){super(e,t);const i=function(e,t,i,s=Ka.DRS){return ny("DRS",{target:s,inputs:iy(t),aggregation:i,source:null},e)}(t,this.indexSymbol,e.aggregation),s=ay(i,this.period,Ka.DRS);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){const t=this.innVal(1,Ka.DRS,e),i=this.innVal(2,Ka.MA,e);let s=null;return ie(t,i)&&0!==i&&(s=100*(t/i-1)),{[Ka.MRS.id]:s}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},PMO:class extends up{constructor(e,t){super(e,t);const i=Ay(t,1),s=e.aggregation,n=lg(i,this.inputs.Period1,s,Ka.ROC,og),r=lg(by(ag,(e,t)=>10*t,n),this.inputs.Period2,s,ag,Ka.PMO),o=ly(r,this.inputs.Period3,Ka.PMO,Ka.PMOS);this.addInner(r,o)}getWrappers(){return[this.wrapInner(Ka.PMO,1),this.wrapInner(Ka.PMOS,2)]}},RVOL:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA")(t,this.period,Ka.Volume,cg,!0);this.addInner(i)}calculateAt(e){let t=null;const i=this.innVal(0,Ka.Volume,e),s=this.innVal(1,cg,e);return ie(i,s)&&0!==s&&(t=i/s),{[this.target.id]:t}}},WGALPH:class extends up{isDaily;isFeasible=!0;constructor(e,t){super(e,t),this.isFeasible=!(t instanceof bh||hg.includes(o[t.query.curveStyle])),this.isDaily=e.aggregation.unit===a.Day}acceptable(e,t,i,s){if(!this.isDaily)return e>0&&i-t>=5;if(0===s)return!0;return!Mi(this.baseVal(Ka.DateTime,t),this.baseVal(Ka.DateTime,i))}pluckValues(e){let t=0;const i=[];let s=e+5;for(let n=0;t<53&&e-n>0;n++){const r=e-n,o=this.baseVal(this.source,r);this.acceptable(o,r,s,t)&&(i.push(o),s=r,t++)}return i}calculateAt(e){let t=null;if(this.isFeasible&&e>=131){let i=1;const s=this.pluckValues(e),n=s.length;if(n>=27)for(let e=0;e<n-1;e++){let t=s[e]/s[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*ug[e]+1,i*=t}t=100*(i-1)}return{[this.target.id]:t}}},VOLAP:class extends pg{constructor(e,t){super(e,!1,t)}},AVWAP:class extends xm{constructor(e,t){super(e,t)}get helpers(){return[Lm,Mm]}isSameOhlcBar(e,t){const{unit:i,size:s}=this.aggregation;switch(i){case a.Tick:return e===t;case a.Intraday:return bi(t,ot(e,s));case a.Day:return bi(t,Xe(e,s));case a.Week:return Mi(e,t);case a.Month:return _i(e,t);case a.Quarter:return xi(e,t);case a.Year:return Ii(e,t);default:throw new Error(`Unexpected aggregation unit ${a[i]}`)}}calculateAt(e){let t=null,i=null,s=null;const n=this.inputs.Anchor,r=this.dateAt(e);if(bi(n,r)||this.isSameOhlcBar(r,n)){const n=e>0,r=n?this.valueAt(Lm,e-1):0,o=n?this.valueAt(Mm,e-1):0,a=this.innVal(0,Ka.Volume,e);i=r+this.innVal(1,this.source,e)*a,s=o+a,t=i/s}return{[Lm.id]:i,[Mm.id]:s,[Ka.AVWAP.id]:t}}},KST:class extends up{constructor(e,t){super(e,t);const i=this.source,s=Cy(i,M(xy,i),t),n=Ay(s,this.inputs.PeriodRoc1,i),r=Ay(s,this.inputs.PeriodRoc2,i),o=Ay(s,this.inputs.PeriodRoc3,i),a=Ay(s,this.inputs.PeriodRoc4,i),l=ay(n,this.inputs.PeriodMa1,Ka.ROC,Ka.MA1),c=ay(r,this.inputs.PeriodMa2,Ka.ROC,Ka.MA2),u=ay(o,this.inputs.PeriodMa3,Ka.ROC,Ka.MA3),h=ay(a,this.inputs.PeriodMa4,Ka.ROC,Ka.MA4),d=by(Ka.KST,(e,t,i,s,n)=>t+2*i+3*s+4*n,l,c,u,h),p=ay(d,this.inputs.PeriodSig,Ka.KST,Ka.KSTSIG);this.addInner(d,p)}getWrappers(){return[this.wrapInner(Ka.KST,1),this.wrapInner(Ka.KSTSIG,2)]}},STC:class extends up{constructor(e,t){super(e,t);const i=ly(t,this.inputs.PeriodShort,Ka.Close,gg),s=ly(t,this.inputs.PeriodLong,Ka.Close,yg),n=by(Ag,(e,t,i)=>t-i,i,s),r=this.inputs.PeriodStoch1,o=this.inputs.PeriodStoch2,a=Oy(e,"EMA"),l=a(py(n,r,Sg,!1,Ag),o,Sg,Tg),c=a(py(l,r,vg,!1,Tg),o,vg,this.target);this.addInner(c)}getWrappers(){return[this.wrapInner(this.target,1)]}},MCCLO:class extends Eg{constructor(e,t){super(e,t)}getTargetSeries(e,t,i){const s=(e,t,i)=>t-i,n="Yes"===this.inputs.RatioAdjusted,r=by(bg,n?(e,t,i)=>(t-i)/(t+i)*1e3:s,t,i),o=ly(r,this.inputs.Period1,bg,Pg),a=ly(r,this.inputs.Period2,bg,Cg);return by(this.target,s,o,a)}},NHLAI:_g,CMBCI:class extends up{constructor(e,t){super(e,t);const i=Sy(t,this.inputs.Period1Rsi,Ka.Close,xg),s=Cy(Ig,_(Iy,this.inputs.Period1Mom,xg),i),n=ay(Sy(t,this.inputs.Period2Rsi,Ka.Close,Dg),this.inputs.Period2Ma,Dg,Og),r=by(Ka.CMBCI,(e,t,i)=>t+i,s,n),o=ay(r,this.inputs.PeriodFastMa,Ka.CMBCI,Ka.CMBCIF),a=ay(r,this.inputs.PeriodSlowMa,Ka.CMBCI,Ka.CMBCIS);this.addInner(r,o,a)}getWrappers(){return[this.wrapInner(Ka.CMBCI,1),this.wrapInner(Ka.CMBCIF,2),this.wrapInner(Ka.CMBCIS,3)]}},COTI:class extends up{constructor(e,t){super(e,function(e){return new zf({source:Ka.Close,inputs:{},outFields:ry("COTLC")},e)}(t));const i=Number.parseInt(this.inputs.History),s=6===i?26:52*i,n=py(this.innerSeries[0],s,Ka.COTI,!1,Ka.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(n)}getWrappers(){return[this.wrapInner(Ka.COTI,1)]}},CHEXI:class extends up{isLong;constructor(e,t){super(e,t),this.isLong="Long"===this.inputs.Direction;const i=this.period,s=gy(t,i),n=this.inputs.Multiplier,r=by(wg,(e,t)=>null===t?null:n*t,s),o=dy(t,i,Ka.High,Ka.HH,!0),a=dy(t,i,Ka.Low,Ka.LL,!1);this.addInner(r,o,a)}calculateAt(e){let t=null,i=null;const s=this.innVal(1,wg,e);if(null!==s)if(this.isLong){t=this.innVal(2,Ka.HH,e)-s}else{i=this.innVal(3,Ka.LL,e)+s}return{[Ka.CHEXL.id]:t,[Ka.CHEXS.id]:i}}},MBBANDS:class extends Hp{constructor(e,t){super(e,"Modified",t)}},OPTIV:class extends Rg{},IVRANK:class extends Rg{},IVPCTL:class extends Rg{},OPTVOLPC:class extends Rg{},OPTOIPC:class extends Rg{},OPTVOL:class extends Rg{},OPTOI:class extends Rg{},CHOP:class extends up{constructor(e,t){super(e,t);const i=gy(t,1),s=this.inputs.Period,n=dy(t,s,Ka.High,Ka.HH,!0),r=dy(t,s,Ka.Low,Ka.LL,!1);this.addInner(i,n,r)}calculateAt(e){let t=null;const i=this.period;if(e>i){const s=this.past(e,i,Ka.ATR,this.innCont(1));if(R(s)){const n=O(s)/(this.innVal(2,Ka.HH,e)-this.innVal(3,Ka.LL,e));t=100*Math.log10(n)/Math.log10(i)}}return{[this.target.id]:t}}},MACLD:class extends up{constructor(e,t){super(e,t);const i=Oy(e,"MA","Average"),s=i(t,e.inputs.Period1,this.source,Ka.MACLD1),n=i(t,e.inputs.Period2,this.source,Ka.MACLD2);this.addInner(s,n)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){const t=this.innVal(1,Ka.MACLD1,e)>this.innVal(2,Ka.MACLD2,e)?1:0;return{[Ka.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(Ka.MACLD1,1),this.wrapInner(Ka.MACLD2,2)]}},BTI:class extends Eg{constructor(e,t){super(e,t)}getTargetSeries(e,t,i){const s=by(Ng,(e,t,i)=>t/(t+i),t,i);return Oy(e,"MA","Average")(s,this.inputs.Period,Ng,this.target)}},FRAMA:class extends up{constructor(e,t){super(e,t),My(this);const i=e.inputs.Period,s=Math.floor(i/2),n=dy(t,i,Ka.High,Gg,!0),r=dy(t,i,Ka.Low,zg,!1),o=dy(t,s,Ka.High,Yg,!0),a=dy(t,s,Ka.Low,jg,!1),l=dy(t,s,Ka.High,Kg,!0),c=dy(t,s,Ka.Low,qg,!1);this.addInner(n,r,o,a,l,c)}calculateAt(e){const t=this.period,i=Math.floor(t/2),[,s]=_y(this),n=s.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:n};const r=this.sourceNeedsCompute?1:0,o=this.innVal(1+r,Gg,e),a=this.innVal(2+r,zg,e),l=this.innVal(3+r,Yg,e),c=this.innVal(4+r,jg,e),u=this.innVal(5+r,Kg,e-i),h=this.innVal(6+r,qg,e-i);if(!ie(o,a,l,c,u,h))return{[this.target.id]:n};const d=(o-a)/t,p=(l-c)/i,f=(u-h)/i;let m=0;p>0&&f>0&&d>0&&(m=(Math.log(p+f)-Math.log(d))/Math.log(2));let g=Math.exp(-4.6*(m-1));g=Math.max(.01,Math.min(1,g));const y=e>0?this.container.getData(this.target)[e-1]:n,A=null!==y?g*n+(1-g)*y:n;return{[this.target.id]:A}}},FISHER:class extends up{constructor(e,t){super(e,t);const i=e.inputs.Period,s=Cy(Xg,M(qp,Xg),t),n=dy(s,i,Xg,Ka.HH,!0),r=dy(s,i,Xg,Ka.LL,!1);this.addInner(s,n,r)}get helpers(){return[Zg]}calculateAt(e){const t=this.innVal(1,Xg,e),i=this.innVal(2,Ka.HH,e),s=this.innVal(3,Ka.LL,e);if(!ie(i,s,t))return{[Ka.FISHER.id]:null,[Ka.FISHTRG.id]:null,[Zg.id]:null};const n=i-s,r=t=>this.container.getData(t)[e-1];let o=.66*((0!==n?(t-s)/n:.5)-.5)+.67*((e>0?r(Zg):null)??0);o>.99?o=.999:o<-.99&&(o=-.999);const a=e>0?r(Ka.FISHER):null,l=.5*Math.log((1+o)/(1-o))+.5*(a??0);return{[Ka.FISHER.id]:l,[Ka.FISHTRG.id]:a,[Zg.id]:o}}},PC:class extends up{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=Ry(e.aggregation),this.stdDevs=this.toInt("StandardDeviations"),this.periodForecast=this.toInt("PeriodForecast");const i=this.getHistVolPeriod();if(null!==i){const s=function(e,t,i,s=Ka.Close,n=Ka.HV){return ny("HV",{source:s,target:n,aggregation:i,inputs:ty(t)},e)}(t,i,e.aggregation);this.addInner(s)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return"Custom"===this.volatilityParam}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(Ka.HV))/100}calculateAt(e){let t=null,i=null,s=null,n=null,r=null,o=null;if(this.haveVolatility){const a=this.base.size-this.periodForecast;if(e>=a){const l=this.base.getLastDataPoint(Ka.Close),c=e-a+1,u=l*this.getVolatilityPercent()*Math.sqrt(c/this.unitsPerYear);if(t=l+u,i=l-u,this.stdDevs>1){const e=2*u;if(s=l+e,n=l-e,this.stdDevs>2){const e=3*u;r=l+e,o=l-e}}}}return{[Ka.PCUP1.id]:t,[Ka.PCDN1.id]:i,[Ka.PCUP2.id]:s,[Ka.PCDN2.id]:n,[Ka.PCUP3.id]:r,[Ka.PCDN3.id]:o}}recalculateAt(e,t,i){const s={tag:Pe(),src:this.innerSeries[0]};i&&this.calculate(s)}},GREEKS:class extends up{constructor(e,t){super(e,lp(t,e=>new Vg(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(Ka.Delta,0),this.wrapInner(Ka.Gamma,0),this.wrapInner(Ka.Theta,0),this.wrapInner(Ka.Vega,0)]}},PVACP:class extends pg{constructor(e,t){super(e,!0,t)}},TDI:class extends up{constructor(e,t){super(e,t),My(this);const i=e.inputs.PeriodRSI,s=e.inputs.PeriodTradeSignal,n=e.inputs.PeriodMarketBase,r=e.inputs.PeriodBB,[o]=_y(this),a=Sy(this.innerSeries[o],i,this.source,Ka.TDIPRC),l=ay(a,s,Ka.TDIPRC,Ka.TDITSL),c=ay(a,n,Ka.TDIPRC,Ka.TDIMBL),u=vy(a,r,Ka.TDIPRC,Ka.MSD);this.addInner(a,l,c,u)}calculateAt(e){const t=this.inputs.MultiplierBB,i=this.sourceNeedsCompute?1:0,s=this.innVal(1+i,Ka.TDIPRC,e),n=this.innVal(2+i,Ka.TDITSL,e),r=this.innVal(3+i,Ka.TDIMBL,e),o=this.innVal(4+i,Ka.MSD,e);let a=null,l=null;if(ie(r,o)){const e=t*o;a=r+e,l=r-e}return{[Ka.TDIPRC.id]:s,[Ka.TDITSL.id]:n,[Ka.TDIMBL.id]:r,[Ka.TDIUPR.id]:a,[Ka.TDILWR.id]:l}}},PPS:class extends up{isLong;isPercent;constructor(e,t){super(e,t);const i=e.inputs.Period,s=e.inputs.Range,n=e.inputs.Direction;this.isLong="Long"===n,this.isPercent="Percent"===e.inputs.Type;const r="Close"===s;let o=Ka.Close;r||(o=this.isLong?Ka.High:Ka.Low);const a=dy(t,i,o,$g,this.isLong);this.addInner(a)}get helpers(){return[Ka.BARCOLIX]}calculateAt(e){let t=null;const i=this.innVal(1,$g,e),s=this.inputs.StopValue;if(null!==i){const e=this.isPercent?i*s/100:s;t=this.isLong?i-e:i+e}const n=this.isLong?1:0;return{[Ka.PPS.id]:t,[Ka.BARCOLIX.id]:n}}},RCI:class extends up{constructor(e,t){super(e,t);const i=this.source,s=new Jg({source:i,target:Ka.RCI,inputs:{Period:e.inputs.Period}},t),n=e.inputs.PeriodSignal,r=Oy(e,"MA","Smoothing")(s,n,Ka.RCI,Ka.RCISIG);this.addInner(s,r)}getWrappers(){return[this.wrapInner(Ka.RCI,1),this.wrapInner(Ka.RCISIG,2)]}},ZIGZAG:class extends up{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow="High/Low"===e.inputs.Method,this.isAtrMode="ATR"===e.inputs.PercentMode,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||My(this),this.isAtrMode){const t=e.inputs.PeriodAtr,[i]=this.useHighLow?[0]:_y(this),s=gy(this.innerSeries[i],t,"SMA",Qg);this.addInner(s)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(Ka.High,e);const[,t]=_y(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(Ka.Low,e);const[,t]=_y(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(Ka.Close,e);const[,t]=_y(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){const t=!this.useHighLow&&this.sourceNeedsCompute?1:0,i=this.innVal(1+t,Qg,e),s=this.getAtrDenom(e);if(null===i||null===s||0===s)return 0;const n=i/s*100;return this.atrMult*n}return this.percent}pct(e,t){return 0===e?0:(t-e)/e*100}resetState(){this.state={mode:0,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:/* @__PURE__ */new Map}}calculateAt(e){const t=this.getHigh(e),i=this.getLow(e),s=this.getDevPct(e);if(null===t||null===i)return{};if(0===e){this.resetState();const i=this.useHighLow?this.baseVal(Ka.Close,e):t;return this.setPivot(i,e),this.setCandidate(i,e),{}}if(0===this.state.mode)this.pct(this.state.pivotPrice,t)>=s?(this.state.mode=1,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,i)>=s&&(this.state.mode=-1,this.setCandidate(i,e));else if(1===this.state.mode){const n=t>=this.state.candPrice;n&&this.setCandidate(t,e);const r=(this.state.candPrice-i)/this.state.candPrice*100;if(!n&&r>=s){const t=this.state.candIndex,s=this.state.candPrice;this.state.confirmedPivots.set(t,s),this.setPivot(s,t),this.setCandidate(i,e),this.state.mode=-1}}else if(-1===this.state.mode){const n=i<=this.state.candPrice;n&&this.setCandidate(i,e);const r=(t-this.state.candPrice)/this.state.candPrice*100;if(!n&&r>=s){const i=this.state.candIndex,s=this.state.candPrice;this.state.confirmedPivots.set(i,s),this.setPivot(s,i),this.setCandidate(t,e),this.state.mode=1}}return{}}getCurrentState(){return this.state}}};function ty(e){return{[gs.INPUT_PERIOD]:e}}function iy(e){return{[gs.INPUT_SYMBOL]:e}}function sy(e){return{target:e,source:null,inputs:fy}}function ny(e,t,i){if(le(ey,e))return new ey[e](t,i);const s=Gv()?.config.extensions?.studyProvider;if(s){const n=s.factory(e,t,i);if(n)return n}throw new Error(`Study ${e} has not been implemented yet.`)}function ry(e){return Ur(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>Ka[e])}function oy(e,t,i,s){return{source:t,target:i,inputs:ty(e),allowEmptyValues:s}}function ay(e,t,i,s=Ka.MA,n=!1){return ny("MA",oy(t,i,s,n),e)}function ly(e,t,i,s=Ka.EMA,n=!1){return ny("MAEXP",oy(t,i,s,n),e)}function cy(e,t,i,s=Ka.SMA,n=!1){return ny("MASMO",oy(t,i,s,n),e)}function uy(e,t,i,s=Ka.WMA,n=!1){return ny("MAWEI",oy(t,i,s,n),e)}function hy(e,t,i,s=Ka.HMA,n=!1){return ny("HMA",oy(t,i,s,n),e)}function dy(e,t,i,s,n,r=!1){return new Op({source:i,target:s,inputs:ty(t)},n,r,e)}function py(e,t,i,s,n=null){return new wp({source:n,target:i,inputs:ty(t)},s,e)}const fy={};function my(e,t=Ka.TR){return ny("_TR",sy(t),e)}function gy(e,t,i="SMA",s=Ka.ATR){return ny("ATR",{target:s,inputs:{[gs.INPUT_PERIOD]:t,[gs.INPUT_SMOOTHING]:i},source:null},e)}function yy(e,t=Ka.TP){return ny("TP",sy(t),e)}function Ay(e,t,i=Ka.Close,s=Ka.ROC){return ny("ROC",{source:i,target:s,inputs:ty(t)},e)}function Sy(e,t,i,s=Ka.RSI,n=!1){return ny("_RSI",{source:i,target:s,inputs:{...ty(t),Modified:n}},e)}function Ty(e,t=Ka.MFMUL){return ny("MFV",sy(t),e)}function vy(e,t,i,s=Ka.MSD){return ny("MSD",{source:i,target:s,inputs:ty(t)},e)}function Py(e,t,i,s=Ka.MOVLR){return ny("MOVLR",{source:i,inputs:ty(t),target:s},e)}function Cy(e,t,i){return new Zp(sy(e),t,i)}function by(e,t,...i){return new Kp(sy(e),t,...i)}function Ey(e,t,i){return t-i}function Ly(e,t,i){return(t-i)/i*100}function My(e){const t=e.source;if(e.sourceNeedsCompute=function(e){switch(e.id){case"HL/2":case"OC/2":case"HLC/3":case"OHLC/4":case"HLCC/4":return!0;default:return!1}}(t),e.sourceNeedsCompute){const i=Cy(t,M(xy,t),e.innerSeries[0]);e.addInner(i)}}function _y(e){const t=e.sourceNeedsCompute?1:0;return[t,e.innCont(t)]}const xy=function(e,t){const i=[Ka.Open,Ka.High,Ka.Low,Ka.Close],[s,n,r,o]=i.map(e=>this.baseVal(e,t));let a=null;const l=e.id;switch(l){case"Open":a=s;break;case"High":a=n;break;case"Low":a=r;break;case"Close":a=o;break;case"HL/2":a=(n+r)/2;break;case"OC/2":a=(s+o)/2;break;case"HLC/3":a=(n+r+o)/3;break;case"OHLC/4":a=(s+n+r+o)/4;break;case"HLCC/4":a=(n+r+o+o)/4}return{[l]:a}},Iy=function(e,t,i){let s=null;if(this.atLeast(i,e+1)){const n=this.baseVal(t,i-e);if(null!==n){s=this.baseVal(t,i)-n}}return{[this.target.id]:s}},Dy={sma:cy,ma:ay,ema:ly,wma:uy,hma:hy};function Oy(e,t,i="Smoothing"){const s=(e.inputs[i]??t).toLowerCase();return Dy[s]}const wy={atr:gy,adjatr:function(e,t,i="MA",s=Ka.Close,n=Ka.ADJATR){return ny("ADJATR",{source:s,target:n,inputs:{[gs.INPUT_PERIOD]:t,[gs.INPUT_SMOOTHING]:i}},e)}};function Ry(e){switch(e.unit){case a.Day:return 252;case a.Week:return 52;case a.Month:return 12;default:return 0}}function Ny(e){const t=[Ka.High,Ka.Low];return e instanceof Vm&&2!==F(e.targetFields,t).length}function Vy(e,t){return e[`Period${t}`]}function Hy(e){return!(e instanceof bh)&&e.query instanceof ip}class By extends hp{constructor(e,t){super(e,t,ly(t,13,Ka.Close),function(e,t,i,s,n=Ka.Close){return ny("MACDEXP",{source:n,inputs:{Period1:t,Period2:i,Period3:s},outFields:[Ka.MACD,Ka.MACDS,Ka.MACDH]},e)}(t,12,26,9,Ka.Close)),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=n.Same;const i=this.innVal(1,Ka.EMA,e),s=this.innVal(1,Ka.EMA,e-1),r=this.innVal(2,Ka.MACDH,e),o=this.innVal(2,Ka.MACDH,e-1);return ie(i,s,r,o)&&(i>s&&r>o?t=n.Up:i<s&&r<o&&(t=n.Down)),{[Ka.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Change,Ka.Volume,Ka.OpenInterest,Ka.TradingDay)}}function Fy(e,t){return ie(t)?(this[e]=t,null):this[e]}class ky{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return Fy.call(this,"_domain",e)}range(e){return Fy.call(this,"_range",e)}padding(e){return Fy.call(this,"_padding",e)}get ready(){return ie(this._domain,this._range)}}const Wy=1/Math.log2(10);function Uy(e,t){const i=(s=e[0],n=e[1],(n-=s)>0?e=>(e-s)/n:e=>isNaN(n)?NaN:.5);var s,n;const r=((e,t)=>i=>e*(1-i)+t*i)(t[0],t[1]);return e=>r(i(e))}function $y(e){return Math.sign(e)*Math.log10(1+Math.abs(e/Wy))}function Gy(e){return Math.sign(e)*Wy*(-1+Math.pow(10,Math.abs(e)))}const zy=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]];class Yy extends ky{constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!function(e,t){if(!Array.isArray(e)||!Array.isArray(t))return!1;if(e===t)return!0;for(let i=0;i<e.length;++i)if(e[i]!==t[i])return!1;return!0}(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let i=I,s=I;switch(this.scaleType){case p.Linear:break;case p.Logarithmic:i=$y,s=Gy;break;default:throw new Error("Unexpected scale type (neither linear nor log)")}const n=this._domain.map(i),r=this.rangeWithPadding(),o=e=>r[1]-e+r[0];return(t?s:o)((t?Uy(r,n):Uy(n,r))((t?o:i)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];const[t,i]=this._range.map(e=>this.mapValue(e,!0));if(t===i&&e>0)return[t];const[s,n]=this._domain;if(this.scaleType===p.Linear||s<0||n>1e5)return jy(t,i,e);const r=this.findLogBand(s),o=this.findLogBand(n),a=2*e;return o-r===0?jy(t,i,a):this.getLogTicks(r,o,a,i<t)}findLogBand(e){return zy.findIndex(([t,i])=>e>=t&&e<i)}getLogTicks(e,t,i,s){const n=[...this._domain];let r=[];try{for(let o=e;o<=t;o++){let[a,l]=zy[o];o===e?a=n[0]:o===t&&(l=n[1]),this.domain([a,l]);const[c,u]=this._range.map(e=>this.mapValue(e,!0)),h=jy(c,u,i);r=s?h.concat(r):r.concat(h)}}finally{this.domain(n)}return function(e,t){const i=e.length;for(let s=1;s<i;++s){const i=e[s];let n=s-1;for(;n>=0&&t(e[n],i);)e[n+1]=e[n],n-=1;e[n+1]=i}}(r,s?(e,t)=>e>t:(e,t)=>e<t),r}checkTicks(){return this.scaleType===p.Logarithmic}}function jy(e,t,i){let s,n,r,o,a=-1;if(i=+i,(e=+e)===(t=+t)&&i>0)return[e];if((s=t<e)&&(n=e,e=t,t=n),0===(o=function(e,t,i){const s=Math.sqrt(50),n=Math.sqrt(10),r=Math.sqrt(2),o=(t-e)/Math.max(0,i),a=Math.floor(Math.log(o)/Math.LN10),l=o/Math.pow(10,a);return a>=0?(l>=s?10:l>=n?5:l>=r?2:1)*Math.pow(10,a):-Math.pow(10,-a)/(l>=s?10:l>=n?5:l>=r?2:1)}(e,t,i))||!isFinite(o))return[];if(o>0)for(e=Math.ceil(e/o),t=Math.floor(t/o),r=new Array(n=Math.ceil(t-e+1));++a<n;)r[a]=(e+a)*o;else for(e=Math.floor(e*o),t=Math.ceil(t*o),r=new Array(n=Math.ceil(e-t+1));++a<n;)r[a]=(e-a)/o;return s&&r.reverse(),r}const Ky={color:gs.COLOR_TRANSPARENT},qy={color:gs.COLOR_TRANSPARENT,width:0,dashStyle:"Solid"},Xy=[Ka.Open,Ka.High,Ka.Low,Ka.Close],Zy=new Set(Xy.map(e=>e.id)),Jy=new xn(0,0,0,0);class Qy{axis;id;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=f.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=Pe(),this.record=new el(""),this.metaData=new en,this.timeSeries=new bh,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=/* @__PURE__ */new Map}get title(){return""}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&ie(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(f.Symbol)}get isExpression(){return this.is(f.Expression)}get isStudy(){return this.is(f.Study)}get isForward(){return this.is(f.Forward)}get isSeasonal(){return this.is(f.Seasonal)}getValueAt(e,t,i){return null}wrapIfAdvancedStyle(e){let t=e;const i=e=>({outFields:e,inputs:{},source:null});if(this.mainCurve.isHeikinAshiStyle)t=new dp(i($u.slice()),e);else if(this.mainCurve.isElderImpulseSystemStyle){const s=$u.slice().concat(Ka.BREL);t=new By(i(s),e)}else this.mainCurve.isPercentChangeStyle&&(t=new cm(i($u.slice()),e));return t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=f[e.type];const t=e;this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),ie(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{const t=new Id;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new Yy(p.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){ie(this.timeSeries)&&ie(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){const e=this.axis.pane.presenter,t=new ip(null,e.data.aggregation,m.Normal,[me(ce(e.data,null,"range","from")),me(ce(e.data,null,"range","to"))]);return t.barsToFetch=e.data.maxDataPoints||gs.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=ce(e.display,null,"xAxis","visibleRange"),t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return ie(this.detachedScale,this.yScale)&&this.detachedScale}getDetachedScaleMargins(){return gs.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;const{y:t,height:i}=e,{top:s,bottom:n}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+s*i),Math.floor(t+i-n*i)])}drawLevels(e){e.save();const t=gs.OUT_OF_SCREEN;for(const i of this.levels.filter(e=>e.visible)){const s=this.priceToY(i.value);nr(e,rr({line:i.line,fill:Ky})),Wn(e,{x:-1,y:s},{x:t,y:s})}e.restore()}drawBands(e){e.save();const t=gs.OUT_OF_SCREEN;for(const i of this.bands){const s=this.priceToY(i.range.to),n=this.priceToY(i.range.from);nr(e,rr({fill:i.fill,line:qy}));Fn(e,new xn(-1,s,t,n-s),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return this.hasEvents&&this.hasEventsData?this.eventsSeries.container.fields.filter(e=>e!==Ka.DateTime):[]}getEventsAt(e){const t=this.eventsSeries.container,i=i=>t.getData(i)[e];return this.getEventFields().map(t=>{const s=i(t);if(!ie(s))return null;const n=this.getEventFor(t);if(!ie(n))return null;const r={field:t,value:s,date:i(Ka.DateTime),text:n.title,color:n.color};if(t===Ka.Custom&&s===gs.FAKE_CUSTOM_EVENT){const t=e%2==0;return{...r,value:t?"___news":"___video",text:t?"N":"V"}}return r}).filter(e=>null!=e)}getRefEventField(e,t,i){return t?e.isOhlc?Ka.High:i.isTick?Ka.Last:Ka.Close:e.fields[0]}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){const i=this.axis.pane.presenter,s=i.view.xAxis.xScale,n=s.domain();if(!ie(n)||!ie(n[0],n[1]))return;const r=(e,t=Ka.DateTime)=>e.container.getData(t),o=r(this.eventsSeries),l=this.getRefPlot(i),c=l.timeSeries,u=r(c),h=i.data.aggregation,d=l===i.mainPlot,p=r(c,this.getRefEventField(l.mainCurve,d,h)),{chart:{fontFamily:f}}=this.axis.pane.presenter.display,m=o.map((e,r)=>{if(!(e=>e.valueOf()>=n[0].valueOf()&&e.valueOf()<=n[1].valueOf())(e))return[];return this.getEventsAt(r).map(e=>{const n=function(e,t){const{unit:i}=e;return i===a.Year?Mt(t):i===a.Quarter?bt(t):i===a.Month?Et(t):i===a.Week?it(t):i===a.Day?nt(t):t}(h,e.date),r=G(u,+n,Number),o=p[r];t.has(r)||t.set(r,-1);let l=t.get(r);t.set(r,++l);const c=s.timeToX(n),d=i.view.getEventRadius(),f=this.axis.yScale.priceToY(o)-l*(d+d+d);return{visible:!0,...e,x:c,y:f,r:d,rect:Jy}})}).flat();e.save();let g=!0;m.forEach(t=>{t.rect=function(e,{x:t,y:i,r:s,color:n,text:r},o){const a=s;e.fillStyle=n,e.beginPath();const l=s+s,c=l,u=new xn(t-s,i-a-c,l,c);e.fillRect(u.x,u.y,u.width,u.height);const h=(1.6*s).toFixed(0);return e.font=`700 ${h}px "${o}"`,e.fillStyle="#fff",e.textAlign="center",e.textBaseline="middle",e.beginPath(),e.fillText(r,t,i-.9*c),u}(e,t,f),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=m,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){const{x:t,y:i,r:s,date:n,value:r}=e;this.customEventPopup?.show({x:t+2*s,y:i-2*s},n,r)}getCustomEventDataAt(e){if(!this._eventsData)return null;const t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===Ka.Custom?t:null}hitTestCustomEvent(e){return null!==this.getCustomEventDataAt(e)}tryHandleCustomEventClick(e){const t=this.getCustomEventDataAt(e);return!!ie(t)&&(this.showCustomEventPopup(t),!0)}isEmpty(){const e=this.timeSeries;return ie(e)&&e.hasData&&e.container.isEmpty}draw(e){if(this.visible){ie(this.levels)&&this.drawLevels(e),ie(this.bands)&&this.drawBands(e);for(const t of this.curves)t.draw(e)}}drawTopmost(e,t){this.hasEventsData&&this.drawEvents(e,t)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,i,s){if(!ie(e)||!this.timeSeries.hasData)return e;if(!this.shouldPriceMap(i,s))return e;const[n,r]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!ie(n)||!ht(n))return e;if(this._firstVisibleDate!==n){this._firstVisibleDate=n;const e=this.timeSeries.container.getTimeData(),t=t=>G(e,+t,Number);this.visFromIndex=t(n),this.visToIndex=t(r),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(i)||this.canPriceMap(t,i),this.priceMap(e,t,i,!1,s)}isOhlcMapping(e){return this.mainCurve.isOhlc&&(t=e,Zy.has(t.id));var t}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===Ka.PreviousClose?Ka.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){const i=this.getRefPriceMapField(t),s=this.dataOf(i);let n=null,r=this.visFromIndex;for(;null===n&&r<=this.visToIndex;)n=s[r++];this._priceMapFirstIndex.set(i,null!==n?r-1:Number.NaN)}priceMap(e,t,i,s=!1,n=d.None){const r=this.getRefPriceMapField(i),o=this._priceMapFirstIndex.get(r);if(!Number.isFinite(o))return e;const a=this.dataOf(r)[o];if(this.isComparison(d.Percent)||n===d.Percent){return s?a+a*e/100:(e>=a?1:-1)*(100*Math.abs(e-a))/Math.abs(a)}return s?a+e:e-a}shouldPriceMap(e,t){return ie(t)?t!==d.None:this.isComparison(d.Percent)||this.isComparison(d.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}}class eA extends Qy{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!ie(this.timeSeries)||!ie(this.timeSeries.record))return null;const e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(Ka[e])}getTimeSeries(){const e=Gv().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.resolved,this.mainCurve.style){case o.Renko:case o.Kagi:case o.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case o.Range:t.barsToFetch=4e3;break;case o.LineBreak:t.inputs=this.inputs}const i=this.axis.pane;if(ie(i.alignedToYear)){const e=Ji(t.symbol);null!==e&&(this.yearOffset=i.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}const s=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(s),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){const e=Gv().getMetaDataSource();this.metaData=e.getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;const e=Gv().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:m.Events,getHashKey:function(){return Object.values(this).filter(e=>"function"!=typeof e).join("|")}};gs.EVENTS.forEach(e=>{t[e]=ce(this.events,!1,e,"show")}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(qa.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return!!ie(this.events)&&gs.EVENTS.some(e=>ce(this.events,!1,e,"show"))}findEvents(e){if(!this.hasEventsData||null===e[0]||null===e[1])return[];const t=e[0],i=e[1];if(i>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){const e=this.timeSeries.container.getTimeData()[i-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,i)=>this.compare(e,t)?this.getEventsAt(i):[]).flat()}fromModel(e){super.fromModel(e);const t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=function(e){switch(e.unit){case a.Tick:return ko;case a.Intraday:case a.Day:return Vo;case a.Week:return Ho;case a.Month:return Bo;case a.Quarter:return Fo;case a.Year:return Ii;default:return ko}}(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){const t=this.events[e.id.toLowerCase()];return ie(t)&&t.show?t:null}async initialize(){return ps.call(this,async()=>(this.resolved=await Hi(this.symbol),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}class tA extends eA{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${a[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=a[e.fundamental],super.fromModel(e)}makeQuery(){let e=new ip(this.symbol,new Wo(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}}class iA{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){const e=Gv().config.touchCrosshairDelayMillis;return ie(e)&&Number.isFinite(e)?e:gs.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,i){q()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,i),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,i){this.cancelLongPress(),this.performLongPress(e,t,i)}cancelLongPress(){q()&&ie(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,i){}}function sA(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}class nA extends iA{constructor(e,t,i){super(),this.annotation=e,this.previous=t,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,i)}cursorSet;moved;snapToSupported;performLongPress(e,t,i){qA(this.annotation,i)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),sA(this.annotation))return;const{point:t,view:i,offset:s}=e;if(!te(t)||t.axis!==this.annotation.axis)return;i.drawCrosshair({ap:t,offset:s}),this.cursorSet||(this.previous.axis.pane.presenter.view.setCursor(y.Move),this.cursorSet=!0);const n=fn(t.point,this.previous.point);this.annotation.offset(n),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=t,this.moved=!0}onMouseUp(e){this.cancelLongPress(),JS(this.annotation,this.moved,E.Moved)}}class rA{constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;onMouseMove(e){if(this.alignPointsMode=e.getModifier(S.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),sA(this.annotation))return;const{point:t,view:i,offset:s}=e;if(i.drawCrosshair({ap:t,offset:s}),ie(t)){const e=this.annotation.points[this.pointIndex],i=fn(t.point,e.point);switch(e.moveDirection){case T.Both:e.update(t.price,t.time);break;case T.Horizontal:e.update(e.price,t.time);break;case T.Vertical:e.update(t.price,e.time)}this.moved=e.moveDirection!==T.None,this.moved&&this.annotation.wasPointMovedByTool(e,i)}this.annotation.requestRedraw()}onMouseUp(e){JS(this.annotation,this.moved,E.PointMoved)}}class oA{constructor(e,t,i){this.anchor=e,this.isVertical=t,this.axis=i}hitTest(e){return!!ie(this.anchor)&&(this.isVertical?Math.abs(e.x-this.anchor.x)<=gs.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=gs.HIT_TEST_TOLERANCE)}draw(e){const t=gs.OUT_OF_SCREEN;this.isVertical?Un(e,this.anchor.x,-t,t):$n(e,this.anchor.y,-t,t)}}class aA{id;axis;_price;_time;passive=!1;moveDirection=T.Both;visible=!0;point;constructor(e,t,i){this.id=Pe(),this.axis=e,void 0!==t&&void 0!==i&&(this.price=t,this.time=i,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==T.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){const e=this.axis.toPoint(this);ie(e)&&ne(e.x)&&ne(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time="number"==typeof t?new Date(t):t,this.toPoint()}updateFromPoint(e){const t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){if(!this.visible)return!1;return this.distance(e)<=gs.HIT_TEST_TOLERANCE}distance(e){const t=e.x-this.point.x,i=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+i*i)-gs.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(ie(this.point)){let i=gs.HALF_ANN_POINT_DIMENSION;ie(t)&&t.locked&&(i*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,i,i,0,0,2*Math.PI),e.stroke()}}}function lA(e){return 0===bn(e.fill.color).a?e.line.color:e.fill.color}function cA(e,t){return{uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function uA(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}class hA{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=Pe()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){return this.drawPoints(e,t),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>void 0!==e.point)}getPriceScaleAdornments(){return gs.EMPTY_ARRAY}getTimeScaleAdornments(){return gs.EMPTY_ARRAY}extractTraits(e=!0){const t=ue(this.traits),i=_r(this.name);return Object.keys(t).forEach(s=>{const n=i.includes(s);(e&&!n||!e&&n)&&delete t[s]}),e||["line","fill","zIndex"].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:se(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(mn(t.point,e))})}get traits(){return this._traits||(this._traits=ue(this.defaultTraits)),this.adjustFill&&(this._traits.fill.color=lA(this._traits),this.adjustFill=!1),this._traits}set traits(e){void 0!==e&&ye(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return rr(this.traits)}get defaultTraits(){return sr(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return rr(this.defaultTraits)}get adornStyle(){const e=ue(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=gs.COLOR_TRANSPARENT,rr(e)}get pointsStyle(){const e=ue(this.defaultTraits);return e.line.dashStyle="Solid",rr(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}isPointDrawn(e){return void 0!==e.price}drawPoints(e,t){this.points.forEach(i=>{const s=this.isPointDrawn(i),n=ie(e);!t||!s&&n||i.toPoint(),n&&s&&(this.isSelected||this.drawn)&&(nr(e,this.pointsStyle),i.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new aA(this.axis))}toModel(){const e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:ue(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){const t=this.activePoints;t.length===e.length&&t.forEach((t,i)=>{const s=e[i];t.update(s.price,s.time)})}updateFrom(e,t,i,s,n){"boolean"==typeof s&&(this.visible=s),"boolean"==typeof n&&(this.locked=n);const r=ie(e)?ue(e):{};ie(t)&&ye(r,t),this.traits=r,ie(i)&&this.updatePoints(i)}priceMap(e){return this.axis.priceMap(e)}flip(e){const t=this.getFlipAnchorIndices();if(!te(t))return;const i=this.points[t[0]],s=this.points[t[1]];if(e){const e=s.time;s.update(s.price,i.time),i.update(i.price,e)}else{const e=s.price;s.update(i.price,s.time),i.update(e,i.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}}function dA(e,t,i,s){return function(n,r=!0){const o=new t(n,e,i);return r?n.appendAnnotation(o):o.drawn=!1,ie(s)&&(o.traits=s),o}}class pA{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,i,s,n){this.axis=n,ie(e,t)&&(this.angle=gn(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=i?this.extendPoint(t,-1):e,this.p2=s?this.extendPoint(e,1):t),this.extended=i||s}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){const i=Math.max(Math.abs(e.x),Math.abs(t.x)),s=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(i*i+s*s)+gs.OUT_OF_SCREEN}hitTest(e){return!!ie(this.p1,this.p2)&&yn([this.p1,this.p2],e,gs.HIT_TEST_TOLERANCE)}draw(e){ie(this.p1,this.p2)&&(Wn(e,this.p1,this.p2),this.extended)}getAdornOffset(e){const t=Vn(e),i=Rn(e,1);var s,n;return(s=this.p1,n=this.p2,-(s.y-n.y)/(s.x-n.x))<0&&(t.y=i+5),t}}class fA{style;axis;rect;constructor(e,t,i,s){this.axis=s,this.rect=new xn(e.x,e.y,t,i)}hitTest(e){return this.rect.contains(e)}draw(e,t){Fn(e,this.rect)}}class mA extends hA{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.prepareDraw(e,t)&&!this.drawn){const t=this.getElements();nr(e,this.style),t.forEach((t,i)=>{nr(e,this.getStyleForElement(t,i)),t.draw(e)}),nr(e,this.adornStyle),this.adornElements(t,e);const i=this.getMarkers();nr(e,this.style),i.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(void 0===this.countCache||this.countCache.time1!==e||this.countCache.time2!==t){const i=this.axis.pane.presenter.view,s=Math.abs(i.toIndex(e)-i.toIndex(t));this.countCache={time1:e,time2:t,barCount:s}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.visible){const t=this.getElements(),i=this.getMarkers();if(t.some(t=>t.hitTest(e)))return!0;return!!i.some(t=>t.hitTest(e))||this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,i)=>this.points[t+i].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return ae(this.traits?.singleStyle,!0)}get showBackground(){return ae(this.traits?.showBackground,!1)}get backgroundOpacity(){return ae(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return rr({line:{color:gs.COLOR_TRANSPARENT,dashStyle:"Solid",width:0},fill:this.traits[e]})}lineOnlyStyle(e){return rr({fill:{color:gs.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new pA(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Tn(Sn(e),this.backgroundOpacity)}getTraitsFor(e){const t={fill:{color:gs.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground?(t.fill.color=this.applyBackgroundOpacity(t.line.color),t):t}getFlipAnchorIndices(){return 2===this.points.length?[0,1]:null}}class gA extends mA{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return gs.AT_FACTORS}get factors(){return Jn(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[gs.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[gs.AT_LEVELS_KIND]}get labels(){return this.traits[gs.AT_LABELS]}get isExtended(){return 3===this.points.length}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,i){let s=this.isBefore(e,t);return i||(s=!s),this.points[s?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[gs.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){const i=this.levelsKind===gs.AT_LEVELS_PERCENTS;let s="";if(this.showLevels&&(s=i?`${(100*e).toFixed(1)}%`:e.toString()),this.showPrices){const e=this.priceMap(this.axis.toPrice(t));s=(s+` (${nd(this.axis,e)})`).trim()}return s}getAdornPointAndAlign(e,t){const i=this.labels,s=e instanceof pA,n=(e,t,i)=>({pt:e,align:t,offset:i});switch(i){case gs.AT_LABELS_LEFT:return n(s?e.anchor1:e,g.Right,-t);default:case gs.AT_LABELS_RIGHT:return n(s?e.anchor2:e,g.Left,t);case gs.AT_LABELS_CENTER:return n(s?dn(e.anchor1,e.anchor2):e,g.Center,0)}}getColoredElements(e){const t=this.singleStyle;return this.factors.map(i=>{const s=e(i);return null===s?null:(t||(s.style=rr(this.getTraitsFor(i))),s._data={factor:i.value},s)}).filter(e=>null!==e)}hitTestAdornments(e,t){const i=this.showLevels,s=this.getTextRef();if(!i||null===s)return!1;const n=this.axis.pane.presenter,r=n.view?.mainContext;if(!r)return!1;let o=null,a=!1;r.save();const{chart:{fontFamily:l},yAxis:{fontSize:c}}=n.display;r.font=`${c??12}px ${l}`;for(const u of e){if(!ie(u._data))continue;const{factor:e}=u._data,{ref:i,spacing:n,offsetY:l,text:c}=s(o,u,e),{pt:h,align:d,offset:p}=this.getAdornPointAndAlign(i,n);if(Hn(r,c,this.getAdornTextPoint(r,l,h,p),d).contains(t)){a=!0;break}o=u}return r.restore(),a}adornElementsForColoredFactors(e,t,i,s){const n=this.singleStyle,r=this.showBackground,o=this.showLevels,a=this.applyBackgroundOpacity(this.traits.line.color),l=s.fillStyle;let c=null;e.forEach(e=>{if(!ie(e._data))return;const{factor:u}=e._data;if(r){const i=t(c,e);s.fillStyle=n?a:e.style.fillStyle,s.fill(i)}if(o){const{ref:t,spacing:r,offsetY:o,text:a}=i(c,e,u),{pt:h,align:d,offset:p}=this.getAdornPointAndAlign(t,r),f=this.getAdornTextPoint(s,o,h,p),m=n?l:e.style.strokeStyle;Bn(s,a,f,d,m)}c=e})}getAdornTextPoint(e,t,i,s){const n=Rn(e,.75);return mn(i,{x:s,y:!0===t?n/2:t})}}class yA extends mA{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get rect(){const[e,t,,]=this.getScreenPoints(),i={x:e.x,y:Math.min(e.y,t.y)},s=new fA(i,t.x-e.x,Math.abs(e.y-t.y),this.axis);return s.style=this.rectStyle,s}get reverse(){return!1}getLinesDataAtLevels(e,t){let[i,s]=this.points;if(this.reverse&&([i,s]=[s,i]),null==this.lines){const n=(e,t=!1)=>i=>({level:i.value,domain:e(i.value),traits:this.getTraitsFor(i),isPrice:t}),r=s.price-i.price,o=n(e=>i.price+e*r,!0),a=e?.map(o)??[],l=this.axis.pane.presenter.timeline,c=G(l,+i.time,Number,ud),u=G(l,+s.time,Number,ud)-c,h=n(e=>+l.at(c+Math.floor(e*u))),d=t?.map(h)||[];this.lines={prices:a,times:d,barsDiff:u,priceDiff:r}}return this.lines}makeColoredLine(e,t,i){const s=this.makeLine(e,t);return this.singleStyle||(s.style=rr(i.traits)),s._data={level:i.level,isPrice:i.isPrice},s}getLineElements(e){const[t,i]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{const s=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:s},{x:i.x,y:s},e)}),timeLines:e.times.map(e=>{const s=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:s,y:t.y},{x:s,y:i.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}}class AA extends aA{constructor(e,t,i){super(e),this.priceRef=t,this.timeRef=i,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}}class SA{constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return ie(this.points[0].point,this.points[1].point)?new xn(this.left,this.top,this.width,this.height):null}}function TA(e){const t=new aA(e),i=new aA(e);return[t,i,new AA(e,t,i),new AA(e,i,t)]}class vA extends hA{helper;constructor(e,t){super(e,t),this.points=TA(e),this.helper=new SA(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return!!this.prepareDraw(e,t)&&(nr(e,this.style),!0)}updatePoints(e){this.allowPricesChangeUI&&2===e.length&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}}class PA{constructor(e,t,i){this.points=e,this.lines=t,this.axis=i,this.helper=new SA(this.points)}helper;_actualWidth=0;_fontSizeForWidth=0;hitTest(e){const t=this.getRect();return!!te(t)&&(t.width=this._actualWidth,t.contains(e))}getRect(){return this.helper.getRect()}get fontSize(){if(0===this.lines.length)return 0;const{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(0===this.lines.length)return;e.save();const{x:t,y:i}=this.getRect(),{chart:{fontFamily:s}}=this.axis.pane.presenter.display,n=this.fontSize;e.textAlign="left",e.textBaseline="top",e.font=`${n}px ${s}`,this.lines.forEach((s,r)=>{const o=i+n*r;e.fillText(s,t,o)}),this.computeActualWidth(e),e.restore()}}class CA extends mA{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=TA(e),this.adjustFill=!0}get textLines(){return this.traits[gs.AT_TEXT_LINES]}set textLines(e){this.traits[gs.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!ie(this._textAnnElement)&&this.visible&&(this._textAnnElement=new PA(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,i,s,n){super.updateFrom(e,t,i,s,n),this._textAnnElement=void 0}getElements(){return this.visible?[this.textElement]:[]}}class bA extends CA{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return!!this.visible&&this.textElement.hitTest(e)}get prices(){return this.traits.prices}get pricesPoints(){const e=this.points[0].time;return this.prices.map(t=>new aA(this.axis,t,e))}updateFrom(e,t,i,s,n){super.updateFrom(e,t,i,s,n),ie(e?.textLines)&&(this.textLines=e.textLines)}getElements(){const e=super.getElements(),t=this.pricesPoints.map(e=>new oA(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();const e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){const{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){const[t,i]=this.defaultFont;e.save(),e.font=`${t}px ${i}`;const s=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:n,y:r}=this.points[0].point;this.points[1].updateFromPoint({x:n+s,y:r+this.textLines.length*t}),e.restore()}}class EA{constructor(e){this.annId=e}annotation;onKeyDown(e){if(null==this.annId)return;const{key:t,code:i,presenter:s}=e;if(X(t,i)){if(ie(this.annotation)){this.annotation.axis.deleteAnnotation(this.annotation,!1),s.view.redraw()}ZS(s,{toolChange:E.Cancelled,annId:this.annId})}}}class LA extends EA{constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}onMouseDown(e){const{point:t,button:i}=e;if(void 0===t)return;const s=te(this.annotation);if(i===A.Left)if(s){const e=!this.thirdPoint||this.dragged?1:2;this.annotation.points[e].update(t.price,t.time),this.dragged=!1,this.signalChange(),this.thirdPoint&&2!==e||this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange();return!0}onMouseMove(e){const{point:t,view:i,offset:s}=e;return i.drawCrosshair({ap:t,offset:s}),ie(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(S.Shift),this.dragged?(this.annotation.points[1].update(t.price,t.time),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.annotation.points[2].update(t.price,t.time),this.signalChange())),!0}finish(){JS(this.annotation,!0,E.Created)}isAccidentalMouseUp(e){const{point:t}=e,i=this.annotation.points[0].point;return pn(t.point,i)<gs.HIT_TEST_TOLERANCE}onMouseUp(e){void 0!==this.annotation?this.isAccidentalMouseUp(e)?this.dragged=!0:(this.dragged=!1,this.thirdPoint||this.finish()):eT(e)}}class MA extends LA{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}}class _A extends LA{constructor(e){super(e,!1),this.snapToSupported=!1}onMouseMove(e){const{point:t,view:i,offset:s}=e;if(i.drawCrosshair({ap:t,offset:s}),ie(this.annotation)&&this.dragged){const[e,i]=this.annotation.points;i.update(t.price,t.time);const s=fn(i.point,e.point),n=e.point.y+s.x*Math.sign(s.y)*Math.sign(s.x),r=this.annotation.axis.toPrice(n);i.update(r,t.time),this.signalChange()}return!0}}class xA extends EA{constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!ie(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew){return{height:100,fontSize:"100%",color:lA(sr(this.anchor.axis.pane.presenter.display,"Text"))}}{const e=this.existing.textElement;return{height:1.05*e.getRect().height,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[gs.AT_FILL].color}}}onMouseDown(e){const{point:t}=e;if(this.isNew)if(0===this.clicks){if(void 0===t)return void eT(e);t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing();else this.onEndEditing()}startEditing(){this.textArea=document.createElement("textarea");const{x:e,y:t}=this.anchor.point,i=this.anchor.axis.pane.getBounds(),s=i.x+i.width-this.anchor.point.x,{height:n,fontSize:r,color:o}=this.styleProps();os(this.textArea,{position:"absolute",top:`${t}px`,left:`${e}px`,border:"none",outline:"none",overflow:"hidden",height:`${n}px`,width:`${s}px`,resize:"none",backgroundColor:"rgba(255, 255, 255, 0.05)",zIndex:"5",fontSize:r,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join("\n"),this.existing.textLines=[""],this.existing.requestRedraw()),setTimeout(()=>this.textArea.focus(),100)}onEndEditing(){const e=this.anchor,t=this.isNew?this.factory(e.axis):this.existing,i=this.textArea.value.split("\n");if(this.isNew){const{actualWidth:s,actualHeight:n}=this.getTextDimensions(i);t.points[0].update(e.price,e.time);const{x:r,y:o}=t.points[0].point;t.points[1].updateFromPoint({x:r+s,y:o+n}),t.drawn=!1}t.textLines=i,this.textArea.onblur=null,this.getChartParent().removeChild(this.textArea),t.requestRedraw(),this.isNew||t.requestRedraw(),JS(t,!0,this.isNew?E.Created:E.TextChanged)}getTextDimensions(e){const t=globalThis.getComputedStyle(this.textArea).getPropertyValue("font-size"),i=parseFloat(t)*e.length;let s=0;const n=this.anchor.axis.pane.presenter,r=n.view.mainContext;r.save();const{chart:{fontFamily:o}}=n.display;r.font=`${t} ${o}`;for(let a=0;a<e.length;a++){const t=r.measureText(e[a]).width;t>s&&(s=t)}return r.restore(),{actualWidth:s,actualHeight:i}}}function IA(e){return Gv().config.tooltipMovement===e}function DA(){return IA("Draggable")}function OA(){return IA("Auto")}const wA=gs.TOOLTIP_STD_LEGACY_CLASS,RA=gs.TOOLTIP_STD_CLASS,NA=gs.TOOLTIP_BUBBLE_CLASS;class VA{constructor(e){this.view=e,this.tooltipElem=us(e.el,"div"),as(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${RA} ${wA}`}),this.leftSide=!0,os(this.tooltipElem,{visibility:"hidden",position:"absolute",cursor:DA()?"move":"default",zIndex:20,top:`${gs.TOOLTIP_Y_OFFSET}px`,left:`${gs.TOOLTIP_X_OFFSET}px`}),this.setMode(e.presenter.display.tooltip.mode),this.handleMouseMove=this.handleMouseMove.bind(this),this.startDrag=this.startDrag.bind(this),this.stopDrag=this.stopDrag.bind(this),this.view.el.addEventListener("mousemove",this.handleMouseMove),this.view.el.addEventListener("mouseleave",this.stopDrag),this.tooltipElem.addEventListener("mousedown",this.startDrag),this.tooltipElem.addEventListener("mouseup",this.stopDrag)}tooltipElem;leftSide;mode;isDrag=!1;canDrag;isToggling;startDrag(){this.isDrag=!0}stopDrag(){this.isDrag=!1}setMode(e){if(this.mode!==e)if(this.mode=e,e===gs.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition="none",this.tooltipElem.classList.remove(RA,wA),this.tooltipElem.classList.add(NA),os(this.tooltipElem,{pointerEvents:"none"});else if(e===gs.TOOLTIP_STD){this.canDrag=DA(),this.tooltipElem.classList.remove(NA),this.tooltipElem.classList.add(RA,wA);const e=gs.TOOLTIP_TOGGLE_SIDE_ANIM_MS;os(this.tooltipElem,{pointerEvents:"all",top:`${gs.TOOLTIP_Y_OFFSET}px`,left:`${gs.TOOLTIP_X_OFFSET}px`,transition:OA()?`left ${e}ms ease-out`:null})}}show(e,t){const i=this.tooltipElem;if(t){const{width:e,height:s,leftOffset:n,rightOffset:r}=this.view,o=i.getBoundingClientRect(),a=o.width/2,l=i.style,c=s*gs.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-c,h=t.x-a,d=t.yMax+c,p=d+o.height,f=u<0?p<s?d:0:u;let m=h;const g=e-r;m<n?m=n:m+o.width>g&&(m=g-o.width),l.top=`${f}px`,l.left=`${m}px`}"hidden"===i.style.visibility&&(i.style.visibility="visible"),ds(i,e)}hide(){this.tooltipElem.style.visibility="hidden"}remove(){this.view.el.removeEventListener("mousemove",this.handleMouseMove),this.view.el.removeEventListener("mouseleave",this.stopDrag),this.tooltipElem.removeEventListener("mousedown",this.startDrag),this.tooltipElem.removeEventListener("mouseup",this.stopDrag),ns(this.tooltipElem)}reposition(e,t){os(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===gs.TOOLTIP_STD&&OA()}handleMouseMove(e){if(this.isDrag&&this.canDrag){const{movementX:t,movementY:i}=e,{top:s,left:n}=this.tooltipElem.style,r=parseInt(s)+i,o=parseInt(n)+t;this.reposition(o,r)}else if(this.isAutoMove()){const t=this.tooltipElem.getBoundingClientRect(),i=this.view.el.getBoundingClientRect(),s=e.pageX,n=gs.TOOLTIP_TOGGLE_DISTANCE_TOLERANCE,r=i.width>2*t.width,o=s>t.x&&s<=t.right+n,a=s<t.x&&s>=t.x-n;r&&(o||a)&&this.toggleSide()}}repositionAuto(){if(this.isAutoMove()){const e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=this.tooltipElem.offsetY,i=e.x+(this.leftSide?gs.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-gs.TOOLTIP_X_OFFSET);this.reposition(i,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,gs.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}}function HA(e){e.showTooltip&&BA(e,{time:gs.ZERO_DATE,offset:gs.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function BA(e,{time:t,lastBarRefresh:i,justMain:s,offset:n,price:r}){const o=bd(e,t,n,0,s,r),{mode:a,showMainPlot:l,hideSymbols:c,revealingClose:u}=e.display.tooltip,{includeTimestamp:h,showMainPlot:d,showPlotActions:p}=Gv().config.tooltipHeaders||{},f=ie(d)?d:l,m=!!ie(h)&&h,g=!!ie(c)&&c,y=!!ie(u)&&u,A=!!ie(p)&&p,S=t.valueOf()===gs.ZERO_DATE.valueOf();switch(a){case gs.TOOLTIP_CARDS:kA(e,o,f,!S,m&&!S,!1,g,y,A,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case gs.TOOLTIP_BUBBLE:if(!S){const t=o.panes.find(e=>{const{top:t,left:i,width:s,height:r}=e.bounds;return new xn(i,t,s,r).contains(n)}),i=t.plots.find(e=>e.isMain)||t.plots[0],s=i.values.find(e=>["Close","Last"].includes(e.id)),r=s?s.y:i.values[0].y,a=t.plots.map(e=>e.values.filter(e=>"Change"!==e.id&&e.y>0).map(e=>e.y)).flat(),l=`<div class="bubble-box">${md({...o,hideSymbols:g,revealingClose:y,plots:t.plots})}</div>`;e.view.tooltip.show(l,{x:n.x,y:r,yMin:Math.min(...a),yMax:Math.max(...a)})}kA(e,o,f,!1,!1,e.hasLegend,g,y,A);break;case gs.TOOLTIP_STD:if(!S){const t=md({...o,hideSymbols:g,revealingClose:y,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}kA(e,o,f,!1,!1,e.hasLegend,g,y,A);break;case gs.TOOLTIP_EXTERNAL:e.notifyHost(qa.CH_TOOLTIPCHANGED,o);break;default:console.warn(`Unknown tooltip mode requested: ${a}`)}}function FA(e,t,i,s,n,r){os(e,{position:"absolute",display:"flex","flex-direction":t,"flex-wrap":"wrap",left:`${i+gs.CARDS_X_OFFSET}px`,top:`${n+gs.CARDS_Y_OFFSET}px`,maxWidth:r-s-2*gs.CARDS_X_OFFSET+"px"})}function kA(e,t,i=!1,s=!1,n=!1,r=!1,o=!1,a=!1,l=!1,c=0){const u=e.view.el,h=gd(e,t,i,s,n,o,a,l);h.some(e=>!ie(e.bounds))||h.forEach(({id:t,isMainPane:i,content:s,moveContent:n,bounds:{left:o,right:a,top:l,width:h}},d)=>{if(!(""===s||r&&i)){const n=ls(t,u,"div");FA(n,i&&pd(e)?"column":"row",o,a,l+c,h),cs(n,{"bcharts-card":!0,"bcharts-card-main":i,"bcharts-card-first":0===d}),n.innerHTML=s}let p=rs(`#right-${t}`,u);ie(p)||(p=document.createElement("div"),p.id=`right-${t}`,u.appendChild(p),cs(p,"bcharts-card bcharts-card-move")),os(p,{position:"absolute",display:"block",right:`${a+gs.CARDS_X_OFFSET}px`,top:`${l+c+gs.CARDS_Y_OFFSET}px`}),p.innerHTML=n})}let WA=null;function UA(){return null===WA&&(WA=Gv().config.hostingModel===b[b.Application]),WA}class $A extends iA{constructor(e){super(),this.ap=e,this.presenter=e.presenter,this.panY=e.axis.isCustomDomain}presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;activated(){}deactivated(){this.cancelLongPress()}startPan(e){this.startLongPress(this.presenter,this.ap,e),this.lastOffset=e,this.lastPanningExtremes=this.ap.axis.yScale.domain();const t=this.ap.presenter;t.enableTooltip(!1),t.view.tooltip.hide(),t.view.drawCrosshair({ap:void 0})}onMouseMove(e){if(e.pinchZoom)return void this.presenter.resetActiveTool();const{point:t,view:i,offset:s}=e;if(t&&t.axis!==this.ap.axis)return;const{x:n,y:r}=s,o=n-this.lastOffset.x,a=Math.abs(o),l=this.lastOffset.y,c=r-l,u=Math.abs(c);a>=1&&this.cancelLongPress();const h=UA();if(q()&&!h&&this.warmUp)return(a>7||u>7)&&(this.warmUp=!1,this.preventDefault=a>u),!1;if(this.preventDefault||!q()||h){if(i.xAxis.pan(o),this.panY&&t&&t.axis){u>=1&&this.cancelLongPress();const e=function(e,t,i,s){const n=i-t,r=n/e.viewBox.height,[o,a]=s,l=r*(a-o);return[o+l,a+l]}(t.axis,l,r,this.lastPanningExtremes);this.lastPanningExtremes=e,t.axis.yScale.domain(e)}this.lastOffset=s,i.redraw(),t&&t.presenter.view.setCursor(y.Grabbing)}return h||this.preventDefault}finished(){ZS(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:i}){q()&&XA(e,t,i)}performLongPress(e,t,i){e.enableTooltip(!0),e.resetActiveTool(),e.activeTool.startTouchCrosshairMode(e,t,i)}}let GA=null;class zA extends vA{constructor(e,t){super(e,t)}hitTest(e){if(!this.visible)return!1;const t=this.getRect();return null!==t&&t.contains(e)}draw(e,t){return!!super.draw(e,t)&&(Fn(e,this.getRect()),!0)}}function YA(e,t){return e<t?[e,t]:[t,e]}const jA={line:{width:1,color:"rgba(127, 127, 127, 0.3)",dashStyle:"LongDash"},fill:{color:"rgba(127, 127, 127, 0.1)"}};class KA extends LA{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(dA("Rectangle",zA,null,jA),!1)}activated(){}deactivated(){ie(this.axis,this.annotation)&&this.axis.deleteAnnotation(this.annotation,!1)}onMouseDown(e){const t=super.onMouseDown(e);if(!0===t){const{point:t}=e;this.axis=t.axis,this.presenter=t.presenter}return t}finish(){if(ie(this.axis,this.presenter)){ZS(this.presenter,{toolChange:E.Executed,annId:"ZoomIn"});const e=this.annotation.points,t=YA(e[0].price,e[1].price),i=YA(e[0].time,e[1].time),s=(e,t)=>Math.abs(t(e[0])-t(e[1])),n=s(i,e=>this.axis.toX(e)),r=s(t,e=>this.axis.toY(e)),o=this.presenter.view,a=gs.MINIMUM_ZOOM_DIMENSION;if(n>a&&r>a){const e=o.xAxis.xScale;this.axis.isCustomDomain=!0,this.axis.yScale.domain(t),e.wasZoomed=!0,e.scaleBarToFitRange(i,!1),e.domain(i)}o.redraw()}}}function qA(e,t){const i=uA(e);i.offset={x:t.x,y:t.y},i.canFlip=null!==e.getFlipAnchorIndices();const s=e.axis.pane.presenter;s.clearSelection(),s.notifyHost(qa.CH_ANNNEEDSCONTEXTMENU,i)}function XA(e,t,i){const s={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:i};e.notifyHost(qa.CH_CHTNEEDSCONTEXTMENU,s)}class ZA extends EA{constructor(e,t){super(e.annName),this.factory=e,this.maxClicks=t}clicks=0;snapToSupported=!0;isDrawingAnnotation=!0;onMouseMove(e){const{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){const{point:t,view:i}=e;if(0===this.clicks){if(void 0===t)return eT(e),!1;t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis)}this.applyToPoints(t),this.clicks++,this.clicks===this.maxClicks&&void 0!==this.annotation?(this.annotation.drawn=!1,this.annotation.requestRedraw(),"function"==typeof this.annotation.updateOtherPoints&&this.annotation.updateOtherPoints(i.mainContext),JS(this.annotation,!0,E.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}}class JA{snapToSupported=!1;constructor(e,t){setTimeout(()=>this.finalize(e,t),10)}finalize(e,t){const i=e(t);t.pane.presenter.clearSelection(),i.drawn=!1,i.requestRedraw(),JS(i,!0,E.None)}}const QA=gs.MARKER_ARROW_ANGLE*Math.PI/180/2;function eS(e,t,i=gs.MARKER_ARROW_LENGTH){return new tS(e,t,i)}class tS{constructor(e,t,i=gs.MARKER_ARROW_LENGTH){this.vertex=t,this.arrowLen=i,this.p1=e[0],this.p2=e[1]}p1;p2;hitTest(e){const{anchor:t,p1:i,p2:s}=this.getArrowPoints();return yn([t,i],e,gs.HIT_TEST_TOLERANCE)||yn([t,s],e,gs.HIT_TEST_TOLERANCE)}draw(e){const{anchor:t,p1:i,p2:s}=this.getArrowPoints();Wn(e,t,i),Wn(e,t,s)}getArrowPoints(){const e=gn(this.p1,this.p2),t="start"===this.vertex?0:Math.PI,i=e-QA+t,s=e+QA+t,n="start"===this.vertex?this.p1:this.p2;return{anchor:n,p1:{x:this.arrowLen*Math.cos(i)+n.x,y:this.arrowLen*Math.sin(i)+n.y},p2:{x:this.arrowLen*Math.cos(s)+n.x,y:this.arrowLen*Math.sin(s)+n.y}}}}class iS{hitTest(){return!1}draw(){}}class sS extends mA{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[gs.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[gs.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[gs.AT_RATIO]}getElements(){const e=this.points[0].point,t=this.points[1].point,i=new pA(e,t,this.extend1,this.extend2,this.axis),s=[];return this.extend1&&s.push(new pA(i.p1,e,!0,!1,this.axis)),s.push(new pA(e,t,!1,!1,this.axis)),this.extend2&&s.push(new pA(t,i.p2,!1,!0,this.axis)),s}formatRatio(e,t){return` (${se(e/t,3)})`}formatPercDiff(e,t){const i=(t-e)/e*100;return` (${i>0?"+":""}${se(i,2)}%)`}formatPrice(e){return nd(this.axis,this.priceMap(e))}adornElements(e,t){if(!(this.showBarCount||this.showPrices||this.showPercentDiff||this.showRatio))return;const[i,s]=this.points,n=e[this.extend1?1:0].getAdornOffset(t);if(this.showBarCount){const e=mn(dn(i.point,s.point),n);Bn(t,this.getBarCount(i.time,s.time).toFixed(0),e,g.Right)}const r=this.showRatio?this.formatRatio(i.price,s.price):"",o=`${this.showPrices?this.formatPrice(i.price):""}${r}`.trim();""!==o&&Bn(t,o,mn(i.point,n),g.Right);const a=this.showPercentDiff?this.formatPercDiff(i.price,s.price):"",l=`${this.showPrices?this.formatPrice(s.price):""}${a}`.trim();""!==l&&Bn(t,l,mn(s.point,n),g.Right)}getMarkers(){const e=this.marker;if(!e||"none"===e.vertex)return[];const{vertex:t,kind:i}=e;return("both"===t?["start","end"]:[t]).map(e=>"arrow"===i?function(e,t){return eS(e.map(e=>e.point),t)}(this.points,e):(console.warn(`There is no marker of ${i} kind`),new iS))}}class nS extends mA{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[gs.AT_SHOW_TIMESTAMPS]}getElements(){return[new oA(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}}class rS extends mA{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new oA(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}}class oS extends mA{constructor(e,t,i){super(e,t),this.addPoints(2),ie(i)&&ie(i.points)&&i.points.forEach((e,t)=>this.points[t].update(e.price,e.time))}allPoints(){const[e,t]=this.points;return ie(e,e.point,t,t.point)?[e,this.axis.toAnnotationPoint(dn(e.point,t.point)),t]:gs.EMPTY_ARRAY}line2(){return this.traits[gs.AT_LINE_2]}use52WeekPrices(){return this.traits[gs.AT_USE_52WEEK_PRICES]}getElements(){const e=this.allPoints();return e===gs.EMPTY_ARRAY?gs.EMPTY_ARRAY:e.map(e=>new pA({x:-8192,y:e.point.y},{x:gs.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){ie(this.use52WeekPrices())&&(this.traits[gs.AT_USE_52WEEK_PRICES]=!1)}getStyleForElement(e,t){const i=this.line2();if(1!==t||!ie(i))return super.getStyleForElement(e,t);const s=ue(this.traits);return s.line=i,rr(s)}getPriceScaleAdornments(){const e=this.allPoints();if(!this.showPrices||e===gs.EMPTY_ARRAY)return super.getPriceScaleAdornments();const t=this.traits.line,i=e.map(e=>({price:e.price,color:t.color})),s=this.line2();return ie(s)&&(i[1].color=s.color),i}getFlipAnchorIndices(){return null}}class aS extends gA{helper;constructor(e,t,i){super(e,t),this.addPoints(i),this.helper=new aA(e)}get showTrendLine(){return this.traits[gs.AT_SHOW_TRENDLINE]}get hasAllPoints(){return ie(...this.points.map(e=>e.point))}get line2(){return this.traits[gs.AT_LINE_2]}get extendLeft(){return this.traits[gs.AT_EXTEND_LEFT]}get extendRight(){return this.traits[gs.AT_EXTEND_RIGHT]}get reverse(){return this.traits[gs.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[gs.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){const e=ue(this.traits);return e.line=this.line2,rr(e)}return super.getStyleForElement(e,t)}getKeyPoints(){const e=e=>e.map(e=>this.points[e]);return this.isExtended?e(this.reverse?[1,0,2]:[0,1,2]):e(this.reverse?[0,1,0]:[1,0,1])}getElements(){if(!this.hasAllPoints)return[];const[e,t,i]=this.getKeyPoints(),s=t.price-e.price,n=t.price/e.price,r=this.extendLeft,o=this.extendRight,a=this.leftPoint,l=this.rightPoint,c=(e,t,i=!1)=>{const s=new pA(e,t,!i&&r,!i&&o,this.axis);return s.isTrend=i,s},u=this.levelsRespectLogScale&&this.axis.scale===p.Logarithmic,h=this.getColoredElements(({value:e})=>{const t=i.price+s*e,r=i.price*Math.pow(n,e),o=u?r:t;this.helper.update(o,i.time);const h=this.helper.point.y;return c({x:a.x,y:h},{x:l.x,y:h})});return this.showTrendLine&&(h.push(c(e.point,t.point,!0)),this.isExtended&&h.push(c((this.reverse?e:t).point,i.point,!0))),h}getAdornPointAndAlign(e,t){const i=this.labels,s=(e,t,i)=>({pt:e,align:t,offset:i}),n=this.axis.pane.getBoundsWithoutScales();switch(i){case gs.AT_LABELS_LEFT:return this.extendLeft?s({x:n.x,y:e.anchor1.y},g.Left,t):super.getAdornPointAndAlign(e,t);default:case gs.AT_LABELS_RIGHT:return this.extendRight?s({x:n.x+n.width,y:e.anchor2.y},g.Right,-t):super.getAdornPointAndAlign(e,t);case gs.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,i)=>({ref:t,spacing:5,offsetY:-5,text:this.formatLevelPrice(i,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),i.lineTo(t.p2.x,e.p1.y),On(i,t.p2),i.lineTo(e.p1.x,t.p2.y)),i},this.getTextRef(),t)}getPriceScaleAdornments(){if(!this.pricesOnScale)return super.getPriceScaleAdornments();const e=this.getElements();if(0===e.length)return super.getPriceScaleAdornments();const t=this.traits.line.color;return this.factors.map((i,s)=>{const n=e[s++].p1,r=this.singleStyle?t:i.line.color;return{price:this.axis.toPrice(n.y),color:r}})}}class lS extends aS{constructor(e,t){super(e,t,2)}}class cS extends aS{constructor(e,t){super(e,t,3)}}const uS=(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),On(i,e.p2),On(i,t.p2)),i};class hS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[gs.AT_REVERSE]}getElements(){const[e,t]=this.getScreenPoints(),i=t.y-e.y;return this.getColoredElements(({value:s})=>{const n=this.reverse?e.y+s*i:t.y-s*i;return new pA(e,{x:t.x,y:n},!1,!0,this.axis)})}getTextRef(){const[e,t]=this.getScreenPoints(),i=t.y-e.y,[s,n]=[this.leftPoint,this.rightPoint];return(r,o,a)=>{const l=this.reverse?e.y+a*i:t.y-a*i;return{ref:new pA({x:s.x,y:l},{x:n.x,y:l},!1,!1,this.axis),spacing:5,offsetY:!0,text:a.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,uS,this.getTextRef(),t)}}class dS extends hS{constructor(e,t){super(e,t)}}class pS{constructor(e,t,i,s,n,r,o){this.center=e,this.rim=t,this.radius=i,this.startAngle=s,this.endAngle=n,this.antiClockwise=r,this.axis=o,null!==t&&(this.left={x:this.center.x-this.radius,y:this.center.y},this.right={x:this.center.x+this.radius,y:this.center.y})}left=null;right=null;scale=null;clip=null;style;get hasScale(){return null!==this.scale}get hasClip(){return null!==this.clip}get hasRim(){return null!==this.rim}applyScale(e){e.translate(this.center.x,this.center.y),e.scale(this.scale.x,this.scale.y),e.translate(-this.center.x,-this.center.y)}inverseScale(e){const t=new DOMPointReadOnly(e.x,e.y),i=this.axis.pane.presenter.view.mouseContext;i.save(),i.resetTransform(),this.applyScale(i);const s=i.getTransform().inverse();return i.restore(),s.transformPoint(t)}hitTest(e){let t=999;if(this.hasRim&&(this.center.y<this.rim.y&&e.y<=this.center.y||this.center.y>=this.rim.y&&e.y>=this.center.y))t=Math.min(pn(this.left,e),pn(this.right,e));else{const i=this.hasScale?this.inverseScale(e):e,{x:s,y:n}=fn(i,this.center);if(!this.hasRim){const{startAngle:e,endAngle:t,antiClockwise:i}=this,r=Math.PI/2;if(0===e&&t===r&&!i&&(s<0||n<0))return!1;if(e===r&&t===Math.PI&&!i&&(s>0||n<0))return!1;if(e===-r&&t===Math.PI&&i&&(s>0||n>0))return!1;if(0===e&&t===-r&&i&&(s<0||n>0))return!1}t=Math.abs(Math.sqrt(s*s+n*n)-this.radius)}return t<=gs.HIT_TEST_TOLERANCE}get isAntiClockwise(){return this.hasRim?this.rim.y<=this.center.y:this.antiClockwise}draw(e){e.save(),this.hasClip&&e.clip(this.clip),this.hasScale&&this.applyScale(e),kn(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}}const fS=(e,t)=>{const i=new Path2D,{center:s}=t;if(Dn(i,s),i.arc(s.x,s.y,t.radius,t.startAngle,t.endAngle,t.isAntiClockwise??!1),null===e)return i;const n=new Path2D,{center:r}=e;return Dn(n,r),n.arc(r.x,r.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),i.addPath(n),i};class mS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){const[e,t]=this.getScreenPoints();if(!ie(e,t))return[];const i=pn(e,t),s=fn(t,e),n=s.y/i,r=s.x/i,o=this.getColoredElements(({value:t})=>{const s=i*t,o=n*s,a=r*s,l={x:e.x+a,y:e.y+o};return function(e,t,i){const s=pn(e,t);return new pS(e,t,s,0,Math.PI,null,i)}(e,l,this.axis)});if(this.showTrendLine){const i=new pA(e,t,!1,!1,this.axis);i.isTrend=!0,o.unshift(i)}return o}get showTrendLine(){return!0}getTextRef(){return(e,t,i)=>{const{center:s}=t,n=t.isAntiClockwise?-1:1;return{ref:{x:s.x,y:s.y+n*t.radius},spacing:0,offsetY:!0,text:i.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,fS,this.getTextRef(),t)}}class gS extends mS{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=ue(this.traits);return e.line=this.line2,rr(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[gs.AT_SHOW_TRENDLINE]}get line2(){return this.traits[gs.AT_LINE_2]}}class yS extends gA{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return gs.AT_ANGLES}getElements(){const[e,t]=this.getScreenPoints(),{x:i,y:s}=fn(t,e);return this.getColoredElements(({value:n})=>{const r=(t,i)=>new pA(e,{x:t,y:i},!1,!0,this.axis),o="1"!==n.charAt(0),a=Number(o?n.charAt(0):n.charAt(2));return o?r(t.x,e.y+s/a):r(e.x+i/a,t.y)})}getTextRef(){return(e,t,i)=>({ref:t.anchor2,spacing:0,offsetY:!0,text:i.toString()})}adornElements(e,t){this.adornElementsForColoredFactors(e,uS,this.getTextRef(),t)}}class AS extends hS{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}getElements(){const[e,t]=this.getScreenPoints();return[new pA(e,t,!1,!1,this.axis)].concat(super.getElements())}}class SS extends mS{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}}class TS extends mA{constructor(e,t){super(e,t),this.addPoints(3)}getElements(){const e=this.points[0].point,t=this.points[1].point,i=this.points[2].point,s=(t.x+i.x)/2-e.x,n=(t.y+i.y)/2-e.y,r=[];return r.push(new pA(t,{x:t.x+s,y:t.y+n},!1,!0,this.axis)),r.push(new pA(e,{x:e.x+s,y:e.y+n},!1,!0,this.axis)),r.push(new pA(i,{x:i.x+s,y:i.y+n},!1,!0,this.axis)),r.push(new pA(t,i,!1,!1,this.axis)),r}}class vS extends vA{constructor(e,t){super(e,t)}getEllipse(){const e=this.getRect();return null===e?null:new In(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.visible)return!1;const t=this.getEllipse();return null!==t&&t.contains(e)}draw(e,t){return!!super.draw(e,t)&&(i=e,s=this.getEllipse(),i.beginPath(),i.ellipse(s.cx,s.cy,s.radiusX,s.radiusY,0,0,2*Math.PI),i.stroke(),i.fill(),!0);var i,s}}class PS extends mA{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}getLastPoint(){const[e,t,i]=this.points;var s=pn(e.point,t.point),n=gn(e.point,t.point);return{x:i.point.x+s*Math.cos(n),y:i.point.y+s*Math.sin(n)}}getElements(){const[e,t,i]=this.points;var s=[];if(s.push(new pA(e.point,t.point,this.extend1,this.extend2,this.axis)),ie(i?.price)){var n=this.getLastPoint();s.push(new pA(i.point,n,this.extend1,this.extend2,this.axis))}return s}}class CS extends vA{constructor(e,t,i){super(e,t),this.kind=i,this.adjustFill=!0}hitTest(e){if(!this.visible)return!1;const t=this.getRect();return null!==t&&t.contains(e)}get dimension(){const e="fish_hook"===this.kind?2:1;return gs.DEFAULT_SYMBOL_WIDTH_HEIGHT*e}updateOtherPoints(){this.points[1].price||this.setBottomRight()}setBottomRight(){const e=this.dimension,t=this.axis.pane.presenter.timeline,{price:i,time:s}=this.points[0],n=G(t,s,Number,ud);if(-1!==n){const s=this.axis.pane.presenter.view.xAxis.xScale.bar.totalWidth;let r=1;for(;(2*r+1)*s<e;)r++;this.points[0].update(i,t.at(n-r)),this.points[1].update(i,t.at(n+r));const o=mn(this.points[0].point,{x:0,y:-e/2}),a=mn(this.points[1].point,{x:0,y:e/2});this.points[0].updateFromPoint(o),this.points[1].updateFromPoint(a)}}draw(e,t){if(!super.draw(e,t))return!1;const i=this.getRect();return 0===i.width&&(i.width=this.dimension),Gn(e,this.kind,i),!0}}class bS extends gA{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new aA(e)}getElements(){const e=this.axis.pane.presenter.timeline,{price:t,time:i}=this.points[0],s=G(e,i,Number,ud),n=G(e,this.points[1].time,Number,ud),r=n-s;if(-1===s||-1===n)return[];return this.getColoredElements(({value:i})=>{const n=e.at(s+i*r);return null===n?null:(this.helper.update(t,n),new oA(this.helper.point,!0,this.axis))})}getTextRef(){return(e,t,i)=>({ref:t.anchor,spacing:3,offsetY:!0,text:i.toString()})}adornElements(e,t){const i=this.axis.pane.getBoundsWithoutScales();this.adornElementsForColoredFactors(e,(e,t)=>{const s=new Path2D;if(null===e)return s;const n=t.anchor.x-e.anchor.x;return s.rect(e.anchor.x,i.y,n,i.height),s},this.getTextRef(),t)}getTimeScaleAdornments(){const e=e=>({time:this.points[e].time,color:this.traits.line.color});return[e(0),e(1)]}}class ES{snapToSupported=!0;isDrawingAnnotation=!0;constructor(){}onMouseMove(e){const{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){if(q()&&e.originalEvent instanceof TouchEvent)return;const{point:t}=e,i=t.axis.pane.presenter,s={chart:i.accessor,axis:t.axis,point:{time:t.time.getTime(),price:t.price}};i.notifyHost(qa.CH_ANNPOINTPICKED,s),ZS(i,void 0)}}const LS="Open",MS="Closed";class _S extends mA{constructor(e,t,i){super(e,t),this.isLong=i,this.addPoints(4);const s=(e,t)=>this.points[e].moveDirection=t;s(1,T.Vertical),s(2,T.Vertical),s(3,T.Horizontal),this.twoDecMeta=new Qs(2)}twoDecMeta;_dataWindow;_metaData;isHit=!1;data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}getDataWindow(e,t,i=!0,s=!0){const n=this.data(Ka.DateTime),r=G(n,+e,Number),o=G(n,+t,Number),a={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[l,c,u]=[Ka.High,Ka.Low,Ka.Close].map(e=>this.data(e)),h=e=>e-r;for(let d=r;d<=o;d++)i&&-1===a.refIndex&&ie(this.entryPrice)&&this.entryPrice>=c[d]&&this.entryPrice<=l[d]&&(a.refIndex=h(d)),(!i||a.refIndex>=0&&h(d)>=a.refIndex)&&((!ie(a.highest)||l[d]>a.highest)&&(a.highest=l[d]),(!ie(a.lowest)||c[d]<a.lowest)&&(a.lowest=c[d])),i&&-1!==a.refIndex&&(-1===a.highestIndex&&l[d]>this.upperPrice&&(a.highestIndex=h(d)),-1===a.lowestIndex&&c[d]<this.lowerPrice&&(a.lowestIndex=h(d))),s&&a.data.push({high:l[d],low:c[d],close:u[d],time:n[d]});if(s&&a.data&&a.data.length>0){a.state=ie(a.highest,a.lowest)&&(this.upperPrice<a.highest||this.lowerPrice>a.lowest)?MS:LS,a.special=-1===a.highestIndex&&-1===a.lowestIndex||a.highestIndex===a.lowestIndex;const e=k(a.data);if(a.toPrice=e.close,a.toTime=e.time,a.state===MS)if(a.special){if(-1!==a.refIndex){const e=a.data[a.refIndex];a.toTime=e.time;const t=this.isLong?this.lowerPrice<a.lowest:this.upperPrice<a.highest;a.toPrice=t?this.upperPrice:this.lowerPrice}}else{const e=-1!==a.highestIndex&&-1!==a.lowestIndex;e&&a.highestIndex<a.lowestIndex||-1===a.lowestIndex?(a.toPrice=this.upperPrice,a.toTime=a.data[a.highestIndex].time):(e&&a.lowestIndex<a.highestIndex||-1===a.highestIndex)&&(a.toPrice=this.lowerPrice,a.toTime=a.data[a.lowestIndex].time)}const t=this.isLong?a.toPrice-this.entryPrice:this.entryPrice-a.toPrice;a.pAndL=se(t,2)}return a}get dataWindow(){return ie(this._dataWindow)||(this._dataWindow=this.getDataWindow(this.entryAnchor.time,this.exitAnchor.time)),this._dataWindow}getVisiblePriceRange(){const e=this.axis.yScale.domain();return e[1]-e[0]}getFutureTimestamp(){const e=this.axis.pane.presenter.timeline,t=G(e,+this.points[0].time,Number,ud),i=Math.min(e.length-1,t+50);return e.at(i).getTime()}get entryPrice(){return this.entryAnchor.price}get entryAnchor(){return this.points[0]}get upperPrice(){return this.upperAnchor.price}get upperAnchor(){return this.points[1]}get lowerPrice(){return this.lowerAnchor.price}get lowerAnchor(){return this.points[2]}get exitAnchor(){return this.points[3]}get accountSize(){return this.traits[gs.AT_ACCOUNT_SIZE]}get risk(){const e=this.traits[gs.AT_RISK_IS_PERCENT],t=this.traits[gs.AT_RISK];return se(e?t/100*this.accountSize:t,2)}get pointValue(){return this._metaData||(this._metaData=this.presenter.mainPlot.metaData),this._metaData.pointValue}formatDollarValue(e){if(!Number.isFinite(e))return gs.NOT_APPLICABLE;return`${e<0?"-":""}$${this.twoDecMeta.format(Math.abs(e))}`}get qty(){return Math.floor(this.risk/(this.isLong?this.entryPrice-this.lowerPrice:this.upperPrice-this.entryPrice))}get upperDiff(){return se(this.upperPrice-this.entryPrice,2)}get amountMultiplier(){return this.isLong?1:-1}get upperAmount(){return se(this.accountSize+this.amountMultiplier*this.qty*this.upperDiff,2)}get upperPandL(){return se(this.amountMultiplier*this.upperDiff*this.pointValue,2)}get isCompact(){return this.traits[gs.AT_COMPACT]}get upper(){const e=nd(this.axis,this.priceMap(this.upperPrice)),t=`(${se(this.upperDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get upperText(){const e=`${this.formatDollarValue(this.upperPandL)}`,t=`${this.formatDollarValue(this.upperAmount)}`,i=this.isLong?"Target":"Stop";return this.isCompact?`${this.upper} ${e}`:`${i}: ${this.upper}, P&L: ${e}, Amount: ${t}`}get lowerDiff(){return se(this.entryPrice-this.lowerPrice,2)}get lowerAmount(){return se(this.accountSize-this.amountMultiplier*this.qty*this.lowerDiff,2)}get lowerPandL(){return se(-this.amountMultiplier*this.lowerDiff*this.pointValue,2)}get lower(){const e=nd(this.axis,this.priceMap(this.lowerPrice)),t=`(${se(this.lowerDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get lowerText(){const e=`${this.formatDollarValue(this.lowerPandL)}`,t=`${this.formatDollarValue(this.lowerAmount)}`,i=this.isLong?"Stop":"Target";return this.isCompact?`${this.lower} ${e}`:`${i}: ${this.lower}, P&L: ${e}, Amount: ${t}`}get riskReward(){return se(this.isLong?this.upperDiff/this.lowerDiff:this.lowerDiff/this.upperDiff,2)}get state(){return this.dataWindow.state}get pAndL(){return this.dataWindow.pAndL}get pAndLValue(){return this.pAndL*this.pointValue}positionPoints(){const e=this.getVisiblePriceRange()/5,t=this.getFutureTimestamp();this.upperAnchor.update(this.entryPrice+e,this.entryAnchor.time),this.lowerAnchor.update(this.entryPrice-e,this.entryAnchor.time),this.exitAnchor.update(this.entryPrice,t)}get lowerStyle(){return this.fillOnlyStyle(gs.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get textStyle(){return this.fillOnlyStyle(gs.AT_FILL_TEXT)}get secondaryLineStyle(){return rr({line:{color:this.traits.line.color,dashStyle:"ShortDash"},fill:{color:gs.COLOR_TRANSPARENT}})}wasModifiedByTool(){ie(this.points[2].price)||this.positionPoints(),this._dataWindow=void 0}wasPointMovedByTool(e,t){const i=this.getVisiblePriceRange()/5e3;if(this.points.indexOf(e)<3){const t=t=>e.update(t,e.time);this.entryAnchor.price>this.upperAnchor.price&&(e===this.entryAnchor?t(this.upperAnchor.price-i):t(this.entryAnchor.price+i)),this.entryAnchor.price<this.lowerAnchor.price&&(e===this.entryAnchor?t(this.lowerAnchor.price+i):t(this.entryAnchor.price-i))}if(e===this.entryAnchor){const t=(t,i,s)=>t.update(i?e.price:t.price,s?e.time:t.time);t(this.exitAnchor,!0,!1),t(this.upperAnchor,!1,!0),t(this.lowerAnchor,!1,!0)}this.wasModifiedByTool()}get isUpperPerPAndL(){const e=this.dataWindow;return this.isLong?e.pAndL>0:e.pAndL<=0}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){const e=new pA(this.entryAnchor.point,this.exitAnchor.point,!1,!1,this.axis),t=this.exitAnchor.point.x<this.entryAnchor.point.x,i=Math.abs(this.exitAnchor.point.x-this.entryAnchor.point.x),s=(e,t)=>({x:e.x+t,y:e.y}),n=new fA(s(this.upperAnchor.point,t?-i:0),i,Math.abs(this.upperAnchor.point.y-this.entryAnchor.point.y),this.axis);n.style=this.upperStyle;const r=new fA(s(this.entryAnchor.point,t?-i:0),i,Math.abs(this.entryAnchor.point.y-this.lowerAnchor.point.y),this.axis);r.style=this.lowerStyle;const o=[e,n,r],a=this.dataWindow;if(-1!==a.refIndex){const e=a.data[a.refIndex],t=new aA(this.axis,this.entryPrice,e.time),i=new aA(this.axis,a.toPrice,a.toTime),s=new pA(t.point,i.point,!1,!1,this.axis);if(s.style=this.secondaryLineStyle,o.push(s),t.time!==i.time){const e=this.entryPrice<a.toPrice,s=new fA({x:t.point.x,y:Math.min(t.point.y,i.point.y)},i.point.x-t.point.x,Math.abs(i.point.y-t.point.y),this.axis);s.style=e?this.upperStyle:this.lowerStyle,o.push(s)}}return o}hitTest(e){if(!this.visible)return!1;const t=this.isHit||!1;return this.isHit=super.hitTest(e),this.isHit!==t&&this.requestRedraw(),this.isHit}get showTextAdornments(){return this.isHit||this.isSelected}getPriceScaleAdornments(){const e=e=>Sn(this.traits[e].color);return[{price:this.upperPrice,color:e(gs.AT_FILL)},{price:this.entryPrice,color:e(gs.AT_LINE)},{price:this.lowerPrice,color:e(gs.AT_FILL2)}]}adornElements(e,t){const[i,s,n]=e;if(this.showTextAdornments){const[e,r]=[!0,!1].map(e=>Nn(t,e)),{x:o,y:a,width:l}=s.rect,c={x:o+l/2,y:a+e},u=this.textStyle.fillStyle;Bn(t,this.upperText,c,g.Center,u,Sn(this.upperStyle.fillStyle));const{x:h,y:d,width:p,height:f}=n.rect,m={x:h+p/2,y:d+f+Math.abs(r)};Bn(t,this.lowerText,m,g.Center,u,Sn(this.lowerStyle.fillStyle));const{p1:y,p2:A}=i,{x:S,y:T}=y,{x:v}=A,P=this.state||gs.NOT_APPLICABLE,C=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${P} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.qty}`,b=this.isCompact?`${this.riskReward.toFixed(2)}`:`Risk/Reward Ratio: ${this.riskReward.toFixed(2)}`,E=e=>t.measureText(e).width,L=Math.max(E(C),E(b)),M={x:S+(v-S)/2,y:Math.abs(v-S)<1.25*L?T+Math.abs(r)+5:T+e+10},_=Sn(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);Bn(t,[C,b],M,g.Center,u,_)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}}class xS extends yA{markers;display=null;constructor(e,t){super(e,t),this.points=TA(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new iS]}isPointDrawn(e){return!!super.isPointDrawn(e)&&e.visible}makeLineArrow(e,t,i,s){const n=[dn(e,t),dn(i,s)];return[this.makeLine(n[0],n[1]),eS(n,"end",10)]}get rectColor(){return this.traits[gs.AT_FILL].color}get textColor(){return this.traits[gs.AT_FILL_TEXT].color}getMarkers(){return this.markers}formatDateDifference(e,t){if(this.presenter.data.aggregation.isEndOfDay)return`${pt(t,e)}d`;const i=function(e,t){var i,s,n,r,o;if(arguments.length<1)throw new TypeError("1 argument required, but only ".concat(arguments.length," present"));var a=tt(),l=null!==(i=null!==(s=null==t?void 0:t.locale)&&void 0!==s?s:a.locale)&&void 0!==i?i:pi,c=null!==(n=null==t?void 0:t.format)&&void 0!==n?n:Ti,u=null!==(r=null==t?void 0:t.zero)&&void 0!==r&&r,h=null!==(o=null==t?void 0:t.delimiter)&&void 0!==o?o:" ";return l.formatDistance?c.reduce(function(t,i){var s="x".concat(i.replace(/(^.)/,function(e){return e.toUpperCase()})),n=e[i];return"number"==typeof n&&(u||e[i])?t.concat(l.formatDistance(s,n)):t},[]).join(h):""}(Ci({start:e,end:t}),{format:["days","hours","minutes","seconds"]});return i.replaceAll(/(days?)|(hours?)|(minutes?)|(seconds?)/g,e=>e[0])}computeState(){}get text(){return null===this.display&&this.computeState(),this.display}getTextCoord(e,t){const i=this.points[0].price<this.points[1].price,s=Nn(t,i,this.text.length),{x:n,y:r,width:o,height:a}=e.rect;return{x:n+o/2,y:r+(i?0:a)+(i?s:Math.abs(s))}}adornElements(e,t){Bn(t,this.text,this.getTextCoord(e[0],t),g.Center,this.textColor,Sn(this.rectColor))}getDateDifference(){const[e,t]=this.points.slice(0,2).map(e=>e.time),i=Math.min(+e,+t),s=Math.max(+e,+t),n=this.data(Ka.DateTime),r=G(n,+i,Number),o=G(n,+s,Number),a=O(this.data(Ka.Volume).slice(r,o+1)),l=this.formatter.format(a,Ka.Volume),c=o-r,u=e<t?"":"-";return[`${u}${c} bars, ${u}${0===c?"":this.formatDateDifference(i,s)}`,`Vol ${l}`]}getPriceDifference(){const[e,t]=this.points.slice(0,2).map(e=>e.price),i=t-e,s=i/e;return[`${this.formatter.format(i,Ka.Close)} (${this.formatter.format(s,Ka.PercentChange)})`]}resetComputedState(){this.display=null}getFlipAnchorIndices(){return[0,1]}}class IS extends xS{getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),n=this.makeLine(e,s),r=this.makeLine(t,i),[o,a]=this.makeLineArrow(e,s,t,i);return this.markers[0]=a,[this.rect,n,r,o]}computeState(){this.display=this.getDateDifference()}}class DS extends xS{getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),n=this.makeLine(e,i),r=this.makeLine(t,s),[o,a]=this.makeLineArrow(e,i,t,s);return this.markers[0]=a,[this.rect,n,r,o]}computeState(){this.display=this.getPriceDifference()}}class OS extends xS{get drawBorder(){return this.traits[gs.AT_DRAW_BORDER]}getBorderElements(){if(!this.drawBorder)return[];const[e,t,i,s]=this.getScreenPoints();return[this.makeLine(e,s),this.makeLine(t,i),this.makeLine(e,i),this.makeLine(t,s)]}getElements(){this.points.slice(2).forEach(e=>e.toPoint());const[e,t,i,s]=this.getScreenPoints(),[n,r]=this.makeLineArrow(e,s,t,i),[o,a]=this.makeLineArrow(e,i,t,s);this.markers=[r,a];const l=this.getBorderElements();return[this.rect,n,o].concat(l)}computeState(){this.display=this.getPriceDifference().concat(this.getDateDifference())}}class wS extends yA{constructor(e,t){super(e,t),this.points=TA(e)}get priceLevels(){return Jn(this.traits[gs.AT_PRICE_LEVELS])}get timeLevels(){return Jn(this.traits[gs.AT_TIME_LEVELS])}get showAngles(){return this.traits[gs.AT_SHOW_ANGLES]}get reverse(){return this.traits[gs.AT_REVERSE]}get showLeftLabels(){return this.traits[gs.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[gs.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[gs.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[gs.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){const i=this.getScreenPoints(),s=this.lineOnlyStyle(gs.AT_LINE_2),n=[];e.concat(t).flatMap(e=>[e.p1,e.p2]).map(e=>{n.some(t=>{return s=t,(i=e).x===s.x&&i.y===s.y;var i,s})||n.push(e)});const r=i.map(e=>n.filter(t=>{return s=e,!((i=t).x===s.x||i.y===s.y);var i,s}).map(t=>this.makeLine(e,t))).flat();return r.forEach(e=>e.style=s),r}getElements(){const e=this.getLinesDataAtLevels(this.priceLevels,this.timeLevels),{priceLines:t,timeLines:i}=this.getLineElements(e),s=this.showAngles?this.getAngles(t,i):[];return[...t,...i,...s]}adornElements(e,t){const i=this.singleStyle,s=this.showBackground,n=t.fillStyle,r=Rn(t,1)/2,{x:o,y:a}=gs.DEFAULT_ADORN_OFFSET,l=(e,i,s,n,r)=>{const o=mn(e,i);Bn(t,Number(s.toFixed(4)).toString(),o,n,r)},c=(e,i)=>{const s=new Path2D;wn(s,e.p1,i.p2),t.fillStyle=i.style.fillStyle,t.fill(s)};let u=null;if(e.forEach(e=>{if(!e._data)return;const{level:t,isPrice:h}=e._data,d=i?n:e.style.strokeStyle,p=u&&s&&!i;h?(this.showLeftLabels&&l(e.p1,{x:o,y:r},t,g.Right,d),this.showRightLabels&&l(e.p2,{x:-o,y:r},t,g.Left,d),p&&c(u,e)):(this.showTopLabels&&l(e.p1,{x:0,y:a},t,g.Center,d),this.showBottomLabels&&l(e.p2,{x:0,y:2*-a},t,g.Center,d),p&&c(u,e)),u=e}),i&&s){const e=this.applyBackgroundOpacity(this.traits.line.color),i=new Path2D,[s,n]=this.getScreenPoints();wn(i,s,n),t.fillStyle=e,t.fill(i)}}resetComputedState(){this.lines=void 0}updateFrom(e,t,i,s,n){const r=e.reverse!==this.reverse;super.updateFrom(e,t,i,s,n),r&&this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}}const RS=e=>e.map(e=>({...e,dimensions:e.value.split("x").map(Number)})),NS=(e,t)=>Math.abs(e-t)<1e-7;class VS extends yA{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=TA(e),this._parsedFans=this._parsedArcs=null}get levels(){return Jn(this.traits[gs.AT_LEVELS])}setComputedAndTraits(e,t){const i={...e,computed:t,traits:this.getTraitsFor(e)};return delete i.line,i}get computedLevels(){return this.levels.map(e=>this.setComputedAndTraits(e,e.value/5))}get showRangesRatio(){return this.traits[gs.AT_SHOW_RANGES_RATIO]}get arcs(){return Jn(this.traits[gs.AT_ARCS])}get fans(){return Jn(this.traits[gs.AT_FANS])}get reverse(){return this.traits[gs.AT_REVERSE]}get parsedFans(){return null===this._parsedFans&&(this._parsedFans=RS(this.fans)),this._parsedFans}get computedFans(){const[,,e,t]=this.getReversedScreenPoints(),{dx:i,dy:s}=this.unit,{signX:n,signY:r}=this.getOrientation();return this.parsedFans.map(o=>{const[a,l]=o.dimensions;return this.setComputedAndTraits(o,a>=l?{x:e.x,y:e.y+l/a*r*5*s}:{x:t.x+a/l*5*n*i,y:t.y})})}get parsedArcs(){return null===this._parsedArcs&&(this._parsedArcs=RS(this.arcs)),this._parsedArcs}get computedArcs(){const{dx:e}=this.unit;return this.parsedArcs.map(t=>{const[i,s]=t.dimensions;return this.setComputedAndTraits(t,Math.sqrt(e**2*(i**2+s**2)))})}getReversedScreenPoints(){const[e,t,i,s]=this.getScreenPoints();return this.reverse?[t,e,s,i]:[e,t,i,s]}get unit(){const[e,t]=this.getReversedScreenPoints();return e.x!==t.x&&e.y!==t.y?{dx:Math.abs(t.x-e.x)/5,dy:Math.abs(t.y-e.y)/5}:null}get priceBarRatio(){return this.traits[gs.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[gs.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,i){const s=this.makeLine(e,t);return this.singleStyle||(s.style=rr(i)),s}getGridLines(e,t){const i=t.x-e.x,s=t.y-e.y;return this.computedLevels.map(({computed:n,traits:r})=>{const o=e.x+n*i,a=e.y+n*s;return[this.makeStyledLine({x:o,y:e.y},{x:o,y:t.y},r),this.makeStyledLine({x:e.x,y:a},{x:t.x,y:a},r)]}).flat()}getArcs(e){const{flipX:t,flipY:i,signY:s}=this.getOrientation(),{dx:n,dy:r}=this.unit,o=NS(n,r)?null:{x:1,y:r/n},a=this.getClipPath();return this.computedArcs.map(({computed:n,traits:r})=>{const l=function(e,t,i,s,n,r){return new pS(e,null,t,i,s,n,r)}(e,n,t?s*Math.PI/2:0,t?Math.PI:s*Math.PI/2,i,this.axis);return null!==o&&(l.scale=o),l.clip=a,this.singleStyle||(l.style=rr(r)),l})}getFans(e){return this.computedFans.map(({computed:t,traits:i})=>this.makeStyledLine(e,t,i))}getElements(){if(null===this.unit)return[];const[e,t]=this.getReversedScreenPoints();return[...this.getGridLines(e,t),...this.getArcs(e),...this.getFans(e)]}getOrientation(){const[e,t]=this.getReversedScreenPoints(),i=t.x<e.x,s=t.y<e.y;return{flipX:i,signX:i?-1:1,flipY:s,signY:s?-1:1}}getClipPath(){const[e,t]=this.getReversedScreenPoints(),i=new Path2D;return wn(i,e,t),i}adornElements(e,t){if(0===e.length)return;const i=(e,i,s)=>{t.fillStyle=s;const n=i.hasScale;n&&(t.save(),i.applyScale(t)),t.fill(e),n&&t.restore()};if(this.showBackground){const s=e.filter(e=>e.radius),n=this.getClipPath();if(t.save(),t.clip(n),this.singleStyle){const e=k(s),t=fS(null,e),n=this.applyBackgroundOpacity(this.traits.line.color);i(t,e,n)}else{let e=null;s.forEach(t=>{const s=fS(e,t),n=t.style.fillStyle;i(s,t,n),e=t})}t.restore()}if(this.showRangesRatio&&null!==this.unit){const e=k(this.computedLevels),i=(this.singleStyle?this:e).traits.line.color,[,s,n,r]=this.getReversedScreenPoints(),{x:o,y:a}=gs.DEFAULT_ADORN_OFFSET,{flipX:l,signX:c,signY:u}=this.getOrientation(),h=mn(n,{x:-o*c,y:a*u}),{priceDiff:d,barsDiff:p}=this.getLinesDataAtLevels(null,null),f=l?g.Right:g.Left;Bn(t,p.toFixed(0),h,f,i);const m=mn(r,{x:2*o*c,y:-a*u}),y=l?g.Left:g.Right;Bn(t,this.formatter.format(d,Ka.Close),m,y,i);const A=mn(s,{x:-o*c,y:-a*u});Bn(t,this.priceBarRatio.toFixed(6),A,f,i)}}resetComputedState(){if(this.lines=void 0,4===this.points.length&&null!==this.unit){const{priceDiff:e,barsDiff:t}=this.getLinesDataAtLevels(null,null);this.priceBarRatio=Math.abs(e/t)}}updateFrom(e,t,i,s,n){if(super.updateFrom(e,t,i,s,n),this._parsedFans=this._parsedArcs=null,!NS(e.priceBarRatio,this.priceBarRatio)){let[t,i,,]=this.points;this.reverse&&([t,i]=[i,t]);const{priceDiff:s,barsDiff:n}=this.getLinesDataAtLevels(null,null);i.update(t.price+Math.sign(s)*e.priceBarRatio*n,i.time),this.resetComputedState()}}getFlipAnchorIndices(){return[0,1]}}const HS=(e,t)=>{const i=new Path2D;return null===e||(Dn(i,e.p1),On(i,e.p2),On(i,t.p2),On(i,t.p1)),i};class BS extends gA{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[gs.AT_EXTEND_PT_1]}get extend2(){return this.traits[gs.AT_EXTEND_PT_2]}getElements(){const[e,t,i]=this.getScreenPoints(),{x:s,y:n}=fn(i,e),r=i=>{const[s,n]=[e,t].map(e=>mn(e,i));return new pA(s,n,this.extend1,this.extend2,this.axis)};return this.getColoredElements(({value:e})=>r({x:s*e,y:n*e}))}getTextRef(){return(e,t,i)=>({ref:t,spacing:5,offsetY:!0,text:this.formatLevelPrice(i,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,HS,this.getTextRef(),t)}}class FS extends mA{levelSize=0;alignLeft=!0;totalVolume=!1;widthPercent=30;useChange=!1;studyPlotId;gotData;boxes=[];periodType="VisibleScreen";period=0;valueRangePercent=.7;levelMode="Count";usesFinerGrainedAgg=!0;constructor(e,t,i){super(e,t),this.computed=!0,this.studyPlotId=i,this.gotData=!1}setOptions(e){switch(this.levelMode=e.LevelMode,this.levelSize=Ce(1,1e3,e.LevelSize),this.alignLeft="Left"===e.Position,this.totalVolume="Total"===e.Volume,this.widthPercent=Ce(5,100,e.WidthPercent)/100,e.BarColoring){case"OpenToClose":this.useChange=!1;break;case"CloseToClose":this.useChange=!0;break;default:{const e=this.presenter.mainPlot?.mainCurve?.attributes;this.useChange=e?.includes(r.ChangeBased)??!1}}te(e.PeriodType)&&(this.periodType=e.PeriodType),this.period=e.Period,this.valueRangePercent=e.ValueRangePercent/100;const t=v[Gv()?.config.mode??"Unspecified"];this.usesFinerGrainedAgg=jr(t)}get isCountMode(){return"Count"===this.levelMode}updateLastBox(){if(this.boxes.length>0){const e=this.boxes.pop(),t=this.getDataForRange(e.firstDate,e.lastDate);t&&this.boxes.push(t)}}invalidate(e){switch(this.periodType){case"VisibleScreen":this.gotData=!1,this.boxes=[];break;case"Bars":case"Days":switch(e){case"DataPointAdded":{const e=this.studySeries.innCont(0),t=e?.getTimeData();if(!ie(t))return;const i=t[t.length-1],s=this.boxes.length>0?this.boxes[this.boxes.length-1]:null;if(te(s)&&i.valueOf()<s.lastDate.valueOf())this.updateLastBox();else{const e=this.getDataForRange(i,this.getBoxEndFromStart(i));e&&this.boxes.push(e)}break}case"DataPointChanged":this.updateLastBox();break;case"NewChunkArrived":this.gotData=!1}}}getBoxRect(e){switch(this.periodType){case"VisibleScreen":return this.axis.pane.getBoundsWithoutScales();case"Bars":case"Days":{const t=this.axis.pane.presenter.view.xAxis.xScale.bar,i=this.axis.toY(e.min),s=this.axis.toY(e.max),n=this.axis.pane.presenter.view.toX(e.firstDate)-t.width/2;let r=0;if("Days"===this.periodType){const i=e.lastDate,s=this.axis.pane.presenter.view.xAxis.xScale.timeline,o=s.at(s.lastSeriesIndex),a=o.valueOf()<i.valueOf(),l=a?o:i,c=(a?1:-2)*t.width/2;r=this.axis.pane.presenter.view.toX(l)+c-n}else r=this.period*t.width+(this.period-1)*t.spacing;return new xn(n,s,r,i-s)}default:throw new Error("Unexpected period type for Volume At Price annotation")}}getElementsForBox(e){const t=this.getBoxRect(e),i=[];if(this.isPeriodic){const e=new fA({x:t.x,y:t.y},t.width,t.height,this.axis);e.style=this.backgroundStyle,i.push(e)}const{x:s,width:n}=t,r=n*this.widthPercent,o=e.bars[e.maxVolumeIndex];return e.bars.forEach((t,a)=>{const{upVolume:l,downVolume:c,totalVolume:u,isValue:h}=t;if(0===l&&0===c)return null;const d=this.axis.toY(e.min+a*e.zone),p=this.axis.toY(e.min+(a+1)*e.zone),f=Math.abs(d-p),m=(e,t,i=0)=>{const r=this.alignLeft?s+i:s+n-e-i,o=new fA({x:r,y:p},e,f,this.axis);return o.style=t,o},g=(e,t,i)=>e/t.totalVolume*i,y=this.studyPlot.curves[2].visible,A=y&&h?this.upValueStyle:this.upStyle,S=y&&h?this.downValueStyle:this.downStyle,T=y&&h?this.totalValueStyle:this.totalStyle;if(this.totalVolume){const e=g(u,o,r);i.push(m(e,T))}else{const e=g(c,o,r),t=g(l,o,r);i.push(m(t,A),m(e,S,t))}if(this.studyPlot.curves[1].visible&&a===e.maxVolumeIndex){const e=i[i.length-1].rect,t=this.alignLeft?e.x+e.width:s,r=(p+d)/2,o=this.alignLeft?s+n:e.x;i.push(new pA({x:t,y:r},{x:o,y:r},!1,!1,this.axis))}}),i}get isVisible(){return this.studyPlot.visible&&this.studyPlot.mainCurve.visible}getElements(){if(this.gotData||this.getData(),!this.gotData||!this.isVisible)return[];if(0===this.boxes.length)return[];switch(this.periodType){case"VisibleScreen":{const e=this.boxes[0];return e&&0!==e.bars.length?this.getElementsForBox(e):[]}case"Bars":case"Days":{const[e,t]=this.presenter.view.xAxis.xScale.domain()||[];if(!ht(e)||!ht(t))return[];let i=this.boxes.findIndex(t=>t.firstDate.getTime()<=e.getTime()&&t.lastDate.getTime()>=e.getTime());-1===i&&(i=0,this.studySeries.loadMoreData());let s=this.boxes.findIndex(e=>e.firstDate.getTime()<=t.getTime()&&e.lastDate.getTime()>=t.getTime());-1===s&&-1!==i&&(s=this.boxes.length-1);const n=[];for(let r=i;r<=s;r++)n.push(...this.getElementsForBox(this.boxes[r]));return n}default:throw new Error("Unexpected period type for Volume At Price annotation")}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}get presenter(){return this.axis.pane.presenter}get downStyle(){return this.fillOnlyStyle(gs.AT_FILL)}get upStyle(){return this.fillOnlyStyle(gs.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(gs.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(gs.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(gs.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(gs.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(gs.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(gs.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case"VisibleScreen":default:return null;case"Days":return _t(gu(a.Day,this.period)(e),1);case"Bars":{const t=this.axis.pane.presenter.data.aggregation;return _t(gu(t.unit,t.size*this.period)(e),1)}}}getData(){const e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!dg(e.spec))return;const[t,i]=this.presenter.view.xAxis.xScale.domain()||[];if(!ht(t)||!ht(i))return;const s=gu(e.unit,e.size);switch(this.periodType){case"VisibleScreen":{const e=this.boxes[0];if(e&&e.firstDate===t&&e.lastDate===i)this.gotData=!0;else{const e=this.getDataForRange(t,i);e&&(this.boxes[0]=e)}break}case"Bars":{const[e,t]=[0,1].map(e=>this.studySeries.innCont(e));if((e?.size??0)<1||(t?.size??0)<1)return;const i=e.getTimeData();let n=0;for(this.boxes=[];n<i.length;){const e=i[n],t=n+this.period,r=_t(t<i.length?i[t]:s(i[i.length-1]),1),o=this.getDataForRange(e,r);o&&this.boxes.push(o),n+=this.period}this.gotData=!0;break}case"Days":{if(e.isEndOfDay)return this.boxes=[],void(this.gotData=!0);const[t,i]=[0,1].map(e=>this.studySeries.innCont(e));if((t?.size??0)<1||(i?.size??0)<1)return;const n=t.getTimeData(),r=t.getData(Ka.TradingDay),o=e=>{let t=0,i=n[e],s=r[e];for(let o=e;o<n.length;o++)if(rt(n[o],i)>0&&r[o]!==s&&(t+=1,i=n[o],s=r[o],t===this.period))return o;return-1};let a=0,l=n[a],c=o(a)-1;for(;(c<0||c===a)&&a<n.length;)a+=1,c=o(a)-1;for(this.boxes=[];a<n.length&&c<n.length&&a<c;){const e=_t(s(n[c]),1),t=this.getDataForRange(l,e);t&&this.boxes.push(t),a=c+1,l=n[a],c=o(a)-1}if(c<0&&a<n.length-1){const e=_t(s(n[n.length-1]),1),t=this.getDataForRange(n[a],e);t&&this.boxes.push(t)}this.gotData=!0;break}}}getBoxAt(e){if(0===this.boxes.length)return null;switch(this.periodType){case"VisibleScreen":{const t=this.boxes[0];return t.firstDate>e||t.lastDate<e?null:t}case"Bars":case"Days":{const t=e.getTime(),i=this.boxes.find(e=>e.firstDate.getTime()<=t&&e.lastDate.getTime()>=t);return i||null}}}getValueAt(e,t,i){if(!this.isVisible)return null;const s=this.getBoxAt(t);if(!s)return null;const n=this.getBarIndex(s,i);if(n<0||n>=s.bars.length)return null;const r=s.bars[n];switch(e){case Ka.UPVOL:return this.totalVolume?null:r.upVolume;case Ka.DNVOL:return this.totalVolume?null:r.downVolume;case Ka.TOTVOL:return this.totalVolume?r.totalVolume:null;case Ka.POC:case Ka.VAREA:case Ka.BARBACK:return null;default:throw new Error("Unexpected Volume At Price field")}}getBarIndex(e,t,i=!1){if(0===e.bars.length||0===e.zone)return-1;const s=Math.floor((t-e.min)/e.zone);return i?Math.min(e.bars.length-1,s):s}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}makeBox(e,t){return{min:Number.MAX_VALUE,max:Number.MIN_VALUE,zone:0,bars:[],maxVolumeIndex:-1,firstDate:e,lastDate:t}}findExtremes(e,t,i,s,n,r){const o=te(n)&&te(r);for(let a=t;a<=i;a++)if(o){const t=n[a];t>e.max&&(e.max=t);const i=r[a];i<e.min&&(e.min=i)}else{const t=s[a];t<e.min&&(e.min=t),t>e.max&&(e.max=t)}}findValueArea(e){if(-1===e.maxVolumeIndex||0===e.bars.length)return;e.bars[e.maxVolumeIndex].isValue=!0;const t=O(e.bars.map(e=>e.totalVolume))*this.valueRangePercent;let i=e.bars[e.maxVolumeIndex].totalVolume,s=e.maxVolumeIndex,n=e.maxVolumeIndex;for(;i<t;){const r=[{dir:"lower",count:2,startIdx:s-2,endIdx:s-1},{dir:"lower",count:1,startIdx:s-1,endIdx:s-1},{dir:"upper",count:2,startIdx:n+1,endIdx:n+2},{dir:"upper",count:1,startIdx:n+1,endIdx:n+1}].filter(t=>t.startIdx>=0&&t.endIdx<e.bars.length).map(t=>{const s=O(e.bars.slice(t.startIdx,t.endIdx+1).map(e=>e.totalVolume));return{...t,volume:s,newTotal:i+s}});if(0===r.length)break;const o=(e,t)=>t.newTotal<e.newTotal?t:e,a=(e,t)=>t.volume>e.volume?t:e,l=r.filter(e=>e.newTotal>=t),c=l.length>0?l.reduce(o):r.reduce(a);for(let t=c.startIdx;t<=c.endIdx;t++)e.bars[t].isValue=!0;if("lower"===c.dir?s=c.startIdx:n=c.endIdx,i=c.newTotal,i>=t)break}}tallyVolume(e,t,i,s,n,r,o){let a=Number.MIN_VALUE,l=!1;for(let c=t;c<=i;c++){const t=n[c],i=this.getBarIndex(e,t,!0);if(-1===i){l=!0;break}const u=o[c],h=this.useChange?r[c]>=0:s[c]<=n[c],d=e.bars[i];h?d.upVolume+=u:d.downVolume+=u,d.totalVolume=d.downVolume+d.upVolume,d.totalVolume>a&&(a=d.totalVolume,e.maxVolumeIndex=i)}l||this.findValueArea(e)}get isPeriodic(){return"Bars"===this.periodType||"Days"===this.periodType}get isVisibleScreen(){return"VisibleScreen"===this.periodType}getDataForRange(e,t){const i=this.makeBox(e,t),s=this.studySeries.innCont(1),n=s?.getTimeData();if(!ie(n))return null;const r=e=>G(n,+e,Number);let o=r(e),l=r(t);if(n[l].getTime()>t.getTime()&&(l-=1),o>l)return null;if(this.axis.pane.presenter.data.aggregation.unit===a.Day&&"Bars"===this.periodType){const e=s.getData(Ka.TradingDay);let t=e[o];for(;t===e[o]&&o>0;)o-=1;o+=1;let i=0;for(l=o;l<n.length&&i<this.period;)e[l]!==t&&(i+=1,t=e[l]),l+=1;l-=2}this.isVisibleScreen&&this.usesFinerGrainedAgg&&o<1e3&&this.studySeries.loadMoreData();const[c,u,h,d,p,f]=["Open","High","Low","Close","Change","Volume"].map(e=>{return t=Ka[e],s.getData(t);var t});this.findExtremes(i,o,l,d,u,h);const m=i.max-i.min,g=e=>({upVolume:0,downVolume:0,isValue:!1,totalVolume:0});if(this.isCountMode)i.zone=m/this.levelSize,i.bars=Y(this.levelSize,g);else{const e=(this.presenter.mainPlot?.metaData.minMovement??1)*this.levelSize,t=Math.max(1,Math.ceil(m/e));i.zone=m/t,i.bars=Y(t,g)}return this.tallyVolume(i,o,l,c,d,p,f),this.gotData=!0,i}}const kS=["None","Absolute","Percent"];class WS extends mA{studyPlotId;displayMode="None";visibleLabelSegments=[];constructor(e,t,i){super(e,t),this.studyPlotId=i}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}setOptions(e){const t=e.ReversalChange;var i;this.displayMode="string"==typeof(i=t)&&kS.includes(i)?t:"None"}formatSegmentValue(e,t){return"Absolute"===this.displayMode?this.formatter.format(t-e,Ka.Close):"Percent"===this.displayMode?0===e?"":this.formatter.format((t-e)/e,Ka.PercentChange):""}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.visible||!this.studyPlot.mainCurve.visible)return[];const e=this.studySeries.getCurrentState();if(!e)return[];const t=e.confirmedPivots,i=Array.from(t.keys()).sort((e,t)=>e-t);if(0===i.length)return[];const s=this.presenter.mainPlot?.timeSeries?.container;if(!s||s.size<2)return[];const n=s.getTimeData();if(!n)return[];const r=this.presenter.view,[o,a]=r.xAxis.xScale.domain()||[];if(!o||!a)return[];const l=o.getTime(),c=a.getTime();let u=-1,h=-1;for(let p=0;p<i.length;p++){const e=n[i[p]].getTime();if(-1===u&&e>=l&&(u=Math.max(0,p-1)),e<=c)h=p;else if(-1!==u)break}if(-1===u){if(i.length>0&&n[i[0]].getTime()>c)return[];u=i.length-1,h=i.length-1}else-1===h&&(h=u);h=Math.min(i.length-1,h+1);const d=[];for(let p=u;p<h;p++){const e=i[p],s=i[p+1],o=t.get(e),a=t.get(s),u=r.toX(n[e]),h=this.axis.toY(o),f=r.toX(n[s]),m=this.axis.toY(a);d.push(this.makeLine({x:u,y:h},{x:f,y:m}));const g=n[s].getTime();g>=l&&g<=c&&this.visibleLabelSegments.push({fromPrice:o,toPrice:a,toPoint:{x:f,y:m}})}if(ie(e.pivotPrice)&&ie(e.candPrice)){const t=n[e.pivotIndex].getTime();if(n[e.candIndex].getTime()>=l&&t<=c){const t=r.toX(n[e.pivotIndex]),i=this.axis.toY(e.pivotPrice),s=r.toX(n[e.candIndex]),o=this.axis.toY(e.candPrice);d.push(this.makeLine({x:t,y:i},{x:s,y:o}))}}return d}adornElements(e,t){if("None"===this.displayMode||0===this.visibleLabelSegments.length)return;const i=Math.abs(Nn(t,!0));this.visibleLabelSegments.forEach(e=>{const s=this.formatSegmentValue(e.fromPrice,e.toPrice);if(""===s)return;const n=e.toPrice>=e.fromPrice,r={x:e.toPoint.x,y:e.toPoint.y+(n?-i:i)};Bn(t,s,r,g.Right,n?"#16A34A":"#DC2626")})}}const US=[gs.AT_LINE,gs.AT_LINE_2,gs.AT_LINE_3];class $S extends mA{studyPlotId;constructor(e,t,i){super(e,t),this.studyPlotId=i}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}isCurveVisible(e){return this.studyPlot.curves[e]?.visible??!1}makeLines(){if(!this.studyPlot?.visible)return null;const e=this.studySeries.getCurrentState();if(!e||null===e.slope||null===e.intercept||null===e.stdDevWidth)return null;const{startIndex:t,endIndex:i,slope:s,intercept:n,stdDevWidth:r,extendLeft:o,extendRight:a}=e;if(null===t||null===i)return null;const l=this.presenter.mainPlot?.timeSeries?.container;if(!l||l.size<2)return null;const c=l.getTimeData();if(!c||c.length<=i)return null;const u=this.presenter.view,h=i-t+1,d=e=>n+s*(e+1),p=d(0),f=d(h-1),m=u.toX(c[t]),g=u.toX(c[i]),y=(e,t)=>{const i=this.axis.toY(p+e),s=this.axis.toY(f+e),n=new pA({x:m,y:i},{x:g,y:s},o,a,this.axis);return n._data={lineIndex:t},n};return[y(r,0),y(0,1),y(-r,2)]}getStyleForElement(e,t){const i=e._data?.lineIndex??t,s=US[i],n=this.traits[s];return n?rr({line:n,fill:{color:gs.COLOR_TRANSPARENT}}):super.getStyleForElement(e,t)}getElements(){const e=this.makeLines();return e?e.filter((e,t)=>this.isCurveVisible(t)):[]}adornElements(e,t){const i=this.makeLines();if(!i)return;if(!i.every(e=>ie(e.p1,e.p2)))return;const[s,n,r]=i,o=(e,i,s)=>{t.fillStyle=s,t.fill(HS(e,i))};this.isCurveVisible(3)&&o(s,n,this.traits?.[gs.AT_FILL]?.color),this.isCurveVisible(4)&&o(n,r,this.traits?.[gs.AT_FILL2]?.color)}}function GS(e){const t=e<0?-1:1,i=Math.abs(e)/Math.SQRT2,s=1/(1+.3275911*i);return.5*(1+t*(1-((((1.061405429*s-1.453152027)*s+1.421413741)*s-.284496736)*s+.254829592)*s*Math.exp(-i*i)))}class zS extends mA{studyPlotId;periodTarget=0;targetPrice1=0;targetPrice2=0;pricesCount=0;targetDate;computed=!1;anchorPrice=0;sigmaAnnualized=0;unitsPerYear=0;probabilityAbove=0;probabilityBelow=0;probabilityBetween=0;styles=[];constructor(e,t,i){super(e,t),this.studyPlotId=i}makeStyles(){const e=this.lineOnlyStyle(gs.AT_LINE),t=this.lineOnlyStyle(gs.AT_LINE_2);this.styles=[e,t,t]}containerOf(e){return e?.timeSeries.container}get mainCont(){return this.containerOf(this.presenter.mainPlot)}get studyCont(){return this.containerOf(this.studyPlot)}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get targetPrice(){return 0!==this.targetPrice1?this.targetPrice1:this.targetPrice2}setOptions(e){if(this.periodTarget=e.PeriodTarget,this.targetPrice1=e.TargetPrice1,this.targetPrice2=e.TargetPrice2,this.pricesCount=(0!==this.targetPrice1?1:0)+(0!==this.targetPrice2?1:0),this.pricesCount>1&&this.targetPrice1<this.targetPrice2){const e=this.targetPrice1;this.targetPrice1=this.targetPrice2,this.targetPrice2=e}}get haveInput(){return 0!==this.periodTarget&&(0!==this.targetPrice1||0!==this.targetPrice2)}get haveData(){return te(this.mainCont)&&!this.mainCont.isEmpty&&this.studySeries.haveVolatility}get studySeries(){return this.studyPlot.timeSeries}getData(){const e=this.presenter.timeline;this.targetDate=e.at(e.lastSeriesIndex+this.periodTarget),this.points=[new aA(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new aA(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=Ry(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(Ka.Close),this.sigmaAnnualized=this.studySeries.getVolatilityPercent()}computeProbabilities(){const e=this.sigmaAnnualized*Math.sqrt(this.periodTarget/this.unitsPerYear),t=t=>(t-this.anchorPrice)/(this.anchorPrice*e),i=GS(t(this.targetPrice));if(this.pricesCount>1){const e=GS(t(this.targetPrice2));this.probabilityAbove=1-i,this.probabilityBelow=e,this.probabilityBetween=i-e}else this.probabilityBelow=i,this.probabilityAbove=1-this.probabilityBelow;this.computed=!0}compute(){this.haveInput&&this.haveData&&(this.getData(),this.computeProbabilities())}getElements(){if(this.computed||this.compute(),!this.computed||!this.studyPlot.mainCurve.visible)return[];const e=[];return e.push(new oA(this.points[0].point,!0,this.axis)),e.push(new oA(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new oA(this.points[1].point,!1,this.axis)),e}getStyleForElement(e,t){return this.styles.length||this.makeStyles(),this.styles[t]}get hasPoint(){return this.points.length>0}getTimeScaleAdornments(){return this.hasPoint?[{time:this.points[0].time,color:this.traits.line.color}]:[]}getPriceScaleAdornments(){if(!this.hasPoint)return[];const e=[];return e.push({price:this.points[0].price,color:this.traits.line2.color}),this.pricesCount>1&&e.push({price:this.points[1].price,color:this.traits.line2.color}),e}adornElements(e,t){if(this.computed){const[e,i]=[!0,!1].map(e=>Math.abs(Nn(t,e))),s=this.pricesCount>1,n=this.points[0].point,r=s?this.points[1].point:n,o=this.traits.line2.color,a=Ln(o),l=Rn(t),c=["Above","Below","Between"],u=(e,t)=>`${se(100*e,2).toFixed(2)}% Probability ${c[t]}`,h=(e,i)=>Bn(t,e,i,g.Right,a,o);if(h(u(this.probabilityAbove,0),{x:n.x-10,y:n.y-e}),s){const e=n.y+(r.y-n.y+l)/2;h(u(this.probabilityBetween,2),{x:n.x-10,y:e})}h(u(this.probabilityBelow,1),{x:r.x-10,y:r.y+i})}}}const YS=new class{resizingPanes=!1;snapToSupported=!1;touchCrosshairMode=!1;notifyZoomChanged;previousTouchTimestamp=null;resizingScale=!1;resizingScaleId=null;lastScaleResizingOffset=null;touchCrosshairTimeout=null;lastResizingOffset=null;splitter;prevZoomingOffset;prevPinchDistance=null;constructor(){this.stopResizingScale(),this.notifyZoomChanged=Q(qa.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,i){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,i)}activated(){}deactivated(){}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return gs.EVENT_PIN_HIT;const t=e.presenter.selectedAnnotation;let i;void 0!==t&&(i=t.points.find(t=>t.hitTest(e.point)));let s=k(e.axis.annotations.filter(t=>t.computed?null:t.hitTest(e.point)));return void 0!==i&&null==s&&(s=t),[s,i]}stopResizingScale(){this.resizingScale=!1,this.resizingScaleId=null,this.lastScaleResizingOffset=null}resetVerticalAxis(e,t=!0){this.stopResizingScale(),e.isCustomDomain=!1,t&&e.setDomain()}resetHorizontalAxis(e,t=!0){e.view.xAxis.resetZoom(),t&&e.view.setPriceAxesDomains(),this.fireZoomChanged(e)}fireZoomChanged(e){this.notifyZoomChanged({chart:e.accessor})}onMouseDblClick({priceAxis:e,offset:t,presenter:i,view:s}){const n=s.xAxis.viewBox.contains(t);let r=!1;if(ie(e))this.resetVerticalAxis(e),r=!0;else if(n)this.resetHorizontalAxis(i),r=!0;else if(q()){const e=i.selectedAnnotation;null!=e?qA(e,t):XA(i,t)}r&&s.redraw()}onMouseEnter(){this.previousTouchTimestamp=null}computePreviousTouchStartDuration(){if(!q())return null;const e=/* @__PURE__ */(new Date).getTime(),t=ie(this.previousTouchTimestamp)?e-this.previousTouchTimestamp:null;return this.previousTouchTimestamp=e,t}onMouseDown(e){const{point:t,button:i,splitter:s,offset:n,priceAxis:r,presenter:o,originalEvent:a}=e,l=window.navigator.platform.toLowerCase().startsWith("mac"),c=l?S.Meta:S.Control,u=i===A.Right||l&&i===A.Left&&e.getModifier(S.Control);this.touchCrosshairMode&&ie(this.touchCrosshairTimeout)&&(clearTimeout(this.touchCrosshairTimeout),this.touchCrosshairTimeout=null);const h=this.computePreviousTouchStartDuration();if(ie(h)&&h<gs.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(n)&&o.notifyHost(qa.CH_LOGOCLICKED,{chart:o.accessor}),ie(t)&&o.allPlots.some(e=>e.tryHandleCustomEventClick(t.point)))return!0;if(ie(s))return this.resizingPanes=!0,this.lastResizingOffset=n,this.splitter=s,o.enableTooltip(!1),!0;if(ie(r)){return re(o.display.chart.zooming)[0]&&this.startAxisScaling(r,n),!0}if(null!=t){if(e.getModifier(c))return o.activeTool=new KA,o.activeTool.onMouseDown(e),!0;const[i,s]=this.findHit(t);if(o.clearSelection(),null!=i&&o.setSelection(i),null==i||i?.locked)return u?(this.hideCrosshairAndTooltips(o.view),null==i?XA(o,n,a):i?.locked&&qA(i,n),!0):!!this.touchCrosshairMode||(o.activeTool=new $A(t),o.activeTool.startPan(n),UA());const r=null!=s;if(u)return qA(i,n),q();{if(r&&!s.movable||!r&&!i.canMove(t.point))return!1;const e=r&&-1!==i.points.indexOf(s);return o.activeTool=e?new rA(i,s):new nA(i,t,n),q()}}return this.prevZoomingOffset=n,!1}onContextMenu(e){return!0}isLogoLink(e){const t=te(GA)&&GA.logoClickable?GA.rect:null;return ie(t)&&t.contains(e)}onMouseMove(e){const{point:t,splitter:i,priceAxis:s,view:n,presenter:r,offset:o}=e;if(ie(e.pinchZoom)&&e.pinchZoom&&ie(e.pinchDistance))return ie(this.prevPinchDistance)&&(e.delta=this.prevPinchDistance-e.pinchDistance,this.onWheel(e)),this.prevPinchDistance=e.pinchDistance,q();if(null!=i||this.resizingPanes)n.setCursor(y.ResizeVertical),this.resizingPanes&&this.resizePanes(n,o);else if(ie(t)){const[e,i]=this.findHit(t);ie(i)?t.presenter.view.setCursor(y.Crosshair):ie(e)?e.isSelected?t.presenter.view.setCursor(y.Move):t.presenter.view.setCursor(y.Hand):t.presenter.view.setCursor(y.Arrow)}else if(ie(s)){re(r.display.chart.zooming)[0]&&(n.setCursor(y.ResizeVertical),this.performAxisScaling(n,s,o))}else{if(this.prevZoomingOffset){const{x:e}=this.prevZoomingOffset,{x:t}=o,i=e-t;this.applyZoom(n.presenter,-i),this.prevZoomingOffset=o}n.setCursor(y.ResizeHorizontal)}return!t||this.resizingPanes?(this.hideCrosshairAndTooltips(n),q()):(this.isLogoLink(o)&&n.setCursor(y.Hand),this.showCrosshairAndTooltips(n,t,o),q())}showCrosshairAndTooltips(e,t,i){if(t.time&&(!q()||this.touchCrosshairMode)){e.drawCrosshair({ap:t,offset:i})&&e.presenter.showTooltip&&BA(e.presenter,{time:t.time,offset:i,price:t.price,lastBarRefresh:void 0,justMain:void 0})}}hideCrosshairAndTooltips(e,t=!1){e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&"cards"===e.tooltip.mode&&!e.presenter?.hasLegend&&HA(e.presenter)}onMouseLeave(e){const{view:t,offset:i}=e,s=t.presenter.accessor.getPaneBounds(),n=s?.every(e=>{return!e.contains(i)||(t=e,(s=i).x===t.x||s.x===t.x+t.width||s.y===t.y||s.y===t.y+t.height);var t,s});n&&(this.hideCrosshairAndTooltips(t,!0),this.stopResizeZoom(t.presenter)),t.setCursor(y.Arrow),this.touchCrosshairMode=!1}stopResizeZoom(e){this.resizingPanes&&(this.resizingPanes=!1,e.enableTooltip(!0),e.onPaneHeightsUpdated()),this.resizingScale&&this.stopResizingScale(),this.prevZoomingOffset&&delete this.prevZoomingOffset}onMouseUp({presenter:e}){if(this.stopResizeZoom(e),q()){const t=function(){const e=Gv().config.touchCrosshairTimeoutMillis;return ie(e)&&Number.isFinite(e)?e:gs.LONG_PRESS_TIMEOUT_MILLIS}();this.touchCrosshairTimeout=window.setTimeout(()=>{this.hideCrosshairAndTooltips(e.view,!0),this.touchCrosshairMode=!1},t)}}applyZoom(e,t,i=!0){if(!re(e.display.chart.zooming)[1])return;const s=Math.sign(t)*(q()?2:10),n=e.view;n.xAxis.zoom(s)&&(n.setPriceAxesDomains(),n.redraw(),i&&this.fireZoomChanged(e))}onWheel({view:e,presenter:t,getModifier:i,delta:s}){const{scrollBehavior:n}=t.display;return!(!(q()?"none"!==n:"wheel"===n||"wheel+shift"===n&&i(S.Shift))||0===s)&&(e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(),this.applyZoom(t,s),!0)}get useKeyboardShortcuts(){return Gv().config.hostingModel!==b[b.Application]}onKeyDown(e){const{key:t,code:i,presenter:s}=e;if(ie(s.selectedAnnotation)&&function(e,t){return"Backspace"===e||"Delete"===e||8===t||46===t}(t,i)){const e=s.selectedAnnotation;e.axis.deleteAnnotation(e),s.onAnnotationModifiedByTool(e,E.Deleted)}if(ie(s.selectedAnnotation)&&(X(t,i)?s.clearSelection():function(e,t){return"F2"===e||113===t}(t,i)&&s.selectedAnnotation instanceof CA&&s.selectedAnnotation.textEditable&&(s.activeTool=new xA(null,s.selectedAnnotation),s.activeTool.startEditing())),Z(t,i)||function(e,t){return"ArrowRight"===e||39===t}(t,i)){const e=Z(t,i)?1:-1,n=s.view;n.xAxis.pan(e*n.xAxis.xScale.bar.totalWidth),this.hideCrosshairAndTooltips(n),n.redraw()}const n=window.navigator.platform.toLowerCase().startsWith("mac")?S.Meta:S.Control;if(e.getModifier(n)&&this.useKeyboardShortcuts){const e=function(e,t){return"z"===e||90===t}(t,i),n=function(e,t){return"y"===e||89===t}(t,i);return e&&s.undoRedoManager.undo(),n&&s.undoRedoManager.redo(),e||n}(function(e,t){return"r"===e||82===t})(t,i)&&e.getModifier(S.Alt)&&this.resetView(s)}resetView(e){e.allAxes.forEach(e=>this.resetVerticalAxis(e,!1)),this.resetHorizontalAxis(e,!1),e.view.xAxis.goToLatest(!0)}resizePanes(e,t){const i=t.y-this.lastResizingOffset.y;if(0===i)return;const s=e.presenter.panes,[n,r]=this.splitter,o=s.map((e,t)=>{const s=e.getBounds().height;return t===n?s+i:t===r?s-i:s});if(o.some(e=>e<gs.MINIMUM_PANE_HEIGHT))return;const a=(e,t)=>e+t,l=o.reduce(a,0),c=s.map(e=>e.height).reduce(a,0);s.forEach((e,t)=>e.height=se(o[t]/l*c,4)),this.lastResizingOffset=t,e.recalculateLayout(),e.redraw()}startAxisScaling(e,t){this.resizingScale=!0,this.resizingScaleId=e.id,this.lastScaleResizingOffset=t}performAxisScaling(e,t,i){if(this.resizingScale&&this.resizingScaleId===t.id){const s=q()?4:5,n=function(e,t,i,s=1,n=-1){const r=(i.y-t.y)/10,o=e.yScale.rangeWithPadding().reverse();return[o[0]+r*s,o[1]+r*n].map(t=>e.yScale.yToPrice(t))}(t,this.lastScaleResizingOffset,i,s,-s);this.lastScaleResizingOffset=i,t.isCustomDomain=!0,t.yScale.domain(n),e.redraw()}}},jS=e=>QS(ZA,CS,1,e),KS=e=>QS(ZA,bA,1,e),qS={Default:()=>function(){return YS},Line:()=>QS(LA,sS,!1),DateRange:()=>QS(LA,IS,!1),PriceRange:()=>QS(LA,DS,!1),DatePriceRange:()=>QS(LA,OS,!1),GannBox:()=>QS(LA,wS,!1),GannSquare:()=>QS(_A,VS),Ray:()=>QS(LA,sS,!1),GannLine:()=>QS(MA,sS,!1),VerticalLine:()=>QS(ZA,nS,1),HorizontalLine:()=>QS(ZA,rS,1),LongPosition:()=>QS(ZA,_S,1,!0),ShortPosition:()=>QS(ZA,_S,1,!1),FiftyPercentLine:function(e,t){return ie(e)?QS(JA,oS,e.axis||t.mainAxis,e):QS(ZA,oS,2)},FibonacciRetracement:()=>QS(LA,lS,!1),TrendBasedFibExtension:()=>QS(LA,cS,!0),FibonacciFan:()=>QS(LA,dS,!1),FibonacciArcs:()=>QS(LA,gS,!1),FibonacciChannel:()=>QS(LA,BS,!0),GannFan:()=>QS(LA,yS,!1),SpeedResistanceFan:()=>QS(LA,AS,!1),SpeedResistanceArcs:()=>QS(LA,SS,!1),AndrewsPitchfork:()=>QS(ZA,TS,3),Rectangle:()=>QS(LA,zA,!1),Ellipse:()=>QS(LA,vS,!1),TrendChannel:()=>QS(LA,PS,!0),SymbolArrowUp:()=>jS("arrow_up"),SymbolArrowDown:()=>jS("arrow_down"),SymbolArrowRight:()=>jS("arrow_right"),SymbolArrowLeft:()=>jS("arrow_left"),SymbolArrowHorizontal:()=>jS("arrow_horizontal"),SymbolArrowVertical:()=>jS("arrow_vertical"),SymbolArcDown:()=>jS("arc_down"),SymbolArcUp:()=>jS("arc_up"),SymbolThumbsUp:()=>jS("thumbs_up"),SymbolThumbsDown:()=>jS("thumbs_down"),SymbolZero:()=>jS("zero"),SymbolOne:()=>jS("one"),SymbolTwo:()=>jS("two"),SymbolThree:()=>jS("three"),SymbolFour:()=>jS("four"),SymbolFive:()=>jS("five"),SymbolSix:()=>jS("six"),SymbolSeven:()=>jS("seven"),SymbolEight:()=>jS("eight"),SymbolNine:()=>jS("nine"),SymbolQuestion:()=>jS("question"),SymbolFishHook:()=>jS("fish_hook"),SymbolBuy:()=>jS("buy"),SymbolSell:()=>jS("sell"),FibonacciTimeZones:()=>QS(LA,bS,!1),Text:()=>QS(xA,CA,null),PickPoint:()=>function(){return new ES},ZoomIn:()=>function(){return new KA},ProfitLoss:KS,RewardRisk:KS,VolumeAtPrice:function(e){return QS(ZA,FS,2,e)},ZigZag:function(e){return QS(JA,WS,null,e)},ProbabilityCones:function(e){return QS(ZA,zS,2,e)},LinearRegressionChannel:function(e){return QS(JA,$S,null,e)}};function XS(e,t=!1,i=null,s=null,n=null){let r=qS[e];return r=r(s,n),r(e,t,i)}function ZS(e,t={}){e.enableTooltip(!0),e.resetActiveTool();const{axis:i,annotation:s,toolChange:n,annId:r}=t;ie(i)&&e.onAnnotationsUpdated(i),ie(s)&&e.onAnnotationModifiedByTool(s,n),[E.Cancelled,E.Executed,E.TextChanged].includes(n)&&e.onAnnotationDone(r,n)}function JS(e,t=!0,i=E.None){e.wasModifiedByTool();const s=e.axis,n={axis:s,annotation:e,toolChange:i};ZS(s.pane.presenter,t?n:void 0)}function QS(e,t,i,s){return function(n,r,o){const a=dA(n,t,s,o);return a.annName=n,r?a:new e(a,i)}}function eT(e){e.button===A.Right&&ZS(e.presenter)}function tT(e,t,i){const s={};s.source=Ka[e.source],s.inputs=fe(e.inputs);const n=void 0!==e.target,r=ie(i)?i:e.curves,o=n?[Ka[e.target]]:r.map(e=>e.fields).flat();return s.outFields=function(e){const t=[];for(const i of e)t.includes(i)||t.push(i);return t}(o),s.target=n?Ka[e.target]:s.outFields[0],s.aggregation=t,s}class iT extends Qy{model;basePlot;_hasEvents;_params;_shiftFmt;_title;range;shouldMaybePriceMap;annIndex;_canPriceMap;#e(e=3){let t=this.model.inputs||[];const i=t.length;if(0===i)return"";let s="";i>e&&(t=t.slice(0,3),s=", ...");const n="AVWAP"===this.model.study;return 0===t.length?"":`(${t.map(e=>n&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value).join(", ")}${s})`}get params(){return ie(this._params)||(this._params=this.#e()),this._params}get fullParams(){return this.#e(Number.MAX_VALUE)}get shiftFmt(){if(!("PC"!==this.model.study))return"";if(!ie(this._shiftFmt)){const e=this.curves.map(e=>Number(e.shift)).filter(e=>0!==e);this._shiftFmt=0===e.length?"":`[${e.join(", ")}]`}return this._shiftFmt}get title(){if(!ie(this._title)){const e=this.params,t=this.shiftFmt;this._title=`${this.model.study} ${e} ${t}`.trim()}return this._title}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(){const e=Ur(this.model.study),t=e.meta.decimals;this.metaData=void 0!==t?new Qs(t):this.basePlot.metaData,ie(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){const e=this.model?.study;return"VOL"===e&&this.axis?.pane.isMain?gs.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){const t=this.model.study;!0===Ur(t).meta.shiftable&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});const i=(e,t,i)=>this.curves[e].zones[t].value=this.model.levels[i].value;switch(t){case"ICHCLD":{const t=e.inputs.Displacement;this.curves[2].shift=-t,this.curves[3].shift=t,this.curves[4].shift=t,this.curves[5].shift=t;break}case"MARIB":{const t=Math.min(Math.max(0,e.inputs.Count),10);this.curves.forEach((e,i)=>e.visible=e.visible&&i<t);break}case"CRS":{const t="PercentChange"===e.inputs.Display;this.axis.comparison=t?d.Percent:d.None;break}case"PERF":{const t="VisibleStart"===e.inputs.Anchor;this.axis.comparison=t?d.Percent:d.None;break}case"JPI":case"CTTP":case"CTTI":{const t=Y(10,e=>.025*(e+1)),i=e=>t.map(t=>Cn(t)(e)),s=([e,t])=>[...i(e).reverse(),t,"#6a4a3a","#a000c8","#ffffff"];this.curves[0].colors=s(this.curves[0].colors),this.curves[1].colors=s(this.curves[1].colors);const n=this.curves[0].colors.length;this.curves[0].colors[n-1]=this.curves[1].colors[t.length],this.curves[1].colors[n-1]=this.curves[0].colors[t.length],this.shouldMaybePriceMap="Performance"===e.inputs.Height;break}case"RSI":case"RSIMOD":case"RSISTO":case"CCI":i(0,0,0),i(0,1,2);break;case"STC":i(0,0,0),i(0,1,1);break;case"RVOL":case"DPO":case"COPP":i(0,0,0);break;case"VOL":this.setCurveAttributes(0,e.inputs.BarColoring);break;case"MAVOL":this.setCurveAttributes(1,e.inputs.BarColoring);break;case"VOLAP":{this.notifyAboutPriceDomains=!0,this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=this.curves[1],i=this.curves[2],s=XS("VolumeAtPrice",!0,{[gs.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[gs.AT_FILL]:{color:this.curves[0].colors[0]},[gs.AT_FILL2]:{color:this.curves[0].colors[1]},[gs.AT_FILL3]:{color:this.curves[0].colors[2]},[gs.AT_FILL4]:{color:i.colors[0]},[gs.AT_FILL5]:{color:i.colors[1]},[gs.AT_FILL6]:{color:i.colors[2]}},this.id)(this.axis,!1);s.setOptions(e.inputs),this.annIndex=this.annotations.push(s)-1;break}case"PVACP":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=this.curves[1],i=this.curves[2],s=this.curves[3],n=XS("VolumeAtPrice",!0,{[gs.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[gs.AT_FILL]:{color:this.curves[0].colors[0]},[gs.AT_FILL2]:{color:this.curves[0].colors[1]},[gs.AT_FILL3]:{color:this.curves[0].colors[2]},[gs.AT_FILL4]:{color:i.colors[0]},[gs.AT_FILL5]:{color:i.colors[1]},[gs.AT_FILL6]:{color:i.colors[2]},[gs.AT_FILL7]:{color:s.colors[0]}},this.id)(this.axis,!1);n.setOptions(e.inputs),this.annIndex=this.annotations.push(n)-1;break}case"ZIGZAG":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const t=XS("ZigZag",!0,{[gs.AT_LINE]:{color:this.curves[0].colors[0],width:this.curves[0].lineWidth,dashStyle:this.curves[0].dashStyle??"Solid"}},this.id)(this.axis,!1);t.setOptions(e.inputs),this.annIndex=this.annotations.push(t)-1;break}case"LINRCHN":{this.customPlotValues=!0,ie(this.annotations)||(this.annotations=[]);const e=this.curves[0],t=this.curves[1],i=this.curves[2],s=this.curves[3],n=this.curves[4],r=XS("LinearRegressionChannel",!0,{[gs.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??"Solid"},[gs.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??"Solid"},[gs.AT_LINE_3]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle??"Solid"},[gs.AT_FILL]:{color:s.colors[0]},[gs.AT_FILL2]:{color:n.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(r)-1;break}case"IVRANK":{let t=Ka.ImplVolRank1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=Ka.ImplVolRank5D;break;case"1-Month":t=Ka.ImplVolRank1M;break;case"3-Month":t=Ka.ImplVolRank3M;break;case"6-Month":t=Ka.ImplVolRank6M;break;case"YTD":t=Ka.ImplVolRankYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"IVPCTL":{let t=Ka.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=Ka.ImplVolPerc5D;break;case"1-Month":t=Ka.ImplVolPerc1M;break;case"3-Month":t=Ka.ImplVolPerc3M;break;case"6-Month":t=Ka.ImplVolPerc6M;break;case"YTD":t=Ka.ImplVolPercYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"OPTIV":{let t=[Ka.WeighImplVolHigh,Ka.WeighImplVol,Ka.WeighImplVolLow];switch(e.inputs.TimeFrame){case"1-Day":default:break;case"5-Day":t=[Ka.WeighImplVolHigh5D,Ka.WeighImplVol5D,Ka.WeighImplVolLow5D];break;case"1-Month":t=[Ka.WeighImplVolHigh1M,Ka.WeighImplVol1M,Ka.WeighImplVolLow1M];break;case"3-Month":t=[Ka.WeighImplVolHigh3M,Ka.WeighImplVol3M,Ka.WeighImplVolLow3M];break;case"6-Month":t=[Ka.WeighImplVolHigh6M,Ka.WeighImplVol6M,Ka.WeighImplVolLow6M];break;case"1-Year":t=[Ka.WeighImplVolHigh1Y,Ka.WeighImplVol1Y,Ka.WeighImplVolLow1Y];break;case"YTD":t=[Ka.WeighImplVolHighYTD,Ka.WeighImplVolYTD,Ka.WeighImplVolLowYTD]}this.curves[0].fields[0]=t[0],this.curves[1].fields[0]=t[1],this.curves[2].fields[0]=t[2],e.outFields=[...t];break}case"PC":{const t=e.inputs.PeriodForecast-1;this.curves.forEach(e=>e.shift=t),ie(this.annotations)||(this.annotations=[]);const i=this.curves[11],s=this.curves[12],n=XS("ProbabilityCones",!0,{[gs.AT_LINE]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle},[gs.AT_LINE_2]:{color:s.colors[0],width:s.lineWidth,dashStyle:s.dashStyle}},this.id)(this.axis,!1);n.setOptions(e.inputs),this.annIndex=this.annotations.push(n)-1;break}}}getValueAt(e,t,i){if(!this.isVolAP)return super.getValueAt(e,t,i);return this.annotations[this.annIndex].getValueAt(e,t,i)}getColorOf(e){if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;const t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case Ka.UPVOL:return t[1];case Ka.DNVOL:return t[0];case Ka.TOTVOL:return t[2];case Ka.POC:case Ka.VAREA:case Ka.BARBACK:return gs.COLOR_TRANSPARENT;case Ka.LINRUP:return t[0];case Ka.LINRMID:return this.curves[1].colors[0];case Ka.LINRLOW:return this.curves[2].colors[0];default:throw new Error("Unexpected Volume At Price field")}}isEmpty(){return!(this.isVolAP||this.isZigZag||this.isLinRegChannel)&&super.isEmpty()}setCurveAttributes(e,t){const i=t=>this.curves[e].attributes=[r[t]];switch(t){case"LikeMain":{const t=this.axis.pane.presenter.mainPlot.curves[0].attributes,s=Gv().config.defaultVolumeBarColoring;if(ie(t))this.curves[e].attributes=[t[0]];else if(ie(s)){i("OpenToClose"===s?"OpenVsClose":"ChangeBased")}else i("OpenVsClose");break}case"OpenToClose":i("OpenVsClose");break;case"CloseToClose":i("ChangeBased");break;default:throw new Error(`Unexpected bar coloring choice: ${t}`)}}get hasEvents(){return this._hasEvents}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){const e=this.timeSeries.helpers;return e.includes(Ka.Buy)||e.includes(Ka.Sell)}getEventFor(e){switch(e){case Ka.Buy:return{show:!0,title:"B",color:"#03c03c"};case Ka.Sell:return{show:!0,title:"S",color:"#c23b22"};default:return null}}getEventFields(){return this.hasEvents?[Ka.Buy,Ka.Sell]:[]}async initialize(){if(this.model.basis!==gs.BASIS_MAIN)throw new Error("Studies can currently only be based on the main (symbol) plot");return ps.call(this,async()=>{this.basePlot=this.axis.pane.presenter.mainPlot,await this.basePlot.initialize(),this.getMetaData();const e=this.axis.pane.presenter.data.aggregation,t=tT(this.model,e,this.curves);this.applySpecifics(t);let i=this.basePlot.timeSeries;i instanceof dp&&(i=i.actual),this.timeSeries=ny(this.model.study,t,i),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;const s=this.title,n=this.basePlot.timeSeries instanceof bh;return this.timeSeries.ready().then(e=>{e||n||this.timeSeries.computedServerSide||Hv(`Unable to calculate study values for ${s}`,"error")}),!0})}get isJpi(){return["JPI","CTTP","CTTI"].includes(this.model.study)}get isVolAP(){return"VOLAP"===this.model.study||"PVACP"===this.model.study}get isZigZag(){return"ZIGZAG"===this.model.study}get isLinRegChannel(){return"LINRCHN"===this.model.study}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[this.annIndex].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations("PriceDomainsChanged")}shouldPriceMap(e){return this.isJpi?!!this.shouldMaybePriceMap&&(e.id===Ka.JPIB.id||e.id===Ka.JPIS.id):super.shouldPriceMap(e)}canPriceMap(e,t){if(!this.isJpi)return super.canPriceMap(e,t);this._canPriceMap=e>0}priceMap(e,t,i){if(!this.isJpi)return super.priceMap(e,t,i);if(t>this.visToIndex)return e;const s=(e,t)=>this.timeSeries.container.getData(e)[t],n=s(Ka.JPIB,t),r=s(Ka.JPIS,t);if(null===n&&i.id===Ka.JPIB.id||null===r&&i.id===Ka.JPIS.id)return null;let o=0,a=this.visFromIndex;const l=this.timeSeries.helpers[0],c=this.timeSeries.helpers[2];for(;a<=t;){o+=1===s(c,a)?0:s(l,a),a++}return o}}const sT=[Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.Volume];class nT extends Qy{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){const e=ca(this._expression);if(this.exprModel=null,this.symbols=null,la(e))this.errorText=e.error;else{const{model:t,clean:i,symbols:s}=e;this.errorText=void 0,this.symbols=s,this.exprModel=t,this._expression=i}}get isValid(){return!ie(this.errorText)}#t(e){return{mapper:e=>e.query.symbol,loadMoreData:!0,recompute:i.Minimum,missing:t.UseNext,stretch:e=>!1,fieldMap:new Map(sT.map(e=>[e,e])),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:e}}getTimeSeries(){const e=this.getInnerSeries(),t=this.axis?.pane.presenter.data?.exprSkipLeadingEmpty??!1,i=new Vm(this.exprModel,e,this.#t(t));this.timeSeries=this.wrapIfAdvancedStyle(i);const s=this.title;this.timeSeries.ready().then(e=>{e||Hv(`Unable to calculate expression: ${s}`,"error")})}getInnerSeries(){const e=pa(this.exprModel),t=Gv().getTimeSeriesDataSource();return e.map(e=>{const i=this.makeQuery();return i.symbol=e,t.getTimeSeries(i)})}getRecord(){if(ie(this.errorText))return;const e=this.metaData.inner.map(e=>[e.symbol,e.resolved]);this.record=new hl(e,ue(this.exprModel)),this.record.ready().then(e=>e)}getMetaData(){this.isValid&&(this.metaData=new tn(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return ps.call(this,async()=>(await this.parseExpression(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}class rT extends Qy{suffix;_forward;offset;errorText;fwdModel=null;outField;roots=null;symbols=[];get title(){return`${this.forward}${this.suffix}`}get forward(){return this._forward}fromModel(e){super.fromModel(e);const t=e;this.offset=t.offset,this._forward=t.forward}async parseForward(){const e=ca(this.forward),t=la(e);if(t?(this.errorText=e.error,this.fwdModel=null,this._forward=e.text):(this.errorText=void 0,this.fwdModel=e.model,this._forward=e.clean),t)this.roots=null;else{this.offset>0?(this.suffix=` (${x(mu(this.offset),fu(gs.FMT_US_DATE_ONLY))(/* @__PURE__ */new Date)})`,this.outField=new Ga(`Close_${this.offset}`,c.Number,h.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix="",this.outField=Ka.Close);const t=e=>Fi(`${e}*1`),{yes:i,no:s}=V(e.symbols,t),n=(await Promise.all(i.map(e=>Xi(e)))).map(e=>e.map(e=>e.name));this.roots=i.reduce((e,t,i)=>(e[t]=n[i],e),{}),this.symbols=s}}get isValid(){return!ie(this.errorText)}getMetaData(){if(this.isValid){const e=Object.values(this.roots).flat();this.metaData=new tn(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}}getForwardPolicy(e){return{mapper:e=>e.query.root,loadMoreData:!1,recompute:i.Everything,missing:t.UseNext,stretch:e=>!1,fieldMap:/* @__PURE__ */new Map([[Ka.Close,this.outField]]),noDataApproach:s.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1,valueProvider:e}}getTimeSeries(){const e=Gv().getTimeSeriesDataSource(),t=Object.keys(this.roots),i=0===this.offset?m.Forward:m.HistoricalForward,s=t.map(t=>{const s={seriesKind:i,root:t,offset:this.offset,symbols:this.roots[t],getHashKey:()=>`${i}|${t}|${this.offset}`};return e.getTimeSeries(s)}),n=this.symbols.length>0?new Ih(this.symbols):void 0;this.timeSeries=new Vm(this.fwdModel,s,this.getForwardPolicy(n)),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e)}})}async initialize(){return ps.call(this,async()=>(await this.parseForward(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}const oT=e=>e.substring(0,e.lastIndexOf("::"));class aT extends Qy{isAverage;hasComputation;offset;offsets;_seasonal;symbolToOffset;errorText;seaModel=null;isPlain=!1;isFutures=!1;suffix="";outField;symbols;coreModel;coreHasComputation;refSeasonal;get title(){if(this.isAverage){let e="YB ";return this.offset<-1&&(e=`${Math.abs(this.offset)}y `),`${e}Average`}return!this.hasComputation&&(this.symbols?.length??0)>0?this.outField.name:`${this.seasonal}${this.suffix}`}get seasonal(){return this._seasonal}fromModel(e){super.fromModel(e);const t=e;this.offset=t.offset,this.offsets=t.offsets,this.isAverage=t.offset<0,this._seasonal=this.refSeasonal=t.seasonal}constructSeasonal(e,t){return da(ma(e,e=>this.applyOffset(e,t)))}constructAverage(e,t=null){const i=null===t?null:t.map(e=>this.symbolToOffset[e]),s=null===i,n=this.offsets.filter(e=>!!s||i.includes(e)).map(t=>`(${this.constructSeasonal(e,t)})`);return`(${n.join("+")})/${n.length}`}prepareFields(){const e=this.isPlain?`${this.yearFromOffset(this.offset)}`:`${this.offset}Y`,t=this.isAverage?"Avg":e;this.suffix=0===this.offset?"":` (${t})`,this.outField=new Ga(`Close_${t}`,c.Number,h.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:es(e,-t)}::${t}`}createSymbolToOffsetMapping(e){this.symbolToOffset={},e.forEach(e=>{this.offsets.forEach(t=>{this.symbolToOffset[this.applyOffset(e,t)]=t})})}async parseSeasonal(){const e=ca(this.seasonal,!0),t=e=>(this.errorText=e,this.seaModel=null,null);if(la(e))return t(e.error);let{model:i,symbols:s}=e;this.prepareFields();const n=/* @__PURE__ */new Map;for(const h of s){const e=Yi(await Hi(h));n.set(h,e)}i=ma(i,e=>n.get(e)),s=Array.from(n.values());const r=s.every(e=>Fi(e)||Wi(e)),o=s.every(e=>$i(e)),a=s.every(e=>!Fi(e)&&!$i(e)&&!Wi(e));if(!r&&!o&&!a)return t("Mixed types of symbols aren't supported yet");this.isPlain=a,this.isFutures=r,this.createSymbolToOffsetMapping(s),this.coreModel=this.isAverage?i:null,this.coreHasComputation=fa(i);const l=this.isAverage?this.constructAverage(i):this.constructSeasonal(i,this.offset),{model:c,symbols:u}=ca(l,!0);this.seaModel=c,this.hasComputation=fa(c),this._seasonal=da(ma(c,oT)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!ie(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(oT))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){const e=oT(this.symbols[0]);if(this.isPlain)return`${e} ${/* @__PURE__ */(new Date).getFullYear()-this.offset}`;if(this.isFutures)return Yi(e,!0)}return this.title}getMetaData(){if(this.isValid){const e=this.getActualSymbols(),t=1===e.length&&!this.hasComputation&&!this.isAverage,i=Gv().getMetaDataSource();this.metaData=t?i.getMetaData(e[0]):new tn(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(qa.MD_CHANGED,{plot:this})})}}getNoDataApproach(){return this.isAverage&&!this.coreHasComputation?s.ModelTransformRequired:this.hasComputation?s.NoAction:s.IgnoreTimelineOnly}get seasonalPolicy(){return{mapper:e=>e.query.surrogate||e.query.symbol,loadMoreData:!1,recompute:i.Everything,missing:this.hasComputation?t.UsePrevious:t.UseNone,stretch:e=>this.shouldStretch(e),fieldMap:/* @__PURE__ */new Map([[Ka.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>{if(0===t.length)return this.seaModel;return ca(this.constructAverage(this.coreModel,e)).model},skipLeadingEmpty:!1}}shouldStretch(e){return 0===this.symbolToOffset[e]&&(this.isAverage&&this.symbols.length>1||this.offset>0)}shiftYears(e){return lt(/* @__PURE__ */new Date,-e)}yearFromOffset(e){return Pi(this.shiftYears(e))}getCmdtyRange(e){const t=this.shiftYears(e);return[Mt(t),Lt(t)]}getTimeSeries(){if(!this.isValid)return;const e=Gv().getTimeSeriesDataSource(),t=Object.keys(this.symbolToOffset).map(t=>{const i=this.makeQuery();return i.surrogate=t,i.symbol=oT(t),i.offset=this.symbolToOffset[t],i.cacheMe=!this.isPlain||0===i.offset,this.isPlain&&(i.range=this.getCmdtyRange(i.offset)),this.isFutures&&i.offset>0&&ie(...i.range)&&(i.range=i.range.map(e=>lt(e,-i.offset))),i.offset>0&&(i.disableStreamingUpdates=!0),e.getTimeSeries(i)});this.timeSeries=new Vm(this.seaModel,t,this.seasonalPolicy),this.timeSeries.ready().then(e=>{if(e){const e={series:this.timeSeries,part:P.Unspecified};this.presenter?.notifyHost(qa.TS_MANYCHANGED,e)}})}async initialize(){return ps.call(this,async()=>(await this.parseSeasonal(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}const lT=["bottom","right","left"],cT={bottom:"center",right:"start",left:"end"};class uT{lineWidth;arrowLength;position;textAlign;fontSize;fontFamily;padding;strokeColor;textColor;backgroundColor;constructor(e){this.lineWidth=1,this.arrowLength=7,this.position="bottom",this.textAlign="center",this.fontSize=12,this.fontFamily="Arial",this.padding=4,this.strokeColor="white",this.textColor="white",this.backgroundColor="black",e&&this.configure(e)}configure(e){Object.assign(this,e)}draw(e,t,i,s,n,r){const o=ie(n);if(r=r||this.fontSize+this.padding+this.padding+(o?this.padding:0),!lT.includes(this.position.toLowerCase()))return void console.error(`Can not draw indicator in position [${this.position}]`);e.font=`bold ${this.fontSize}px ${this.fontFamily}`,e.textAlign=cT[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=Sn(this.backgroundColor),e.lineWidth=this.lineWidth;const a=[s,n??""].map(t=>e.measureText(t).width),l=Math.max(...a),c="bottom"!==this.position?this.arrowLength:0,u=Math.round(l+c+this.padding+this.padding),h=Math.round(u/2),d=Math.round(r/2);e.setLineDash([]);const p=t;e.beginPath(),e.moveTo(p,i);const f=i+d,m=i+2*d,g=i-d;if("right"===this.position){e.lineTo(p,f);const t=p+u;o&&(e.lineTo(p,m),e.lineTo(t,m)),e.lineTo(t,f),e.lineTo(t,g),e.lineTo(p,g)}else if("left"===this.position){e.lineTo(p,f);const t=p-u;o&&(e.lineTo(p,m),e.lineTo(t,m)),e.lineTo(t,f),e.lineTo(t,g),e.lineTo(p,i-d)}else if("bottom"===this.position){const t=p-h,s=p+h;e.lineTo(p,i),e.lineTo(s,i),e.lineTo(s,i+r),e.lineTo(t,i+r),e.lineTo(t,i),e.lineTo(p,i)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline="middle","bottom"===this.position)e.fillText(s,p,i+Rn(e,1));else if("right"===this.position){const t=p+this.arrowLength+this.padding;e.fillText(s,t,i),o&&e.fillText(n,t,i+this.padding+d)}else if("left"===this.position){const t=p-this.arrowLength-this.padding;e.fillText(s,t,i),o&&e.fillText(n,t,i+this.padding+d)}}}const hT=({y:e,halfHeight:t})=>e+t;const dT=({x:e,halfWidth:t})=>e-t-4,pT=({x:e,halfWidth:t})=>e+t+4,fT=(e,t)=>e-1-t-4,mT=(e,t)=>e+1+t+4;const gT=Array.from(Array(6),(e,t)=>++t).reverse();function yT(e){const t=e.plot.timeSeries.container;return null===t||t.size<1?null:e.getColor(t.size-1)}function AT(e){return e.curves.filter(t=>e.visible&&t.visible&&(e.type!==f.Study||t.style!==o.Ribbon)).map(t=>{const i=t.pickMainField(),[s,n]=function(e,t){const i=e.timeSeries.container;if(null===i||i.size<1)return[null,-1];let s=i.getLastDataPoint(t);const n=i.getData(t);let r=n.length-1;const o=e.type===f.Study&&["JPI","CTTP","CTTI"].includes(e.model.study);return null!=s||o||(r=H(n,e=>null!==e),s=-1!==r?n[r]:null),[s,r]}(e,i);return{value:s,color:yT(t),field:i,index:n}})}class ST{constructor(e){this.pane=e,this.id=Pe(),this.ticks=null,this.lastUsedOptions=null;const{chart:{fontSize:t},yAxis:{fontSize:i}}=this.pane.presenter.display,s=i||t||12;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:s},this.crosshairIndicator=new uT({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}annotations=[];id;isCustomDomain=!1;primary=!1;onTheRight=!0;viewBox;plots=[];comparison;scale;yScale;label="";crosshairIndicator;ticks;lastUsedOptions;config;_fullDomain;makePlot(e){let t=null;switch(f[e.type]){case f.Symbol:t=new eA;break;case f.Expression:t=new nT;break;case f.Study:t=new iT;break;case f.IncomeStatement:t=new tA(m.IncomeStatement);break;case f.BalanceSheet:t=new tA(m.BalanceSheet);break;case f.Forward:t=new rT;break;case f.Seasonal:t=new aT;break;default:throw new Error(`${e.type} isn't supported yet`)}return t.axis=this,t.fromModel(e),t}toPrice(e){const t=this.yScale.yToPrice(e);return this.comparison!==d.None?this.pane.presenter.mainPlot.priceMap(t,void 0,Ka.Close,!0):t}toTime(e){return this.pane.presenter.view.toTime(e)}toAnnotationPoint(e){const t=this.toPrice(e.y),i=this.toTime(e.x);return new aA(this,t,i||void 0)}toX(e){return this.pane.presenter.view.toX(e)}priceMap(e){return this.comparison!==d.None?this.pane.presenter.mainPlot.priceMap(e,void 0,Ka.Close):e}toY(e){const t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){const e=[];return this.plots.forEach(t=>{t.annotations&&e.push(...t.annotations)}),e}annTimeToX(e){return this.pane.presenter.view.xAxis?.annTimeToX(e)}snapTo(e){const t={x:this.annTimeToX(e.time),y:this.toY(e.price)},i=this.pane.presenter,s=i.activeTool,n=s.annotation;return s.alignPointsMode&&n&&n.alignPointsSupported&&n.points.includes(e)?this.alignPoints(n,e,t):!s.snapToSupported||!i.display.yAxis.snapAnnotationsToPrices||e.passive||e.moveDirection!==T.Both&&e.moveDirection!==T.Vertical||this.snapToPrices(e,t),t}snapToPrices(e,t){const i=this.plots.find(e=>e.main);if(i&&i.timeSeries&&i.timeSeries.hasData){const s=i.timeSeries.container,n=G(s.getTimeData(),+e.time,Number),r=Array().concat(...i.curves.map(e=>e.fields)).filter(e=>s.hasField(e)).map(e=>{const i=s.getData(e)[n],r=this.toY(i);return{priceSnap:i,ySnap:r,dist:Math.abs(r-t.y)}}).filter(e=>e.dist<=gs.SNAP_PROXIMITY_PIXELS).reduce((e,t)=>null===e||t.dist<e.dist?t:e,null);ie(r)&&(e.price=r.priceSnap,t.y=r.ySnap,e.time=s.getTimeData()[n],t.x=this.toX(e.time))}}alignPoints(e,t,i){const s=e.points.find(e=>e!==t);if(t!==s&&s&&s.point){const e=s.point,n=(360+180*-gn(e,i)/Math.PI)%360,r=22.5,o=n>90-r&&n<90+r||n>270-r&&n<270+r;if(n>360-r||n<r||n>180-r&&n<180+r)i.y=e.y,t.price=this.toPrice(i.y);else if(o)i.x=e.x,t.time=this.toTime(i.x);else{const s=Math.abs(i.x-e.x),n=e.y>i.y?-1:1;i.y=e.y+s*n,t.price=this.toPrice(i.y)}}}toPoint(e){if(ie(this.pane.presenter.view))return this.snapTo(e)}makeAnnotation(e,t=!0){const i=XS(e.id,!0,e.traits)(this,!1);t&&e.uid&&(i.uid=e.uid);const s=i.activePoints,n=e.points.length-s.length;return n>0&&i.addPoints(n),i.activePoints.forEach((t,i)=>{const s=e.points[i];ne(s.price)&&ne(s.time)&&t.update(s.price,s.time)}),i.visible=e.visible,i.locked=e.locked,i}expand(e){const t=[];switch(e.type){case"Forward":{const i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;for(let n=0;n<i.length;n++){const r=Object.assign({},e);r.curves=[i[n]],r.offset=s[n],t.push(r)}break}case"Seasonal":{const i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;const n=s.filter(e=>e>=0);for(let r=0;r<i.length;r++){const o=Object.assign({},e);o.curves=[i[r]],o.offset=s[r];const a=o.offset<0;if(a){const e=-1===o.offset;o.offsets=e?n:Y(Math.abs(o.offset),e=>e+1)}else o.offsets=[o.offset];(!a||o.offsets.length>1)&&t.push(o)}break}default:t.push(e)}return t}fromModel(e){this.comparison=d[e.comparison??"None"],this.scale=p[e.scale??"Linear"],this.yScale=new Yy(this.scale,this),this.label=e.label,this.plots=Array().concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e));const t=e.annotations||[];this.annotations=t.map(e=>this.makeAnnotation(e));const{chart:{fontFamily:i,backgroundColor:s},yAxis:{textColor:n,crosshair:{color:r},primaryOnTheLeft:o}}=this.pane.presenter.display,a=o??!1;this.onTheRight=this.primary&&!a||!this.primary&&a,this.crosshairIndicator.configure({position:this.onTheRight?"right":"left",fontFamily:i,strokeColor:r,textColor:n,backgroundColor:Cn(.15)(s)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){const t=this.makeAnnotation(e,!0);this.appendAnnotation(t),t.requestRedraw(),this.fireAnnotationsChanged()}appendAnnotation(e){-1===this.findIndex(e)&&this.annotations.push(e)}fireAnnotationsChanged(e=!1){this.pane.presenter.onAnnotationsUpdated(this,e)}deleteAnnotation(e,t=!0){e.isSelected&&this.pane.presenter.clearSelection();const i=this.findIndex(e);-1!==i&&this.annotations.splice(i,1),t&&this.fireAnnotationsChanged(!e.isSelected)}fliphorizontalAnnotation(e){e.flip(!0),this.fireAnnotationsChanged(!0)}flipverticalAnnotation(e){e.flip(!1),this.fireAnnotationsChanged(!0)}duplicateAnnotation(e){const t=e.axis,i=this.makeAnnotation(e.toModel(),!1);i.drawPoints(null,!0),i.offset({x:gs.ANN_DUPLICATE_OFFSET,y:gs.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(i),i.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&this.pane.presenter.clearSelection(),Co(e.name,t.traits),e.updateFrom(t.traits,t.extras,t.isUndoRedo?null:t.points,t.visible,t.locked),t.isUndoRedo&&ie(t.points)&&e.updateActivePoints(t.points),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(cA(e,E.Moved)),e.requestRedraw(),this.fireAnnotationsChanged()}setViewBox(e){this.viewBox=e;const{y:t,height:i}=this.viewBox;this.yScale.range([Math.floor(t),Math.floor(t+i)]),this.plots.forEach(t=>t.setViewBox(e))}get fullDomain(){return ie(this._fullDomain)||(this._fullDomain=this.getDataDomain().domain),this._fullDomain}updateFullDomain(e=null){if(null===e&&this.comparison!==d.None)return;const t=this.fullDomain;this._fullDomain=this.getDataDomain([e,e],t).domain}getPlotDataDomain(e,t,i){const s=e.timeSeries;if(!s.hasData)return{domain:null};const n=s.container,r=n.getTimeData(),a=e=>G(r,+e,Number),l=ie(t),c=l?a(t):0,u=ie(i),h=u?a(i):r.length-1,d=e.curves.map(e=>e.fields).flat().filter(e=>e.id!==Ka.Change.id),p=ie(e.targetFields);p&&d.push(...e.targetFields);const f={},m=t=>{const[i,s]=(t=>{const i=p?e.curves[0]:e.curves.find(e=>e.fields.includes(t));if(!ie(i)||0===i.shift)return[c,h];if(!ie(f[i.id])){const e=i.shiftedTimeDomain;if(!ie(e))return[c,h];f[i.id]=[a(e[0]),a(e[1])]}return f[i.id]})(t),r=n.getData(t),o=Math.max(i,0),l=Math.min(r.length-1,s);return r.slice(o,l+1).map((i,s)=>e.priceMapper(i,s,t))},g=[null,null],y=e=>e.id,A=new Set(F(n.fields,d,y).map(y));e.curves.filter(e=>e.visible).map(e=>{const t=e.fields.filter(e=>A.has(e.id));if(e.isStackedColumn){j(z(t.map(e=>m(e)).reduce((e,t)=>t.map((t,i)=>(e[i]||0)+(t||0)),[])),g)}else t.map(e=>{const t=(e=>z(m(e)))(e);j(t,g)})});let S=L.None;const T=[o.Column,o.MultiColumn,o.StackedColumn];if(l&&u&&!e.main&&e.curves.some(e=>T.includes(e.style))){const e=g[0]>0,t=g[1]<0;e?(S=L.Min,g[0]=0):t&&(S=L.Max,g[1]=0)}return{domain:g,clamped:S}}getDataDomain([e,t]=[null,null],i=[null,null]){const s=ue(i);let n=!1;for(const c of this.plots.filter(e=>!e.hasDetachedScale)){const{domain:i,clamped:r}=this.getPlotDataDomain(c,e,t);ie(i)&&(j(i,s),n=n||r!==L.None)}if(!ie(s))return{domain:null};const[r,o]=s;if(!ie(r,o))return{domain:null};const a=[Number(r),Number(o)];a[0]===a[1]&&(a[0]-=1,a[1]+=1);let l=L.None;return n&&(0===a[0]?l=L.Min:0===a[1]&&(l=L.Max)),{domain:a,clamped:l}}setDomain(){const e=this.pane.presenter,t=e.view.xAxis.xScale.domain();if(!ie(t))return;for(const n of this.plots.filter(e=>e.hasDetachedScale)){const{domain:e}=this.getPlotDataDomain(n,t[0],t[1]);ie(e)&&n.yScale.domain(e)}if(this.isCustomDomain)return;const{domain:i,clamped:s}=this.getDataDomain(t);if(this===e.mainAxis&&e.mainPlot?.showPrevious){const t=e.mainPlot.getPreviousValue(),s=ce(e.display,!1,"chart","previous","forceVisible");ie(t,i)&&s&&(i[0]=Math.min(i[0],t),i[1]=Math.max(i[1],t))}if(this.yScale.domain(i),ie(i)){const e=this.getPadding(s);ie(e)&&this.yScale.padding(e)}}getInitialPadding(){const e=is(this.pane.presenter.hostElement);let t=rs(`#${gs.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!ie(t)){t=us(e,"div"),os(t,{display:"none"}),as(t,{id:gs.HEADER_SIZE_PLACEHOLDER_ID,class:"bcharts-card bcharts-card-first"});const{lineHeight:i}=getComputedStyle(t);isNaN(Number.parseFloat(i))&&os(t,{lineHeight:"120%"})}const{paddingTop:i,paddingBottom:s,marginTop:n,lineHeight:r}=getComputedStyle(t),o=this.pane.isMain?n:"0";if("cards"!==this.pane.presenter.display.tooltip.mode)return Number.parseFloat(o);return[i,s,o,r].map(Number.parseFloat).reduce((e,t)=>e+t,0)+gs.CARDS_Y_OFFSET}getPadding(e){const t=this.pane.presenter,i=t.display,s=ce(i,null,"yAxis","minPaddingPercent"),n=ce(i,null,"yAxis","maxPaddingPercent"),r=ie(s),o=ie(n),a=r||o?0:this.getInitialPadding(),l=r?s:gs.PANE_CAP_MIN_PADDING_PERCENT,c=o?n:gs.PANE_CAP_MAX_PADDING_PERCENT,u=l*this.viewBox.height,h=[o?c*this.viewBox.height:Math.max(u,Math.min(c*this.viewBox.height,a)),u];e===L.Max?h[0]=gs.PANE_TINY_PADDING_PIXELS:e===L.Min&&(h[1]=gs.PANE_TINY_PADDING_PIXELS);const d=t.mainPlot;return d&&d.hasEvents&&(h[0]+=3*t.view.getEventRadius()),h}clearTicks(){this.ticks=null}getTicks(e,t=0){const{height:i}=this.viewBox,s=Rn(e,1.3),n={height:i,approxLineHeight:s,domain:this.yScale.domain()};if(ie(this.ticks)&&ie(n.domain)&&ie(this.lastUsedOptions)&&ie(this.lastUsedOptions.domain)&&n.height===this.lastUsedOptions.height&&n.approxLineHeight===this.lastUsedOptions.approxLineHeight&&n.domain[0]===this.lastUsedOptions.domain[0]&&n.domain[1]===this.lastUsedOptions.domain[1])return this.ticks;this.lastUsedOptions=n;const r=Math.floor((i+40)/(s+40));let o=this.yScale.getTicks(r);const a=ce(Gv().config,null,"overrides","yAxis","tickProvider");if(ie(a)&&"function"==typeof a&&n.height>0&&ie(n.domain)){const e=ue(n);e.autoTicks=ue(o),o=a(e)}const{innerTickSize:l,tickPadding:c,fontSize:u}=this.config;let h=null;const d=this.yScale?.checkTicks(),p=d?30:40;return this.ticks=o.map(i=>{const s=Math.round(this.yScale.priceToY(i)),n=Math.abs(s-(h??s));if(d&&null!==h&&n<p)return null;h=s;const r=nd(this,i),o=e.measureText(r).width,a={x1:0,x2:0,y1:s,y2:s,dy:0,label:r,labelX:0,labelY:s+.32*u};return this.onTheRight?(a.x1=t,a.x2=a.x1+l,a.labelX=a.x2+o+c):(a.x1=t-l,a.x2=a.x1+l,a.labelX=a.x1-c),a}).filter(e=>null!==e),this.ticks}widthNeeded(e){if(!ie(this.fullDomain))return gs.DEFAULT_PRICE_AXIS_WIDTH;e.save();const{fontWeight:t,fontSize:i}=this.config,{chart:{fontFamily:s}}=this.pane.presenter.display;e.font=`${t} ${i}px ${s}`;const n=Math.max(...this.fullDomain.map(t=>e.measureText(nd(this,t,!0)).width)),{innerTickSize:r,tickPadding:o}=this.config,a=n+r+2*o+(ie(this.label)?Rn(e,1.6):0);return e.restore(),a}draw(e){const{chart:{fontFamily:t},yAxis:{gridLines:i,textColor:s,visible:n}}=this.pane.presenter.display;if(!n||!this.viewBox)return;e.save();const{x:r,y:o,width:a,height:l}=this.viewBox,{fontWeight:c,fontSize:u}=this.config;if(_n(e,this.viewBox),e.font=`${c} ${u}px ${t}`,e.lineWidth=2,e.strokeStyle=i.color,e.textAlign="end",ie(this.label)){e.save();const t=Pn(.4);e.fillStyle=t(s),e.translate(0,0);const i=this.onTheRight?1:-1;e.rotate(i*Math.PI/2),e.textAlign="center";const n=Rn(e),c=i*(o+l/2);this.onTheRight?e.fillText(this.label,c,-(r+a-n)):e.fillText(this.label,c,r+n),e.restore()}const h=this.onTheRight?r:a;e.setLineDash([]),Un(e,h,o,o+l);const d=this.getTicks(e,h);this.drawTicks(e,d,s),this.drawPriceAdornments(e),e.restore()}drawTicks(e,t,i){t&&(e.fillStyle=i,t.forEach(t=>{e.fillText(t.label,t.labelX,t.labelY+t.dy)}))}drawCrosshairIndicator(e,t){if(0===this.plots.length||!this.pane.presenter.display.yAxis.crosshair.enabled)return;const i=this.onTheRight?this.viewBox.x:this.viewBox.width,s=nd(this,this.yScale.yToPrice(t));this.crosshairIndicator.draw(e,i,t,s)}get indicatorHeight(){return this.config.fontSize+this.config.indicatorPadding+this.config.indicatorPadding}drawPriceAdornments(e){const t=this.pane.presenter,{chart:{fontFamily:i,previous:s},yAxis:{showLastValue:n,preventLabelOverlap:r,includePercentChangeWithLastValue:o}}=t.display,a=t.view,l=[],c=(e,t,i,s,n,r)=>{if(null!=t){const a=t;let c;t=e.priceMapper(t,r,n);const u=e.is(f.Symbol)||e.is(f.Expression);if(o&&u){const t=e.axis.comparison===d.Percent?d.None:d.Percent;c=e.priceMapper(a,r,n,t)}const h=e.hasDetachedScale?e.metaData.format(t,n):void 0,p=ie(c)?1:2;l.push({y:e.priceToY(t),formattedValue:h,value:t,auxValue:c,color:i,halfHeight:Math.round(this.indicatorHeight/p),priority:s})}};this.plots.forEach(e=>{if(e.timeSeries&&e.timeSeries.hasData){if("All"===n||"Main"===n&&e.main){const t=e.main?1:3;AT(e).filter(e=>null!=e.value&&-1!==e.index).forEach(i=>c(e,i.value,i.color,t,i.field,i.index))}e.showPrevious&&c(e,e.getPreviousValue(),s.color,2,Ka.PreviousClose,void 0)}});this.annotations.concat(this.plotAnnotations).forEach(e=>{l.push(...e.getPriceScaleAdornments().map(e=>({y:this.toY(e.price),value:this.priceMap(e.price),color:e.color,halfHeight:Math.round(this.indicatorHeight/2),priority:4})))}),l.sort((e,t)=>e.y-t.y),r&&function(e,t){e.forEach((e,i,s)=>{if(0===i&&e.y-e.halfHeight<t.y)e.y=t.y+e.halfHeight+1;else if(i>0){const n=s[i-1],r=(({y:e,halfHeight:t})=>e-t)(e),o=hT(n);r<o&&(e.y=o+1+e.halfHeight),hT(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}(l,this.viewBox);const u=({y:t,value:s,formattedValue:n,color:r,auxValue:o})=>{const{leftOffset:l,rightOffset:c}=a,u=this.onTheRight?this.pane.viewBox.width-c:l,h=Ln(r),p=new uT({position:this.onTheRight?"right":"left",fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:i,textColor:h,strokeColor:r,backgroundColor:r}),f=n||nd(this,s);let m;const g=this.comparison===d.Percent;te(o)&&(m=g?sd(this,o):id(o)),p.draw(e,u,t,f,m)};r?l.forEach(u):gT.forEach(e=>l.filter(t=>t.priority===e).forEach(u))}}const TT=/* @__PURE__ */Symbol.for("__dloacip__");class vT{constructor(e){this.presenter=e,this.id=Pe()}id;axes=[];height=0;alignedToYear=null;viewBox;fromModel(e){this.height=e.height,!0===e.alignOnExpirations&&(this.alignedToYear=function(e){const t=e.map(e=>e.plots).flat().filter(e=>f[e.type]==f.Symbol).map(e=>e.symbol).map(e=>Ji(e)).filter(e=>null!==e).map(e=>e.getFullYear());return 0!=t.length?Math.max(...t):null}(e.axes)),this.axes=e.axes.map((e,t)=>{const i=new ST(this);return i.primary=0===t,i.fromModel(e),i},this)}getBounds(){return this.viewBox}setViewBox(e){this.viewBox=e}drawBackground(e){ie(this.viewBox)&&(this.drawAxes(e),e.save(),this.clipToNoScales(e),this.drawGrid(e),e.restore())}draw(e){ie(this.viewBox)&&(e.save(),this.clipToNoScales(e),this.drawPrevious(e),this.drawPlots(e),this.drawAnnotations(e),this.drawLogo(e),e.restore())}drawLogo(e){this.isMain&&!1!==this.presenter[TT]&&function(e,{x:t,y:i,height:s,width:n}){if(!te(GA))return;const{path:r,width:o,height:a,rect:l}=GA,c=n/8,u=Math.min(Math.max(50,c),o)/o;l.width=o*u,l.height=a*u,l.x=t+5,l.y=i+s-l.height-5,e.save();const h=getComputedStyle(e.canvas).getPropertyValue("--widget-logo-fill-color");e.fillStyle=0===h.length?"rgba(127, 127, 127, 0.6)":h,e.translate(l.x,l.y),e.scale(u,u),e.fill(r),e.restore()}(e,this.getBoundsWithoutScales())}drawAxes(e){for(const t of this.axes)t.draw(e)}drawPrevious(e){const t=this.presenter.mainPlot;if(t.showPrevious&&this.isMain){let i=t.getPreviousValue();if(i=t.priceMapper(i,void 0,Ka.PreviousClose),null!=i){const{leftOffset:s,rightOffset:n}=this.presenter.view,r=s,o=this.viewBox.width-n,a=t.axis.yScale.priceToY(i),{color:l,dashStyle:c,lineWidth:u}=this.presenter.display.chart.previous,h=An(c);e.save(),e.strokeStyle=l,e.lineWidth=u,e.setLineDash(h),$n(e,a,r,o),e.restore()}}}getBoundsWithoutScales(){const e=this.viewBox.duplicate(),t=this.presenter.view;return e.x=t.leftOffset,e.width-=t.leftOffset+t.rightOffset,e}clipToNoScales(e){_n(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();const{chart:{fontFamily:t},yAxis:{fontSize:i}}=this.presenter.display;e.font=`${i??12}px ${t}`;const s=t=>t.draw(e,!0);this.axes.forEach(e=>{e.annotations.forEach(s),e.plotAnnotations.forEach(s)}),e.restore()}drawGrid(e){const{chart:{fontFamily:t},yAxis:{gridLines:i,visible:s,minorGridLines:n}}=this.presenter.display;if(!s||!i.visible)return;const{lineWidth:r,color:o,dashStyle:a}=i;e.save();const l=0===this.axes[0].plots?.length&&this.axes.length>1,c=this.axes[l?1:0],{fontWeight:u,fontSize:h}=c.config;e.font=`${u} ${h}px ${t}`;const d=c.getTicks(e),{leftOffset:p,rightOffset:f}=this.presenter.view,m=p,g=this.viewBox.width-f,y=(t,i,s)=>{e.lineWidth=t,e.strokeStyle=i,e.setLineDash(An(s)),e.beginPath()};if(y(r,o,a),d.forEach(t=>{e.moveTo(m,t.y1),e.lineTo(g,t.y2)}),e.stroke(),n&&n.visible&&d.length>=2){const{lineWidth:t,color:i,dashStyle:s}=n,r=(d[0].y1-d[1].y1)/5;y(t,i,s),d.forEach(t=>{for(let i=1;i<5;i++){const s=Math.ceil(t.y1+i*r);e.moveTo(m,s),e.lineTo(g,s)}}),e.stroke()}e.restore()}drawYCrosshair(e,t){const{yAxis:{crosshair:{enabled:i,showValue:s,color:n,dashStyle:r}}}=this.presenter.display;if(!i)return;const o=An(r);e.strokeStyle=n,e.setLineDash(o);const a=this.presenter.view.leftOffset,l=this.viewBox.width-this.presenter.view.rightOffset,c=Kn();c.prolog(e),$n(e,c.adjust(t.y),c.adjust(a),c.adjust(l)),c.epilog(e),s&&this.axes.forEach(i=>{i.drawCrosshairIndicator(e,t.y)})}drawNoData(e){e.save(),e.font=`800 14px ${this.presenter.display.chart.fontFamily}`,e.fillStyle="#f00";Bn(e,Gv().config.noDataText||gs.NO_DATA_TEXT,{x:this.viewBox.centerX,y:this.viewBox.centerY},g.Center),e.restore()}get isMain(){const e=this.presenter.mainPlot;return this.axes.some(t=>t.plots.includes(e))}drawPlots(e){e.save();const t=this.presenter.mainPlot,i=this.presenter.display.chart.showNoDataText,s=!ie(i)||i,n=/* @__PURE__ */new Map;let r=!0;const o=i=>{for(const e of this.axes){for(const s of e.plots){const e=s.isEmpty();r=r&&s.main&&e,s===t||e||i(s)}e.plots.includes(t)&&!t.isEmpty()&&i(t)}s&&r&&this.drawNoData(e)};o(t=>t.draw(e)),o(t=>t.drawTopmost(e,n)),e.restore()}}function PT(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}class CT extends ky{constructor(e,t){super(),this.timeline=e,this.aggregation=t;const i=e.presenter.display;this.marginBars=i.xAxis.marginBars||0,this.bar=PT(ce(i,gs.DEFAULT_BAR_WIDTH,"chart","bar","width"),ce(i,gs.DEFAULT_BAR_SPACING,"chart","bar","spacing")),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}marginBars;bar;resetBar;wasZoomed;fitAllData;extent(e){return Fy.call(this,"_extent",e)}get presenter(){return this.timeline.presenter}get display(){return this.presenter.display}scaleBarToFit(){if(this.wasZoomed)return;if(this.fitAllData)return this._domain=null,this.scaleBarToFitDensity(this.timeline.withoutPrologEpilogLength);const e=this.display.xAxis.visibleRange;if(ie(e))return this.scaleBarToFitRange([e.from,e.to]);const t=this.display.density;if(Number.isFinite(t))return this.scaleBarToFitDensity(t);const i=this.display.period;return Number.isFinite(i)?this.scaleBarToFitPeriod(i):void 0}deriveExtentsFromBarWidth(e){if(!ie(this._range))return null;if(0===this.timeline.length)return null;const t=this._range[1]-this._range[0],i=t/e.totalWidth,s=Math.ceil(i);e.offset=t-s*e.totalWidth;let n=this.timeline.lastSeriesIndex+this.marginBars;const r=this._domain&&this._domain[1];r&&(n=G(this.timeline,+r,Number,ud));return[n-s+1,n]}adjustDomain(){if(!ie(this._range))return;this.scaleBarToFit();const e=this.deriveExtentsFromBarWidth(this.bar);ie(e)&&(this.extent(e),this.setDomainFromExtent())}xToTime(e){if(!this.ready)return null;const t=e-this._range[0]-this.bar.offset,i=Math.floor(t/this.bar.totalWidth),s=this._extent[0]+i;return this.timeline.at(s)}timeToIndex(e){return this.ready?(e="number"==typeof e?e:+e,G(this.timeline,e,Number,ud)):null}indexToX(e){const t=e-this._extent[0];return this.bar.width/2+this.range()[0]+this.bar.offset+t*this.bar.totalWidth}timeToX(e){if(!this.ready)return null;const t=this.timeToIndex(e);return this.indexToX(t)}zoom(e){const t=e,i=t*this.bar.width/100,s=this.bar.width-i,n=this.bar.spacing-t*this.bar.spacing/100;if(s>gs.MAXIMUM_BAR_WIDTH||s<gs.MINIMUM_BAR_WIDTH)return!1;const r=PT(s,n),o=this.deriveExtentsFromBarWidth(r);return!!this.isUsableExtent(o)&&(this.setBar(s,n),this.adjustDomain(),this.wasZoomed=!0,!0)}scaleBarToFitRange(e,t=!0){const i=(e,t,i,s)=>ie(e)?G(this.timeline,e,Number,ud,i,s):t,{from:s,to:n}=this.presenter.data.range||{},r=+e[0]===s&&+e[1]===n,{firstSeriesIndex:o,lastSeriesIndex:a}=this.timeline,l=r?o:void 0,c=r?a:void 0,u=[i(e[0],o,l,c),i(e[1],a,l,c)];this.timeline.at(u[1])>e[1]&&(u[1]=Math.max(0,u[1]-1)),this.extent(u),this.scaleBarToFitDensity(u[1]-u[0]+1,t)}scaleBarToFitDensity(e,t=!0){const i=Math.max(gs.MINIMUM_BARS_VISIBLE,e),s=t&&this.display.xAxis.marginBars||0,n=(this._range[1]-this._range[0])/(i+s);this.setBar(2/3*n,1/3*n,!1)}scaleBarToFitPeriod(e){const t=this.timeline.lastSeriesIndex,i=this.timeline.at(t);let s=i,n=t;const r=this.presenter.data.aggregation;if(r.isEndOfDay||r.isIntraday&&e>=gs.INTRA_THRESHOLD)for(;n>0&&ft(i,s)<e;)n--,s=this.timeline.at(n);else if(!r.isTick){let t=Math.floor(e/gs.ONE_DAY_MILLIS);const s=e=>yt(e,nt(e)),r=s(i);let o=i;for(;n>0;){const e=this.timeline.at(n),i=ut(e,o);if(0===t){if(s(e)<=r||!i)break}else i||(t--,o=e);n--}}this.scaleBarToFitDensity(t-n+1)}setBar(e,t,i=!0){const[s,n]=ve(e,t,gs.MINIMUM_BAR_WIDTH,gs.MAXIMUM_BAR_WIDTH);this.bar.width=s,this.bar.spacing=n,this.wasZoomed||(this.resetBar={width:s,spacing:n}),i&&(this.presenter.model.display.chart.bar={width:e,spacing:t})}resetZoom(){ie(this.resetBar)?(this.bar.width=this.resetBar.width,this.bar.spacing=this.resetBar.spacing):(this.bar.width=gs.DEFAULT_BAR_WIDTH,this.bar.spacing=gs.DEFAULT_BAR_SPACING),delete this.presenter.model.display.chart.bar,this.adjustDomain()}isUsableExtent(e){return ie(e)&&ie(e[0],e[1])&&e[0]>=0&&e[1]<this.timeline.withPrologEpilogLength&&e[1]-e[0]>=gs.MINIMUM_BARS_VISIBLE}shiftBars(e,t=null){if(!this._extent)return;const i=this._extent.map(t=>t+e);this.isUsableExtent(i)&&(ie(t)&&(this.bar.offset=t),this.extent(i),this.setDomainFromExtent())}setDomainFromExtent(){this.domain(this.extent().map(e=>this.timeline.at(e)))}pan(e){if(!Number.isFinite(e)||0===e)return;const t=e%this.bar.totalWidth;let i=this.bar.offset+t;const s=Math.sign(e);let n=-(e<0?Math.ceil:Math.floor)(e/this.bar.totalWidth);(i>this.bar.totalWidth||i<-this.bar.totalWidth)&&(n+=i>0?-1:1,i-=s*this.bar.totalWidth),this.shiftBars(n,i)}getSeriesThatCouldLoadMoreData(){const e=this.domain();if(!ie(e)||!ie(e[0]))return[];const t=e[0].getTime();return this.timeline.presenter.allPlots.map(e=>e.timeSeries).filter(e=>!(!ie(e)||!e.hasData||0===e.container.size||!0!==e.canLoadMoreData)&&t<=e.container.getTimeData()[0].getTime())}}function bT(e){return{date:e,priority:1,text:td(e)}}class ET{constructor(e){this.view=e,this.xScale=new CT(e.presenter.timeline,e.presenter.data.aggregation),this.ticks=null,this.lastUsedOptions=null,this.wasPanned=!1,this.panningXAxisAllowed=ce(e.presenter.display,!0,"xAxis","panning"),this.updateConfigFromModel();const t=e.presenter.renderTo.id,i=ce(Gv().config,null,"overrides","xAxis","tickProvider");ie(i)&&"function"==typeof i&&(this.overrideTickGetter=M(i,t));const s=ce(Gv().config,null,"overrides","xAxis","formatter");ie(s)&&"function"==typeof s&&(this.overrideFormatter=M(s,t))}xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;viewBox;overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;updateConfigFromModel(){const{chart:{fontFamily:e,backgroundColor:t,fontSize:i},xAxis:{textColor:s,visible:n,fontSize:r,crosshair:{color:o}}}=this.view.presenter.display,a=r||i||12;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:a},this.isVisible=n,this.crosshairIndicator=new uT({position:"bottom",fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:s,backgroundColor:Cn(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();const e=this.view.presenter.display.period===gs.FIFTY_YEARS_MILLIS;ie(this.xScale.extent())&&!e&&this.checkForMoreData()}zoom(e){const t=this.xScale.zoom(e);return this.checkForMoreData(),t}checkForMoreData(){this.xScale.getSeriesThatCouldLoadMoreData().forEach(e=>e.loadMoreData())}shouldScrollIntoView(e){const t=this.xScale.extent();return!!ie(t)&&(e-this.xScale.timeline.lastSeriesIndex>=0&&e-t[1]<=1)}pan(e){this.panningXAxisAllowed&&(this.xScale.pan(e),this.checkForMoreData(),this.view.setPriceAxesDomains(),this.wasPanned=!0)}get wasVisibleRangeChanged(){return this.wasPanned||this.xScale.wasZoomed}resetZoom(){this.xScale.resetZoom()}get barsToLast(){const e=this.xScale.timeline.lastSeriesIndex+this.getMaxCurveOffset(),t=this.xScale.extent();return e-(t?t[1]:e)}canGoToLast(){return this.barsToLast>0}getMaxCurveOffset(){return Math.max(...this.view.presenter.allCurves.map(e=>e.shift))}goToLatest(e=!1){if(this.canGoToLast()||e){const e=0!==this.barsToLast?this.barsToLast+this.xScale.marginBars+1:0;this.xScale.shiftBars(e),this.view.setPriceAxesDomains(),this.view.redraw()}}setViewBox(e){this.viewBox=e;const{x:t,width:i}=this.viewBox;this.xScale.range([t,t+i])}heightNeeded(e){if(!this.isVisible)return 0;const t=this.view.presenter.display.chart.fontFamily,{fontWeight:i,fontSize:s}=this.config;e.save(),e.font=`${i} ${s}px ${t}`;const{innerTickSize:n,tickPadding:r,indicatorPadding:o}=this.config,a=Rn(e,1)+n+r+o;return e.restore(),a}getTickGetter(e){if(this.overrideTickGetter)return this.overrideTickGetter;const t=this.view.presenter.display.xAxis.isOrdinal||!1,i=function(e){switch(e.agg.unit){case a.Tick:return new qh(e);case a.Intraday:return new Xh(e,e.agg.size);case a.Day:return new Zh(e);case a.Week:return new Jh(e);case a.Month:case a.Quarter:return new Qh(e);case a.Year:return new ed(e);default:throw new Error(`Aggregation unit ${a[e.agg.unit]} not supported.`)}}(e);return t?bT:e=>i.getTick(e)}getTicks(e){if(ie(this.lastUsedOptions)&&(t=e.agg,i=this.lastUsedOptions.agg,t.unit===i.unit&&t.size===i.size&&t.spec===i.spec)&&e.unitWidth===this.lastUsedOptions.unitWidth&&e.barWidth===this.lastUsedOptions.barWidth&&e.extent[0]===this.lastUsedOptions.extent[0]&&e.extent[1]===this.lastUsedOptions.extent[1]&&e.formatString===this.lastUsedOptions.formatString&&e.minTickInterval===this.lastUsedOptions.minTickInterval&&ie(this.ticks))return this.ticks;var t,i;this.lastUsedOptions=e;const s=this.getTickGetter(e),n=Math.max(0,e.extent[0]),r=Math.min(this.xScale.timeline.withPrologEpilogLength-1,e.extent[1]+1);return this.ticks=this.view.presenter.timeline.slice(n,r).map((e,t)=>{if(!ie(e)||Number.isNaN(e.getTime()))return null;const i=s(e);return ie(i)&&(i.index=n+t),i}).filter(e=>ie(e)),this.ticks}normalizeDuration(e){const t=function(){const e=Object.keys(Wh);return 1===Wh.Day.Multipliers[0]&&e.forEach(e=>{const t=Wh[e],i=Te(t.Period);t.One=1*i,t.Multipliers=t.Multipliers.map(e=>e*i)}),Wh}();let i=t.Year;const s=Object.keys(t);for(let a=0;a<s.length-1;++a){const n=t[s[a]].Multipliers,r=t[s[a+1]].Multipliers,o=(k(n)+W(r))/2;if(e<=o){i=t[s[a]];break}}const n=i.Multipliers,r=n.findIndex(t=>e<t);let o=-1===r?k(n):n[r];return"P1M"===i.Period?o*=.9:"P1W"===i.Period&&(o*=.84),o}draw(e){if(!this.isVisible)return;const{xAxis:{gridLines:t,textColor:i,minTickInterval:s,tickPixelInterval:n,format:r,forceTicksVisible:o},chart:{fontFamily:a}}=this.view.presenter.display,{fontWeight:l,fontSize:c,innerTickSize:u,tickPadding:h}=this.config,{x:d,y:p,width:f}=this.viewBox,{lineWidth:m,color:g,dashStyle:y}=t,A=An(y);e.textAlign="center",e.font=`${l} ${c}px ${a}`,e.lineWidth=1,e.strokeStyle=g,e.fillStyle=i,e.setLineDash([]),$n(e,p,d,d+f);const S=this.xScale.extent(),T=e=>!ie(e)||!ie(e[0],e[1]);if(T(S))return;const v=t=>e.measureText(t).width,P=n>0?n:120,C=this.xScale.domain();if(T(C))return;const b=(C[1].getTime()-C[0].getTime())*P*.6/f,E=this.normalizeDuration(b),L=this.view.presenter.data.aggregation.isEndOfDay,M=(e,t)=>{if(e.date.valueOf()===gs.ZERO_DATE.valueOf())return!0;if(i=e.date,n=t.date,(ie(i)?ft(n,i):gs.FIFTY_YEARS_MILLIS)<s)return!1;var i,n;const r=t.x-e.x,o=t.date.getTime()-e.date.getTime()>=E,a=r>P;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||!!L&&o)},_=d+f,x=({text:i,x:s,date:n,forced:r})=>{ie(n)&&(r||Un(e,s,p,p+u),e.fillText(i,s,p+u+h+.71*c),t.visible&&!r&&(e.save(),e.lineWidth=m,e.setLineDash(A),Un(e,s,0,p),e.restore()))},I={agg:this.view.presenter.data.aggregation,unitWidth:v("M"),barWidth:this.xScale.bar.width,extent:S,formatString:r,minTickInterval:s||0,duration:b},D=this.getTicks(I);let O={date:gs.ZERO_DATE,priority:999,x:-999,text:"",textWidth:0};D.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=v(e.text),(e=>{const{x:t,textWidth:i}=e;let s=t;if(o){const n=i/2;s=t-n<d?d+n:t,s=s+n>_?_-n:s,e.x=s,e.forced=t!==s}else e.forced=!1})(e),M(O,e)?(x(O),O=e):e.priority<O.priority&&(O=e)}),x(O),this.drawTimeTransitions(e),this.drawTimeAdornments(e)}drawTransitionsFor(e,t,i,s,n){const r=this.xScale.domain(),o=this.view.presenter?.mainPlot?.timeSeries.container;if(!te(o))return;const a=o.getTimeData(),l=null===t?a:o.getData(t);if(!ie(l))return;const c=G(a,+r[0],Number),u=G(a,+r[1],Number,$,c);if(c<u){const t=this.viewBox.y,r=this.view.leftOffset,o=this.viewBox.x+this.viewBox.width;if(s.save(),n){s.fillStyle=e.fillColor;let h=l[c],d=Math.max(r,this.xScale.timeToX(a[c]));for(let e=c+1;e<=u;++e){const r=e<l.length?l[e]:null;if(e===u||i(r,h)){const i=e<a.length?a[e]:null;let l=te(i)?this.xScale.timeToX(i):o;l=Math.min(l,o),n(h)%2==0&&s.fillRect(d,0,l-d,t),h=r,d=l}}}const h=Kn();h.prolog(s),s.strokeStyle=e.color,s.lineWidth=e.width,s.setLineDash(An(e.dashStyle));let d=null;for(let e=c;e<u;++e){const n=l[e];if(i(n,d)){const i=a[e],r=this.xScale.timeToX(i);ie(r,d)&&Un(s,r,0,t),d=n}}h.epilog(s),s.restore()}}drawTimeTransitions(e){const t=this.xScale.domain();if(!te(t)||!ie(t[0],t[1]))return;const i=this.view.presenter,{xAxis:{contractTransition:s,cycleTransition:n}}=i.display,r=(e,t)=>e!==t;if(s.enabled&&i?.data?.aggregation.isMultiContract){const t=i?.mainPlot?.timeSeries.container,n=t?.getData(Ka.Symbol);if(n&&n.length>0){const t=n[0];if(this.contractParityCacheKey!==t||!this.contractParityCache){const e=[...new Set(n)];e.sort((e,t)=>{const i=Ji(e),s=Ji(t);return(i?.getTime()??0)-(s?.getTime()??0)});let i=0;if(this.contractParityCache)for(let t=0;t<e.length;t++){const s=e[t],n=this.contractParityCache.get(s);if(void 0!==n){i=(n-t)%2==0?0:1;break}}this.contractParityCache=/* @__PURE__ */new Map,e.forEach((e,t)=>this.contractParityCache.set(e,t+i)),this.contractParityCacheKey=t}const i=e=>this.contractParityCache.get(e)??0;this.drawTransitionsFor(s,Ka.Symbol,r,e,i)}}if(n.enabled)if(i?.data?.aggregation.isIntraday)this.drawTransitionsFor(n,Ka.TradingDay,r,e,e=>e);else if(i?.data?.aggregation.unit===a.Day){const t=(e,t)=>!_i(e,t),i=e=>e.getMonth();this.drawTransitionsFor(n,null,t,e,i)}else if(i?.data?.aggregation.unit===a.Week){const t=(e,t)=>!Ii(e,t),i=e=>e.getFullYear();this.drawTransitionsFor(n,null,t,e,i)}}getAnnXScore(e,t){return[ut,Mi,_i,Ii].map((i,s)=>(4-s)*Number(i(e,t))).reduce((e,t)=>e+t,0)}annTimeToX(e){const t=this.xScale.timeToIndex(e);if(!te(t))return null;const i=this.xScale.timeline.at(t),s=this.xScale.timeToX(e);if(t>0&&i.valueOf()!==e.valueOf()){const n=t-1,r=this.xScale.timeline.at(n),o=this.xScale.indexToX(n),a=this.view.presenter.display?.xAxis?.isOrdinal;if(!a){if(r.valueOf()>e.valueOf())return s;const t=this.getAnnXScore(r,e),n=this.getAnnXScore(i,e);if(t>n)return o;if(n>t)return s;const a=this.view.presenter?.data?.aggregation?.isIntraday;return a?o:s}return o+(s-o)*((e.valueOf()-r.valueOf())/(i.valueOf()-r.valueOf()))}return s}drawTimeAdornments(e){e.save();const t=this.view.presenter,{chart:{fontFamily:i},xAxis:{preventLabelOverlap:s}}=t.display,n=[],r=t.mainPane?.getBoundsWithoutScales()??new xn(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).forEach(i=>{n.push(...i.getTimeScaleAdornments().map(i=>{const s=this.annTimeToX(i.time);if(s<r.x||s>r.x+r.width)return null;const n=!this.view.presenter?.display?.xAxis?.isOrdinal?this.xScale.xToTime(s):i.time,o=rd(t,n),a=e.measureText(o).width/2;return{x:s,value:o,color:i.color,halfWidth:a}}).filter(e=>null!=e))}),n.sort((e,t)=>e.x-t.x),s&&function(e,t){const i=e.length-1;e.forEach((e,s,n)=>{const r=0===s,o=r?null:n[s-1],a=dT(e),l=r?t.x:pT(o);if(e.x-e.halfWidth<t.x&&(e.x=mT(t.x,e.halfWidth)),a<l)e.x=mT(l,e.halfWidth+4);else{const t=pT(e),r=s<i?dT(n[s+1]):Number.MAX_SAFE_INTEGER;if(t>r){const i=fT(e.x,t-r),s=fT(e.x,e.halfWidth-2),n=mT(l,o?.halfWidth??0);e.x=Math.max(s,i,n)}}pT(e)>t.x+t.width&&(e.x=fT(t.x+t.width,e.halfWidth))})}(n,this.viewBox),n.forEach(t=>{const s=Ln(t.color);new uT({position:"bottom",fontSize:this.config.fontSize,fontFamily:i,padding:this.config.indicatorPadding,strokeColor:gs.COLOR_TRANSPARENT,textColor:s,backgroundColor:t.color,arrowLength:this.config.innerTickSize}).draw(e,t.x,this.viewBox.y+1,t.value)}),e.restore()}drawCrosshair(e,{x:t}){const i=this.view.presenter,s=i.display.xAxis,{enabled:n,showValue:r,color:o,dashStyle:a,format:l}=s.crosshair,c=this.xScale.xToTime(t);if(!(ie(c)&&ht(c)))return!1;if(!n)return!0;t=this.xScale.timeToX(c);const u=An(a);e.strokeStyle=o,e.setLineDash(u);const h=Kn();if(h.prolog(e),Un(e,h.adjust(t),0,h.adjust(this.viewBox.y)),h.epilog(e),!r||!s.visible)return!0;const d=ie(s.format)?l:void 0,p=rd(i,c,d);this.crosshairIndicator.draw(e,t,this.viewBox.y+1,p,void 0,this.viewBox.height-2);const{plotHover:f}=i.display.chart;return f&&i.allPlots.filter(e=>e.visible).forEach(i=>i.curves.forEach(i=>i.drawHover(e,c,t))),!0}}const LT={mousedown:"onMouseDown",mousemove:"onMouseMove",mouseup:"onMouseUp",dblclick:"onMouseDblClick",contextmenu:"onContextMenu",mouseover:"onMouseEnter",mouseout:"onMouseLeave",wheel:"onWheel",touchstart:"onMouseDown",touchmove:"onMouseMove",touchend:"onMouseUp",keydown:"onKeyDown"},MT={Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"};class _T{constructor(e){this.view=e}subscriptions=[];init(e){const t=q();Object.keys(LT).filter(e=>!(e=>e.startsWith("touch"))(e)||t).forEach(t=>{const i=e=>{const i=LT[t];!0===this.notifyActiveTool(i,e)&&e.preventDefault()};e.addEventListener(t,i),this.subscriptions.push(()=>{e.removeEventListener(t,i)})})}shutdown(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}notifyActiveTool(e,t){const i=this.view.presenter;if(void 0===i||null===i.activeTool)return!1;const s=this.getPayload(t,i),n=i.activeTool;let r=!1;return"function"==typeof n[e]&&(r=n[e](s)||!1),r}getPayload(e,t){const i=e instanceof MouseEvent,s=q()&&e instanceof TouchEvent;if(i||s){const n={x:0,y:0};if(s&&1===e.touches.length){const t=e.touches[0],{left:i,top:s}=e.target.getBoundingClientRect();n.x=t.clientX-i,n.y=t.clientY-s}else i&&(n.x=e.offsetX,n.y=e.offsetY);const r={button:i?e.which:A.Left,offset:n,view:t.view,presenter:t,originalEvent:e,getModifier:t=>e[MT[S[t]]]};if(e instanceof WheelEvent&&(r.delta=e.shiftKey?e.deltaX:e.deltaY),s&&2===e.touches.length){const t=e.touches[0],i=e.touches[1];r.pinchZoom=!0;const s=t.clientX-i.clientX,n=t.clientY-i.clientY;r.pinchDistance=Math.sqrt(s*s+n*n)}return this.view.splitters.forEach((e,t)=>{e.contains(n)&&(r.splitter=[t,t+1])}),t.panes.forEach(e=>{const t=e.getBounds();if(ie(t)&&t.contains(n)){const t=e.axes.find(e=>e.viewBox?.contains(n));if(t)r.priceAxis=t;else{const t=e.axes.find(e=>e.primary);r.point=t.toAnnotationPoint(n)}}}),r}if(e instanceof KeyboardEvent){return{key:e.key??e.keyIdentifier,code:e.keyCode||e.charCode,repeat:e.repeat,presenter:t,getModifier:t=>e.getModifierState(S[t])}}}}const xT=$u.concat(Ka.PercentChange);class IT{constructor(e){this.view=e,this.id=`bc-legend-${Pe()}`}id;isOptionsChart=!1;getLegendElem(){const e=this.view.el;return ls(this.id,e,"div")}update(){const e=this.getLegendElem(),t=Ed(this.presenter.mainPane);if(!ie(t))return;this.isOptionsChart=this.mainPlot.title.startsWith(gs.FAKE_SYMBOL_PREFIX);const{left:i,right:s,top:n,width:r}=t;FA(e,"row",i,s,n,r),cs(e,{"bcharts-card":!0,"bcharts-legend":!0});const o=this.mainPlot,a=o.isSeasonal||this.isOptionsChart?this.getFirstColorBadge(o):"",l=this.getPlotTitle(o),c=this.maybeGetQuote(),u=this.div(`${a} ${l} `)+this.div(`${c}`),h=this.maybeGetAdditionalPlots();e.innerHTML=`${u} ${h}`}remove(){ns(this.getLegendElem())}get presenter(){return this.view.presenter}get mainPlot(){return this.presenter.mainPlot}getAttributes(e){return Object.entries(e).map(([e,t])=>{if(null===t)return"";return`${e} = "${Array.isArray(t)?t.join(" "):t}" `}).join(" ")}span(e,t={}){return`<span ${this.getAttributes(t)}>${e}</span>`}div(e){return`<div class="plot" style="flex: 0 0 auto">${e}</div>`}get meta(){return this.mainPlot.metaData}isSingleSymbolSeasonal(e){return e.isSeasonal&&!e.hasComputation}format(e,t,i){return(i??this.meta).format(e,t)}spanAsName(e){return this.span(e,{class:"field-name"})}spanAsValue(e,t=null,i=null){return this.span(e,{class:["field-value",t],style:i})}getQuoteFromRecord(e){const t=xT.map(t=>e.getValue(t));if(R(t)){const e=t[4],i=`field-${e>0?"up":e<0?"down":"same"}-value`;return`${t.slice(0,-1).map((e,t)=>{const s=xT[t],n=this.format(e,s),r=xd(s);return`${this.spanAsName(r)}${this.spanAsValue(n,i)}`}).join(" ")} ${this.spanAsValue(`(${this.format(k(t),k(xT))})`,i)}`}return""}maybeGetQuote(){if(this.mainPlot.isSymbol&&this.mainPlot.timeSeries?.record?.isValid){const e=Gv().getRecordSource().getRecord(this.mainPlot.timeSeries.record.symbol);return this.getQuoteFromRecord(e)}if(this.mainPlot.isExpression&&this.mainPlot.record.isValid){const e=this.mainPlot.record;return e.evaluate(),this.getQuoteFromRecord(e)}return""}getTitle(e,t,i){const s=t?"value-main":null;return`${this.span(`${e.name} (${e.symbol})`,{"data-plot-id":i,class:["value-title",s]})}${t?` ${this.span(e.exchange,{class:"value-subtitle"})}`:""}`}getPlotTitle(e){if(e.isSymbol)return this.getTitle(e.metaData,e.main,e.id);if(this.isSingleSymbolSeasonal(e)&&0===e.offset&&(e.symbols?.length??0)>0){const t=Gv().getMetaDataSource().getMetaData(e.getActualSymbols()[0]);return this.getTitle(t,!0,e.id)}return this.span(e.title,{"data-plot-id":e.id,class:"value-title"})}getFirstColorBadge(e){return Ad("rectangle",e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?"":AT(e).filter(e=>ie(e.value)).map(t=>{const i=this.format(t.value,t.field,e.metaData);return this.spanAsValue(i,null,`color:${t.color}`)}).join(" ")}canBeDeleted(e){return e.isStudy||!e.main&&this.isOptionsChart}maybeGetAdditionalPlots(){const e=this.presenter.mainPane.axes.map(e=>e.plots).flat().filter((e,t)=>!e.main||e.isSeasonal&&t>0),t=this.presenter.display.yAxis.showLastValue;return e.length>0?e.map(e=>{const i=this.getFirstColorBadge(e),s=this.getPlotTitle(e),n=this.canBeDeleted(e)?Cd(e.id):"",r="All"!==t&&!e.isSeasonal?this.getLastValues(e):"";return this.div(`${n} ${i} ${s} ${r}`)}).join(" "):""}}class DT{presenter;splitters=[];canvasContainer=null;mouseCanvas=null;mainCanvas=null;mouseContext;mainContext;leftOffset=0;rightOffset=0;legend;notifyLayoutChanged;el=null;listeners=[];tooltip;width;height;customEventPopup=null;goToLatestButton=null;xAxis;eventCapture;resetZoomAndVisibleRange=!1;constructor(){this.legend=new IT(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=ee(qa.CH_CHTLAYOUTCHANGED,gs.LAYOUT_THROTTLE_DELAY)}get canShowLegend(){if(!this.presenter.hasLegend)return!1;const e=this.presenter.display.chart.showLegend;return!("boolean"==typeof e&&!e)}updateLegend(){this.canShowLegend&&this.legend.update()}removeLegend(){this.legend.remove()}findSvgParentWithClass(e,t){return[e,e.parentElement,e.parentElement.parentElement].find(e=>ie(e)&&e.className===t)}onNonToolHandledMouseDown(e){const t=this.presenter,i=e.target;if("string"==typeof i.className&&i.className.split(" ").includes("value-title"))t.onCardClicked(i);else{const s=this.findSvgParentWithClass(i,"move-pane");if(te(s))return void t.onMovePaneClicked(s);const n=this.findSvgParentWithClass(i,"delete-plot");if(te(n))return void t.deletePlotClicked(n);const r=this.findSvgParentWithClass(i,"show-hide-plot");if(te(r))return void t.showHidePlotClicked(r);const o=this.findSvgParentWithClass(i,"more-actions");if(te(o))return void t.plotMoreActionsClicked(o,e)}}initialize(e){this.presenter=e,this.el=this.presenter.hostElement;const t=new ResizeObserver(e=>{for(const t of e){const{width:e,height:i}=t.contentRect;this.setSize(e,i),ie(this.tooltip)&&this.tooltip.repositionAuto()}});t.observe(this.el.parentElement),this.listeners.push(()=>t.unobserve(this.el.parentElement));const i=e=>this.onNonToolHandledMouseDown(e);this.el.addEventListener("mousedown",i),this.listeners.push(()=>this.el.removeEventListener("mousedown",i)),os(this.el,{flex:1,display:"flex",position:"relative","flex-direction":"column","touch-action":"pan-x pan-y"}),this.tooltip=new VA(this);const s=Gv().config.getCustomEventPopup;this.customEventPopup=s?s(this):null;const{clientHeight:n,clientWidth:r}=this.el;this.width=r,this.height=n,this.canvasContainer=us(this.el,"div"),as(this.canvasContainer,{class:"chart-canvas-container"}),os(this.canvasContainer,{flex:1,display:"flex","flex-direction":"column",position:"relative",height:"100%"}),this.mainCanvas=us(this.canvasContainer,"canvas");const o={height:`${n}px`,width:`${r}px`,"z-index":2,position:"absolute",top:0,left:0};os(this.mainCanvas,o),this.mouseCanvas=us(this.canvasContainer,"canvas"),as(this.mouseCanvas,{tabIndex:0}),o["z-index"]=3,o.outline="none",os(this.mouseCanvas,o),this.goToLatestButton=us(this.el,"button"),ds(this.goToLatestButton,'<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">\n <path d="M13.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0zM6.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0z"></path>\n </svg>'),os(this.goToLatestButton,{position:"absolute",right:0,bottom:0,"z-index":3}),as(this.goToLatestButton,{class:"go-to-latest"}),this.goToLatestButton.onclick=()=>{this.xAxis.goToLatest()},this.listeners.push(()=>{this.goToLatestButton.onclick=null}),this.mainContext=this.mainCanvas.getContext("2d"),this.mouseContext=this.mouseCanvas.getContext("2d"),this.splitters=[],this.xAxis=new ET(this),this.eventCapture=new _T(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(r,n);const a=is(this.el);ie(rs(`.${gs.SVG_ICONS_DOM_NODE}`,a))||function(e){const t=us(e,"div");as(t,{class:gs.SVG_ICONS_DOM_NODE});const i=Object.keys(dd).map(e=>`<symbol id="${yd(e)}" viewBox="0 0 1024 1024">${dd[e]}</symbol>`).join("");t.innerHTML=`<svg style="display:none" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>${i}</defs></svg>`}(a)}reinitialize(){this.el&&hs(".bcharts-card",this.el).forEach(e=>e.remove()),this.customEventPopup?.hide(),this.drawCrosshair({ap:void 0}),this.tooltip.hide(),this.tooltip.setMode(this.presenter.display.tooltip.mode),this.resetZoomAndVisibleRange?this.xAxis=new ET(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,i=!1){this.setChartSize(e,t),this.redraw(i)}setChartSize(e,t){const i={width:`${e}px`,height:`${t}px`};os(this.el,i),this.width=e,this.height=t;const s=globalThis.devicePixelRatio||1,n={height:this.height*s,width:this.width*s};[this.mainCanvas,this.mouseCanvas].forEach(e=>{as(e,n),os(e,i)}),this.mainContext.scale(s,s),this.mouseContext.scale(s,s),this.recalculateLayout(),this.presenter&&HA(this.presenter)}widthNeeded(e,t){const i=this.presenter.allAxes.filter(e=>e.onTheRight===t);return 0===i.length?0:Math.max(...i.map(t=>t.widthNeeded(e)))}recalculateLayout(){if(!this.isHostElementVisible)return;this.leftOffset=0,this.rightOffset=0,this.presenter.allAxes.forEach(e=>e.clearTicks()),this.splitters.length=0;const e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),i=this.widthNeeded(this.mainContext,!1),s=this.height-e,n=this.presenter.panes;let r=O(n.map(e=>e.height)),o=0;const a=gs.PANE_SPLITTER_PERCENT_HEIGHT/100,l=Math.floor(a*s);r*=1+(n.length-1)*a;const c=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;if(this.presenter.display.yAxis.visible){n.some(e=>e.axes.length>1)?(this.leftOffset=i,this.rightOffset=t):c?this.leftOffset=i:this.rightOffset=t}n.forEach((e,i,n)=>{const a=i===n.length-1,c=Math.floor(s*e.height/r),u=new xn(0,o,this.width,c);e.setViewBox(u);const h=new xn(this.width-this.rightOffset,o,t,c),d=new xn(0,o,this.leftOffset,c),p=e=>e.setViewBox(e.onTheRight?h:d);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),o+=c,!a){const e=new xn(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,l);this.splitters.push(e),o+=l}});const u=new xn(this.leftOffset,o,this.width-this.rightOffset-this.leftOffset,e);this.xAxis.setViewBox(u),os(this.goToLatestButton,{right:`${t+5}px`,bottom:`${e+5}px`}),this.updateLegend(),this.xAxis.setDomain(),this.setPriceAxesDomains(),this.notifyLayoutChanged({chart:this.presenter.accessor})}setPriceAxesDomains(){this.presenter.allAxes.forEach(e=>{e.setDomain(),e.updateFullDomain()}),this.presenter.priceDomainsUpdated()}draw(){this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext);for(const s of this.presenter.panes)s.drawBackground(this.mainContext);this.xAxis.draw(this.mainContext);for(const s of this.presenter.panes)s.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext);const e=Gv().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart,i=ie(e)?e:t;this.goToLatestButton.style.display=i&&this.xAxis.canGoToLast()?"block":"none",this.mainContext.restore()}get isHostElementVisible(){return ie(this.el)&&ie(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():Gv().redraw(this.presenter.hostElement))}drawBackground(e){const t=this.presenter.display.chart.backgroundColor;e.clearRect(0,0,this.width,this.height),e.fillStyle=t,e.fillRect(0,0,this.width,this.height)}drawCrosshair({ap:e,offset:t}){const i=this.mouseContext;if(i.clearRect(0,0,this.width,this.height),!e)return!1;return!!this.xAxis.drawCrosshair(i,t)&&(this.presenter.display.yAxis.visible&&e.axis.pane.drawYCrosshair(i,t),!0)}drawSplitters(e){const t=(e=>{const t=bn(e);return Mn(vn(function({r:e,g:t,b:i,a:s}){return{r:255-e,g:255-t,b:255-i,a:s}}(t),t,.7))})(this.presenter.display.chart.backgroundColor);e.strokeStyle=t,e.lineWidth=2,this.splitters.forEach(t=>{const{x:i,y:s,width:n,height:r}=t,o=s+r/2;e.beginPath(),e.moveTo(i,o),e.lineTo(i+n,o),e.stroke()})}toTime(e){return this.xAxis.xScale.xToTime(e)}toIndex(e){return this.xAxis.xScale.timeToIndex(e)}toX(e){return this.xAxis.xScale.timeToX(e)}setCursor(e){const t=function(e){switch(e){case y.Arrow:default:return"default";case y.Crosshair:return"crosshair";case y.Hand:return"pointer";case y.Move:return"move";case y.ResizeVertical:return"ns-resize";case y.Grabbing:return"grabbing";case y.ResizeHorizontal:return"ew-resize"}}(e);os(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&hs(".bcharts-card",this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){const e=this.xAxis.xScale.bar.width/2;return Math.max(e,gs.MIN_EVENT_RADIUS)}}class OT{view;popupElement;date;value;visible;_initialized;constructor(e){this.view=e,this.date=null,this.value=null,this.visible=!1,this._initialized=!1}initialize(){this.popupElement=us(this.view.el,"div"),as(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),os(this.popupElement,{visibility:"hidden",position:"absolute","z-index":30,top:"0px",left:"0px",padding:"5px 10px 10px 10px",display:"flex","flex-direction":"column",background:"var(--chartPopupElemBg, #999)","box-shadow":"0px 2px 10px rgba(0,0,0,.3)","border-radius":"4px",border:"1px solid var(--chartPopupElemBorderColor, #888)","max-height":"400px",overflow:"auto"});const e=us(this.popupElement,"a");as(e,{class:"custom-event-close-button"}),os(e,{position:"absolute",right:"10px",top:"5px",fill:"var(--text-color,#888)",cursor:"pointer"}),e.innerHTML='<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="12px" height="12px"><use xlink:href="#bchart-icon-delete"></use></svg>',e.addEventListener("click",e=>this.hide()),this._initialized=!0}showValue(){}show(e,t,i){this._initialized||this.initialize(),this.date=t,this.value!==i&&(this.value=i,this.showValue()),os(this.popupElement,{visibility:"visible",top:`${e.y}px`,left:`${e.x}px`,width:"310px"}),this.visible=!0}hideValue(){}hide(){this.visible&&(this.hideValue(),os(this.popupElement,{visibility:"hidden"}),this.visible=!1)}}function wT(e,t){if(!((i=e).annotations&&i.annotations.length>0))return;var i;let s=t.annotations||[];t.annotations=s.concat(e.annotations)}const RT='..axes{..plots{.type==="Study"}}';const NT={ok:!1,change:void 0,toApply:void 0};class VT{constructor(e){this.presenter=e,this.clear()}paused=null;undoStack=[];redoStack=[];initial=/* @__PURE__ */new Map;isPaused=!1;clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=/* @__PURE__ */new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,cA(e,E.Moved)))}done(e){this.isPaused?this.paused=e:(this.undoStack.push(e),this.redoStack.length=0)}undo(){this.undoRedo(this.undoStack,this.redoStack,!0)}pause(){this.isPaused=!0}resume(e){this.isPaused=!1,e&&te(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){const t={...e,id:"Delete"};this.presenter.handleAnnotationChange(t)}add(e){const t={annotation:e,id:"Add"};this.presenter.handleAnnotationChange(t)}apply(e,t,i){if(!ie(e))return!1;switch(t){case E.None:case E.Undo:case E.Redo:Hv(`Unexpected tool change ${E[t]} for undo/redo`,"warn");break;case E.Created:i?this.delete(e):this.add(e);break;case E.Deleted:i?this.add(e):this.delete(e);break;default:{const t={...e,id:"Update"};this.presenter.handleAnnotationChange(t);break}}const s=this.presenter.allAnnotations.find(t=>t.uid===e.uid),n=i?E.Undo:E.Redo;return ie(s)&&this.presenter.onAnnotationModifiedByTool(s,n),!0}can(e){const t=e?this.undoStack:this.redoStack;if(t.length<1)return NT;const i=k(t),s=i.toolChange;if(!(e&&s!==E.Deleted&&s!==E.Created))return{ok:!0,change:s,toApply:i};const n=U(t,e=>e.uid===i.uid,t.length-2),r=-1!==n?t[n]:null,o=null===r;return o&&!this.initial.has(i.uid)?NT:{ok:!0,change:s,toApply:o?this.initial.get(i.uid):r}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,i){const{ok:s,change:n,toApply:r}=this.can(i);if(!s)return;const o=e.pop();this.apply(r,n,i),t.push(o)}}class HT{constructor(e){this.presenter=e}text=null;align="center";verticalAlign="top";x=0;y=0;style={color:"#333",fontSize:18};update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;const{fontFamily:t}=this.presenter.display.chart,{fontSize:i,color:s,fontWeight:n}=this.style,{x:r,y:o,width:a,height:l}=this.presenter.mainPlot.axis.pane.getBounds(),c=r+this.presenter.view.leftOffset,u=r+a-this.presenter.view.rightOffset;let h=c;h="center"===this.align?a/2:"right"===this.align?u:c;let d=o+i;"middle"===this.verticalAlign?d=o+i+l/2:"bottom"===this.verticalAlign&&(d=o+l),h+=this.x,d+=this.y,e.save();const p=n||"normal";e.font=`${p} ${i}px ${t}`,e.textAlign=this.align,e.textBaseline="bottom",e.fillStyle=s,e.fillText(this.text,h,d),e.restore()}}function BT(e={}){const t=this.allPlots;if(!t.every(e=>ie(e.timeSeries)&&e.timeSeries.hasData))return"No data to export";const i=e.excludeHeader??!1,s=e.numDecimals??null,n=e.excludeFields??[],r=e=>{const t=/* @__PURE__ */new Map;return e.main&&(t.set(Ka.DateTime,0),this.data.aggregation.isMultiContract&&!e.isExpression&&t.set(Ka.Symbol,0)),e.curves.forEach(e=>{e.fields.forEach(i=>{n.includes(i.id)||t.set(i,e.shift)})}),Array.from(t)},o=this.data.aggregation.isEndOfDay?gs.FMT_ISO_DATE_ONLY:gs.FMT_EXPORT_ALL_BUT_MILLIS,a=(e,t)=>e===Ka.DateTime?Si(t,o):(e=>ie(s,e)?se(e,s):e)(t)?.toString()??"",l={},c=this.timeline.lastSeriesIndex,u=W(this.mainPlot.timeSeries.container.getTimeData()),h=G(this.timeline,+u,Number,ud),d=(e,t)=>{const i=this.timeline.at(e),s=t.timeSeries.container,n=s.getTimeData(),c=l[t.id]||0,u=G(n,+i,Number,$,c),h=+i===+n[u];return h&&(l[t.id]=u),r(t).map(([t,r])=>{if(0===r)return h?a(t,s.getData(t)[u]):t===Ka.DateTime?Si(i,o):"";{const i=this.timeline.at(e-r),o=G(n,+i,Number,$,0);return+i===+n[o]?a(t,s.getData(t)[o]):""}})},p=e=>{const i=t.map(e).flat();return i.slice(1).every(e=>0===e.length)?null:i.join(",")},m=[];if(!i){const e=e=>{const t=new Array(r(e).length).fill("");return t[0]=(e=>`"${f[e.type]}: ${e.title}"`)(e),t};m.push(p(e)),m.push(p(e=>r(e).map(([e,t])=>`"${e.name}"`)))}const g=[0,0];this.allCurves.forEach(e=>{e.fields.every(e=>n.includes(e.id))||(e.shift<0&&(g[0]=Math.min(g[0],e.shift)),e.shift>0&&(g[1]=Math.max(g[1],e.shift)))});for(let f=h+g[0];f<=c+g[1];f++){const e=p(M(d,f));null!==e&&m.push(e)}return m.join("\n")}function FT(e={}){const t=this.view.mainCanvas,{width:i,height:s}=t,{width:n,height:r,title:o}=e,a=(e,t)=>{const i=document.createElement("canvas");return i.width=e,i.height=t,i.getContext("2d")},l=a(i,s),c=globalThis.devicePixelRatio;if(l.drawImage(t,0,0),l.scale(c,c),te(o)){const e=new HT(this);e.update(o),e.draw(l)}const u=this.mainPlot?.timeSeries.container?.getLastDataPoint(Ka.DateTime);if(te(u)){const{fontFamily:e}=this.display.chart,{fontWeight:i,fontSize:s}=this.mainAxis.config;l.font=`${i} ${1.2*s}px ${e}`,l.textBaseline="top";const n=1.5*s,r=getComputedStyle(t),o=r.getPropertyValue("--app-hc-color"),a=r.getPropertyValue("--app-color-pl"),c={x:gs.CARDS_X_OFFSET,y:gs.CARDS_Y_OFFSET},h=bd(this,u,c,0,!1,0),d=`${h.date} ${h.time??""}`.trim(),[p,m]=[1,5],g=(e,t)=>l.measureText(e).width+t,y=(e,t,i,s,n)=>(l.fillStyle=s,l.fillText(e,t,i),g(e,n)),A=(e,t)=>e.type===f[t],S=e=>{let t=e.name;return e.isMain&&A(e,"Symbol")?t=`${e.description} (${e.name}) [${e.exchange}]`:A(e,"Study")&&(t=`${e.description} ${e.name.substring(e.name.indexOf(" "))}`),t};h.panes.forEach(e=>{const{top:t,left:i,width:s,right:r}=e.bounds,l=i+s-r-m;let u=i+c.x,h=t+c.y;e.plots.some(e=>e.isMain)&&(u+=y(d,u,h,o,m)),e.plots.forEach((e,t)=>{const s=S(e),r=!A(e,"Study")&&e.values.length>1;if(!e.isMain&&t>0){let t=u+g(s,m);e.values.forEach(e=>{r&&(t+=g(e.abbreviation,p)),t+=g(e.value,m)}),t>=l&&(u=i+c.x,h+=n)}u+=y(s,u,h,o,m),e.values.forEach(e=>{r&&(u+=y(e.abbreviation,u,h,a,p)),u+=y(e.value,u,h,e.color,m)})})})}const h=e=>({width:n??i,height:r??s,data:e.toDataURL("image/png")});if(te(n)&&te(r)){const e=a(n,r);return e.drawImage(l.canvas,0,0,n,r),h(e.canvas)}return h(l.canvas)}const kT=/* @__PURE__ */Symbol.for("__ias__");class WT{constructor(e){this.accessor=e,this.defaultTool=XS("Default"),this._activeTool=this.defaultTool,this.timeline=new hd(this),this.undoRedoManager=new VT(this),this.title=new HT(this),this.notifySelectionChanged=Q(qa.CH_ANNSELECTIONCHANGED),this.notifyRecreated=Q(qa.CH_RECREATED),this.notifyDefinitionChanged=Q(qa.CH_DEFINITION_CHANGED)}view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken="";metaChangedToken="";streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;getModel(){return this.model}get isEmpty(){return!ie(this.model)}notifyHost(e,t){J(e,t)}async fromModel(e,t){if(this._isShutdown)return;ie(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearSelection(),this.model=e;const i=ue(e);this.data=i.data,this.data.aggregation=No(i.data.aggregation),this.display=i.display,ie(this.display.period)&&(this.display.period=Te(this.display.period)),this.panes=i.panes.map(e=>{const t=new vT(this);return t.fromModel(e),t},this);const s=this.allPlots.map(e=>e.initialize());await Promise.all(s),this._isShutdown||(this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),ie(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view)if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{const i=!t||function(e,t,i){const s={id:"Aggregation",context:{id:"Get"}},n=Ro(Pv(s,t,i)),r=Ro(Pv(s,e,i));if(GT(n,r))return!0;if(!UT(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!UT(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;const o=Sa(t),a=Sa(e);if(function(e,t){const i=e=>e.curves[0],s=i(e),n=i(t),r=$T.includes(s.style),o=$T.includes(n.style);if(r!==o)return!0;if(!o)return!1;if(s.style!==n.style)return!0;if(t.inputs){if(GT(fe(e.inputs),fe(t.inputs)))return!0}return!1}(o,a))return!0;const l=(e,t)=>e.type===t,c=e=>{const t=e.toLowerCase();return l(a,e)&&l(o,e)&&o[t]!==a[t]},u=o.type!==a.type,h=c("Forward"),d=c("Expression"),p=c("Symbol");return u||h||d||p}(e,t,this);this.view.resetZoomAndVisibleRange=i,i&&(this._maxOffset=0)}}closeView(){ie(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(ie(this.view)?this.view.reinitialize():(this.view=new DT,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e))}get activeTool(){return this._activeTool}set activeTool(e){ie(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,ie(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(qa.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){const e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){const e=[];return this.allPlots.forEach(t=>{t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){const e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){const e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){const e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}fixupDensityForForwards(){const e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;const i=t.series,s=e=>e.timeSeries===i||e.eventsSeries===i,n=this.allPlots.find(s);if(!ie(n))return;const r=ie(n)&&n.main;let o=!1,a=!1;if(e===qa.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}const l=ie(t.index)?i.container.getTimeData()[t.index]:null,c=e===qa.TS_EVENTSCHANGED,u=this.view.xAxis,h=u.xScale;if(e===qa.TS_MANYCHANGED||c){if(r&&this.data.checkRange){if(ie(this.display.xAxis.visibleRange)){const e={id:"Period",context:{range:this.display.xAxis.visibleRange}};return e[kT]=!0,void this.accessor.change(e)}delete this.data.checkRange}n.isForward&&this.fixupDensityForForwards();const e=this.view.xAxis?.getMaxCurveOffset()??0;if(n.isStudy){e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0));n.invalidateAssociatedAnnotations("NewChunkArrived")}if((n.isSeasonal&&!u.wasVisibleRangeChanged||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===P.Tail){const e=G(this.timeline,l,Number,ud);u.shouldScrollIntoView(e)&&h.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===qa.TS_DATAPOINTADDED){const e=this.timeline.mergeDateIntoTimeline(l);-1!=e&&u.shouldScrollIntoView(e)?(h.shiftBars(1),o=!0):a=!0,n.isStudy&&n.invalidateAssociatedAnnotations("DataPointAdded")}else e===qa.TS_DATAPOINTCHANGED&&(a=!0,n.isStudy&&n.invalidateAssociatedAnnotations("DataPointChanged"));if(!c&&s(this.mainPlot)&&i.hasData&&0===i.container.size&&this.notifyHost(qa.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),a){o&&Hv("Performance : redundant call to recompute price domains (layout recalculation took care of this)","warn");this.allAxes.filter(e=>e.plots.includes(n)).forEach(e=>{e.setDomain(),ie(l)&&e.updateFullDomain(l)})}if(!this.sentInitialLoadNotification&&e===qa.TS_MANYCHANGED){if(this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(qa.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),HA(this);const e=this.display.period===gs.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(h.fitAllData=!0,h.adjustDomain())}}this.view.redraw()}onMetaChanged(e,t){e===qa.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){const t=this.panes.indexOf(e.pane),i=e.pane.axes.indexOf(e),s={chart:this.accessor,paneIndex:t,axisIndex:i};this.notifyHost(qa.CH_AXISSCALECHANGED,s)}get previousMask(){return ie(this._previousMask)||(this._previousMask=Za(Ka.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return ie(this._hasLegend)||(this._hasLegend=Gv().config.mode===v[v.cmdtyView]),this._hasLegend}onStreamingUpdates(e){ie(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return ie(this._ohlcMask)||(this._ohlcMask=Za(Ka.Open,Ka.High,Ka.Low,Ka.Close,Ka.PreviousClose)),this._ohlcMask}updateMatches(e,t){if(0===(e&this.ohlcMask))return!1;const i=(e,t)=>te(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?i(this.mainPlot.timeSeries.record,t):!!this.mainPlot.isExpression&&i(this.mainPlot.record,t)}getStreamingSubscription(){return Gv().getRecordSource().subject.pipe(uc(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),pc(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return ie(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:rs(`#${e}`),!this._hostElement)throw new Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=ap.subscribe(qa.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=ap.subscribe(qa.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return ap.unsubscribe(this.seriesChangedToken),ap.unsubscribe(this.metaChangedToken),ie(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(qa.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor})}clearSelection(){ie(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(y.Arrow)}print(e={}){const t=us(document.body,"iframe");t.src="",t.style.display="none",t.onload=()=>{const{title:i}=e,s=FT.call(this,{title:i}),n=new Image;n.src=s.data,n.style.width="100%";var r;t.contentDocument.body.appendChild(n),(r=n,new Promise(e=>{const t=()=>{r&&void 0!==r.naturalWidth&&0!==r.naturalWidth&&r.complete?e():setTimeout(t,150)};t()})).then(()=>{const e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),ie(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;const t=this.display.tooltip.mode===gs.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){const t=this.display.tooltip,i=q();!e&&t.visible&&t.mode===gs.TOOLTIP_CARDS&&hs(".bcharts-card",this.hostElement).forEach(e=>{const t=e.classList.contains("bcharts-card-move");if(i&&t)return;e.classList.contains("bcharts-legend")||(e.style.display="none")})}handleAnnotationChange(e){const t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if("List"===e.id)return this.allAnnotations.map(t);if("Cache"===e.id){return ro(this.model,"..annCache{.annotations}").map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}))}if("Add"===e.id)return this.mainAxis.addAnnotation(e.annotation);const i=this.allAnnotations.find(t=>t.uid===e.uid);if(void 0!==i){const t=i.axis,s=t[`${e.id.toLowerCase()}Annotation`];if("function"==typeof s)return s.call(t,i,e),void("Delete"!==e.id||e.isUndoRedo||this.onAnnotationModifiedByTool(i,E.Deleted))}throw new Error(`Unknown sub-action ${e.id} for action ${gs.ANN_ACTION_ID}`)}getPlotInfoFromDomId(e){const t=e.attributes.getNamedItem("data-plot-id").value,i=this.allPlots,s=i.findIndex(e=>e.id===t);return{type:f[i[s].type],index:s}}getSimplePlot(e,t){return this.accessor.change({id:"Plot",context:{id:gs.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){const t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index),s={chart:this.accessor,plot:i};this.notifyHost(qa.CH_CARDPLOTCLICKED,s)}deletePlotClicked(e){const t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index);this.accessor.change({id:"Plot",context:{id:"Delete",type:t.type,index:t.index}});const s={chart:this.accessor,plot:i};this.notifyHost(qa.CH_CARDPLOTREMOVED,s)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);const t=this.getPlotInfoFromDomId(e),i="Show"===e.attributes.getNamedItem("data-act").value;this.accessor.change({id:"Plot",context:{id:"Update",type:t.type,index:t.index,visible:i}});const s=this.getSimplePlot(t.type,t.index),n={chart:this.accessor,plot:s,visible:i};this.notifyHost(qa.CH_CARDPLOTVISIBILITYCHANGED,n)}plotMoreActionsClicked(e,t){const i=this.getPlotInfoFromDomId(e),s=this.getSimplePlot(i.type,i.index),n={x:t.clientX,y:t.clientY},r={chart:this.accessor,plot:s,offset:n,originalEvent:t};this.notifyHost(qa.CH_PLOTNEEDSCONTEXTMENU,r)}onMovePaneClicked(e){const t=parseInt(e.attributes.getNamedItem("data-pane").value),i="Down"===e.attributes.getNamedItem("data-dir").value,s=t+(i?1:0),n=t-(i?0:1);setTimeout(()=>{this.accessor.change({id:"MovePane",context:{from:s,to:n}}),this.notifyHost(qa.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){const i=this.allAxes.indexOf(e),s=e.annotations.map(e=>e.toModel()),n=oo(this.model,`..axes[${(r={axisIndex:i,annotations:s}).axisIndex}]`,e=>(e.annotations=r.annotations,e));var r;try{this.model=Wa(n,gs.CHART_SCHEMA)}catch(o){Hv(`Cannot update annotation (corrupts definition), error is: ${o.message}`,"error")}t&&this.view.draw(),this.notifyHost(qa.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,i=!0){if(t!==E.None){if(i&&t!==E.Undo&&t!==E.Redo){const i=cA(e,t);this.undoRedoManager.done(i)}const s=uA(e);s.toolChange=E[t],this.notifyHost(qa.CH_ANNMODIFIEDBYTOOL,s)}}onAnnotationDone(e,t){const i={id:e,chart:this.accessor,toolChange:E[t]};this.notifyHost(qa.CH_ANNMODIFIEDBYTOOL,i)}onPaneHeightsUpdated(){const e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=function(e,t){let i=e;return t.paneHeights.forEach(e=>{i=oo(i,`..panes[${e.index}]`,t=>(t.height=e.relativeHeight,t))}),i}(this.model,{paneHeights:e}),this.notifyHost(qa.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){const e=this.mainPlot.timeSeries.container;if(!ie(e)||0===e.size)return null;const t=e.getTimeData();return{dataRange:{from:W(t).getTime(),to:k(t).getTime()},barCount:e.size}}}function UT(e,t){return e?.from===t?.from&&e?.to===t?.to}const $T=["Renko","Range","LineBreak","Kagi","PointAndFigure"];function GT(e,t){for(const i of Object.keys(e))if(e[i]!==t[i])return!0}const zT="MARKED_FOR_DELETION";function YT(e,t){if(0===t.plots.length)return e;let i=e;return t.plots.forEach(e=>{const t=qT(e.index),s=XT(i,t);ie(s)&&s.type===e.type&&(i=oo(i,t,e=>(e[zT]=!0,e)))}),i=oo(i,`..plots{.${zT} === true}`,e=>gs.NULL_OBJECT),Ua(i)}function jT(e,{main:t,type:i,index:s},n){const r="..plots{.main === true}",o=ro(e,"..panes").map((e,t)=>{const i=1===ro(e,r).length;return ro(e,"..axes").map((e,s)=>{const o=1===ro(e,r).length;return ro(e,"..plots").map(e=>{const r=function(e,t,i,s){const n=f[e.type],r={curves:ue(e.curves),type:e.type};r.precision=e.precision,r.visible=e.visible;const o=(e,t)=>{ie(e[t])?r[t]=e[t].map(e=>ue(e)):r[t]=[]},a=(e,t,i=!1)=>{!0===t.main&&(e.main=!0,e.showPrevious=t.showPrevious,i&&null!=t.events&&(e.events=ue(t.events)))},l=(e,t=e=>!0)=>{ie(s)&&(e.subtitles=s.allPlots.filter(e=>e.type===n).filter(t).map(e=>e.title))};switch(n){case f.Symbol:{const t=e;r.title=t.symbol;const i=t=>{o(e,"inputs"),0===r.inputs.length&&(r.inputs=ue(t))};switch(r.curves[0].style){case"Renko":i(gs.DEFAULT_RENKO_INPUTS);break;case"Kagi":i(gs.DEFAULT_KAGI_INPUTS);break;case"PointAndFigure":i(gs.DEFAULT_PNF_INPUTS);break;case"LineBreak":i(gs.DEFAULT_LINEBREAK_INPUTS);break;case"Baseline":i(gs.DEFAULT_BASELINE_INPUTS)}a(r,e,!0);break}case f.Study:{o(e,"inputs");const s=Ur(e.study),n=r.inputs,a="AVWAP"===e.study,l=e=>a&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value,c=0===n.length?"":` (${n.map(l).join(", ")})`,u=r.curves.map(e=>Number(e.shift)).filter(e=>e>0),h=0===u.length?"":` [${u.join(", ")}]`;r.title=`${s.id}${c}${h}`,r.studyId=s.id,o(e,"levels"),o(e,"bands"),r.placement=t?i?"overlay":"withMain":"standalone",r.detachedScale=e.detachedScale;break}case f.BalanceSheet:case f.IncomeStatement:{const t=Ka[e.curves[0].fields[0]];r.title=`${t.name} (${e.fundamental.substring(0,1)})`,r.fundamentalId=t.id,r.frequency=e.fundamental;break}case f.Expression:r.title=e.expression,a(r,e);break;case f.Forward:r.title=e.forward,o(e,"offsets"),l(r),a(r,e);break;case f.Seasonal:r.title=e.seasonal,l(r,e=>e.refSeasonal===r.title),o(e,"offsets"),a(r,e);break;default:throw new Error("Unexpected plot type")}return r}(e,i,o,n);return r.paneIndex=t,r.axisIndex=s,r})})}).flat(2).map((e,t)=>(e.index=t,e));if(t)return o.filter(e=>e.main);if(ie(i)){const e=o.filter(e=>e.type===i);return ie(s)?e.filter(e=>e.index===s):e}return o}function KT(e,t){"Study"===e.type&&t.curves?.forEach(e=>delete e.varyColorPerBar),function(e){const t=f[e.type];return t===f.Forward||t===f.Seasonal}(e)?ie(t.curves)&&(e.curves=t.curves):function(e,t){if(i=t,void 0!==i&&t.length===e.length)for(let s=0;s<e.length;++s){const i=t[s],n=e[s];de(n,i);const r=["shift","dashStyle","lineSmoothing","lineMarker"];for(const e of r){const t=i[e];ie(t)&&(n[e]=t)}}var i}(e.curves,t.curves);const i=f[t.type],s=e;if(ie(t.precision)?s.precision=t.precision:delete s.precision,i===f.Symbol)e.symbol=t.symbol;else if(i===f.Study)!function(e,t,i){const s=fe(e),n=fe(t);de(s,n);const r=(o=n,Object.keys(o).map(e=>({name:e,value:o[e]})));var o;r.length>0&&(i.inputs=r)}(e.inputs,t.inputs,e),["bands","levels","detachedScale"].forEach(i=>function(e,t,i){t[i]&&(e[i]=t[i])}(e,t,i));else if(i!==f.BalanceSheet&&i!==f.IncomeStatement||!t.frequency){if(i===f.Expression){const i=e;ie(t.expression)&&(i.expression=t.expression)}else if(i===f.Forward){const i=e;ie(t.offsets)&&(i.offsets=t.offsets),ie(t.forward)&&(i.forward=t.forward)}else if(i===f.Seasonal){const i=e;ie(t.offsets)&&(i.offsets=t.offsets),ie(t.seasonal)&&(i.seasonal=t.seasonal),ie(t.usesInAverage)&&(s.usesInAverage=t.usesInAverage),_o(i)}}else e.fundamental=t.frequency}const qT=e=>`..plots[${e}]`;function XT(e,t){const i=ro(e,t);return 1!==i.length?null:i[0]}const ZT=["withMain","overlay","standalone","clone"];function JT(e){return{axes:[{plots:[]}],height:e.display.chart.newPaneHeight??1}}function QT(e){const t=JT(e);return e.panes.push(t),t}function ev(e,t){const i=te(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:QT(e),s=i.axes[0];return t.oppositeScale??!1?hv(i,s):s}function tv(e,t,i){let s=null;const{mainPane:n,mainAxis:r}=Ta(e);switch(t){case"withMain":s=hv(n,r);break;case"overlay":s=r;break;case"standalone":s=QT(e).axes[0];break;case"clone":if("number"==typeof i){const t={main:!1,index:i,type:f[f.Study]},n=jT(e,t).find(e=>e.index===t.index);s=ro(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}}return s}const iv=[{fields:[Ka.Close.id],colors:["#888"],style:"Line",lineWidth:2,varyColorPerBar:!1,visible:!0}];function sv(e){return"Symbol"===e.type}const nv={attributes:["OpenVsClose"],colors:["#b63400","#007f3e","#1664db"],fields:["Open","High","Low","Close","Change"],style:"Candlestick",varyColorPerBar:!0,lineWidth:1};let rv=0;const ov=["#0d223a","#8abc21","#910000","#2f7ed8","#42ccdc","#bf95df","#860262","#e5daa3","#4682e8","#aaa9c1","#fcccdc","#f66b00","#d875be","#e84b46"],av="Symbol",lv="Expression";function cv(e,t){const i={curves:[{attributes:[],colors:ov.slice(rv,rv+1),fields:e?[Ka.Last.id]:[Ka.Close.id],style:"Line",dashStyle:"Solid",varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0}]};return delete t.oppositeScale,pe(i,t),ie(t.curves)&&de(i.curves,t.curves),rv=(rv+1)%ov.length,i}const uv='..plots{(.type === "Symbol" || .type === "Expression") && .main !== true}';function hv(e,t){let i=e.axes.find(e=>e!==t);return ie(i)||(i={plots:[]},e.axes.push(i)),i}const dv=()=>gs.NULL_OBJECT;function pv(e){return oo(e,"..axes.annotations",dv)}function fv(e){return Ua(oo(e,'..plots{.type === "Symbol" && .main !== true}',dv))}const mv=".display.chart.previous";function gv(e,t,i){const s=[],n=i.allPlots[t.index];if(n?.type!==f[t.type])return s;const r=i.panes.indexOf(n.axis.pane),o=0===r,a=r===i.panes.length-1,l=1===i.panes[r].axes.reduce((e,t)=>e+t.plots.length,0);return o||s.push("ExistingAbove"),l||s.push("NewAbove"),a||s.push("ExistingBelow"),l||s.push("NewBelow"),s}function yv(e,t,i){const s=[],n=i.allPlots[t.index];if(n?.type!==f[t.type])return s;const r=n.axis.pane,o=n.axis===r.axes[0],a=r.axes.some(e=>e.plots.some(e=>n!==e&&!e.hasDetachedScale)),l=n.hasDetachedScale;return(o||l)&&s.push("SecondaryAxis"),o&&!l||s.push("PrimaryAxis"),a&&s.push("NoAxis"),s}function Av(e,t){const i=e.panes[t],s=i.axes.map(e=>e.plots.reduce((e,t)=>e+(t.detachedScale?1:0),0)),n=i.axes.length;return i.axes.forEach((e,t)=>{const r=s[t],o=e.plots.length;if(!(0===r||r<o)&&r===o)if(n>1&&1===r){const r=(t+1)%n;if(s[r]<i.axes[r].plots.length){const t=e.plots.find(e=>e.detachedScale);t&&(i.axes[r].plots.push(t),e.plots=e.plots.filter(e=>!e.detachedScale),s[r]++)}}else{const t=e.plots.find(e=>e.detachedScale);t&&(t.detachedScale=!1)}}),e}function Sv(e,t){const i=e.allPlots[t],s=e.panes.indexOf(i.axis.pane),n=e.panes[s].axes.indexOf(i.axis);return{pane:s,axis:n,plot:e.panes[s].axes[n].plots.findIndex(e=>e===i)}}const Tv={MainPlot:Ma,Aggregation:{Update:Ia,Get:function(e,t,i){return ue(e.data.aggregation)}},Period:{Update:function(e,t,i){const s=ie(t.period),n=ie(t.range),r=ie(t.density),o=e=>e?1:0;if(o(s)+o(n)+o(r)>1)throw new Error("Cannot set more than one of: period, range, density.");if(s&&(e.display.period=t.period,$o(e),zo(e)),n)if(ie(e.display.period)&&!Da(e.display.period)||(e.display.xAxis.visibleRange=t.range),Go(e),zo(e),ie(i)){const s=function(e){const t=e.getDataStats();return null===t?null:t.dataRange}(i),n=No(e.data.aggregation),r=i.data.aggregation,o=(l=r,(a=n).unit!==l.unit||a.size!==l.size||a.spec!==l.spec||!ie(s)||e.data.checkRange);let c=o;if(!o){const{from:e,to:i}=s,{from:n,to:r}=t.range;c=n<e||n>i||r<e||r>i}c&&(e.data.range=t.range),delete e.data.checkRange}else e.data.checkRange=!0;var a,l;return r&&(e.display.density=t.density,$o(e),Go(e)),(s||n||r)&&(Uo(e),i&&(i.forceResetVisibleRange=!0)),e},Delete:function(e,t,i){return ie(t.period)&&t.period&&(delete e.display.period,_a(e),i&&(i.forceResetVisibleRange=!0)),e}},Crosshair:{Update:function(e,t){let[i,s]=re(t.crosshair);const{color:n,dashStyle:r}=t.horizontal||{},{color:o,dashStyle:a}=t.vertical||{},l=(e,t,i)=>{t&&(e.color=t),i&&(e.dashStyle=i)};let c=oo(e,".display.xAxis.crosshair",e=>(e.enabled=i,l(e,o,a),e));return c=oo(c,".display.yAxis.crosshair",e=>(e.enabled=s,l(e,n,r),e)),ie(t.haloTracking)&&"boolean"==typeof t.haloTracking&&(c=oo(c,".display.chart",e=>(e.plotHover=t.haloTracking,e))),c},Get:function(e,t,i){const s=t=>ro(e,t)[0],n=s(".display.chart"),r=s(".display.xAxis.crosshair"),o=s(".display.yAxis.crosshair");let a="none";return r.enabled&&o.enabled?a="both":r.enabled?a="vertical":o.enabled&&(a="horizontal"),{crosshair:a,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:r.color,dashStyle:r.dashStyle},haloTracking:n.plotHover}}},Tooltip:{Update:function(e,t){return oo(e,".display.tooltip",e=>(null!=t.visible&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),null!=t.showMainTitle&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))},Get:function(e,t,i){const s=ro(e,".display.tooltip")[0];return{visible:s.visible,mode:s.mode,showMainTitle:s.showMainTitle,mainTitle:s.mainTitle}}},Events:function(e,t){const i=ue(t);return Object.keys(t).forEach(e=>{gs.EVENTS.includes(e)||delete i[e];let s=t[e];"boolean"==typeof s?s={show:t[e]}:Object.keys(s).forEach(e=>{gs.EVENT_PROPERTIES.includes(e)||delete s[e]}),i[e]=s}),oo(e,Aa,e=>("Symbol"===e.type&&(e.events=e.events||{},Object.keys(i).forEach(t=>{e.events[t]=e.events[t]||{},he(e.events[t],i[t],!1)})),e))},Scale:{Update:function(e,t){let i=oo(e,"..panes[0]..axes",e=>(te(t.scale)&&(e.scale=t.scale),e));return i=oo(i,".display.xAxis",e=>(te(t.marginBars)&&(e.marginBars=t.marginBars),te(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),te(t.ordinalName)&&(e.ordinalName=t.ordinalName),te(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e)),i=oo(i,".display.yAxis",e=>{(ie(t.minPadding)||ie(t.maxPadding))&&Hv("The 'minPadding' and 'maxPadding' are deprecated (ignored)","warn");const i=te(t.preventLabelOverlap)&&!te(t.preventVerticalLabelOverlap);i&&Hv("The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'","warn");const s=i?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return te(s)&&(e.preventLabelOverlap=s),ie(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),ie(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),e}),ie(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{const{axis:t,text:s,index:n,paneIndex:r}=e;if(ie(t,s,n)&&"vertical"===t&&Number.isInteger(n)){i=oo(i,`..panes[${r??0}]..axes[${n}]`,e=>ie(e)?(e.label=s,e):gs.NULL_OBJECT)}}),te(t.contractTransition)&&(i=oo(i,".display.xAxis",e=>(de(e.contractTransition,t.contractTransition),e))),te(t.cycleTransition)&&(i=oo(i,".display.xAxis",e=>(de(e.cycleTransition,t.cycleTransition),e))),i},Get:function(e,t,i){const{mainAxis:s}=Ta(e),n=ro(e,".display.xAxis")[0],r=ro(e,".display.yAxis")[0];return{scale:s.scale,marginBars:n.marginBars??0,preventLabelOverlap:r.preventLabelOverlap,preventVerticalLabelOverlap:r.preventLabelOverlap,preventHorizontalLabelOverlap:n.preventLabelOverlap,snapAnnotationsToPrices:r.snapAnnotationsToPrices,nonEodLabelWithDate:n.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:r.includePercentChangeWithLastValue??!1,ordinalName:n.ordinalName??"",contractTransition:n.contractTransition,cycleTransition:n.cycleTransition}}},Other:{Update:function(e,t,i){let s=e;if(ie(t.comparisonMode)&&"string"==typeof t.comparisonMode&&le(d,t.comparisonMode)&&(s=oo(s,`..panes{${Aa}}.axes`,e=>(e.comparison=t.comparisonMode,e))),ie(t.gridLines)){const[e,i]=re(t.gridLines);s=oo(s,".display.xAxis.gridLines",t=>(t.visible=e,t)),s=oo(s,".display.yAxis.gridLines",e=>(e.visible=i,e))}if(ie(t.minorGridLines)){const[,e]=re(t.minorGridLines);s=oo(s,".display.yAxis.minorGridLines",t=>(t.visible=e,t))}ie(t.newPaneHeight)&&"number"==typeof t.newPaneHeight&&(s=oo(s,".display.chart{.newPaneHeight > 0}",e=>(e.newPaneHeight=t.newPaneHeight,e))),ie(t.showNavigator)&&"boolean"==typeof t.showNavigator&&(s=oo(s,".display.scrollbar",e=>(e.visible=t.showNavigator,e))),ie(t.plotHover)&&"boolean"==typeof t.plotHover&&(s=oo(s,".display.chart",e=>(e.plotHover=t.plotHover,e))),ie(t.showLastValue)&&"string"==typeof t.showLastValue&&(s=oo(s,".display.yAxis",e=>(e.showLastValue=t.showLastValue,e))),ie(t.showMinMaxArc)&&"boolean"==typeof t.showMinMaxArc&&(s=oo(s,".display.chart",e=>(e.showMinMaxArc=t.showMinMaxArc,e))),ie(t.showGoToLatest)&&"boolean"==typeof t.showGoToLatest&&(s=oo(s,".display.chart",e=>(e.showGoToLatest=t.showGoToLatest,e))),ie(t.showLegend)&&"boolean"==typeof t.showLegend&&(s=oo(s,".display.chart",e=>(e.showLegend=t.showLegend,e)),t.showLegend||i.view.removeLegend()),ie(t.allAnnotationsLocked)&&"boolean"==typeof t.allAnnotationsLocked&&(s=oo(s,".display",e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),ie(t.exprSkipLeadingEmpty)&&"boolean"==typeof t.exprSkipLeadingEmpty&&(s=oo(s,".data",e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));const n=[];if(ie(t.extendedHours)&&"boolean"==typeof t.extendedHours&&(s=oo(s,".data",e=>(e.extendedHours=t.extendedHours,e))),ie(t.realTimeCboeBzx)&&"boolean"==typeof t.realTimeCboeBzx&&(s=oo(s,".data",e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&n.push("realTimeCboeBzx"),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),ie(t.buildContinuation)&&"boolean"==typeof t.buildContinuation&&(s=oo(s,".data",e=>(e.buildContinuation=t.buildContinuation,e))),n.length>0){const e={chart:i.accessor,hostPropsChanged:n};i.notifyHost(qa.CH_HOST_PROPS_CHANGED,e)}return s},Get:function(e,t,i){const s=ro(e,`..panes{${Aa}}.axes.comparison`)[0],n=e.display,r=(e,t)=>ce(e,!1,t,"visible"),o=e=>function(e,t){const i=e=>ie(e)&&"boolean"==typeof e&&e,s=i(e),n=i(t);return s&&n?"both":s?"vertical":n?"horizontal":"none"}(r(n.xAxis,e),r(n.yAxis,e)),a=ce(n.chart,!0,"showLegend");return{comparison:s,gridLines:o("gridLines"),minorGridLines:o("minorGridLines"),newPaneHeight:n.chart.newPaneHeight,showLastValue:n.yAxis.showLastValue,showLegend:a,showMinMaxArc:n.chart.showMinMaxArc,allAnnotationsLocked:n.allAnnotationsLocked,exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}},Plot:{Add:function(e,t){switch(t.type){case"Study":return function(e,t){const i=Ur(t.studyId);if(!te(i))return Hv(`Unknown or unavailable study with the id '${t.studyId}'`,"error"),e;const s=Sa(e),n=Yr(i);if(s.type===f[f.Expression]&&n)return Hv(`Cannot add study "${i.meta.title}" because it cannot be based on an expression (current main plot); study needs more than "OHLCV" fields to be calculated.`,"error"),e;const r=t.placement||(i.meta.overlay?"overlay":"standalone"),o={type:"Study",study:t.studyId,visible:!0};"overlay"===r&&"VOL"===t.studyId&&(o.detachedScale=!0),void 0!==t.curves&&(o.curves=i.defaults.curves),KT(o,t);const a=tv(e,r,t.cloneIndex);ie(a)&&a.plots.push(o);const l=e.data.aggregation;return xa(e,"Tick"===l.unit&&"None"===l.spec)}(e,t);case"IncomeStatement":case"BalanceSheet":return function(e,t){const i=Sa(e);if(i.type!==f[f.Symbol])throw new Error("Cannot add fundamental to the chart whose main plot is not a Symbol plot.");const s=i.symbol,n={curves:[{fields:[t.fundamentalId],lineWidth:2,style:"Line",varyColorPerBar:!1,visible:!0,colors:["#888"]}],fundamental:"Quarter",symbol:s,type:h[Ka[t.fundamentalId].category],visible:!0};return KT(n,t),function(e,t){e.panes.push({axes:[{plots:[t]}]})}(e,n),e}(e,t);case"Expression":return function(e,t){const i=Sa(e),s={curves:ue(sv(i)?i.curves:iv),expression:"",type:"Expression",visible:!0};return KT(s,t),ev(e,t).plots.push(s),e}(e,t);case"Symbol":return function(e,t){const i=Sa(e),s=Gv().getDefaultMultiFieldCurve(),n=ie(s)?s:nv,r=i.curves?.length,o={curves:r===t.curves.length&&1===r?ue(sv(i)?i.curves:[n]):t.curves,symbol:"",type:"Symbol",visible:!0};return KT(o,t),ev(e,t).plots.push(o),e}(e,t);case"Seasonal":return function(e,t){const i={curves:ue(iv),offsets:[0],seasonal:"",type:"Seasonal",visible:!0,main:!1};return KT(i,t),t.paneIndex=t.paneIndex??0,ev(e,t).plots.push(i),e}(e,t);default:throw new Error("Unexpected plot type '${type}', not supported currently")}},Get:jT,Delete:YT,Update:function(e,t,i){if(ie(t.placement)&&!ZT.includes(t.placement))throw new Error(`Unknown placement: ${t.placement}`);const s=t.main?Aa:qT(t.index),n=XT(e,s);if(!te(n)||te(t.type)&&n.type!==t.type)return e;if(te(t.visible))return n.visible=t.visible,e;if(n.main&&function(e){const t=f[e.type];return t===f.Symbol||t===f.Expression}(n)){if(t.curves){const i=e=>e.curves[0].style===o[o.Range],[s,r]=[i(n),i(t)],a=!s&&r;s&&!r?e=Ia(e,{unit:"Day",size:1,spec:"None"}):a&&(e=Ia(e,{unit:"Intraday",size:100,spec:"PerRange"}))}t.type||(t.type=n.type);const i=n;return ie(t.precision)?i.precision=t.precision:delete i.precision,ie(t.showPrevious)&&(e=oo(e,Aa,e=>(e.showPrevious=t.showPrevious,e))),t.curves?Xo(e,t):e}{let n=oo(e,s,e=>(KT(e,t),e));const r=jT(n,t,i).find(e=>e.index===t.index);if(!ie(r))return e;if(!(t.type===f[f.Study]&&ie(t.placement)&&t.placement!==r.placement))return n;const o=XT(n,s);n=YT(n,{plots:[{index:t.index,type:t.type}]});const a=tv(n,t.placement);return null!==a&&a.plots.push(o),n}}},Compare:{Update:function(e,t){const i=function(e){return ie(e.symbols)&&(Hv("Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types","warn"),e.plots=e.symbols.map(e=>(e.type=av,e))),e.plots?.some(e=>ie(e.leftScale))?(Hv("Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'","warn"),e.plots.map(e=>{const t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}(t),{yes:s,no:n}=V(i,e=>e.oppositeScale??!1),{mainPane:r,mainAxis:o}=Ta(e);r.alignOnExpirations=t.alignOnExpirations||!1;const a=hv(r,o),l=e=>![av,lv].includes(e.type);a.plots=a.plots.filter(l);const c=o.plots.filter(e=>e.main||l(e)),u="Tick"===e.data.aggregation.unit;rv=0;const h=M(cv,u);return o.plots=c.concat(n.map(h)),s.length>0&&(a.plots.push(...s.map(h)),a.comparison=o.comparison,a.scale=o.scale),Ua(e)},Get:function(e,t){const i=ro(e,uv),{mainPane:s,mainAxis:n}=Ta(e),r=[];for(const o of i){const e=n.plots.includes(o),t=o.type.toLowerCase(),i={curves:ue(o.curves),type:o.type,[t]:o[t],leftScale:!e};r.push(i)}return{plots:r,alignOnExpirations:s.alignOnExpirations}}},Annotation:{Get:function(e,t,i){const s=ro(e,"..panes").map((e,t)=>ro(e,"..axes").map((e,i)=>ro(e,".annotations").map(e=>({...e,paneIndex:t,axisIndex:i})))).flat(2).map((e,t)=>({...e,index:t}));return ie(t.index)&&Number.isFinite(t.index)?t.index<s.length?[s[t.index]]:gs.EMPTY_ARRAY:s}},MovePane:function(e,t){let i=e.panes;return i.splice(t.to,0,i.splice(t.from,1)[0]),e},Template:function(e,t){let i=ue(e);if(t.strip.main){const e=Sa(i),t=e.type.toLowerCase();e[t]=gs.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(i=pv(i)),t.strip.compare&&(i=fv(i)),i=oo(i,".data",e=>(e.range&&(delete e.range,e.checkRange=!0),e)),i},Outline:function(e,t,i){const s=jT(e,{main:!0},i)[0],n=s.title===gs.PLACEHOLDER_SYMBOL_NAME,r="Symbol"===s.type,o="Expression"===s.type,a=ca(s.title);let l=[];return o&&!la(a)?l=a.symbols:n||(l=[s.title]),{isTemplate:n,isDefinition:!n,main:{isSymbol:r,isExpression:o,symbols:l,title:n?null:s.title},compare:ro(e,uv).map(e=>e.symbol),annotations:ro(e,"..annotations").map(e=>e.id),studies:jT(e,{type:"Study"},i).map(e=>e.title)}},Theme:{Update:function(e,t){let i=e;const{backgroundColor:s,axis:{gridLinesColor:n,textColor:r,crosshairColor:o,gridLinesStyle:a},fontSize:l}=t,{chart:c,xAxis:u,yAxis:h}=l||{};if((s||c)&&(i=oo(e,".display.chart",e=>(s&&(e.backgroundColor=s),c&&(e.fontSize=c),e))),n){const e=e=>(e.color=n,e);i=oo(i,".display.xAxis.gridLines",e),i=oo(i,".display.yAxis.gridLines",e),i=oo(i,".display.yAxis.minorGridLines",e)}if(a){const e=e=>(e.dashStyle=a,e);i=oo(i,".display.xAxis.gridLines",e),i=oo(i,".display.yAxis.gridLines",e),i=oo(i,".display.yAxis.minorGridLines",e)}if(r){const e=e=>(e.textColor=r,e);i=oo(i,".display.xAxis",e),i=oo(i,".display.yAxis",e)}if(o){const e=e=>(e.color=o,e);i=oo(i,".display.xAxis.crosshair",e),i=oo(i,".display.yAxis.crosshair",e)}if(u||h){const e=e=>t=>(t.fontSize=e,t);u&&(i=oo(i,".display.xAxis",e(u))),h&&(i=oo(i,".display.yAxis",e(h)))}return i},Get:function(e,t,i){const{chart:s,xAxis:n,yAxis:r}=e.display||{},{fontSize:o,backgroundColor:a}=s||{},{fontSize:l,gridLines:c,textColor:u,crosshair:h}=n||{},{color:d,dashStyle:p}=c||{},{fontSize:f}=r||{},{color:m}=h||{};return{backgroundColor:a,axis:{gridLinesColor:d,textColor:u,crosshairColor:m,gridLinesStyle:p},fontSize:{chart:o,xAxis:l,yAxis:f}}}},Clear:function(e,t,i){const{paneIndex:s,annotations:n,studies:r}=t||{},o=`..panes${Number.isInteger(s)?`[${s}]`:""}`;let a=e;const l=e=>gs.NULL_OBJECT;if(!0===n){const e=e=>i.onAnnotationModifiedByTool(e,E.Deleted,!1);i.allAnnotations.forEach(e),a=oo(a,`${o}..annotations`,l)}return!0===r&&(a=oo(a,`${o}..plots{.type=="Study"}`,l)),a=Ua(a),a},Previous:{Update:function(e,t,i){return oo(e,mv,e=>(de(e,t),e))},Get:function(e,t,i){return ro(e,mv)[0]}},MovePlot:{Update:function(e,t,i){if(!gv(0,t,i).includes(t.targetPane))return e;const s=Sv(i,t.index),n=XT(e,qT(t.index));e.panes[s.pane].axes[s.axis].plots.splice(s.plot,1);let r=s.pane,o=!0;switch(t.targetPane){case"ExistingAbove":r--;break;case"NewAbove":e.panes.splice(r,0,JT(e)),o=!1;break;case"ExistingBelow":r++;break;case"NewBelow":r++,o=!1,e.panes.splice(r,0,JT(e))}o&&i.panes[r].isMain&&"Study"===n?.type&&"VOL"===n.study&&(n.detachedScale=!0);const a=e.panes[r];a.axes.length<2&&a.axes[0].plots.length>0&&a.axes.push({plots:[]});const l=a.axes.findIndex(e=>0===e.plots.length),c=-1===l?a.axes.length-1:l;a.axes[c].plots.push(n);let u=Av(e,s.pane);return u=Av(u,r),Ua(u)},Get:gv},PinPlot:{Update:function(e,t,i){if(!yv(0,t,i).includes(t.targetAxis))return e;const s=Sv(i,t.index),n=e.panes[s.pane],r=XT(e,qT(t.index));let o=-1;switch(t.targetAxis){case"PrimaryAxis":o=0;break;case"SecondaryAxis":o=1;break;case"NoAxis":r.detachedScale=!0}if(-1!==o)if(o!==s.axis)delete r.detachedScale,n.axes.length<2&&o>0&&n.axes.push({plots:[]}),n.axes[o].plots.push(r),n.axes[0===o?1:0].plots.splice(s.plot,1);else{delete n.axes[s.axis].plots[s.plot].detachedScale}return Ua(Av(e,s.pane))},Get:yv}};function vv(e){return"function"==typeof e}function Pv(e,t,i){return function(e,t){const i=Tv[e];if(vv(i))return i;{let e=void 0!==t?i[t]:void 0;if(!vv(e)&&(e=i[gs.DEFAULT_ACCESSOR_SUBACTION],!vv(e)))throw new Error("Invalid accesor id and/or sub id");return e}}(e.id,e.context.id)(t,e.context,i)}function Cv(e){return{id:"MainPlot",context:e}}const bv={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},Ev=/* @__PURE__ */Symbol.for("__ias__");class Lv{constructor(e=!1){this.headless=e,this.presenter=e?null:new WT(this)}presenter;_model;get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless)console.error("You cannot initialize a headless chart.");else if(this.presenter.initialize(e),te(t)){const e="string"==typeof t;e?Hv("Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.","warn"):(t.template&&this.load(t.template),delete t.template);const i=e?{symbol:t}:t;this.change(Cv(i))}}shutdown(){if(!this.headless){const e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,i=null){if(!this.headless)if(ie(e)){bo(e,t),Co(e,t);const s=XS(e,!1,t,i,this.presenter);s.isDrawingAnnotation&&this.presenter.view.setCursor(y.Crosshair),this.presenter.activeTool=s,q()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}zoom(e){this.headless||"boolean"!=typeof e||(e?this.annotate("ZoomIn"):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return zv()}get model(){return(this.headless?this._model:this.presenter.getModel())||zv()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:gs.ACTION_TEMPLATE,context:{strip:e}})}change(...e){const t={chart:this,actions:e.filter(e=>!e[Ev])};t.actions.length>0&&this.presenter?.notifyHost(qa.CH_API_ACTIONS_RECEIVED,t);const i=Gv().config.validateInput,s=e.map(e=>i?Wa(e,gs.ACCESSOR_SCHEMA):e);if(1===s.length){const e=s[0];if(e.id===gs.ACTION_TEMPLATE||e.context.id===gs.ACTION_GET)return Pv(e,this.model,this.presenter);if(!this.headless&&e.id===gs.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}const{yes:n,no:r}=V(s,e=>e.id===gs.ACTION_PLOT&&ie(e.context)&&e.context.id===gs.ACTION_DELETE),o=ue(this.model);let a=ue(this.model);const l=r;n.length>0&&l.push({id:gs.ACTION_PLOT,context:{id:gs.ACTION_DELETE,plots:n.map(e=>e.context)}}),l.forEach(e=>{if(a=Pv(e,a,this.presenter),!ie(a))throw new Error("Forgot to return model from accessor")}),this.fromModel(a,o)}async fromModel(e,t){const i=Wa(e,gs.CHART_SCHEMA);this.headless?this._model=i:await(this.presenter?.fromModel(i,t))}async load(e,t){const i={...bv,...t};let s=Wa(JSON.parse(e),gs.CHART_SCHEMA);const n=this.model,r=ue(n);if(ie(n)){if(s=function(e,t,i){const s=Sa(t),n=s.type.toLowerCase();if(s[n]===gs.PLACEHOLDER_SYMBOL_NAME){const s=Sa(e),{mainAxis:n}=Ta(t),r=n.annotations,o=Ma(t,s);if(i){const{mainAxis:e}=Ta(o);e.annotations=r}return o}return t}(n,s,i.keepNewAnnotations),i.keepNewAnnotations||(s=pv(s)),i.keepOldAnnotations&&(s=function(e,t){const{mainAxis:i}=Ta(e),{mainAxis:s}=Ta(t);wT(i,s);const n=e=>ro(e,'..plots{.type==="Study"}.study')[0],r=ro(e,RT).filter(e=>e!==i),o=ro(t,RT).filter(e=>e!==s);return r.forEach(e=>{const t=n(e),i=o.find(e=>t===n(e));ie(i)&&wT(e,i)}),t}(n,s)),i.keepNewCompare||(s=fv(s)),i.keepOldCompare&&(s=function(e,t){const i=ro(e,uv),s=ro(t,uv),n=Math.max(0,4-s.length);if(0===n)return t;const r=i.filter(e=>!s.find(t=>e.symbol===t.symbol)).slice(0,n);if(0===r.length)return t;const{mainPane:o,mainAxis:a}=Ta(t),{mainAxis:l}=Ta(e);return r.forEach(e=>{l.plots.includes(e)?a.plots.push(e):hv(o,a).plots.push(e)}),t}(n,s)),i.keepOldAggregation){const e={id:gs.ACTION_AGGREGATION,context:n.data.aggregation},t=s.display.density;s=Pv(e,s,this.presenter),i.keepNewBarWidth&&ie(t)&&(s.display.density=t)}await this.fromModel(s,r),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){this.headless||this.presenter.undoRedoManager.clear(!0)}reset(e=!0){const t=zv();if(this.headless)this._model=t;else if(this.presenter.getModel()){const i=this.presenter.mainPlot;let s=null;const n=i;if(i.isSymbol?s={symbol:n.symbol}:i.isExpression?s={expression:n.expression}:i.isForward?s={forward:n.forward}:i.isSeasonal&&(s={seasonal:n.seasonal}),ie(s)){const i=Pv({id:"Theme",context:{id:"Get"}},this.model,this.presenter);let n=Pv(Cv(s),t,this.presenter);e&&(n=Pv({id:"Theme",context:i},n,this.presenter)),this.presenter?.fromModel(n)}}this.clearUndoRedo(),this.presenter?.notifyHost(qa.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){Hv("Obsolete: please use 'exportImage' method instead.","warn")}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}exportData(e={}){return this.headless?null:BT.call(this.presenter,e)}exportImage(e={}){return this.headless?null:FT.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&this.presenter.undoRedoManager.canUndo}get canRedo(){return!this.headless&&this.presenter.undoRedoManager.canRedo}undo(){this.canUndo&&this.presenter.undoRedoManager.undo()}redo(){this.canRedo&&this.presenter.undoRedoManager.redo()}pauseUndoRedo(){this.headless||this.presenter.undoRedoManager.pause()}resumeUndoRedo(e){this.headless||this.presenter.undoRedoManager.resume(e)}priceToY(e,t=0,i=0){const s=this.presenter;if(this.headless||t<0||i<0||t>s.panes.length)return null;const n=s.panes[t];if(i>n.axes.length)return null;return n.axes[i].toY(e)}yToPrices(e){const t=this.presenter;if(this.headless)return null;for(const[i,s]of t.panes.entries()){const t=s.getBounds();if(ie(t)&&e>=t.y&&e<=t.y+t.height)return{pane:i,prices:s.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(qa.CH_DIDBECOMEACTIVE,{chart:this})}}function Mv(){const e=globalThis.parent?.location?.hostname||"";return["","localhost","127.0.0.1"].includes(e)||function(e){const t=e.split(".");if(!t||4!==t.length)return!1;const i=t.map(Number);if(!i.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;const[s,n]=i;return 10===s||172===s&&n>=16&&n<=31||192===s&&168===n}(e)}function _v(){let e=document.domain;const t=e.split("."),i="__tld"+/* @__PURE__ */(new Date).getTime();let s=0;for(;s<t.length-1&&-1===document.cookie.indexOf(`${i}=${i}`);)e=t.slice(-1-++s).join("."),document.cookie=`${i}=${i};domain=${e};`;return document.cookie=`${i}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function xv(e,t){var i;i=t,Object.keys(i).forEach(e=>!ie(i[e])&&delete i[e]);return`${e}/?${new URLSearchParams(t).toString()}`}function Iv(e,t=""){return xv(atob("aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ=="),{module:atob("YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy"),secret:t,referer:e})}function Dv(e,t){return e+Math.random()*(t-e)}const Ov=new Function(atob("Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg")),wv=new Function("f",atob("Zi5yZW1vdmVBbGxDaGFydHMoKTsg")),Rv=new Function("m",atob("cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw=="));async function Nv(e,t){if(t&&!Rv(e.mode))return;let i=!1,s=0,n=25;for(;!i&&s<5;){const t=Mv()||"FreeWidget"===e.mode,r=t?e.apiKey:"";try{const n=Iv(t?"":_v(),r),o=await fetch(n);if(o.ok){const t=await o.json(),s=t[atob("YXV0aG9yaXplZA==")];e.knownSite=s,s?(e.dataEndpoint=(t[atob("ZGF0YS1lbmRwb2ludA==")]||"").replace(/\/$/g,""),e.allowCredentials=t[atob("YWxsb3dDcmVkZW50aWFscw==")]):(e.dataEndpoint="",e.allowCredentials=!1),i=!0;break}s++}catch{}s++,n*=2,await new Promise(e=>setTimeout(e,n))}i&&e.knownSite||(setTimeout(Ov,Dv(2e3,3e3)),setTimeout(()=>wv(Gv()),Dv(4e3,5e3)))}const Vv={major:2,minor:366,patch:1};function Hv(e,t="info",i=""){const s=globalThis.console;s[void 0!==s[t]?t:"log"](e,i)}const Bv={environment:"Browser",validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${gs.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:"wheel+shift",bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:"Auto",tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:"Unspecified",hostingModel:"Page",overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,baseUrl:{instruments:"/proxies/instruments",futures:"/proxies/futures",timeseries:"/proxies/timeseries",timeseriesNew:"/proxies/new-timeseries",ondemand:"/proxies/ondemand",options:"/proxies/core-api"},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){const i=this.baseUrl[e];let s=`${i}${t}`;if(Rv(this.mode)&&this.knownSite){const{username:n,password:r}=this.credentials||{},o=ie(n,r),a=("timeseries"===e||"timeseriesNew"===e)&&o&&this.allowCredentials?`&username=${n}&password=${r}`:"";s=`https://${this.dataEndpoint}${i}${t}${a}`}const n=await fetch(s);return await n.text()},getCustomEventPopup:e=>null};async function Fv(e,t){const i=Gv()?.config;if(!i||!i.fetch)throw new Error("You should call initFeed first");let s=t;return"timeseries"===e?s=`/historical${t}`:"options"===e&&(s=`/options-historical${t}`),await i.fetch.call(i,e,s)}let kv=!1,Wv=null;function Uv(e){const t=e.extensions?.studyProvider;if(!ie(t))return;const i=t.getFields(),s=t.getStudies(),n=ue(Rr(gs.CHART_SCHEMA)),r=n.definitions,o=r.studyField.enum,a=r.study.enum;for(const u of i)if(o.includes(u.id))throw new Error(`Field with id ${u.id} already exists`);for(const u of s)if(a.includes(u.id))throw new Error(`Study with id ${u.id} already exists`);var l,c;o.push(...i.map(e=>e.id)),a.push(...s.map(e=>e.id)),l=gs.CHART_SCHEMA,c=n,ka.addSchema(l,c),ja(i),Fr(s)}function $v(e,t={}){if(kv)throw new Error("You should only call initFeed once during page's lifetime");kv=!0;const i=Object.assign(Bv);return de(i,t),te(i.logo)&&function(e,t){const i=(new DOMParser).parseFromString(e,"image/svg+xml"),s=i.querySelector("svg")?.getAttribute("viewBox"),n=i.querySelector("path")?.getAttribute("d");if(te(s)&&te(n)){const e=s.split(" ").map(Number);4===e.length&&e.every(Number.isFinite)&&(GA={path:new Path2D(n),width:e[2],height:e[3],rect:new xn(0,0,0,0),logoClickable:t})}}(i.logo,i.logoClickable??!1),Uv(i),Wv=new e(i),Wv.version=`${Vv.major}.${Vv.minor}.${Vv.patch}`,Hv(`%cBarchart Chart version ${Wv.version}`,"info","font-size: larger"),Wv.cachesData&&(Wv.subject?.subscribe(Wv.onPerformInternalGc.bind(Wv)),ap.subscribe(qa.CH_ALL,Wv.onChartChanged.bind(Wv))),Wv}function Gv(){return Wv}function zv(){return ue(Gv()?.template)}function Yv(){te(Wv)&&(Wv.shutdown(),kv=!1,Wv=null)}function jv(){return new Lv(!0)}function Kv(e){const t=jv();return t.load(e),t.change({id:"Outline",context:{id:"Get"}})}function qv(e,t,i,s=null){return new Proxy(e,{get:function(e,n,r){return n===t?function(t){const r=s?t[s]:t;return(i.handlesRequestsFor(r)?i:e)[n](t)}:Reflect.get(e,n,r)}})}class Xv{constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=/* @__PURE__ */new Map,this.pendingRedraw=/* @__PURE__ */new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=Pe()}version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;get subject(){return this.isAuxiliary||te(this._subject)||(this._subject=(new ql).pipe(fc(gs.INTERNAL_GC_MILLIS),pc(e=>e.length>0))),this._subject}get isAuxiliary(){return null!==window.opener}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=qv(this.timeSeriesSource,"getTimeSeries",e,"symbol"),this.metaDataSource=qv(this.metaDataSource,"getMetaData",e),this.recordSource=qv(this.recordSource,"getRecord",e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!te(this.timeSeriesSource))throw new Error("No time series source defined");return this.timeSeriesSource}getMetaDataSource(){if(!te(this.metaDataSource))throw new Error("No metadata source defined");return this.metaDataSource}getRecordSource(){if(!te(this.recordSource))throw new Error("No record source defined");return this.recordSource}async ready(){return ps.call(this,async()=>{const e=this instanceof tP||this instanceof Zv||this instanceof nP;await Nv(this.config,e);let t=this.config.defaultTemplate;if(!t)throw new Error("Must provide a default template");if("string"==typeof t){const e=await fetch(t);t=await e.json()}return this.template=Wa(t,gs.CHART_SCHEMA),!0})}getHeadlessChart(){return jv()}fixupRenderTo(e){if(!te(e))return null;if(e instanceof HTMLElement)return e;const t=rs(`#${e}`);if(te(t))return t;const i=[...this.charts.keys()].find(t=>t.id===e);return te(i)?i:null}checkChart(e,t){const i=this.fixupRenderTo(e),s=te(i)&&this.charts.has(i);return te(t)&&t!==s&&Hv(`There is ${t?"no":"already a"} chart inside the element ${e}`,"error"),i}addChart(e,t=null){const i=this.checkChart(e,!1),s=new Lv;return this.charts.set(i,s),s.initialize(e,t),s}removeChart(e){const t=this.checkChart(e,!0);if(!te(t))return;this.charts.get(t).shutdown(),this.charts.delete(t)}removeAllCharts(){for(const e of this.charts.keys())this.removeChart(e)}getChart(e){const t=this.checkChart(e);return te(t)?this.charts.get(t):null}redraw(e){const t=this.checkChart(e,!0);te(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),te(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{const t=this.getChart(e);if(!te(t?.presenter?.view))return;const i=t.presenter.view;i.isHostElementVisible&&i.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:/* @__PURE__ */new Set,records:/* @__PURE__ */new Set,timeSeries:/* @__PURE__ */new Set}}getAllCacheableEntities(e){for(const t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){const e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{te(t)&&(te(t.record)&&e.records.add(t.record),te(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){this.getTimeSeriesDataSource().refresh(),J(qa.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){const e=this.getCacheableEntities();this.evictUnused(e)}triggerGc(){this.subject?.next()}onChartChanged(e,t){e!==qa.CH_RECREATED&&e!==qa.CH_SHUTDOWN||(this.isAuxiliary?this._mainFeed?.triggerGc():this.triggerGc())}getDefaultMultiFieldCurve(){if(!te(this.template))return null;if(!this.knowDefaultCurve){const e=Sa(this.template);1===e.curves.length&&function(e){switch(o[e]){case o.OHLC:case o.HLC:case o.Candlestick:case o.HollowCandles:case o.HeikinAshi:case o.ElderImpulseSystem:case o.Range:case o.MultiColumn:return!0;default:return!1}}(e.curves[0].style)?this.defaultOhlcCurve=ue(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=ue(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}}class Zv extends Xv{constructor(e){super(e),this.timeSeriesSource=new Rh(!1),this.metaDataSource=new nn,this.recordSource=new iu}}class Jv extends Xv{constructor(e){super(e),this.timeSeriesSource=new Rh(!0),this.metaDataSource=new nn,this.recordSource=new su}}class Qv extends Xv{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new Rh(!0),this.metaDataSource=new nn,this.recordSource=new iu}}const eP=["drazen.dotlic@barchart.com","princec","b.hebert24@barchart.com"];class tP extends Xv{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new Rh(!0),this.metaDataSource=new rn,this.recordSource=new nu,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,te(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){te(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug("need to refresh caches"),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on("events",this.onEvents),this.connection.on("timestamp",this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&eP.includes(this.connection._username)&&Hv(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===gs.BC_EVENT_DISCONNECTED||e===gs.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):e!==gs.BC_EVENT_LOGGED_IN&&e!==gs.BC_EVENT_FEED_RESUMED||(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),te(this._connection)&&(this.connection.off("timestamp",this.onTimestamp),this.connection.off("events",this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}}function iP(e,t){return new sP(e,t)}class sP{_client;_subscriptions=/* @__PURE__ */new Map;_listeners=/* @__PURE__ */new Set;constructor(e,t){this._client=e;const i=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{const s=e.marketSnapshot;if(te(s)){const e=i(t);null!==e&&this._listeners.forEach(t=>t.onSnapshot?.(s,e))}const n=e.marketUpdate;if(te(n)){const e=i(t);null!==e&&this._listeners.forEach(t=>t.onUpdate?.(n,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return te(await this._client.connection)}shutdown(){te(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!te(this._client))return;const t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!te(this._client))return;const t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){const t=await this._client.connection;return await(t?.getInstrument(e))??[]}}class nP extends Xv{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new Rh(!0),this.metaDataSource=new on,this.recordSource=new ru,ap.subscribe(qa.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(const i of this._auxFeeds)i.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&J(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw new Error("Cannot set adapter on auxiliary feed");this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){const e=await(this._mainFeed?.ready())??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await(this._adapter?.ready())??!1}subscribe(e){this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){const t=this._auxFeeds.findIndex(t=>t.id==e.id);-1!==t&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc())}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(const t of this._auxFeeds)t.getAllCacheableEntities(e)}}const rP=ap;export{Wo as Aggregation,l as AggregationSpec,a as AggregationUnit,Zv as BarchartSiteDataFeed,Xv as BaseDataFeed,tu as BaseRecordSource,P as ChunkPart,Eh as ContainerWrapperTimeSeries,OT as CustomEventPopup,tl as EmptyRecord,t as ExpressionMissingBar,s as ExpressionNoDataApproach,i as ExpressionRecompute,Vm as ExpressionSeries,Ga as Field,h as FieldCategory,u as FieldFormat,c as FieldValueType,Ka as Fields,tP as MarketDataFeed,Qv as MiniWidgetDataFeed,Eu as OHLCDataPointBuilder,nP as OpenFeed,rP as PubSub,m as SeriesKind,Jv as SnapshotDataFeed,up as StudySeries,Mu as TimeSeriesContainer,ip as TimeSeriesQuery,qa as Topics,iP as adaptOpenFeedClient,us as appendDOMElement,ps as asyncReady,Cy as convertSeries,fa as doesExpressionHaveComputation,zr as doesStudyExist,ua as evaluateExpression,da as formatExpression,zs as formatPriceWithDecimals,Pe as generateUid,$r as getAnnotationTraits,Kv as getChartOutline,Ys as getCombinedMetaData,pa as getExpressionSymbols,Gv as getFeed,En as getLightness,tT as getStudyOptions,Zr as getTaxonomies,Ki as hasOpenInterest,$v as initFeed,Py as linReg,Nm as makeExpression,cp as makeHelperField,ny as makeStudy,by as mapSeries,ay as movAvg,ly as movExp,hy as movHul,cy as movSmo,uy as movWei,Tu as optionValueToDate,ca as parseExpression,ma as replaceExpressionSymbols,Ay as roc,as as setAttributesDOMElement,Yv as shutdownFeed,vy as stdDev,os as styleDOMElement,my as trueRange,yy as typical};
|