@barchart/chart-lib 2.361.0 → 2.361.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.
@@ -4,7 +4,7 @@ ${d.error}`),a=d.clean):d.hasErrors||p(`[Main Plot] "${a}" is an expression, uns
4
4
  Symbol: ${e.symbol} %cPrice: ${e.tradePrice} %cSize: ${e.tradeSize} %cTime: ${o5(e.time,tz.DEBUG_TIME_FORMAT)} %cSession: ${e.session}`,"color:#0f0","color:#a7a","color:#f96","color:#bee")}else if(e.type===tz.REALTIME_VOLUME){let t=this.updateFromVolume(e);0!==t&&(this.subject.next({topic:aS.RT_VOLUME,data:e,updated:t}),e.symbol===tz.DEBUG_SYMBOL&&console.log(`Volume
5
5
  Symbol: ${e.symbol} %cValue: ${e.value} %cSession: ${e.session}`,"color:#a7a","color:#bee"))}}updateFromQuote(e,t=!1){let i=this.findRecordForSymbol(e.symbol);i.resetUpdated(),i.update(aA.Open,e.openPrice),i.update(aA.High,e.highPrice),i.update(aA.Low,e.lowPrice),i.update(aA.Last,e.lastPrice),i.update(aA.Close,e.lastPrice);let s=(e,t)=>{eF(t)&&i.update(e,t)};return s(aA.Volume,e.volume),i.update(aA.PreviousClose,e.previousPrice),t&&(s(aA.PreviousOpen,e.previousOpenPrice),s(aA.PreviousHigh,e.previousHighPrice),s(aA.PreviousLow,e.previousLowPrice)),i.computeWellKnown(),i.updated}updateFromVolume(e){let t=this.findRecordForSymbol(e.symbol);return t.resetUpdated(),t.update(aA.Volume,e.value),t.updated}}class lF extends lR{localTimeZone;constructor(){super(),this.localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone}get feed(){return AA()}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),this.feed.unsubscribe(e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new aI(e))}postInit(e,t){e&&this.feed.subscribe(t.translated)}onSnapshot(e,t){let i=this.findRecordForSymbol(t),s=AA().metaDataSource.getMetaData(t);if(!s.isReady)return;let r=(e,t)=>{if(eH(t)){let r=s.asPrice(t);return i.update(e,r),r}};i.resetUpdated();let n=r(aA.Open,e.open?.price),a=r(aA.High,e.high?.price),o=r(aA.Low,e.low?.price),l=r(aA.Last,e.last?.price);if(eH(r(aA.Close,e.close?.price))||r(aA.Close,e.settlement?.price),eH(e.instrumentStatus?.tradeDate)){let t=e.instrumentStatus.tradeDate%100;i.update(aA.TradingDay,t)}e.volume?.volume&&i.update(aA.Volume,s.asQuantity(e.volume.volume));let u=this.toExchangeTime(e.transactionTime,s.timeZone);eH(r(aA.PreviousClose,e.prevClose?.price))||r(aA.PreviousClose,e.previousSession?.settlement?.price),r(aA.PreviousOpen,e.previousSession?.open?.price),r(aA.PreviousHigh,e.previousSession?.high?.price),r(aA.PreviousLow,e.previousSession?.low?.price),r(aA.YearHigh,e.yearHigh?.price),r(aA.YearLow,e.yearLow?.price),i.computeWellKnown();let h={topic:"rt.quote",data:{symbol:t,openPrice:n,highPrice:a,lowPrice:o,lastPrice:l,tradeTime:u},updated:i.updated};this.subject.next(h)}skip(e){return void 0===e||e.blockTrade||e.doesNotUpdateLast||e.doesNotUpdateVolume}asDate(e){return!eH(e)||e.isZero()?null:new Date(e.div(1e6).toNumber())}toExchangeTime(t,i){var s,r,n,a;let o=this.asDate(t);if(null===o)return null;let l=function(t,i,s){if("string"==typeof t&&!t.match(ll)){var r=e(lI)(void 0);return r.timeZone=i,lC(t,r)}var n=lC(t,void 0),a=o8(n.getFullYear(),n.getMonth(),n.getDate(),n.getHours(),n.getMinutes(),n.getSeconds(),n.getMilliseconds()).getTime(),o=li(i,new Date(a));return new Date(a+o)}(o,this.localTimeZone);return r=li(i,s=lC(l,void 0),!0),n=new Date(s.getTime()-r),(a=new Date(0)).setFullYear(n.getUTCFullYear(),n.getUTCMonth(),n.getUTCDate()),a.setHours(n.getUTCHours(),n.getUTCMinutes(),n.getUTCSeconds(),n.getUTCMilliseconds()),a}onUpdate(e,t){if(!this.recordCache.has(t))return void Ad(`[OpenFeed] update for unsubscribed symbol: ${t}`,"warn");let i=AA().metaDataSource.getMetaData(t);if(!i.isReady)return;let s=this.toExchangeTime(e.transactionTime,i.timeZone);if(e.trades?.trades)for(let{trade:r}of e.trades.trades){if(this.skip(r))continue;let e=i.asPrice(r.price),n=i.asQuantity(r.quantity);if(null===e||0===n)continue;let a=this.toExchangeTime(r.transactionTime,i.timeZone),o=this.findRecordForSymbol(t),[l,u,h,c]=["High","Low","Volume","TradingDay"].map(e=>aA[e]).map(e=>o.getValue(e));(!eH(u)||e<u)&&o.update(aA.Low,e),(!eH(l)||e>l)&&o.update(aA.High,e),o.update(aA.Last,e),o.update(aA.Close,e),o.update(aA.Volume,(eH(h)?h:0)+n),o.computeWellKnown();let d={data:{symbol:t,tradePrice:e,tradeSize:n,session:r.session,time:a??s,tradingDay:c},topic:"rt.trade",updated:o.updated};this.subject.next(d)}}}function lB(e,t){var i=e.getFullYear()-t.getFullYear()||e.getMonth()-t.getMonth()||e.getDate()-t.getDate()||e.getHours()-t.getHours()||e.getMinutes()-t.getMinutes()||e.getSeconds()-t.getSeconds()||e.getMilliseconds()-t.getMilliseconds();return i<0?-1:i>0?1:i}function lk(e,t){tt(2,arguments);var i=ts(e),s=ts(t),r=lB(i,s),n=Math.abs(tu(i,s));i.setDate(i.getDate()-r*n);var a=Number(lB(i,s)===-r),o=r*(n-a);return 0===o?0:o}function lW(e){tt(1,arguments);var t=ts(e);return t.setHours(23,59,59,999),t}function lU(e,t){tt(2,arguments);var i=ts(e),s=te(t);return isNaN(s)?new Date(NaN):(s&&i.setDate(i.getDate()+s),i)}function l$(e,t){return tt(2,arguments),lU(e,-te(t))}function lG(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,r=Array(s),n=0;n<s;n++)r[n]=arguments[n];return lG(e,t,i.concat(r))}}var lz=lG(o5,2),lY=lG(lU,2);function lj(e,t){return tt(2,arguments),oL(e,6e4*te(t))}var lK=lG(lj,2),lq=lG(tr,2),lX=lG(function(e,t){return tt(2,arguments),tr(e,3*te(t))},2);function lZ(e,t){return tt(2,arguments),oL(e,1e3*te(t))}var lJ=lG(lZ,2),lQ=lG(function(e,t){return tt(2,arguments),lU(e,7*te(t))},2),l0=lG(tn,2);function l1(e,t){switch(e){case G.Tick:return lJ(t);case G.Intraday:return lK(t);case G.Day:return lY(t);case G.Week:return lQ(t);case G.Month:return lq(t);case G.Quarter:return lX(t);case G.Year:return l0(t);default:throw Error(`Unexpected aggregation unit ${G[e]}`)}}function l2(e,t){return t.getFullYear()-1-(t.getFullYear()-1)%e}function l3(e){return new Date(e*tz.OPTIONS_DATA_INCREMENT+tz.OPTIONS_DATA_BASE)}function l4(e,t=tz.ZERO_DATE){let i=new Date(`${e}T00:00:00`);return oE(i)?i:t}function l5(e){return e.size-1}class l6{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(aA.DateTime)}prepend(e){this.base.prepend(e),this.processRetrieved()}append(e){this.base.append(e),this.processRetrieved()}}class l7 extends l6{constructor(e){super(),this.container=e,this.retryCountForChunk=tz.FETCH_TICK_CHUNK_RETRY_COUNT}getFirstDate(e){let t=super.getFirstDate(0);return e>0&&e<this.retryCountForChunk?lW(l$(t,e)):t}process(e){let t=this.container,i=t.size>0?t.getLastDataPoint(aA.Last):null,s=t.getLastDataPoint(aA.DateTime),r=e.time;return void 0!==s&&r<=s&&(r=oL(s,1)),t.addDataPoint(aA.DateTime,r),t.addDataPoint(aA.Last,e.tradePrice),t.addDataPoint(aA.TradeSize,e.tradeSize),t.addDataPoint(aA.Change,eF(i)?e.tradePrice-i:null),t.hasField(aA.TradingDay)&&t.addDataPoint(aA.TradingDay,e.tradingDay),{isUpdate:!1,time:r.getTime(),index:l5(t)}}}class l8 extends l6{agg;durationAdd;constructor(e,t){super(),this.agg=t,this.container=e,this.durationAdd=function(e){switch(e.unit){case G.Tick:case G.Intraday:case G.Day:return l1(e.unit,e.size);case G.Week:case G.Month:case G.Quarter:case G.Year:return l1(e.unit,1);default:throw Error(`Unexpected aggregation unit ${G[e.unit]}`)}}(t)}isSameBar(e,t){switch(this.agg.unit){case G.Tick:case G.Intraday:case G.Day:return ao(t,this.durationAdd(e));case G.Week:return nL(e,t);case G.Month:return nv(e,t);case G.Quarter:return nC(e,t);case G.Year:return n_(e,t);default:throw Error(`Unexpected aggregation unit ${G[this.agg.unit]}`)}}fixupTimeBasedAggregationTimestamp(e){return e}isCorrection(e,t){let i=ao(t,e);return i&&Ad("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){tt(2,arguments);var i=ts(e),s=ts(t);return i.getTime()===s.getTime()}(i,e)}getPosition(e){if(0===this.container.size){let t=this.fixupTimeBasedAggregationTimestamp(e.time);return{lastTimestamp:null,newTimestamp:t,nextTimestamp:t,isUpdate:!1}}let t=this.container.getLastDataPoint(aA.DateTime),i=e.time,s=this.computeNextStamp(t,i);if(null===s)return null;let r=this.isUpdate(t,i,s,e);return null===r?null:{lastTimestamp:t,newTimestamp:i,nextTimestamp:s,isUpdate:r}}createBar(e,t,i,s,r,n,a){let o=this.container,l=o.size>0?o.getLastDataPoint(aA.Close):null;o.addDataPoint(aA.DateTime,n),o.addDataPoint(aA.Open,e),o.addDataPoint(aA.High,t),o.addDataPoint(aA.Low,i),o.addDataPoint(aA.Close,s),o.addDataPoint(aA.Change,eF(l)?s-l:null),o.addDataPoint(aA.Volume,r),o.hasField(aA.OpenInterest)&&o.addDataPoint(aA.OpenInterest,null),o.hasField(aA.TradingDay)&&o.addDataPoint(aA.TradingDay,a??null)}addBar(e,t){let{nextTimestamp:i}=t,{tradePrice:s,tradingDay:r}=e;return this.createBar(s,s,s,s,e.tradeSize,i,r),{isUpdate:!1,time:i.getTime(),index:l5(this.container)}}updateLastBar(e,t,i,s){let r=this.container,n=e=>r.getLastDataPoint(e);if(eF(e)&&e>n(aA.High)&&r.setLastDataPoint(aA.High,e),eF(t)&&t<n(aA.Low)&&r.setLastDataPoint(aA.Low,t),eF(i)){r.setLastDataPoint(aA.Close,i);let e=r.getData(aA.Close)[r.size-2];r.setLastDataPoint(aA.Change,i-e)}if(eF(s)){let e=r.getLastDataPoint(aA.Volume)+s;r.setLastDataPoint(aA.Volume,e)}}changeLastBar(e,t){let{lastTimestamp:i}=t,s=e.tradePrice;return this.updateLastBar(s,s,s,e.tradeSize),{isUpdate:!0,time:i.getTime(),index:l5(this.container)}}process(e){let t=this.getPosition(e);if(null===t)return null;let i=lz(tz.DEBUG_TIME_FORMAT);return t.isUpdate?(e.symbol===tz.DEBUG_SYMBOL&&console.log(`Adding ${this.agg.describe()} Bar
6
6
  Bars %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)):eF(e.tradePrice)?(e.symbol===tz.DEBUG_SYMBOL&&console.log(`Updating ${this.agg.describe()} Bar
7
- Bars %csame %c${i(t.lastTimestamp)} == ${i(t.newTimestamp)}`,"color:#0f0","color:#f96"),this.addBar(e,t)):null}alignToQuote(e){if(eF(e.lastPrice,e.time))return this.updateLastBar(e.highPrice,e.lowPrice,e.lastPrice,void 0),{isUpdate:!0,time:e.time.getTime(),index:l5(this.container)}}}class l9 extends l8{innerBuilder;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.processRetrieved()}get base(){return this.innerBuilder.container}fixupTimeBasedAggregationTimestamp(e){let t=lk(e,tz.START_OF_LAST_CENTURY);return l$(e,t%this.agg.size)}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:0,tradePrice:0,tradingDay:0};[aA.Open,aA.High,aA.Low].forEach(i=>{t.tradePrice=this.base.getData(i)[e],super.process(t)}),t.tradePrice=this.base.getData(aA.Close)[e],t.tradeSize=this.base.getData(aA.Volume)[e],super.process(t)}}process(e){return this.innerBuilder.process(e),super.process(e)}}class ue{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!==aA.Change||!this.hasField(aA.Close)||t<1)return;let i=this.storage[e.id],s=this.storage[aA.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){let t=e.getLastDataPoint(aA.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){let t=e.getTimeData()[0].getTime()===this.getLastDataPoint(aA.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}getTimeData(){return this.getData(aA.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 Error(`This container does not store values for field ${e.id}`)}addDataPoint(e,t){this.checkField(e),this.getData(e).push(t)}getLastDataPoint(e){return this.checkField(e),eC(this.getData(e))}setLastDataPoint(e,t){this.checkField(e);let i=this.getData(e);i[i.length-1]=t}keepOnlyLast(e){if(this.size<=e)return;let t=this.size-e;this.fields.forEach(e=>this.getData(e).splice(0,t))}}class ut extends ue{constructor(){super([])}get size(){return 0}}class ui extends ue{wrapper;constructor(e,t){super(e),this.wrapper=t}isWrapped(e){return e$(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)}}let us=tz.RENKO_KAGI_NAMES;function ur(e){let{Method:t,Period:i,Source:s,BrickSize:r}=eK(e),n=eU(t,[us.ATR,us.TRD,us.PCT],us.ATR),a=Number.isFinite(i)?i:14;return{method:n,period:a,source:eU(s,[us.CLS,us.HL],us.CLS),brickSize:Number.isFinite(r)?r:10}}function un(e,t,i){return e.getData(t)[i]}function ua(e,t){let[i,s]=[aA.High,aA.Low].map(i=>un(e,i,t)),r=un(e,aA.Close,t-1);return Math.max(i-s,Math.abs(i-r),Math.abs(s-r))}function uo(e,t){if(e.size<t)return null;let i=t-1,s=[];s.push(un(e,aA.High,0)-un(e,aA.Low,0));for(let i=1;i<t;++i)s.push(ua(e,i));let r=eg(s);for(let s=t;s<e.size;++s)r=(r*i+ua(e,s))/t;return r}let ul=e=>aA[e],uu=["DateTime","Open","High","Low","Close","Volume"].map(ul),uh=uu.concat(["Change","Projection","BarIndex"].map(ul));class uc extends l6{innerBuilder;inputs;brickSize;lastFinalBrick;projectionCount;refPrices;constructor(e,t){super(),this.supportsChunks=!1,this.innerBuilder=e,this.inputs=ez(t.inputs),this.brickSize=null,this.container=new ue(uh),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){let[i,s,r,n,a,o]=uu.map(i=>t.getData(i)[e]);return{date:i,open:s,high:r,low:n,close:a,volume:o}}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){let[s,r]=this.refPrices(t.close,t.high,t.low),n=s-e.high,a=e.low-r;return{climbing:(i&&n>0||n>=this.brickSize)&&n>=a,falling:(i&&a>0||a>=this.brickSize)&&a>n,moveUp:n,moveDown:a}}initFirstBrick(e,t){e.open=e.high=e.low=e.close=Math.max(this.brickSize,eB(t.close-t.close%this.brickSize,4)),e.date=t.date,e.volume=e.change=0}findSafeStartIndex(){let e=0,t=this.base.size-1,i=2*tz.RENKO_MAX_BARS;for(;t>0&&e<i;)e+=Math.floor(ua(this.base,t)/this.brickSize),t--;return t}processRetrieved(){let e=ur(this.inputs),{method:t,period:i,source:s}=e;if(this.brickSize=e.brickSize,t===us.ATR)this.brickSize=uo(this.base,i);else if(t===us.PCT)if((this.base?.size??0)>0){let e=this.base.getLastDataPoint(aA.Close);this.brickSize=e*this.brickSize/100}else this.brickSize=null;if(!eF(this.brickSize))return;this.refPrices=s===us.HL?(e,t,i)=>[t,i]:(e,t,i)=>[e,e];let r={},n=this.findSafeStartIndex();for(let e=n;e<this.base.size;e++){let t=this.getBarAt(e);if(e===n){this.initFirstBrick(r,t);continue}let i=this.isLastBase(e),{climbing:s,falling:a,moveUp:o,moveDown:l}=this.getMove(r,t,i);if(!s&&!a){r.volume+=t.volume;continue}r.proj=Number(i),r.barIndex=e;let u=t.date.getTime();if(s){let e=this.getBricksCount(o);for(let t=0;t<e;++t)this.constructClimbing(r,u,t,this.brickSize);i&&(this.constructClimbing(r,u,e,o%this.brickSize),this.projectionCount=e+1)}else if(a){let e=this.getBricksCount(l);for(let t=0;t<e;++t)this.constructFalling(r,u,t,this.brickSize);i&&(this.constructFalling(r,u,e,l%this.brickSize),this.projectionCount=e+1)}i||(this.lastFinalBrick=this.container.size-1,r.volume=0)}this.container.keepOnlyLast(tz.RENKO_MAX_BARS)}constructClimbing(e,t,i,s,r=!0){let n=e.high,a=e.close;e.open=e.low=n,e.high=e.close=n+s,e.date=new Date(t+i),e.change=e.close-a,r?this.addToContainer(e):this.updateLastDataPoint(e)}constructFalling(e,t,i,s,r=!0){let n=e.low,a=e.close;e.open=e.high=n,e.low=e.close=n-s,e.date=new Date(t+i),e.change=e.close-a,r?this.addToContainer(e):this.updateLastDataPoint(e)}process(e){let t=this.innerBuilder.process(e);return this.processUpdate(t)}alignToQuote(e){let 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;let t=this.base.size-1,i=this.getBarAt(t),s=this.getBrickAt(this.lastFinalBrick),{climbing:r,falling:n,moveUp:a,moveDown:o}=this.getMove(s,i,!0),l=1===this.container.getLastDataPoint(aA.Projection);if(!r&&!n)return l?this.rebuild():null;let u=this.getBricksCount(r?a:o)+1;if(!l||this.projectionCount!==u)return this.rebuild();{let 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}}}addToContainer(e){let t=this.container;t.addDataPoint(aA.DateTime,e.date),t.addDataPoint(aA.Open,e.open),t.addDataPoint(aA.Close,e.close),t.addDataPoint(aA.High,e.high),t.addDataPoint(aA.Low,e.low),t.addDataPoint(aA.Change,e.change),t.addDataPoint(aA.Volume,e.volume),t.addDataPoint(aA.Projection,e.proj),t.addDataPoint(aA.BarIndex,e.barIndex)}updateLastDataPoint(e){let t=this.container;t.setLastDataPoint(aA.DateTime,e.date),t.setLastDataPoint(aA.Open,e.open),t.setLastDataPoint(aA.Close,e.close),t.setLastDataPoint(aA.High,e.high),t.setLastDataPoint(aA.Low,e.low),t.setLastDataPoint(aA.Change,e.change),t.setLastDataPoint(aA.Volume,e.volume),t.setLastDataPoint(aA.Projection,e.proj),t.setLastDataPoint(aA.BarIndex,e.barIndex)}}let ud=[aA.DateTime,aA.TradingDay,aA.Last,aA.TradeSize,aA.Change],up=[aA.DateTime,aA.Open,aA.High,aA.Low,aA.Close,aA.Volume,aA.Change],uf=[...up,aA.OpenInterest],um=[...uf,aA.Symbol],ug=[aA.Open,aA.High,aA.Low,aA.Close,aA.Change];function uy(e,t){let i=tL(e);if(t.isTick)return ud;{let e=up;return t.isMultiContract?e=um:(i||t.isEndOfDay)&&(e=uf),t.isIntraday?[...e,aA.TradingDay]:e}}class uA{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=new Date(0),this.timeZone=this.getTimeZone(),this.isFuture=ty(e),this.padded=s,this.needsResolution=tE(e),this.hasOpenInterest=tL(e)}makeContainer(){return new ue(uy(this.symbol,this.aggregation))}parse(e){this.container=this.makeContainer();let t=e.split("\n"),i=this.getParseFunc();if(null!==i){let e=i.bind(this);t.forEach(t=>{let i=t.trim();i&&e(i.split(","))})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){let t=e.length-5;(0===t||1===t)&&(this.container.addDataPoint(aA.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(aA.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(aA.Last,parseFloat(e[3+t])),this.container.addDataPoint(aA.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(aA.Change,this.calculateChange(aA.Last)))}nullify(e){return null==e||0===e?null:e}parseMinutes(e){let t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,i=+!!t;e.length===7+i&&(this.container.hasField(aA.Symbol)&&this.container.addDataPoint(aA.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(aA.DateTime,this.parseDate(e[0+i])),this.container.addDataPoint(aA.TradingDay,parseInt(e[1+i])),this.container.addDataPoint(aA.Open,parseFloat(e[2+i])),this.container.addDataPoint(aA.High,parseFloat(e[3+i])),this.container.addDataPoint(aA.Low,parseFloat(e[4+i])),this.container.addDataPoint(aA.Close,parseFloat(e[5+i])),this.container.addDataPoint(aA.Volume,this.nullify(parseInt(e[6+i]))),this.container.addDataPoint(aA.Change,this.calculateChange()))}parseFloatOrNull(e){let t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){let t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){let t=this.aggregation.isMultiContract,i=7+ +!!this.hasOpenInterest;e.length===i&&(t&&this.container.addDataPoint(aA.Symbol,e[0]),this.container.addDataPoint(aA.DateTime,this.parseDate(e[1])),this.container.addDataPoint(aA.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(aA.High,parseFloat(e[3])),this.container.addDataPoint(aA.Low,parseFloat(e[4])),this.container.addDataPoint(aA.Close,parseFloat(e[5])),this.container.addDataPoint(aA.Volume,this.nullify(this.parseIntOrNull(e[6]))),this.hasOpenInterest&&this.container.addDataPoint(aA.OpenInterest,this.nullify(this.parseIntOrNull(e[7]))),this.container.addDataPoint(aA.Change,this.calculateChange()))}calculateChange(e=aA.Close){let t=this.container.size;if(!(t>1))return 0;{let i=this.container.getData(e);return i[t-1]-i[t-2]}}parseTimestamp(e){switch(this.aggregation.unit){case G.Tick:case G.Intraday:return function(e,t=tz.ZERO_DATE){let i=new Date(e.replace(" ","T"));return oE(i)?i:t}(e);default:return l4(e)}}parseDate(e){let t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?tn(t,this.offset):(!function(e,t){tt(2,arguments);var i=ts(e),s=ts(t);return i.getTime()>s.getTime()}(t,this.previousTime)?this.previousTime=oL(this.previousTime,1):this.previousTime=t,this.previousTime)}getTimeZone(){return t_(this.symbol)}}let{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:uS,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:uT}=tz;class uv{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case G.Tick:return tz.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case G.Intraday:return t&&e.spec===z.Nearest?uS:uT;case G.Day:case G.Week:case G.Month:case G.Quarter:case G.Year:return tz.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return""}}addExtraParams(e){}makeUrl(e){let t={},i=t0(e.symbol);t.symbol=i;let s=e.aggregation,r=this.getDataParam(s);r.length>0&&(t.data=r),s.size>1&&s.unit===G.Intraday&&(t.interval=(s.spec===z.PerRange?1:s.size).toString());let[n,a]=e.range,o=null!==n,l=null!==a;if(o&&(t.start=this.toHistoricalFeedDate(n,s)),!o||e.alwaysUseBarsToFetch){let i=e.barsToFetch||tz.DEFAULT_MAX_RECORDS;s.unit===G.Tick&&s.spec!==z.None&&(i*=tz.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=i.toString()}l&&(t.end=this.toHistoricalFeedDate(a,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);let u=eX(t),h=ty(i),c=this.getPageNameFor(s,h);return`/${c}?${u}`}toHistoricalFeedDate(e,t){return o5(e,t.isTick||t.isIntraday?tz.FMT_HIST_FEED_PARAM_DATE_TIME:tz.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t="",i=this.getSpecPart(e);switch(e.unit){case G.Tick:case G.Intraday:break;case G.Day:t=`daily${i}`;break;case G.Week:t=`weekly${i}`;break;case G.Month:t=`monthly${i}`;break;case G.Quarter:t=`quarterly${i}`;break;case G.Year:t=`yearly${i}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===z.Continue?"continue":"nearest":""}getParser(e){return new uA(t0(e.symbol),e.aggregation,e.offset,e.padded)}async retrieve(e){let t=this.makeUrl(e),i=e.aggregation.unit===G.Tick?"timeseriesNew":"timeseries",s=await Af(i,t);return this.getParser(e).parse(s)}}class uP{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){let t=t0(e.symbol),i=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==G.Day)return i;let s={symbol:t};this.addExtraParams(s);let r=`/${this.getPageName()}.json?${eX(s)}`,n=await Af("ondemand",r);try{let e=JSON.parse(n);if(200===e.status.code){let 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)}}catch(e){Ad(`Failed parsing the JSON result from OnDemand, error is ${e.message}`)}return i}}class uC extends uP{emptyContainer(e,t){return new ue(uy(e,t))}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){let s=i.hasField(aA.Symbol),r=t>0?i.getLastDataPoint(aA.Close):null;i.addDataPoint(aA.DateTime,l4(e.date)),s&&i.addDataPoint(aA.Symbol,e.symbol),i.addDataPoint(aA.Open,e.open),i.addDataPoint(aA.High,e.high),i.addDataPoint(aA.Low,e.low),i.addDataPoint(aA.Close,e.close),i.addDataPoint(aA.Volume,e.volume),i.addDataPoint(aA.OpenInterest,e.openInterest);let n=null===r?null:eB(e.close-r,2);i.addDataPoint(aA.Change,n)}}let ub={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 uE{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){let t=t0(e.symbol).replace(/\.bz$/i,""),i=e.fields.concat(aA.DateTime),s=()=>new ue(i);if(e.aggregation.unit!==G.Day)return s();let r={symbol:t,apiKey:"default",fields:i.map(e=>ub[e.id]).join(",")},n=`/get?${eX(r)}`,a=await Af("options",n);try{let e=JSON.parse(a).data,t=s();return e.forEach(e=>{i.forEach(i=>{if(i===aA.DateTime)t.addDataPoint(aA.DateTime,l4(e.date));else{let s;t.addDataPoint(i,(s=e[ub[i.id]],Number.parseFloat(s.replace(/,/g,""))))}})}),t}catch(e){Ad(`Failed parsing options JSON historical data result, error is ${e.message}`)}return s()}}function uL(e,t){return oA(function(i,s){var r=0;i.subscribe(oS(s,function(i){s.next(e.call(t,i,r++))}))})}var u_=lG(l$,2);function uM(e,t){return tt(2,arguments),ts(e).getTime()-ts(t).getTime()}var ux={ceil:Math.ceil,round:Math.round,floor:Math.floor,trunc:function(e){return e<0?Math.ceil(e):Math.floor(e)}};function uD(e){return e?ux[e]:ux.trunc}function uI(e,t,i){tt(2,arguments);var s=uM(e,t)/1e3;return uD(null==i?void 0:i.roundingMethod)(s)}class uO extends l8{innerBuilder;isBuildingBars;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=tz.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;let[e,t,i,s]=[aA.DateTime,aA.TradeSize,aA.Last,aA.TradingDay].map(e=>this.base.getData(e));for(let r=this.startFromIndex;r<this.base.size;r++){let n={isTrade:!0,time:e[r],tradeSize:t[r],tradePrice:i[r],tradingDay:s[r]};super.process(n)}this.isBuildingBars=!1}process(e){let t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}}class uw extends uO{constructor(e,t,i){super(e,t,i)}fixupTimeBasedAggregationTimestamp(e){let t=uI(e,tc(al(e,1)));return function(e,t){return tt(2,arguments),lZ(e,-te(t))}(e,t%this.agg.size)}}class uR extends uO{series;constructor(e,t,i,s){super(e,i,s),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}}let uN=new am("_TICK_COUNT");class uV extends uR{anchorTimestamp=null;constructor(e,t,i,s){super(e,t,i,s)}get startFromIndex(){let e=0,t=this.base.getTimeData();if(eF(this.anchorTimestamp))e=eE(t,e=>e===this.anchorTimestamp);else{let i=this.base.size;if(i>2)for(let s=i-2;s>2;--s){let 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){let i=super.addBar(e,t);return this.container.addDataPoint(uN,1),i}changeLastBar(e,t){let i=super.changeLastBar(e,t),s=this.container.getLastDataPoint(uN);return this.container.setLastDataPoint(uN,s+1),i}isUpdate(e,t,i,s){return this.container.getLastDataPoint(uN)<this.agg.size}}let uH=new am("_VOLUME_TALLY");class uF extends uR{constructor(e,t,i,s){super(e,t,i,s)}addBar(e,t){let i=this.container,s=(i.getLastDataPoint(uH)||0)+e.tradeSize,r=Math.floor(s/this.agg.size),n=s%this.agg.size,a=s<this.agg.size;i.size>0&&(i.setLastDataPoint(aA.Volume,a?1:r),i.setLastDataPoint(uH,s));let o=super.addBar(e,t);return i.setLastDataPoint(aA.Volume,1),i.addDataPoint(uH,a?0:n),o}changeLastBar(e,t){let i=this.container,s=super.changeLastBar(e,t);i.setLastDataPoint(aA.Volume,1);let r=i.getLastDataPoint(uH)??0;return i.setLastDataPoint(uH,r+e.tradeSize),s}isUpdate(e,t,i,s){if(!nT(e,t))return!1;let r=this.container.getLastDataPoint(uH)??0;return s.tradeSize+r<this.agg.size}}class uB extends l8{innerBuilder;metadata;range;step;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.range=i.size,this.step=1;let r=AA().getMetaDataSource();this.metadata=r.getMetaData(s)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return tU.call(this,async()=>{let 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++){let t=this.base.getData(aA.Volume)[e],i=this.useHighOrLow(e);if(!eF(i)){this.updateLastBar(void 0,void 0,void 0,t);continue}let s={isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:t,tradePrice:i,tradingDay:0};super.process(s)}}useHighOrLow(e){let t=this.base.getData(aA.Close)[e];if(0==this.container.size)return t;let i=this.container.getLastDataPoint(aA.High),s=this.container.getLastDataPoint(aA.High),r=this.base.getData(aA.High)[e],n=this.base.getData(aA.Low)[e],a=r>i,o=n<s;return a&&o?r-t<t-n?r:n:a?r:o?n: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){let i=e.tradePrice,s=this.container.getLastDataPoint(aA.Low)+this.priceRange;if(i>s)return this.changeAndAddBar(s,e,t);let r=this.container.getLastDataPoint(aA.High)-this.priceRange;return i<r?this.changeAndAddBar(r,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,i){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(aA.Projection,0),this.addBar(t,i)}addBar(e,t){return this.container.addDataPoint(aA.Projection,1),super.addBar(e,t)}}let uk=[aA.Open,aA.High,aA.Low,aA.Close],uW=[aA.BARCOLIX,aA.High,aA.Low],uU=tz.RENKO_KAGI_NAMES;function u$(e){let{BoxSizeMethod:t,Period:i,ReversalAmount:s}=eK(e),r=eU(t,[uU.ATR,uU.TRD],uU.ATR);return{method:r,period:Number.isFinite(i)?i:14,reversal:Number.isFinite(s)?s:30}}class uG extends l8{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ez(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(aA.BARCOLIX,null),this.container.size>1){let e=this.dataAt(aA.Close,this.container.size-2);this.setLast(aA.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,i,s){let r=s.tradePrice,n=r-this.getLast(aA.Close),a=n>=0,o=Math.abs(n)>=this.reversal,[l,u,h,c]=uk.map(e=>this.getLast(e)),d=c-l,p=d>=0!==a||0===d;return p&&!o||!p&&(a?r<u:r>h)?null:Math.abs(d)<this.reversal||!p||!o}computeBarColor(){let e=e=>this.dataAt(aA.Close,e)>this.dataAt(aA.Open,e),t=this.container.size;if(t>1){let i=e(t-1),[s,r,n]=uW.map(e=>this.dataAt(e,t-2)),[,a,o]=uW.map(e=>this.dataAt(e,t-1)),l=s;0===s&&i&&a>r?l=1:1===s&&!i&&o<n&&(l=0),this.setLast(aA.BARCOLIX,l)}else this.setLast(aA.BARCOLIX,+!!e(0))}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);let t=super.process(e);return this.computeBarColor(),t}processRetrieved(){let{method:e,period:t,reversal:i}=u$(this.inputs);if(this.reversal=i,e===uU.ATR&&(this.reversal=uo(this.base,t)),eF(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(aA.DateTime,e),tradePrice:this.baseAt(aA.Close,e),tradeSize:this.baseAt(aA.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}function uz(e){let{LineCount:t}=eK(e);return{lineBreak:Number.isFinite(t)?t:3}}class uY extends l8{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.inputs=ez(s.inputs);let r=uz(this.inputs);this.lineBreak=r.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:this.base.getData(aA.Volume)[e],tradePrice:this.base.getData(aA.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++){let 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){let r=this.findOpen(i,0,1);this.currentVolume+=s,null!==r?(super.updateLastBar(void 0,void 0,i,void 0),this.container.setLastDataPoint(aA.Open,r),this.container.setLastDataPoint(aA.Low,Math.min(r,i)),this.container.setLastDataPoint(aA.High,Math.max(r,i))):this.resetProjection()}resetProjection(){let e=this.container;e.setLastDataPoint(aA.High,null),e.setLastDataPoint(aA.Low,null),e.setLastDataPoint(aA.Open,null),e.setLastDataPoint(aA.Close,null),e.setLastDataPoint(aA.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(aA.DateTime,t.nextTimestamp);let i=this.changeLastBar(e,t);return i.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},i}addBar(e,t){let i=this.container,{nextTimestamp:s}=t;if(1===i.getLastDataPoint(aA.Projection)){let s=i.getLastDataPoint(aA.Close);if(null===this.findOpen(s,this.lineBreak,1))return this.updateProjection(e,t);i.setLastDataPoint(aA.Projection,0),i.setLastDataPoint(aA.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;let 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(aA.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;let 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(aA.Projection,1),!0)}findOpen(e,t,i=0){if(!eF(e))return null;let s=this.container,r=s.size-1-i,n=s.getData(aA.Close)[r],a=s.getData(aA.Open)[r];if(n>a){if(e<=n){if(e>=a)return null;for(let i=0;i<Math.min(s.size,t);i++)if(e>=s.getData(aA.Low)[r-i])return null;return a}return n}if(e>=n){if(e<=a)return null;for(let i=0;i<Math.min(s.size,t);i++)if(e<=s.getData(aA.High)[r-i])return null;return a}return n}startLine(e){this.container.addDataPoint(aA.Projection,0);let 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)}}let uj=tz.RENKO_KAGI_NAMES;function uK(e){switch(e){case tz.BARKIND_O:case tz.BARKIND_XO:return!0;default:return!1}}function uq(e){switch(e){case tz.BARKIND_X:case tz.BARKIND_OX:return!0;default:return!1}}function uX(e){let t=eK(e),{Source:i,BoxSizeMethod:s,Period:r}=t,{ReversalAmount:n,BoxSize:a,OneStepBack:o}=t,l=eU(i,[uj.CLS,uj.HL],uj.CLS),u=eU(s,[uj.ATR,uj.TRD],uj.ATR),h=Number.isFinite(r)?a:14,c=Number.isFinite(n)?n:3;return{method:u,period:h,source:l,boxSize:Number.isFinite(a)?a:20,reversal:c,oneStepBack:"Yes"===o}}class uZ extends l8{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ez(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){let s=Math.abs(t-e);return e+i*this.roundToBox(s)}get closeBased(){return this.source===uj.CLS}get currentKind(){return this.getLast(aA.BARKIND)}getTrendField(e){return this.closeBased?aA.Close:e?aA.Low:aA.High}getTrendPrice(e,t){return this.closeBased?e.tradePrice:t?e._lowPrice:e._highPrice}changeLastBar(e,t){let i=uK(this.currentKind),s=i?-1:1,r=this.getLast(this.getTrendField(i)),n=this.getTrendPrice(e,i);return e.tradePrice=this.roundedDiff(r,n,s),super.changeLastBar(e,t),null}addBar(e,t){let i=0===this.container.size,s=uK(this.currentKind),r=s?1:-1,n=i?null:this.getLast(aA.Close),a=this.getTrendPrice(e,!s);if(e.tradePrice=(i?this.roundToBox(this.baseAt(aA.Open,0)):n)+r*(i?0:this.boxSize),super.addBar(e,t),!i){let e=this.roundedDiff(n,a,r);this.updateLastBar(e,e,e)}return this.container.addDataPoint(aA.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){let e=uK(this.currentKind)?tz.BARKIND_OX:tz.BARKIND_XO;this.setLast(aA.BARKIND,e)}canInplaceReverse(){return!function(e){switch(e){case tz.BARKIND_OX:case tz.BARKIND_XO:return!0;default:return!1}}(this.currentKind)&&this.getLast(aA.High)===this.getLast(aA.Low)}isUpdate(e,t,i,s){let r=uK(this.currentKind),n=this.getTrendPrice(s,r),a=this.getTrendPrice(s,!r),o=n-this.getLast(aA.Close),l=o>=0,u=Math.abs(o)>=this.boxSize,h=a-this.getLast(aA.Close),c=h>=0,d=Math.abs(h)>=this.reversal*this.boxSize;if(r){if(!l&&u)return!0;if(c&&d)if(!this.oneStepBack||!this.canInplaceReverse())return!1;else return this.inplaceReverse(),!0;return null}if(l&&u)return!0;if(!c&&d)if(!this.oneStepBack||!this.canInplaceReverse())return!1;else return this.inplaceReverse(),!0;return null}findFirstDiffLargerThanBox(e,t){let i=this.baseAt(aA.Open,0),s=this.innerBuilder.container.size;for(let r=1;r<s;++r){let s=this.baseAt(e,r)-i;if(Math.abs(s)>this.boxSize){if(1===t&&s>0)return[r,tz.BARKIND_X];if(2===t&&s<0)return[r,tz.BARKIND_O];if(3===t)return[r,s>0?tz.BARKIND_X:tz.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){let[,e]=this.findFirstDiffLargerThanBox(aA.Close,3);return e}{let[e,t]=this.findFirstDiffLargerThanBox(aA.High,1),[i,s]=this.findFirstDiffLargerThanBox(aA.Low,2);return null===t&&null===s?null:null===s?t:null===t?s:e<i?t:s}}computeBarColor(){let e=this.container.size,t=this.firstTrend;e>1&&(t=uK(this.dataAt(aA.BARKIND,e-2))?tz.BARKIND_X:tz.BARKIND_O),this.setLast(aA.BARKIND,t)}process(e){return(this.isProcessingRetrieved||this.innerBuilder.process(e),null===this.firstTrend)?null:super.process(e)}processRetrieved(){let{method:e,period:t,reversal:i,source:s,boxSize:r,oneStepBack:n}=uX(this.inputs);if((this.reversal=i,this.source=s,e===uj.ATR?this.boxSize=uo(this.base,t):this.boxSize=r,eF(this.reversal,this.boxSize))&&(this.oneStepBack=n&&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++){let t={isTrade:!0,time:this.baseAt(aA.DateTime,e),tradePrice:this.baseAt(aA.Close,e),_highPrice:this.baseAt(aA.High,e),_lowPrice:this.baseAt(aA.Low,e),tradeSize:this.baseAt(aA.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}let uJ=new nN(G.Intraday,0);class uQ{query;container;canLoadMoreData;alignToQuote;record;isLoading;serverComputedSeries;builder;retriever;streamingSubscription;constructor(e){this.query=e,this.canLoadMoreData=!0,this.alignToQuote=!1,this.isLoading=!1,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new ab(e.symbol)}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){let t=this.query.aggregation;if(!t.isTick)return new l8(e,t);switch(t.spec){case z.None:case z.PerSeconds:case z.PerCount:case z.PerVolume:return new l7(e);default:throw Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}}makeBuilder(e){let t=this.makeInnerBuilder(e),i=this.query.aggregation,s=(e,t=[])=>new ue(uy(this.query.symbol,e).concat(t));switch(this.query.curveStyle){case $.Renko:return new uc(t,this.query);case $.Kagi:return new uG(t,s(uJ,[aA.BARCOLIX]),this.query);case $.PointAndFigure:return new uZ(t,s(uJ,[aA.BARKIND]),this.query);case $.LineBreak:return new uY(t,s(i,[aA.Projection]),i,this.query)}if(i.isIntraday&&i.spec===z.PerRange)return new uB(t,s(uJ,[aA.Projection]),i,this.query.symbol);if(i.isTick)switch(i.spec){case z.PerSeconds:return new uw(t,s(uJ),i);case z.PerCount:return new uV(t,this,s(uJ,[uN]),i);case z.PerVolume:return new uF(t,this,s(uJ,[uH]),i)}return i.unit===G.Day&&i.size>1?new l9(t,s(i),i):t}onStreamingUpdates(e){this.isLoading||e.map(e=>{if("isTrade"in e)return this.builder.process(e);if("isQuote"in e&&(eN(aS.TS_QUOTEMARKER,{series:this}),this.alignToQuote)){let t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>eF(e)).filter((e,t,i)=>{if(0===t)return!0;let s=i[t-1];return s.isUpdate!==e.isUpdate||s.time!==e.time||e.timeCorrection}).forEach(e=>{if(-1===e.index)eN(aS.TS_MANYCHANGED,{series:this,part:en.Unspecified});else{let t={series:this,index:e.index};eN(e.isUpdate?aS.TS_DATAPOINTCHANGED:aS.TS_DATAPOINTADDED,t)}e.timeCorrection&&eN(aS.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return null!==this.container}getRetriever(){return tP(this.query.symbol)&&this.query.aggregation.isEndOfDay?new uC:new uv}getStreamingSubscription(){return AA().getRecordSource().subject.pipe(uL(e=>{let t=this.query.aggregation.isEndOfDay,i=aV(aS.RT_TRADE,this.record.symbol),s=e=>"T"!==e.data.session||this.query.extendedHours&&!t,r=e.filter(i).filter(e=>eF(e.data.time)).filter(s).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay})).reduce((e,t)=>{let i=eC(e);return eF(i)&&eF(i.tradePrice)&&eF(t.tradePrice)&&i.tradePrice===t.tradePrice&&i.time.getTime()===t.time.getTime()&&i.tradingDay===t.tradingDay?i.tradeSize+=t.tradeSize:e.push(Object.assign({},t)),e},[]),n=aV(aS.RT_QUOTE,this.record.symbol);return r.concat(e.filter(n).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}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(){let e=this.query.duplicate(),t=this.builder.getLastDate();eF(e.offset)&&0!==e.offset&&(t=tn(t,-e.offset)),e.range=[t,null];let i=await this.retriever.retrieve(e),s=this.container.size;this.builder.append(i);let r=this.container.size-s;eN(aS.TS_MANYCHANGED,{series:this,part:en.Tail,count:r,index:s})}async loadHeadChunk(){let e=!1,t=null;for(let i=0;i<this.builder.retryCountForChunk&&!e;++i){let s=this.query.duplicate(),r=this.builder.getFirstDate(i);eF(s.offset)&&0!==s.offset&&(r=tn(r,-s.offset)),s.range=[null,r],e=(t=await this.retriever.retrieve(s)).size>1}this.canLoadMoreData=e,e&&null!==t&&(this.builder.prepend(t),eN(aS.TS_MANYCHANGED,{series:this,part:en.Head}))}async applyNearbyFixup(e){let t=this.query.aggregation,i=t.spec===z.Nearest,s=this.query.symbol,r=ty(s);return r&&t.isMultiContract&&i&&!(e.size<1)&&!this.serverComputedSeries?e.getLastDataPoint(aA.Symbol):r&&tE(s)?await tm(s):s}async ready(){return tU.call(this,async()=>{this.retriever=this.getRetriever();let e=await this.retriever.retrieve(this.query),t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=AA().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0})}getCacheableEntities(e){e.add(this)}shutdown(){eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class u0{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new ut}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw Error("Should not be called.")}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}}class u1{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return null!==this.container}loadMoreData(e){throw Error("Should not be called.")}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}}class u2{query;container;supplyCustomDemoData;canLoadMoreData;isLoading;constructor(e){this.query=e,this.canLoadMoreData=!0,this.isLoading=!0,this.container=null,this.supplyCustomDemoData="DemoSite"===AA().config.mode}refresh(){}loadMoreData(e){throw Error("Should not be called.")}get hasData(){return null!==this.container}shutdown(){}parseEvents(e){let t=new ue([aA.DateTime,aA.Dividends,aA.Earnings,aA.Splits,aA.Custom]),i=e.split("\n"),s=(e,i,s,r)=>{t.addDataPoint(e,i===s?r:null)};return i.forEach(e=>{if(""===e.trim())return;let i=e.split(",");if(4!==i.length)return;let r=l4(i[1]);t.addDataPoint(aA.DateTime,r),s(aA.Dividends,"Dividend",i[2],i[3]),s(aA.Earnings,"Earnings",i[2],i[3]),s(aA.Splits,"Split",i[2],i[3]),this.supplyCustomDemoData?s(aA.Custom,"Custom","Custom",tz.FAKE_CUSTOM_EVENT):s(aA.Custom,"Custom",i[2],i[3])}),t}makeUrl(){let e={};e.symbols=this.query.symbol,e.start="19700102",e.end="20501230",tz.EVENTS_BUILT_IN.forEach(t=>e[t]=this.query[t]);let t=eX(e);return`/queryevents.ashx?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("timeseries",e);return this.parseEvents(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),this.isLoading=this.canLoadMoreData=!1,!0))}getCacheableEntities(e){e.add(this)}}class u3{query;container;canLoadMoreData;isLoading;constructor(e){this.query=e,this.canLoadMoreData=!1,this.isLoading=!0,this.query=e,this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw Error("Should not be called.")}shutdown(){}parseFundamental(e){let t=JSON.parse(e),i=t.status.code,s=204===i;if(200!==i&&!s)return null;let r=new ue(this.query.fields.concat(aA.DateTime));if(s)return r;let n=this.query.fields[0],a=n.id.substring(0,1).toLowerCase()+n.id.substring(1);return t.results.reverse().forEach(e=>{r.addDataPoint(aA.DateTime,l4(e.date)),r.addDataPoint(n,parseFloat(e[a]))}),this.isLoading=!1,r}makeUrl(){let e={count:0,rawData:1};e.symbols=this.query.symbol,e.frequency=this.query.aggregation.unit===G.Quarter?"Quarter":"Annual";let t=eX(e),i=this.query.seriesKind===J.BalanceSheet?"getBalanceSheets":"getIncomeStatements";return`/${i}.json?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("ondemand",e);return this.parseFundamental(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}function u4(e,t){let i=e.findIndex(e=>e>t);return Math.max(i<0?e.length:i,0)}class u5{records;streamingSubscription;setSymbols(e){let t=AA().getRecordSource();this.records=e.reduce((e,i)=>{let s=t.getRecord(i);return this.addFieldsToRecord(s,i),e[i]=s,e},{})}getStreamingSubscription(){return AA().getRecordSource().subject.pipe(oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}onStreamingUpdates(e){e.forEach(e=>{let t=e.data,i=this.records[t.symbol];eF(i)&&this.process(i)}),this.notifyAboutUpdates()}async retrieve(){let e=Object.values(this.records);return(await Promise.all(e.map(e=>e.ready()))).every(ep)&&(this.onRecordsReady(),e.forEach(e=>this.process(e)),this.streamingSubscription=this.getStreamingSubscription()),this.hasData}async ready(){return tU.call(this,async()=>await this.retrieve())}shutdown(){eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class u6 extends u5{symbols=[];constructor(e){super(),this.symbols=e,this.setSymbols(e)}addFieldsToRecord(e,t){e.addFields(aA.Symbol),e.update(aA.Symbol,t)}notifyAboutUpdates(){eN(aS.RT_QUOTEGROUP,{source:this})}process(e){}onRecordsReady(){}get hasData(){return!0}getValue(e){let t=this.records[e];return void 0===t?null:t.getValue(aA.Close)}}class u7 extends u5{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=[aA.DateTime,aA.Close,aA.Symbol]}addFieldsToRecord(e,t){e.addFields(aA.DateTime,aA.Symbol),e.update(aA.DateTime,tx(t)),e.update(aA.Symbol,t)}refresh(){}loadMoreData(e){throw Error("Should not be called.")}get hasData(){return null!==this.container&&this.container.size===this.dataPoints}notifyAboutUpdates(){eN(aS.TS_MANYCHANGED,{series:this,part:en.Unspecified})}onRecordsReady(){this.container=new ue(this.fields)}findOrAddIndex(e){let t=this.container.getData(aA.Symbol).indexOf(e.symbol);return t<0&&(t=u4(this.container.getData(aA.DateTime),tx(e.symbol)),this.fields.forEach(e=>this.container.getData(e).splice(t,0,null))),t}process(e){let t=this.fields.map(t=>{let i=e.getValue(t);return"Close"!==t.id?i:e.getValue(aA.Last)??i});if(!ey(t))return;let i=this.findOrAddIndex(e);this.fields.forEach((e,s)=>this.container.getData(e)[i]=t[s])}getCacheableEntities(e){e.add(this)}}class u8{query;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){this.query=e,this.fields=[aA.DateTime,aA.Close,aA.Symbol],this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw Error("Should not be called.")}shutdown(){}insertValues(e,t,i){let s=(t,i,s)=>e.getData(i).splice(t,0,s),r=e.getData(aA.DateTime),n=tx(t),a=u4(r,n);s(a,aA.DateTime,n),s(a,aA.Close,i),s(a,aA.Symbol,t)}parseHistoricalForward(e){let t=new ue(this.fields);return e.split("\n").filter(e=>e.trim().length>0).forEach(e=>{let i=e.split(","),s=i[0];this.insertValues(t,s,parseFloat(i[5]))}),t}makeUrl(){let e={};e.symbols=this.query.symbols.join(","),e.maxrecords=1,e.data="daily",e.end=ed(u_(this.query.offset),lz(tz.FMT_HIST_FEED_PARAM_DATE_ONLY))(new Date);let t=eX(e);return`/querylatesteod.ashx?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("timeseries",e);return this.parseHistoricalForward(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}class u9 extends uQ{constructor(e){super(e)}getRetriever(){return new uE}onStreamingUpdates(e){}}class he{cacheSeries;seriesCache;constructor(e=!1){this.cacheSeries=e,this.seriesCache=new Map}getTimeSeries(e){return eF(e.symbol)&&e.symbol===tz.PLACEHOLDER_SYMBOL_NAME?new u0(e):this.getSeries(e)}evictUnused(e){for(let[t,i]of this.seriesCache)!e.has(i)&&i.isCached&&(i.isCached=!1,i.shutdown(),this.seriesCache.delete(t))}refresh(){for(let e of this.seriesCache.values())"function"==typeof e.refresh&&e.refresh()}getSeries(e){let t=(e.cacheMe||this.cacheSeries)&&!e?.alwaysUseBarsToFetch,i=e.getHashKey();if(t&&this.seriesCache.has(i))return this.seriesCache.get(i);{let s=this.makeSeries(e);return s.isCached=t,t&&this.seriesCache.set(i,s),s}}makeSeries(e){switch(e.seriesKind){case J.Normal:return new uQ(e);case J.BalanceSheet:case J.IncomeStatement:return new u3(e);case J.Events:return new u2(e);case J.Forward:return new u7(e);case J.HistoricalForward:return new u8(e);default:case J.Options:return new u9(e);case J.Study:throw Error(`The series kind '${J[e.seriesKind]}' is not supported yet.`)}}}var ht={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"}},hi={date:oj({formats:{full:"EEEE d MMMM y",long:"d MMMM y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:oj({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:oj({formats:{full:"{{date}} 'à' {{time}}",long:"{{date}} 'à' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},hs={lastWeek:"eeee 'dernier à' p",yesterday:"'hier à' p",today:"'aujourd’hui à' p",tomorrow:"'demain à' p'",nextWeek:"eeee 'prochain à' p",other:"P"},hr={code:"fr",formatDistance:function(e,t,i){var s,r=ht[e];if(s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),null!=i&&i.addSuffix)if(i.comparison&&i.comparison>0)return"dans "+s;else return"il y a "+s;return s},formatLong:hi,formatRelative:function(e,t,i,s){return hs[e]},localize:{ordinalNumber:function(e,t){var i,s=Number(e),r=null==t?void 0:t.unit;return 0===s?"0":(i=1===s?r&&["year","week","hour","minute","second"].includes(r)?"ère":"er":"ème",s+i)},era:oX({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:oX({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:oX({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:oX({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:oX({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:oJ({matchPattern:/^(\d+)(ième|ère|ème|er|e)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e)}}),era:oZ({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:oZ({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:oZ({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:oZ({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:oZ({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}};function hn(e){return tt(1,arguments),ts(e).getDay()}function ha(e){tt(1,arguments);var t=ts(e);return t.setMinutes(0,0,0),t}function ho(e,t){tt(2,arguments);var i=ha(e),s=ha(t);return i.getTime()===s.getTime()}function hl(e){tt(1,arguments);var t=ts(e);return t.setSeconds(0,0),t}let hu=/{value:([^}]+)}/,hh=/%([aAdewbBmyYHkIlMpPSL])+/g;var hc=((D=hc||{})[D.Second=0]="Second",D[D.Minute=1]="Minute",D[D.Hour=2]="Hour",D[D.Day=3]="Day",D[D.Week=4]="Week",D[D.Month=5]="Month",D[D.Year=6]="Year",D);let hd={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]}},hp=new Map;function hf(e){if(!eF(e))return null;if(!hp.has(e)){var t;let i=eF(t=e)?t.replace(hu,(e,t)=>t.replace(hh,(e,t)=>tz.PHP_TO_UNICODE_TS_35_MAP[t])):t;hp.set(e,i)}return hp.get(e)}class hm{barWidth;unitWidth;minTickInterval;duration;format;prevDate;size;constructor({barWidth:e,unitWidth:t,formatString:i,minTickInterval:s,duration:r},n){this.size=n,this.barWidth=e,this.unitWidth=t,this.minTickInterval=s,this.duration=r,this.format=hf(i),this.prevDate=null}get noPrevDate(){return!eF(this.prevDate)}formatDate(e,t){return hO(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)}}let hg="yyyy",hy="LLL ''yy",hA=()=>"fr"===hI()?"d LLL":"LLL d",hS="HH:mm";class hT extends hm{repeatEach;repeatCounter;constructor(e){super(e),this.repeatEach=tz.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(!nT(this.prevDate,e))return this.asTick(e,1,"EEE");if(!ho(this.prevDate,e))return this.asTick(e,2,hS);this.repeatCounter++;let t=this.repeatCounter===this.repeatEach;return!function(e,t){tt(2,arguments);var i=hl(e),s=hl(t);return i.getTime()===s.getTime()}(this.prevDate,e)||t?this.asTick(e,t?4:3,hS):null}}class hv extends hm{getTick(e){let t=this.checkPrev(e),i=0===this.minTickInterval||0==(e=>{let t=tl(e);return uI(e,t)})(e)%(this.minTickInterval/1e3),s=!nT(this.prevDate,e),r=function(e){return tt(1,arguments),ts(e).getMinutes()}(e),n=!ho(this.prevDate,e)||t&&0===r;if(i){if(s)return this.asTick(e,1,hA());if(n)return this.asTick(e,2,hS);if(0==r%30&&this.size<15)return this.asTick(e,3,hS);if(0==r%15&&this.size<=5)return this.asTick(e,4,hS)}return null}}class hP extends hm{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<22*hd.Day.One,this.monthYear=this.duration>22*hd.Day.One&&this.duration<7*hd.Month.One,this.year=this.duration>7*hd.Month.One}useTuesday(e){return!!this.noPrevDate||2===hn(e)&&uM(e,this.prevDate)>1728e5}getTick(e){this.checkPrev(e);let t=!nv(e,this.prevDate),i=!n_(e,this.prevDate);return this.monthDay?1===hn(e)||this.useTuesday(e)?this.asTick(e,1,hA()):null:this.monthYear?t?this.asTick(e,1,hy):null:this.year&&i?this.asTick(e,1,hg):null}}class hC extends hm{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<4*hd.Week.One,this.monthYear=this.duration>4*hd.Week.One&&this.duration<6*hd.Month.One,this.year=this.duration>6*hd.Month.One}getTick(e){this.checkPrev(e);let t=!nv(e,this.prevDate),i=!n_(e,this.prevDate);return this.monthDay?this.asTick(e,1,hA()):this.monthYear?t?this.asTick(e,1,hy):null:this.year&&i?this.asTick(e,1,hg):null}}class hb extends hm{showMonths;constructor(e){super(e),this.showMonths=this.duration<7*hd.Month.One}getTick(e){this.checkPrev(e);let t=!n_(e,this.prevDate);return this.showMonths?this.asTick(e,1,hy):t?this.asTick(e,1,hg):null}}class hE extends hm{constructor(e){super(e)}getTick(e){return this.checkPrev(e),n_(e,this.prevDate)?null:this.asTick(e,1,hg)}}function hL(e){return((e.valueOf()-tz.OPTIONS_DATA_BASE)/tz.OPTIONS_DATA_INCREMENT).toString()}function h_(e){return eF(e)?`${e.toFixed(2)}%`:""}function hM(e,t,i=!1){let s=e.plots[0],r=s.curves[0],n=eF(r)&&r.fields.length>0?r.fields[0]:null;if(!eF(n))return"";let a={range:e.fullDomain,allDigits:!1,forceTrailingZeros:i};return hZ(s,e.pane.presenter,a),s.metaData.format(t,n,a)}function hx(e,t,i=!1){return e.comparison===q.Percent?h_(t):hM(e,t,i)}function hD(e,t,i){let s=e.view?.xAxis?.overrideFormatter;if(s)return s(t);if(eF(e.display.xAxis.isOrdinal))return hL(t);let r=i||e.display.xAxis.format;if(eF(r))return hO(t,hf(r));let n=e.data.aggregation,a=e.display?.xAxis?.nonEodLabelWithDate??!1;return n.isEndOfDay?hw(n,t):hR(n,t,a)}function hI(){let e=eG(AA().config,null,"overrides","xAxis","getLocaleName");if(eF(e)&&"function"==typeof e)try{return e()}catch(e){Ad(`Failed retrieving the locale name, error is ${e.message}`,"warn")}}function hO(e,t){return o5(e,t,"fr"===hI()?{locale:hr}:void 0)}function hw(e,t){if(!oE(t))return"";switch(e.unit){case G.Tick:case G.Intraday:case G.Day:case G.Week:default:return hO(t,"P");case G.Month:return hO(t,"LLL yyyy");case G.Quarter:return hO(t,"qqq yyyy");case G.Year:return hO(t,"yyyy")}}function hR(e,t,i){return oE(t)?hO(t,`${i?"P ":""} ${e.isTick?"pp":"p"}`):""}let hN=(e,t)=>e.at(t);class hV{presenter;_dates;pendingRebuild;constructor(e){this.presenter=e,this._dates=[],this.pendingRebuild=!1,this._dates=[],this.invalidate()}checkRebuild(){this.pendingRebuild&&this.rebuild()}get withPrologLength(){return this.checkRebuild(),this._dates.length+tz.TIMELINE_PROLOG_PADDING_BARS}get withPrologEpilogLength(){return this.withPrologLength+tz.TIMELINE_EPILOG_PADDING_BARS}get firstSeriesIndex(){return tz.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<tz.TIMELINE_PROLOG_PADDING_BARS){let t=eb(this._dates),i=e-tz.TIMELINE_PROLOG_PADDING_BARS;return this.applyDateShift(t,i)}if(e>=this.withPrologLength){let t=eC(this._dates),i=e-this.withPrologLength+1;return this.applyDateShift(t,i)}return this._dates[e-tz.TIMELINE_PROLOG_PADDING_BARS]}get length(){return this.checkRebuild(),this._dates.length>0?this.withPrologEpilogLength:0}slice(e,t){this.checkRebuild();let i=[];for(let s=e;s<t;++s)i.push(this.at(s));return i}tryToCorrectLastBar(e,t,i=!0){i&&this.checkRebuild();let s=+e,r=e_(this._dates,s,Number),n=+this._dates[r];return r===this._dates.length-1&&n===s&&(this._dates[r]=t,!0)}mergeDateIntoTimeline(e,t=!0){t&&this.checkRebuild();let i=+e,s=e_(this._dates,i,Number),r=+this._dates[s];if(r!==i){let t=s+ +(i>r);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;let e=this.presenter.mainPlot.timeSeries;if(!e.hasData)return;let t=e.container.getTimeData();for(let e=t.length-1;e>=0;e--)this._dates[e]=t[e];this.presenter.allPlots.forEach(t=>{t.timeSeries!==e&&t.timeSeries.hasData&&t.timeSeries.container.getTimeData().forEach(e=>this.mergeDateIntoTimeline(e,!1))}),this.pendingRebuild=!1}applyDateShift(e,t){let{unit:i,size:s}=this.presenter.data.aggregation;switch(i){case G.Year:return tr(e,12*t);case G.Quarter:return tr(e,3*t);case G.Month:return tr(e,t);case G.Week:return lU(e,7*t);case G.Day:return this.addTradingDays(e,t);case G.Intraday:return oL(e,s*t*tz.ONE_MINUTE_MILLIS);case G.Tick:return oL(e,1e3*t)}}addTradingDays(e,t){if(0===t){let t=e.getDay();return 0===t?lU(e,1):6===t?lU(e,2):e}let i=t>0?1:-1,s=Math.abs(t),r=e;for(;s>0;){let e=(r=lU(r,i)).getDay();0!==e&&6!==e&&s--}return r}}let hH={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 hF(e){return!0===AA().config.useAllFieldsForComparison&&e.mainPlot.mainCurve.isOhlc&&e.mainAxis.comparison===q.None&&e.mainPane.axes.map(e=>e.plots).flat().reduce((e,t)=>e+ +!!t.isSymbol,0)>1}let hB=new nN;function hk({plots:e,isMultiSymbol:t,isMultiContract:i,date:s,time:r,dateFieldName:n,hideSymbols:a,revealingClose:o}){let l=a&&o,u=[hG(n,s,null,"heading"),r?hG("Time",r,null,"heading"):""].concat(e.map(e=>{if(0===e.values.length)return null;let s=(e=>{let s=e.name.startsWith(tz.FAKE_SYMBOL_PREFIX);switch(e.type){case Z.Expression:return!0;case Z.Symbol:if((t||i)&&!s)return!0;return!a;default:return!1}})(e)?hz(Z[e.type],e.name,e.values[0].color):"",r=e.values.map(t=>hG(t.id===aA.Close.id&&l?e.description:t.longName,t.value,t.color));if(e.events&&e.events.length){let t=e.events.map(e=>hz(`${e.field.name} (${hw(hB,e.date)})`,e.value,e.color));r.push(...t)}return r.unshift(s),eF(e.unalignedDate)&&r.unshift(hG("Date",e.unalignedDate,e.values[0].color,"heading")),r}).filter(e=>null!=e).flat()).filter(e=>""!==e).join("");return`<table class="values-table">${u}</table>`}function hW(e){return`bchart-icon-${e}`}function hU(e,t=null,i=10){let s=eF(t)?`style="fill:${t}"`:"",r=hW(e);return`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="${i}px" height="${i}px" ${s}><use xlink:href="#${r}"></use></svg>`}function h$(e,t){let i=e?"Up":"Down",s=hU(`chevron${i}`);return`<span data-pane="${t}" data-dir="${i}" title="Move ${i}" class="move-pane">${s}</span>`}function hG(e,t,i=null,s=[]){"string"==typeof s&&(s=s.split(" "));let r=["value-row",...s],n="string"==typeof i?` style="color: ${i}"`:"";return`
7
+ Bars %csame %c${i(t.lastTimestamp)} == ${i(t.newTimestamp)}`,"color:#0f0","color:#f96"),this.addBar(e,t)):null}alignToQuote(e){if(eF(e.lastPrice,e.time))return this.updateLastBar(e.highPrice,e.lowPrice,e.lastPrice,void 0),{isUpdate:!0,time:e.time.getTime(),index:l5(this.container)}}}class l9 extends l8{innerBuilder;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.processRetrieved()}get base(){return this.innerBuilder.container}fixupTimeBasedAggregationTimestamp(e){let t=lk(e,tz.START_OF_LAST_CENTURY);return l$(e,t%this.agg.size)}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:0,tradePrice:0,tradingDay:0};[aA.Open,aA.High,aA.Low].forEach(i=>{t.tradePrice=this.base.getData(i)[e],super.process(t)}),t.tradePrice=this.base.getData(aA.Close)[e],t.tradeSize=this.base.getData(aA.Volume)[e],super.process(t)}}process(e){return this.innerBuilder.process(e),super.process(e)}}class ue{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!==aA.Change||!this.hasField(aA.Close)||t<1)return;let i=this.storage[e.id],s=this.storage[aA.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){let t=e.getLastDataPoint(aA.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){let t=e.getTimeData()[0].getTime()===this.getLastDataPoint(aA.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}getTimeData(){return this.getData(aA.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 Error(`This container does not store values for field ${e.id}`)}addDataPoint(e,t){this.checkField(e),this.getData(e).push(t)}getLastDataPoint(e){return this.checkField(e),eC(this.getData(e))}setLastDataPoint(e,t){this.checkField(e);let i=this.getData(e);i[i.length-1]=t}keepOnlyLast(e){if(this.size<=e)return;let t=this.size-e;this.fields.forEach(e=>this.getData(e).splice(0,t))}}class ut extends ue{constructor(){super([])}get size(){return 0}}class ui extends ue{wrapper;constructor(e,t){super(e),this.wrapper=t}isWrapped(e){return e$(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)}}let us=tz.RENKO_KAGI_NAMES;function ur(e){let{Method:t,Period:i,Source:s,BrickSize:r}=eK(e),n=eU(t,[us.ATR,us.TRD,us.PCT],us.ATR),a=Number.isFinite(i)?i:14;return{method:n,period:a,source:eU(s,[us.CLS,us.HL],us.CLS),brickSize:Number.isFinite(r)?r:10}}function un(e,t,i){return e.getData(t)[i]}function ua(e,t){let[i,s]=[aA.High,aA.Low].map(i=>un(e,i,t)),r=un(e,aA.Close,t-1);return Math.max(i-s,Math.abs(i-r),Math.abs(s-r))}function uo(e,t){if(e.size<t)return null;let i=t-1,s=[];s.push(un(e,aA.High,0)-un(e,aA.Low,0));for(let i=1;i<t;++i)s.push(ua(e,i));let r=eg(s);for(let s=t;s<e.size;++s)r=(r*i+ua(e,s))/t;return r}let ul=e=>aA[e],uu=["DateTime","Open","High","Low","Close","Volume"].map(ul),uh=uu.concat(["Change","Projection","BarIndex"].map(ul));class uc extends l6{innerBuilder;inputs;brickSize;lastFinalBrick;projectionCount;refPrices;constructor(e,t){super(),this.supportsChunks=!1,this.innerBuilder=e,this.inputs=ez(t.inputs),this.brickSize=null,this.container=new ue(uh),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){let[i,s,r,n,a,o]=uu.map(i=>t.getData(i)[e]);return{date:i,open:s,high:r,low:n,close:a,volume:o}}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){let[s,r]=this.refPrices(t.close,t.high,t.low),n=s-e.high,a=e.low-r;return{climbing:(i&&n>0||n>=this.brickSize)&&n>=a,falling:(i&&a>0||a>=this.brickSize)&&a>n,moveUp:n,moveDown:a}}initFirstBrick(e,t){e.open=e.high=e.low=e.close=Math.max(this.brickSize,eB(t.close-t.close%this.brickSize,4)),e.date=t.date,e.volume=e.change=0}findSafeStartIndex(){let e=0,t=this.base.size-1,i=2*tz.RENKO_MAX_BARS;for(;t>0&&e<i;)e+=Math.floor(ua(this.base,t)/this.brickSize),t--;return t}processRetrieved(){let e=ur(this.inputs),{method:t,period:i,source:s}=e;if(this.brickSize=e.brickSize,t===us.ATR)this.brickSize=uo(this.base,i);else if(t===us.PCT)if((this.base?.size??0)>0){let e=this.base.getLastDataPoint(aA.Close);this.brickSize=e*this.brickSize/100}else this.brickSize=null;if(!eF(this.brickSize))return;this.refPrices=s===us.HL?(e,t,i)=>[t,i]:(e,t,i)=>[e,e];let r={},n=this.findSafeStartIndex();for(let e=n;e<this.base.size;e++){let t=this.getBarAt(e);if(e===n){this.initFirstBrick(r,t);continue}let i=this.isLastBase(e),{climbing:s,falling:a,moveUp:o,moveDown:l}=this.getMove(r,t,i);if(!s&&!a){r.volume+=t.volume;continue}r.proj=Number(i),r.barIndex=e;let u=t.date.getTime();if(s){let e=this.getBricksCount(o);for(let t=0;t<e;++t)this.constructClimbing(r,u,t,this.brickSize);i&&(this.constructClimbing(r,u,e,o%this.brickSize),this.projectionCount=e+1)}else if(a){let e=this.getBricksCount(l);for(let t=0;t<e;++t)this.constructFalling(r,u,t,this.brickSize);i&&(this.constructFalling(r,u,e,l%this.brickSize),this.projectionCount=e+1)}i||(this.lastFinalBrick=this.container.size-1,r.volume=0)}this.container.keepOnlyLast(tz.RENKO_MAX_BARS)}constructClimbing(e,t,i,s,r=!0){let n=e.high,a=e.close;e.open=e.low=n,e.high=e.close=n+s,e.date=new Date(t+i),e.change=e.close-a,r?this.addToContainer(e):this.updateLastDataPoint(e)}constructFalling(e,t,i,s,r=!0){let n=e.low,a=e.close;e.open=e.high=n,e.low=e.close=n-s,e.date=new Date(t+i),e.change=e.close-a,r?this.addToContainer(e):this.updateLastDataPoint(e)}process(e){let t=this.innerBuilder.process(e);return this.processUpdate(t)}alignToQuote(e){let 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;let t=this.base.size-1,i=this.getBarAt(t),s=this.getBrickAt(this.lastFinalBrick),{climbing:r,falling:n,moveUp:a,moveDown:o}=this.getMove(s,i,!0),l=1===this.container.getLastDataPoint(aA.Projection);if(!r&&!n)return l?this.rebuild():null;let u=this.getBricksCount(r?a:o)+1;if(!l||this.projectionCount!==u)return this.rebuild();{let 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}}}addToContainer(e){let t=this.container;t.addDataPoint(aA.DateTime,e.date),t.addDataPoint(aA.Open,e.open),t.addDataPoint(aA.Close,e.close),t.addDataPoint(aA.High,e.high),t.addDataPoint(aA.Low,e.low),t.addDataPoint(aA.Change,e.change),t.addDataPoint(aA.Volume,e.volume),t.addDataPoint(aA.Projection,e.proj),t.addDataPoint(aA.BarIndex,e.barIndex)}updateLastDataPoint(e){let t=this.container;t.setLastDataPoint(aA.DateTime,e.date),t.setLastDataPoint(aA.Open,e.open),t.setLastDataPoint(aA.Close,e.close),t.setLastDataPoint(aA.High,e.high),t.setLastDataPoint(aA.Low,e.low),t.setLastDataPoint(aA.Change,e.change),t.setLastDataPoint(aA.Volume,e.volume),t.setLastDataPoint(aA.Projection,e.proj),t.setLastDataPoint(aA.BarIndex,e.barIndex)}}let ud=[aA.DateTime,aA.TradingDay,aA.Last,aA.TradeSize,aA.Change],up=[aA.DateTime,aA.Open,aA.High,aA.Low,aA.Close,aA.Volume,aA.Change],uf=[...up,aA.OpenInterest],um=[...uf,aA.Symbol],ug=[aA.Open,aA.High,aA.Low,aA.Close,aA.Change];function uy(e,t){let i=tL(e);if(t.isTick)return ud;{let e=up;return t.isMultiContract?e=um:(i||t.isEndOfDay)&&(e=uf),t.isIntraday?[...e,aA.TradingDay]:e}}class uA{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=new Date(0),this.timeZone=this.getTimeZone(),this.isFuture=ty(e),this.padded=s,this.needsResolution=tE(e),this.hasOpenInterest=tL(e)}makeContainer(){return new ue(uy(this.symbol,this.aggregation))}parse(e){this.container=this.makeContainer();let t=e.split("\n"),i=this.getParseFunc();if(null!==i){let e=i.bind(this);t.forEach(t=>{let i=t.trim();i&&e(i.split(","))})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){let t=e.length-5;(0===t||1===t)&&(this.container.addDataPoint(aA.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(aA.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(aA.Last,parseFloat(e[3+t])),this.container.addDataPoint(aA.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(aA.Change,this.calculateChange(aA.Last)))}nullify(e){return null==e||0===e?null:e}parseMinutes(e){let t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,i=+!!t;e.length===7+i&&(this.container.hasField(aA.Symbol)&&this.container.addDataPoint(aA.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(aA.DateTime,this.parseDate(e[0+i])),this.container.addDataPoint(aA.TradingDay,parseInt(e[1+i])),this.container.addDataPoint(aA.Open,parseFloat(e[2+i])),this.container.addDataPoint(aA.High,parseFloat(e[3+i])),this.container.addDataPoint(aA.Low,parseFloat(e[4+i])),this.container.addDataPoint(aA.Close,parseFloat(e[5+i])),this.container.addDataPoint(aA.Volume,this.nullify(parseInt(e[6+i]))),this.container.addDataPoint(aA.Change,this.calculateChange()))}parseFloatOrNull(e){let t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){let t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){let t=this.aggregation.isMultiContract,i=7+ +!!this.hasOpenInterest;e.length===i&&(t&&this.container.addDataPoint(aA.Symbol,e[0]),this.container.addDataPoint(aA.DateTime,this.parseDate(e[1])),this.container.addDataPoint(aA.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(aA.High,parseFloat(e[3])),this.container.addDataPoint(aA.Low,parseFloat(e[4])),this.container.addDataPoint(aA.Close,parseFloat(e[5])),this.container.addDataPoint(aA.Volume,this.nullify(this.parseIntOrNull(e[6]))),this.hasOpenInterest&&this.container.addDataPoint(aA.OpenInterest,this.nullify(this.parseIntOrNull(e[7]))),this.container.addDataPoint(aA.Change,this.calculateChange()))}calculateChange(e=aA.Close){let t=this.container.size;if(!(t>1))return 0;{let i=this.container.getData(e);return i[t-1]-i[t-2]}}parseTimestamp(e){switch(this.aggregation.unit){case G.Tick:case G.Intraday:return function(e,t=tz.ZERO_DATE){let i=new Date(e.replace(" ","T"));return oE(i)?i:t}(e);default:return l4(e)}}parseDate(e){let t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?tn(t,this.offset):(!function(e,t){tt(2,arguments);var i=ts(e),s=ts(t);return i.getTime()>s.getTime()}(t,this.previousTime)?this.previousTime=oL(this.previousTime,1):this.previousTime=t,this.previousTime)}getTimeZone(){return t_(this.symbol)}}let{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:uS,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:uT}=tz;class uv{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case G.Tick:return tz.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case G.Intraday:return t&&e.spec===z.Nearest?uS:uT;case G.Day:case G.Week:case G.Month:case G.Quarter:case G.Year:return tz.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return""}}addExtraParams(e){}makeUrl(e){let t={},i=t0(e.symbol);t.symbol=i;let s=e.aggregation,r=this.getDataParam(s);r.length>0&&(t.data=r),s.size>1&&s.unit===G.Intraday&&(t.interval=(s.spec===z.PerRange?1:s.size).toString());let[n,a]=e.range,o=null!==n,l=null!==a;if(o&&(t.start=this.toHistoricalFeedDate(n,s)),!o||e.alwaysUseBarsToFetch){let i=e.barsToFetch||tz.DEFAULT_MAX_RECORDS;s.unit===G.Tick&&s.spec!==z.None&&(i*=tz.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=i.toString()}l&&(t.end=this.toHistoricalFeedDate(a,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);let u=eX(t),h=ty(i),c=this.getPageNameFor(s,h);return`/${c}?${u}`}toHistoricalFeedDate(e,t){return o5(e,t.isTick||t.isIntraday?tz.FMT_HIST_FEED_PARAM_DATE_TIME:tz.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t="",i=this.getSpecPart(e);switch(e.unit){case G.Tick:case G.Intraday:break;case G.Day:t=`daily${i}`;break;case G.Week:t=`weekly${i}`;break;case G.Month:t=`monthly${i}`;break;case G.Quarter:t=`quarterly${i}`;break;case G.Year:t=`yearly${i}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===z.Continue?"continue":"nearest":""}getParser(e){return new uA(t0(e.symbol),e.aggregation,e.offset,e.padded)}async retrieve(e){let t=this.makeUrl(e),i=e.aggregation.unit===G.Tick?"timeseriesNew":"timeseries",s=await Af(i,t);return this.getParser(e).parse(s)}}class uP{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){let t=t0(e.symbol),i=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==G.Day)return i;let s={symbol:t};this.addExtraParams(s);let r=`/${this.getPageName()}.json?${eX(s)}`,n=await Af("ondemand",r);try{let e=JSON.parse(n);if(200===e.status.code){let 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)}}catch(e){Ad(`Failed parsing the JSON result from OnDemand, error is ${e.message}`)}return i}}class uC extends uP{emptyContainer(e,t){return new ue(uy(e,t))}get iterateForward(){return!0}getPageName(){return"getEquityOptionsHistory"}processRow(e,t,i){let s=i.hasField(aA.Symbol),r=t>0?i.getLastDataPoint(aA.Close):null;i.addDataPoint(aA.DateTime,l4(e.date)),s&&i.addDataPoint(aA.Symbol,e.symbol),i.addDataPoint(aA.Open,e.open),i.addDataPoint(aA.High,e.high),i.addDataPoint(aA.Low,e.low),i.addDataPoint(aA.Close,e.close),i.addDataPoint(aA.Volume,e.volume),i.addDataPoint(aA.OpenInterest,e.openInterest);let n=null===r?null:eB(e.close-r,2);i.addDataPoint(aA.Change,n)}}let ub={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 uE{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){let t=t0(e.symbol).replace(/\.bz$/i,""),i=e.fields.concat(aA.DateTime),s=()=>new ue(i);if(e.aggregation.unit!==G.Day)return s();let r={symbol:t,apiKey:"default",fields:i.map(e=>ub[e.id]).join(",")},n=`/get?${eX(r)}`,a=await Af("options",n);try{let e=JSON.parse(a).data,t=s();return e.forEach(e=>{i.forEach(i=>{if(i===aA.DateTime)t.addDataPoint(aA.DateTime,l4(e.date));else{let s;t.addDataPoint(i,(s=e[ub[i.id]],Number.parseFloat(s.replace(/,/g,""))))}})}),t}catch(e){Ad(`Failed parsing options JSON historical data result, error is ${e.message}`)}return s()}}function uL(e,t){return oA(function(i,s){var r=0;i.subscribe(oS(s,function(i){s.next(e.call(t,i,r++))}))})}var u_=lG(l$,2);function uM(e,t){return tt(2,arguments),ts(e).getTime()-ts(t).getTime()}var ux={ceil:Math.ceil,round:Math.round,floor:Math.floor,trunc:function(e){return e<0?Math.ceil(e):Math.floor(e)}};function uD(e){return e?ux[e]:ux.trunc}function uI(e,t,i){tt(2,arguments);var s=uM(e,t)/1e3;return uD(null==i?void 0:i.roundingMethod)(s)}class uO extends l8{innerBuilder;isBuildingBars;constructor(e,t,i){super(t,i),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=tz.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;let[e,t,i,s]=[aA.DateTime,aA.TradeSize,aA.Last,aA.TradingDay].map(e=>this.base.getData(e));for(let r=this.startFromIndex;r<this.base.size;r++){let n={isTrade:!0,time:e[r],tradeSize:t[r],tradePrice:i[r],tradingDay:s[r]};super.process(n)}this.isBuildingBars=!1}process(e){let t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}}class uw extends uO{constructor(e,t,i){super(e,t,i)}fixupTimeBasedAggregationTimestamp(e){let t=uI(e,tc(al(e,1)));return function(e,t){return tt(2,arguments),lZ(e,-te(t))}(e,t%this.agg.size)}}class uR extends uO{series;constructor(e,t,i,s){super(e,i,s),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}}let uN=new am("_TICK_COUNT");class uV extends uR{anchorTimestamp=null;constructor(e,t,i,s){super(e,t,i,s)}get startFromIndex(){let e=0,t=this.base.getTimeData();if(eF(this.anchorTimestamp))e=eE(t,e=>e===this.anchorTimestamp);else{let i=this.base.size;if(i>2)for(let s=i-2;s>2;--s){let 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){let i=super.addBar(e,t);return this.container.addDataPoint(uN,1),i}changeLastBar(e,t){let i=super.changeLastBar(e,t),s=this.container.getLastDataPoint(uN);return this.container.setLastDataPoint(uN,s+1),i}isUpdate(e,t,i,s){return this.container.getLastDataPoint(uN)<this.agg.size}}let uH=new am("_VOLUME_TALLY");class uF extends uR{constructor(e,t,i,s){super(e,t,i,s)}addBar(e,t){let i=this.container,s=(i.getLastDataPoint(uH)||0)+e.tradeSize,r=Math.floor(s/this.agg.size),n=s%this.agg.size,a=s<this.agg.size;i.size>0&&(i.setLastDataPoint(aA.Volume,a?1:r),i.setLastDataPoint(uH,s));let o=super.addBar(e,t);return i.setLastDataPoint(aA.Volume,1),i.addDataPoint(uH,a?0:n),o}changeLastBar(e,t){let i=this.container,s=super.changeLastBar(e,t);i.setLastDataPoint(aA.Volume,1);let r=i.getLastDataPoint(uH)??0;return i.setLastDataPoint(uH,r+e.tradeSize),s}isUpdate(e,t,i,s){if(!nT(e,t))return!1;let r=this.container.getLastDataPoint(uH)??0;return s.tradeSize+r<this.agg.size}}class uB extends l8{innerBuilder;metadata;range;step;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.range=i.size,this.step=1;let r=AA().getMetaDataSource();this.metadata=r.getMetaData(s)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return tU.call(this,async()=>{let 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++){let t=this.base.getData(aA.Volume)[e],i=this.useHighOrLow(e);if(!eF(i)){this.updateLastBar(void 0,void 0,void 0,t);continue}let s={isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:t,tradePrice:i,tradingDay:0};super.process(s)}}useHighOrLow(e){let t=this.base.getData(aA.Close)[e];if(0==this.container.size)return t;let i=this.container.getLastDataPoint(aA.High),s=this.container.getLastDataPoint(aA.High),r=this.base.getData(aA.High)[e],n=this.base.getData(aA.Low)[e],a=r>i,o=n<s;return a&&o?r-t<t-n?r:n:a?r:o?n: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){let i=e.tradePrice,s=this.container.getLastDataPoint(aA.Low)+this.priceRange;if(i>s)return this.changeAndAddBar(s,e,t);let r=this.container.getLastDataPoint(aA.High)-this.priceRange;return i<r?this.changeAndAddBar(r,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,i){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(aA.Projection,0),this.addBar(t,i)}addBar(e,t){return this.container.addDataPoint(aA.Projection,1),super.addBar(e,t)}}let uk=[aA.Open,aA.High,aA.Low,aA.Close],uW=[aA.BARCOLIX,aA.High,aA.Low],uU=tz.RENKO_KAGI_NAMES;function u$(e){let{BoxSizeMethod:t,Period:i,ReversalAmount:s}=eK(e),r=eU(t,[uU.ATR,uU.TRD],uU.ATR);return{method:r,period:Number.isFinite(i)?i:14,reversal:Number.isFinite(s)?s:30}}class uG extends l8{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ez(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(aA.BARCOLIX,null),this.container.size>1){let e=this.dataAt(aA.Close,this.container.size-2);this.setLast(aA.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,i,s){let r=s.tradePrice,n=r-this.getLast(aA.Close),a=n>=0,o=Math.abs(n)>=this.reversal,[l,u,h,c]=uk.map(e=>this.getLast(e)),d=c-l,p=d>=0!==a||0===d;return p&&!o||!p&&(a?r<u:r>h)?null:Math.abs(d)<this.reversal||!p||!o}computeBarColor(){let e=e=>this.dataAt(aA.Close,e)>this.dataAt(aA.Open,e),t=this.container.size;if(t>1){let i=e(t-1),[s,r,n]=uW.map(e=>this.dataAt(e,t-2)),[,a,o]=uW.map(e=>this.dataAt(e,t-1)),l=s;0===s&&i&&a>r?l=1:1===s&&!i&&o<n&&(l=0),this.setLast(aA.BARCOLIX,l)}else this.setLast(aA.BARCOLIX,+!!e(0))}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);let t=super.process(e);return this.computeBarColor(),t}processRetrieved(){let{method:e,period:t,reversal:i}=u$(this.inputs);if(this.reversal=i,e===uU.ATR&&(this.reversal=uo(this.base,t)),eF(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(aA.DateTime,e),tradePrice:this.baseAt(aA.Close,e),tradeSize:this.baseAt(aA.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}function uz(e){let{LineCount:t}=eK(e);return{lineBreak:Number.isFinite(t)?t:3}}class uY extends l8{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,i,s){super(t,i),this.innerBuilder=e,this.inputs=ez(s.inputs);let r=uz(this.inputs);this.lineBreak=r.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(aA.DateTime)[e],tradeSize:this.base.getData(aA.Volume)[e],tradePrice:this.base.getData(aA.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++){let 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){let r=this.findOpen(i,0,1);this.currentVolume+=s,null!==r?(super.updateLastBar(void 0,void 0,i,void 0),this.container.setLastDataPoint(aA.Open,r),this.container.setLastDataPoint(aA.Low,Math.min(r,i)),this.container.setLastDataPoint(aA.High,Math.max(r,i))):this.resetProjection()}resetProjection(){let e=this.container;e.setLastDataPoint(aA.High,null),e.setLastDataPoint(aA.Low,null),e.setLastDataPoint(aA.Open,null),e.setLastDataPoint(aA.Close,null),e.setLastDataPoint(aA.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(aA.DateTime,t.nextTimestamp);let i=this.changeLastBar(e,t);return i.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},i}addBar(e,t){let i=this.container,{nextTimestamp:s}=t;if(1===i.getLastDataPoint(aA.Projection)){let s=i.getLastDataPoint(aA.Close);if(null===this.findOpen(s,this.lineBreak,1))return this.updateProjection(e,t);i.setLastDataPoint(aA.Projection,0),i.setLastDataPoint(aA.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;let 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(aA.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;let 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(aA.Projection,1),!0)}findOpen(e,t,i=0){if(!eF(e))return null;let s=this.container,r=s.size-1-i,n=s.getData(aA.Close)[r],a=s.getData(aA.Open)[r];if(n>a){if(e<=n){if(e>=a)return null;for(let i=0;i<Math.min(s.size,t);i++)if(e>=s.getData(aA.Low)[r-i])return null;return a}return n}if(e>=n){if(e<=a)return null;for(let i=0;i<Math.min(s.size,t);i++)if(e<=s.getData(aA.High)[r-i])return null;return a}return n}startLine(e){this.container.addDataPoint(aA.Projection,0);let 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)}}let uj=tz.RENKO_KAGI_NAMES;function uK(e){switch(e){case tz.BARKIND_O:case tz.BARKIND_XO:return!0;default:return!1}}function uq(e){switch(e){case tz.BARKIND_X:case tz.BARKIND_OX:return!0;default:return!1}}function uX(e){let t=eK(e),{Source:i,BoxSizeMethod:s,Period:r}=t,{ReversalAmount:n,BoxSize:a,OneStepBack:o}=t,l=eU(i,[uj.CLS,uj.HL],uj.CLS),u=eU(s,[uj.ATR,uj.TRD],uj.ATR),h=Number.isFinite(r)?a:14,c=Number.isFinite(n)?n:3;return{method:u,period:h,source:l,boxSize:Number.isFinite(a)?a:20,reversal:c,oneStepBack:"Yes"===o}}class uZ extends l8{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,i){super(t,i.aggregation),this.innerBuilder=e,this.inputs=ez(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){let s=Math.abs(t-e);return e+i*this.roundToBox(s)}get closeBased(){return this.source===uj.CLS}get currentKind(){return this.getLast(aA.BARKIND)}getTrendField(e){return this.closeBased?aA.Close:e?aA.Low:aA.High}getTrendPrice(e,t){return this.closeBased?e.tradePrice:t?e._lowPrice:e._highPrice}changeLastBar(e,t){let i=uK(this.currentKind),s=i?-1:1,r=this.getLast(this.getTrendField(i)),n=this.getTrendPrice(e,i);return e.tradePrice=this.roundedDiff(r,n,s),super.changeLastBar(e,t),null}addBar(e,t){let i=0===this.container.size,s=uK(this.currentKind),r=s?1:-1,n=i?null:this.getLast(aA.Close),a=this.getTrendPrice(e,!s);if(e.tradePrice=(i?this.roundToBox(this.baseAt(aA.Open,0)):n)+r*(i?0:this.boxSize),super.addBar(e,t),!i){let e=this.roundedDiff(n,a,r);this.updateLastBar(e,e,e)}return this.container.addDataPoint(aA.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){let e=uK(this.currentKind)?tz.BARKIND_OX:tz.BARKIND_XO;this.setLast(aA.BARKIND,e)}canInplaceReverse(){return!function(e){switch(e){case tz.BARKIND_OX:case tz.BARKIND_XO:return!0;default:return!1}}(this.currentKind)&&this.getLast(aA.High)===this.getLast(aA.Low)}isUpdate(e,t,i,s){let r=uK(this.currentKind),n=this.getTrendPrice(s,r),a=this.getTrendPrice(s,!r),o=n-this.getLast(aA.Close),l=o>=0,u=Math.abs(o)>=this.boxSize,h=a-this.getLast(aA.Close),c=h>=0,d=Math.abs(h)>=this.reversal*this.boxSize;if(r){if(!l&&u)return!0;if(c&&d)if(!this.oneStepBack||!this.canInplaceReverse())return!1;else return this.inplaceReverse(),!0;return null}if(l&&u)return!0;if(!c&&d)if(!this.oneStepBack||!this.canInplaceReverse())return!1;else return this.inplaceReverse(),!0;return null}findFirstDiffLargerThanBox(e,t){let i=this.baseAt(aA.Open,0),s=this.innerBuilder.container.size;for(let r=1;r<s;++r){let s=this.baseAt(e,r)-i;if(Math.abs(s)>this.boxSize){if(1===t&&s>0)return[r,tz.BARKIND_X];if(2===t&&s<0)return[r,tz.BARKIND_O];if(3===t)return[r,s>0?tz.BARKIND_X:tz.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){let[,e]=this.findFirstDiffLargerThanBox(aA.Close,3);return e}{let[e,t]=this.findFirstDiffLargerThanBox(aA.High,1),[i,s]=this.findFirstDiffLargerThanBox(aA.Low,2);return null===t&&null===s?null:null===s?t:null===t?s:e<i?t:s}}computeBarColor(){let e=this.container.size,t=this.firstTrend;e>1&&(t=uK(this.dataAt(aA.BARKIND,e-2))?tz.BARKIND_X:tz.BARKIND_O),this.setLast(aA.BARKIND,t)}process(e){return(this.isProcessingRetrieved||this.innerBuilder.process(e),null===this.firstTrend)?null:super.process(e)}processRetrieved(){let{method:e,period:t,reversal:i,source:s,boxSize:r,oneStepBack:n}=uX(this.inputs);if((this.reversal=i,this.source=s,e===uj.ATR?this.boxSize=uo(this.base,t):this.boxSize=r,eF(this.reversal,this.boxSize))&&(this.oneStepBack=n&&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++){let t={isTrade:!0,time:this.baseAt(aA.DateTime,e),tradePrice:this.baseAt(aA.Close,e),_highPrice:this.baseAt(aA.High,e),_lowPrice:this.baseAt(aA.Low,e),tradeSize:this.baseAt(aA.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}}let uJ=new nN(G.Intraday,0);class uQ{query;container;canLoadMoreData;alignToQuote;record;isLoading;serverComputedSeries;builder;retriever;streamingSubscription;constructor(e){this.query=e,this.canLoadMoreData=!0,this.alignToQuote=!1,this.isLoading=!1,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new ab(e.symbol)}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){let t=this.query.aggregation;if(!t.isTick)return new l8(e,t);switch(t.spec){case z.None:case z.PerSeconds:case z.PerCount:case z.PerVolume:return new l7(e);default:throw Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}}makeBuilder(e){let t=this.makeInnerBuilder(e),i=this.query.aggregation,s=(e,t=[])=>new ue(uy(this.query.symbol,e).concat(t));switch(this.query.curveStyle){case $.Renko:return new uc(t,this.query);case $.Kagi:return new uG(t,s(uJ,[aA.BARCOLIX]),this.query);case $.PointAndFigure:return new uZ(t,s(uJ,[aA.BARKIND]),this.query);case $.LineBreak:return new uY(t,s(i,[aA.Projection]),i,this.query)}if(i.isIntraday&&i.spec===z.PerRange)return new uB(t,s(uJ,[aA.Projection]),i,this.query.symbol);if(i.isTick)switch(i.spec){case z.PerSeconds:return new uw(t,s(uJ),i);case z.PerCount:return new uV(t,this,s(uJ,[uN]),i);case z.PerVolume:return new uF(t,this,s(uJ,[uH]),i)}return i.unit===G.Day&&i.size>1?new l9(t,s(i),i):t}onStreamingUpdates(e){this.isLoading||e.map(e=>{if("isTrade"in e)return this.builder.process(e);if("isQuote"in e&&(eN(aS.TS_QUOTEMARKER,{series:this}),this.alignToQuote)){let t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>eF(e)).filter((e,t,i)=>{if(0===t)return!0;let s=i[t-1];return s.isUpdate!==e.isUpdate||s.time!==e.time||e.timeCorrection}).forEach(e=>{if(-1===e.index)eN(aS.TS_MANYCHANGED,{series:this,part:en.Unspecified});else{let t={series:this,index:e.index};eN(e.isUpdate?aS.TS_DATAPOINTCHANGED:aS.TS_DATAPOINTADDED,t)}e.timeCorrection&&eN(aS.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return null!==this.container}getRetriever(){return tP(this.query.symbol)&&this.query.aggregation.isEndOfDay?new uC:new uv}getStreamingSubscription(){return AA().getRecordSource().subject.pipe(uL(e=>{let t=this.query.aggregation.isEndOfDay,i=aV(aS.RT_TRADE,this.record.symbol),s=e=>"T"!==e.data.session||this.query.extendedHours&&!t,r=e.filter(i).filter(e=>eF(e.data.time)).filter(s).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay})).reduce((e,t)=>{let i=eC(e);return eF(i)&&eF(i.tradePrice)&&eF(t.tradePrice)&&i.tradePrice===t.tradePrice&&i.time.getTime()===t.time.getTime()&&i.tradingDay===t.tradingDay?i.tradeSize+=t.tradeSize:e.push(Object.assign({},t)),e},[]),n=aV(aS.RT_QUOTE,this.record.symbol);return r.concat(e.filter(n).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}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(){let e=this.query.duplicate(),t=this.builder.getLastDate();eF(e.offset)&&0!==e.offset&&(t=tn(t,-e.offset)),e.range=[t,null];let i=await this.retriever.retrieve(e),s=this.container.size;this.builder.append(i);let r=this.container.size-s;eN(aS.TS_MANYCHANGED,{series:this,part:en.Tail,count:r,index:s})}async loadHeadChunk(){let e=!1,t=null;for(let i=0;i<this.builder.retryCountForChunk&&!e;++i){let s=this.query.duplicate(),r=this.builder.getFirstDate(i);eF(s.offset)&&0!==s.offset&&(r=tn(r,-s.offset)),s.range=[null,r],e=(t=await this.retriever.retrieve(s)).size>1}this.canLoadMoreData=e,e&&null!==t&&(this.builder.prepend(t),eN(aS.TS_MANYCHANGED,{series:this,part:en.Head}))}async applyNearbyFixup(e){let t=this.query.aggregation,i=t.spec===z.Nearest,s=this.query.symbol,r=ty(s);return r&&t.isMultiContract&&i&&!(e.size<1)&&!this.serverComputedSeries?e.getLastDataPoint(aA.Symbol):r&&tE(s)?await tm(s):s}async ready(){return tU.call(this,async()=>{this.retriever=this.getRetriever();let e=await this.retriever.retrieve(this.query),t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=AA().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0})}getCacheableEntities(e){e.add(this)}shutdown(){eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class u0{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new ut}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw Error("Should not be called.")}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}}class u1{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return null!==this.container}loadMoreData(e){throw Error("Should not be called.")}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}}class u2{query;container;supplyCustomDemoData;canLoadMoreData;isLoading;constructor(e){this.query=e,this.canLoadMoreData=!0,this.isLoading=!0,this.container=null,this.supplyCustomDemoData="DemoSite"===AA().config.mode}refresh(){}loadMoreData(e){throw Error("Should not be called.")}get hasData(){return null!==this.container}shutdown(){}parseEvents(e){let t=new ue([aA.DateTime,aA.Dividends,aA.Earnings,aA.Splits,aA.Custom]),i=e.split("\n"),s=(e,i,s,r)=>{t.addDataPoint(e,i===s?r:null)};return i.forEach(e=>{if(""===e.trim())return;let i=e.split(",");if(4!==i.length)return;let r=l4(i[1]);t.addDataPoint(aA.DateTime,r),s(aA.Dividends,"Dividend",i[2],i[3]),s(aA.Earnings,"Earnings",i[2],i[3]),s(aA.Splits,"Split",i[2],i[3]),this.supplyCustomDemoData?s(aA.Custom,"Custom","Custom",tz.FAKE_CUSTOM_EVENT):s(aA.Custom,"Custom",i[2],i[3])}),t}makeUrl(){let e={};e.symbols=this.query.symbol,e.start="19700102",e.end="20501230",tz.EVENTS_BUILT_IN.forEach(t=>e[t]=this.query[t]);let t=eX(e);return`/queryevents.ashx?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("timeseries",e);return this.parseEvents(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),this.isLoading=this.canLoadMoreData=!1,!0))}getCacheableEntities(e){e.add(this)}}class u3{query;container;canLoadMoreData;isLoading;constructor(e){this.query=e,this.canLoadMoreData=!1,this.isLoading=!0,this.query=e,this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw Error("Should not be called.")}shutdown(){}parseFundamental(e){let t=JSON.parse(e),i=t.status.code,s=204===i;if(200!==i&&!s)return null;let r=new ue(this.query.fields.concat(aA.DateTime));if(s)return r;let n=this.query.fields[0],a=n.id.substring(0,1).toLowerCase()+n.id.substring(1);return t.results.reverse().forEach(e=>{r.addDataPoint(aA.DateTime,l4(e.date)),r.addDataPoint(n,parseFloat(e[a]))}),this.isLoading=!1,r}makeUrl(){let e={count:0,rawData:1};e.symbols=this.query.symbol,e.frequency=this.query.aggregation.unit===G.Quarter?"Quarter":"Annual";let t=eX(e),i=this.query.seriesKind===J.BalanceSheet?"getBalanceSheets":"getIncomeStatements";return`/${i}.json?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("ondemand",e);return this.parseFundamental(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}function u4(e,t){let i=e.findIndex(e=>e>t);return Math.max(i<0?e.length:i,0)}class u5{records;streamingSubscription;setSymbols(e){let t=AA().getRecordSource();this.records=e.reduce((e,i)=>{let s=t.getRecord(i);return this.addFieldsToRecord(s,i),e[i]=s,e},{})}getStreamingSubscription(){return AA().getRecordSource().subject.pipe(oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}onStreamingUpdates(e){e.forEach(e=>{let t=e.data,i=this.records[t.symbol];eF(i)&&this.process(i)}),this.notifyAboutUpdates()}async retrieve(){let e=Object.values(this.records);return(await Promise.all(e.map(e=>e.ready()))).every(ep)&&(this.onRecordsReady(),e.forEach(e=>this.process(e)),this.streamingSubscription=this.getStreamingSubscription()),this.hasData}async ready(){return tU.call(this,async()=>await this.retrieve())}shutdown(){eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}}class u6 extends u5{symbols=[];constructor(e){super(),this.symbols=e,this.setSymbols(e)}addFieldsToRecord(e,t){e.addFields(aA.Symbol),e.update(aA.Symbol,t)}notifyAboutUpdates(){eN(aS.RT_QUOTEGROUP,{source:this})}process(e){}onRecordsReady(){}get hasData(){return!0}getValue(e){let t=this.records[e];return void 0===t?null:t.getValue(aA.Close)}}class u7 extends u5{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=[aA.DateTime,aA.Close,aA.Symbol]}addFieldsToRecord(e,t){e.addFields(aA.DateTime,aA.Symbol),e.update(aA.DateTime,tx(t)),e.update(aA.Symbol,t)}refresh(){}loadMoreData(e){throw Error("Should not be called.")}get hasData(){return null!==this.container&&this.container.size===this.dataPoints}notifyAboutUpdates(){eN(aS.TS_MANYCHANGED,{series:this,part:en.Unspecified})}onRecordsReady(){this.container=new ue(this.fields)}findOrAddIndex(e){let t=this.container.getData(aA.Symbol).indexOf(e.symbol);return t<0&&(t=u4(this.container.getData(aA.DateTime),tx(e.symbol)),this.fields.forEach(e=>this.container.getData(e).splice(t,0,null))),t}process(e){let t=this.fields.map(t=>{let i=e.getValue(t);return"Close"!==t.id?i:e.getValue(aA.Last)??i});if(!ey(t))return;let i=this.findOrAddIndex(e);this.fields.forEach((e,s)=>this.container.getData(e)[i]=t[s])}getCacheableEntities(e){e.add(this)}}class u8{query;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){this.query=e,this.fields=[aA.DateTime,aA.Close,aA.Symbol],this.container=null}get hasData(){return null!==this.container}refresh(){}loadMoreData(e){throw Error("Should not be called.")}shutdown(){}insertValues(e,t,i){let s=(t,i,s)=>e.getData(i).splice(t,0,s),r=e.getData(aA.DateTime),n=tx(t),a=u4(r,n);s(a,aA.DateTime,n),s(a,aA.Close,i),s(a,aA.Symbol,t)}parseHistoricalForward(e){let t=new ue(this.fields);return e.split("\n").filter(e=>e.trim().length>0).forEach(e=>{let i=e.split(","),s=i[0];this.insertValues(t,s,parseFloat(i[5]))}),t}makeUrl(){let e={};e.symbols=this.query.symbols.join(","),e.maxrecords=1,e.data="daily",e.end=ed(u_(this.query.offset),lz(tz.FMT_HIST_FEED_PARAM_DATE_ONLY))(new Date);let t=eX(e);return`/querylatesteod.ashx?${t}`}async retrieve(){let e=this.makeUrl(),t=await Af("timeseries",e);return this.parseHistoricalForward(t)}async ready(){return tU.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}}class u9 extends uQ{constructor(e){super(e)}getRetriever(){return new uE}onStreamingUpdates(e){}}class he{cacheSeries;seriesCache;constructor(e=!1){this.cacheSeries=e,this.seriesCache=new Map}getTimeSeries(e){return eF(e.symbol)&&e.symbol===tz.PLACEHOLDER_SYMBOL_NAME?new u0(e):this.getSeries(e)}evictUnused(e){for(let[t,i]of this.seriesCache)!e.has(i)&&i.isCached&&(i.isCached=!1,i.shutdown(),this.seriesCache.delete(t))}refresh(){for(let e of this.seriesCache.values())"function"==typeof e.refresh&&e.refresh()}getSeries(e){let t=(e.cacheMe||this.cacheSeries)&&!e?.alwaysUseBarsToFetch,i=e.getHashKey();if(t&&this.seriesCache.has(i))return this.seriesCache.get(i);{let s=this.makeSeries(e);return s.isCached=t,t&&this.seriesCache.set(i,s),s}}makeSeries(e){switch(e.seriesKind){case J.Normal:return new uQ(e);case J.BalanceSheet:case J.IncomeStatement:return new u3(e);case J.Events:return new u2(e);case J.Forward:return new u7(e);case J.HistoricalForward:return new u8(e);default:case J.Options:return new u9(e);case J.Study:throw Error(`The series kind '${J[e.seriesKind]}' is not supported yet.`)}}}var ht={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"}},hi={date:oj({formats:{full:"EEEE d MMMM y",long:"d MMMM y",medium:"d MMM y",short:"dd/MM/y"},defaultWidth:"full"}),time:oj({formats:{full:"HH:mm:ss zzzz",long:"HH:mm:ss z",medium:"HH:mm:ss",short:"HH:mm"},defaultWidth:"full"}),dateTime:oj({formats:{full:"{{date}} 'à' {{time}}",long:"{{date}} 'à' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},defaultWidth:"full"})},hs={lastWeek:"eeee 'dernier à' p",yesterday:"'hier à' p",today:"'aujourd’hui à' p",tomorrow:"'demain à' p'",nextWeek:"eeee 'prochain à' p",other:"P"},hr={code:"fr",formatDistance:function(e,t,i){var s,r=ht[e];if(s="string"==typeof r?r:1===t?r.one:r.other.replace("{{count}}",String(t)),null!=i&&i.addSuffix)if(i.comparison&&i.comparison>0)return"dans "+s;else return"il y a "+s;return s},formatLong:hi,formatRelative:function(e,t,i,s){return hs[e]},localize:{ordinalNumber:function(e,t){var i,s=Number(e),r=null==t?void 0:t.unit;return 0===s?"0":(i=1===s?r&&["year","week","hour","minute","second"].includes(r)?"ère":"er":"ème",s+i)},era:oX({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:oX({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:oX({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:oX({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:oX({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:oJ({matchPattern:/^(\d+)(ième|ère|ème|er|e)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e)}}),era:oZ({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:oZ({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:oZ({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:oZ({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:oZ({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}};function hn(e){return tt(1,arguments),ts(e).getDay()}function ha(e){tt(1,arguments);var t=ts(e);return t.setMinutes(0,0,0),t}function ho(e,t){tt(2,arguments);var i=ha(e),s=ha(t);return i.getTime()===s.getTime()}function hl(e){tt(1,arguments);var t=ts(e);return t.setSeconds(0,0),t}let hu=/{value:([^}]+)}/,hh=/%([aAdewbBmyYHkIlMpPSL])+/g;var hc=((D=hc||{})[D.Second=0]="Second",D[D.Minute=1]="Minute",D[D.Hour=2]="Hour",D[D.Day=3]="Day",D[D.Week=4]="Week",D[D.Month=5]="Month",D[D.Year=6]="Year",D);let hd={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]}},hp=new Map;function hf(e){if(!eF(e))return null;if(!hp.has(e)){var t;let i=eF(t=e)?t.replace(hu,(e,t)=>t.replace(hh,(e,t)=>tz.PHP_TO_UNICODE_TS_35_MAP[t])):t;hp.set(e,i)}return hp.get(e)}class hm{barWidth;unitWidth;minTickInterval;duration;format;prevDate;size;constructor({barWidth:e,unitWidth:t,formatString:i,minTickInterval:s,duration:r},n){this.size=n,this.barWidth=e,this.unitWidth=t,this.minTickInterval=s,this.duration=r,this.format=hf(i),this.prevDate=null}get noPrevDate(){return!eF(this.prevDate)}formatDate(e,t){return hO(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)}}let hg="yyyy",hy="LLL ''yy",hA=()=>"fr"===hI()?"d LLL":"LLL d",hS="HH:mm";class hT extends hm{repeatEach;repeatCounter;constructor(e){super(e),this.repeatEach=tz.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(!nT(this.prevDate,e))return this.asTick(e,1,"EEE");if(!ho(this.prevDate,e))return this.asTick(e,2,hS);this.repeatCounter++;let t=this.repeatCounter===this.repeatEach;return!function(e,t){tt(2,arguments);var i=hl(e),s=hl(t);return i.getTime()===s.getTime()}(this.prevDate,e)||t?this.asTick(e,t?4:3,hS):null}}class hv extends hm{getTick(e){let t=this.checkPrev(e),i=0===this.minTickInterval||0==(e=>{let t=tl(e);return uI(e,t)})(e)%(this.minTickInterval/1e3),s=!nT(this.prevDate,e),r=function(e){return tt(1,arguments),ts(e).getMinutes()}(e),n=!ho(this.prevDate,e)||t&&0===r;if(i){if(s)return this.asTick(e,1,hA());if(n)return this.asTick(e,2,hS);if(0==r%30&&this.size<15)return this.asTick(e,3,hS);if(0==r%15&&this.size<=5)return this.asTick(e,4,hS)}return null}}class hP extends hm{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<22*hd.Day.One,this.monthYear=this.duration>22*hd.Day.One&&this.duration<7*hd.Month.One,this.year=this.duration>7*hd.Month.One}useTuesday(e){return!!this.noPrevDate||2===hn(e)&&uM(e,this.prevDate)>1728e5}getTick(e){this.checkPrev(e);let t=!nv(e,this.prevDate),i=!n_(e,this.prevDate);return this.monthDay?1===hn(e)||this.useTuesday(e)?this.asTick(e,1,hA()):null:this.monthYear?t?this.asTick(e,1,hy):null:this.year&&i?this.asTick(e,1,hg):null}}class hC extends hm{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<4*hd.Week.One,this.monthYear=this.duration>4*hd.Week.One&&this.duration<6*hd.Month.One,this.year=this.duration>6*hd.Month.One}getTick(e){this.checkPrev(e);let t=!nv(e,this.prevDate),i=!n_(e,this.prevDate);return this.monthDay?this.asTick(e,1,hA()):this.monthYear?t?this.asTick(e,1,hy):null:this.year&&i?this.asTick(e,1,hg):null}}class hb extends hm{showMonths;constructor(e){super(e),this.showMonths=this.duration<7*hd.Month.One}getTick(e){this.checkPrev(e);let t=!n_(e,this.prevDate);return this.showMonths?this.asTick(e,1,hy):t?this.asTick(e,1,hg):null}}class hE extends hm{constructor(e){super(e)}getTick(e){return this.checkPrev(e),n_(e,this.prevDate)?null:this.asTick(e,1,hg)}}function hL(e){return((e.valueOf()-tz.OPTIONS_DATA_BASE)/tz.OPTIONS_DATA_INCREMENT).toString()}function h_(e){return eF(e)?`${e.toFixed(2)}%`:""}function hM(e,t,i=!1){let s=e.plots[0],r=s.curves[0],n=eF(r)&&r.fields.length>0?r.fields[0]:null;if(!eF(n))return"";let a={range:e.fullDomain,allDigits:!1,forceTrailingZeros:i};return hZ(s,e.pane.presenter,a),s.metaData.format(t,n,a)}function hx(e,t,i=!1){return e.comparison===q.Percent?h_(t):hM(e,t,i)}function hD(e,t,i){let s=e.view?.xAxis?.overrideFormatter;if(s)return s(t);if(eF(e.display.xAxis.isOrdinal))return hL(t);let r=i||e.display.xAxis.format;if(eF(r))return hO(t,hf(r));let n=e.data.aggregation,a=e.display?.xAxis?.nonEodLabelWithDate??!1;return n.isEndOfDay?hw(n,t):hR(n,t,a)}function hI(){let e=eG(AA().config,null,"overrides","xAxis","getLocaleName");if(eF(e)&&"function"==typeof e)try{return e()}catch(e){Ad(`Failed retrieving the locale name, error is ${e.message}`,"warn")}}function hO(e,t){return o5(e,t,"fr"===hI()?{locale:hr}:void 0)}function hw(e,t){if(!oE(t))return"";switch(e.unit){case G.Tick:case G.Intraday:case G.Day:case G.Week:default:return hO(t,"P");case G.Month:return hO(t,"LLL yyyy");case G.Quarter:return hO(t,"qqq yyyy");case G.Year:return hO(t,"yyyy")}}function hR(e,t,i){return oE(t)?hO(t,`${i?"P ":""} ${e.isTick?"pp":"p"}`):""}let hN=(e,t)=>e.at(t);class hV{presenter;_dates;pendingRebuild;constructor(e){this.presenter=e,this._dates=[],this.pendingRebuild=!1,this._dates=[],this.invalidate()}checkRebuild(){this.pendingRebuild&&this.rebuild()}get withPrologLength(){return this.checkRebuild(),this._dates.length+tz.TIMELINE_PROLOG_PADDING_BARS}get withPrologEpilogLength(){return this.withPrologLength+tz.TIMELINE_EPILOG_PADDING_BARS}get firstSeriesIndex(){return tz.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<tz.TIMELINE_PROLOG_PADDING_BARS){let t=eb(this._dates),i=e-tz.TIMELINE_PROLOG_PADDING_BARS;return this.applyDateShift(t,i)}if(e>=this.withPrologLength){let t=eC(this._dates),i=e-this.withPrologLength+1;return this.applyDateShift(t,i)}return this._dates[e-tz.TIMELINE_PROLOG_PADDING_BARS]}get length(){return this.checkRebuild(),this._dates.length>0?this.withPrologEpilogLength:0}slice(e,t){this.checkRebuild();let i=[];for(let s=e;s<t;++s)i.push(this.at(s));return i}tryToCorrectLastBar(e,t,i=!0){i&&this.checkRebuild();let s=+e,r=e_(this._dates,s,Number),n=+this._dates[r];return r===this._dates.length-1&&n===s&&(this._dates[r]=t,!0)}mergeDateIntoTimeline(e,t=!0){t&&this.checkRebuild();let i=+e,s=e_(this._dates,i,Number),r=+this._dates[s];if(r!==i){let t=s+ +(i>r);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;let e=this.presenter.mainPlot.timeSeries;if(!e.hasData)return;let t=e.container.getTimeData();for(let e=t.length-1;e>=0;e--)this._dates[e]=t[e];this.presenter.allPlots.forEach(t=>{t.timeSeries!==e&&t.timeSeries.hasData&&t.timeSeries.container.getTimeData().forEach(e=>this.mergeDateIntoTimeline(e,!1))}),this.pendingRebuild=!1}applyDateShift(e,t){let{unit:i,size:s}=this.presenter.data.aggregation;switch(i){case G.Year:return tr(e,12*t);case G.Quarter:return tr(e,3*t);case G.Month:return tr(e,t);case G.Week:return lU(e,7*t);case G.Day:return this.addTradingDays(e,t);case G.Intraday:return oL(e,s*t*tz.ONE_MINUTE_MILLIS);case G.Tick:return oL(e,1e3*t)}}addTradingDays(e,t){if(this.presenter.display?.xAxis?.isOrdinal)return lU(e,t);if(0===t){let t=e.getDay();return 0===t?lU(e,1):6===t?lU(e,2):e}let i=t>0?1:-1,s=Math.abs(t),r=e;for(;s>0;){let e=(r=lU(r,i)).getDay();0!==e&&6!==e&&s--}return r}}let hH={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 hF(e){return!0===AA().config.useAllFieldsForComparison&&e.mainPlot.mainCurve.isOhlc&&e.mainAxis.comparison===q.None&&e.mainPane.axes.map(e=>e.plots).flat().reduce((e,t)=>e+ +!!t.isSymbol,0)>1}let hB=new nN;function hk({plots:e,isMultiSymbol:t,isMultiContract:i,date:s,time:r,dateFieldName:n,hideSymbols:a,revealingClose:o}){let l=a&&o,u=[hG(n,s,null,"heading"),r?hG("Time",r,null,"heading"):""].concat(e.map(e=>{if(0===e.values.length)return null;let s=(e=>{let s=e.name.startsWith(tz.FAKE_SYMBOL_PREFIX);switch(e.type){case Z.Expression:return!0;case Z.Symbol:if((t||i)&&!s)return!0;return!a;default:return!1}})(e)?hz(Z[e.type],e.name,e.values[0].color):"",r=e.values.map(t=>hG(t.id===aA.Close.id&&l?e.description:t.longName,t.value,t.color));if(e.events&&e.events.length){let t=e.events.map(e=>hz(`${e.field.name} (${hw(hB,e.date)})`,e.value,e.color));r.push(...t)}return r.unshift(s),eF(e.unalignedDate)&&r.unshift(hG("Date",e.unalignedDate,e.values[0].color,"heading")),r}).filter(e=>null!=e).flat()).filter(e=>""!==e).join("");return`<table class="values-table">${u}</table>`}function hW(e){return`bchart-icon-${e}`}function hU(e,t=null,i=10){let s=eF(t)?`style="fill:${t}"`:"",r=hW(e);return`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="${i}px" height="${i}px" ${s}><use xlink:href="#${r}"></use></svg>`}function h$(e,t){let i=e?"Up":"Down",s=hU(`chevron${i}`);return`<span data-pane="${t}" data-dir="${i}" title="Move ${i}" class="move-pane">${s}</span>`}function hG(e,t,i=null,s=[]){"string"==typeof s&&(s=s.split(" "));let r=["value-row",...s],n="string"==typeof i?` style="color: ${i}"`:"";return`
8
8
  <tr class="${r.join(" ")}">
9
9
  <td class="field-name">${e}</td>
10
10
  <td${n} class="field-value">${t}</td>
@@ -17,5 +17,5 @@ Bars %csame %c${i(t.lastTimestamp)} == ${i(t.newTimestamp)}`,"color:#0f0","color
17
17
  </div>
18
18
  `.trim()})(t,a,f,r,l,u,h,e)),y=`${m}${g.join("")}`,A=function(e,t){let i=e>0,s=e<t-1;return`${i?h$(!0,e):""} ${s?h$(!1,e):""}`.trim()}(d,t.length);return{id:`bc-tip-${c.id.substring(0,8)}`,isMainPane:f,content:y,moveContent:A,bounds:c.bounds}})}(e,t,i,s,r,a,o,l);c.some(e=>!eF(e.bounds))||c.forEach(({id:t,isMainPane:i,content:s,moveContent:r,bounds:{left:a,right:o,top:l,width:c}},d)=>{if(""!==s&&(!n||!i)){let r=tH(t,h,"div");mq(r,i&&hF(e)?"column":"row",a,o,l+u,c),tF(r,{"bcharts-card":!0,"bcharts-card-main":i,"bcharts-card-first":0===d}),r.innerHTML=s}let p=tR(`#right-${t}`,h);eF(p)||((p=document.createElement("div")).id=`right-${t}`,h.appendChild(p),tF(p,"bcharts-card bcharts-card-move")),tN(p,{position:"absolute",display:"block",right:`${o+tz.CARDS_X_OFFSET}px`,top:`${l+u+tz.CARDS_Y_OFFSET}px`}),p.innerHTML=r})}let mZ=null;function mJ(){return null===mZ&&(mZ=AA().config.hostingModel===eo[eo.Application]),mZ}class mQ extends mp{ap;presenter;panY;snapToSupported;warmUp;preventDefault;lastOffset;lastPanningExtremes;constructor(e){super(),this.ap=e,this.snapToSupported=!1,this.warmUp=!0,this.preventDefault=!1,this.presenter=e.presenter,this.panY=e.axis.isCustomDomain}activated(){}deactivated(){this.cancelLongPress()}startPan(e){this.startLongPress(this.presenter,this.ap,e),this.lastOffset=e,this.lastPanningExtremes=this.ap.axis.yScale.domain();let 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();let{point:t,view:i,offset:s}=e;if(t&&t.axis!==this.ap.axis)return;let{x:r,y:n}=s,a=r-this.lastOffset.x,o=Math.abs(a),l=this.lastOffset.y,u=Math.abs(n-l);o>=1&&this.cancelLongPress();let h=mJ();if(eO()&&!h&&this.warmUp)return(o>7||u>7)&&(this.warmUp=!1,this.preventDefault=o>u),!1;if(this.preventDefault||!eO()||h){if(i.xAxis.pan(a),this.panY&&t&&t.axis){u>=1&&this.cancelLongPress();let e=function(e,t,i,s){let r=(i-t)/e.viewBox.height,[n,a]=s,o=r*(a-n);return[n+o,a+o]}(t.axis,l,n,this.lastPanningExtremes);this.lastPanningExtremes=e,t.axis.yScale.domain(e)}this.lastOffset=s,i.redraw(),t&&t.presenter.view.setCursor(ee.Grabbing)}return h||this.preventDefault}finished(){gQ(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:i}){eO()&&m6(e,t,i)}performLongPress(e,t,i){e.enableTooltip(!0),e.resetActiveTool(),e.activeTool.startTouchCrosshairMode(e,t,i)}}let m0=null;class m1 extends mO{constructor(e,t){super(e,t)}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return null!==t&&t.contains(e)}draw(e,t){return!!super.draw(e,t)&&(i$(e,this.getRect()),!0)}}function m2(e,t){return e<t?[e,t]:[t,e]}let m3={line:{width:1,color:"rgba(127, 127, 127, 0.3)",dashStyle:"LongDash"},fill:{color:"rgba(127, 127, 127, 0.1)"}};class m4 extends mH{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(mC("Rectangle",m1,null,m3),!1)}activated(){}deactivated(){eF(this.axis,this.annotation)&&this.axis.deleteAnnotation(this.annotation,!1)}onMouseDown(e){let t=super.onMouseDown(e);if(!0===t){let{point:t}=e;this.axis=t.axis,this.presenter=t.presenter}return t}finish(){if(eF(this.axis,this.presenter)){gQ(this.presenter,{toolChange:el.Executed,annId:"ZoomIn"});let e=this.annotation.points,t=m2(e[0].price,e[1].price),i=m2(e[0].time,e[1].time),s=(e,t)=>Math.abs(t(e[0])-t(e[1])),r=s(i,e=>this.axis.toX(e)),n=s(t,e=>this.axis.toY(e)),a=this.presenter.view,o=tz.MINIMUM_ZOOM_DIMENSION;if(r>o&&n>o){let e=a.xAxis.xScale;this.axis.isCustomDomain=!0,this.axis.yScale.domain(t),e.wasZoomed=!0,e.scaleBarToFitRange(i,!1),e.domain(i)}a.redraw()}}}function m5(e,t){let i=mv(e);i.offset={x:t.x,y:t.y},i.canFlip=null!==e.getFlipAnchorIndices();let s=e.axis.pane.presenter;s.clearSelection(),s.notifyHost(aS.CH_ANNNEEDSCONTEXTMENU,i)}function m6(e,t,i){let s={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:i};e.notifyHost(aS.CH_CHTNEEDSCONTEXTMENU,s)}class m7 extends mV{factory;maxClicks;clicks;snapToSupported;isDrawingAnnotation;constructor(e,t){super(e.annName),this.factory=e,this.maxClicks=t,this.clicks=0,this.snapToSupported=!0,this.isDrawingAnnotation=!0}onMouseMove(e){let{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){let{point:t,view:i}=e;if(0===this.clicks){if(void 0===t)return g2(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),g0(this.annotation,!0,el.Created)):this.annotation.requestRedraw()}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}}class m8{snapToSupported=!1;constructor(e,t){setTimeout(()=>this.finalize(e,t),10)}finalize(e,t){let i=e(t);t.pane.presenter.clearSelection(),i.drawn=!1,i.requestRedraw(),g0(i,!0,el.None)}}let m9=tz.MARKER_ARROW_ANGLE*Math.PI/180/2;function ge(e,t,i=tz.MARKER_ARROW_LENGTH){return new gt(e,t,i)}class gt{vertex;arrowLen;p1;p2;constructor(e,t,i=tz.MARKER_ARROW_LENGTH){this.vertex=t,this.arrowLen=i,this.p1=e[0],this.p2=e[1]}hitTest(e){let{anchor:t,p1:i,p2:s}=this.getArrowPoints();return iv([t,i],e,tz.HIT_TEST_TOLERANCE)||iv([t,s],e,tz.HIT_TEST_TOLERANCE)}draw(e){let{anchor:t,p1:i,p2:s}=this.getArrowPoints();iz(e,t,i),iz(e,t,s)}getArrowPoints(){let e=iT(this.p1,this.p2),t="start"===this.vertex?0:Math.PI,i=e-m9+t,s=e+m9+t,r="start"===this.vertex?this.p1:this.p2,n=this.arrowLen*Math.cos(i)+r.x,a=this.arrowLen*Math.sin(i)+r.y,o=this.arrowLen*Math.cos(s)+r.x,l=this.arrowLen*Math.sin(s)+r.y;return{anchor:r,p1:{x:n,y:a},p2:{x:o,y:l}}}}class gi{hitTest(){return!1}draw(){}}class gs extends mL{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[tz.AT_EXTEND_PT_1]}get extend2(){return this.traits[tz.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[tz.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[tz.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[tz.AT_RATIO]}getElements(){let e=this.points[0].point,t=this.points[1].point,i=new mb(e,t,this.extend1,this.extend2,this.axis),s=[];return this.extend1&&s.push(new mb(i.p1,e,!0,!1,this.axis)),s.push(new mb(e,t,!1,!1,this.axis)),this.extend2&&s.push(new mb(t,i.p2,!1,!0,this.axis)),s}formatRatio(e,t){return` (${eB(e/t,3)})`}formatPercDiff(e,t){let i=(t-e)/e*100,s=i>0?"+":"";return` (${s}${eB(i,2)}%)`}formatPrice(e){return hx(this.axis,this.priceMap(e))}adornElements(e,t){if(!this.showBarCount&&!this.showPrices&&!this.showPercentDiff&&!this.showRatio)return;let[i,s]=this.points,r=e[+!!this.extend1].getAdornOffset(t);if(this.showBarCount){let e=iS(ig(i.point,s.point),r);iU(t,this.getBarCount(i.time,s.time).toFixed(0),e,Q.Right)}let n=this.showRatio?this.formatRatio(i.price,s.price):"",a=this.showPrices?this.formatPrice(i.price):"",o=`${a}${n}`.trim();""!==o&&iU(t,o,iS(i.point,r),Q.Right);let l=this.showPercentDiff?this.formatPercDiff(i.price,s.price):"",u=this.showPrices?this.formatPrice(s.price):"",h=`${u}${l}`.trim();""!==h&&iU(t,h,iS(s.point,r),Q.Right)}getMarkers(){let e=this.marker;if(!e||"none"===e.vertex)return[];let{vertex:t,kind:i}=e;return("both"===t?["start","end"]:[t]).map(e=>{if("arrow"===i){var t;return t=this.points,ge(t.map(e=>e.point),e)}return console.warn(`There is no marker of ${i} kind`),new gi})}}class gr extends mL{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[tz.AT_SHOW_TIMESTAMPS]}getElements(){return[new my(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}}class gn extends mL{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new my(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}}class ga extends mL{constructor(e,t,i){super(e,t),this.addPoints(2),eF(i)&&eF(i.points)&&i.points.forEach((e,t)=>this.points[t].update(e.price,e.time))}allPoints(){let[e,t]=this.points;return eF(e,e.point,t,t.point)?[e,this.axis.toAnnotationPoint(ig(e.point,t.point)),t]:tz.EMPTY_ARRAY}line2(){return this.traits[tz.AT_LINE_2]}use52WeekPrices(){return this.traits[tz.AT_USE_52WEEK_PRICES]}getElements(){let e=this.allPoints();return e===tz.EMPTY_ARRAY?tz.EMPTY_ARRAY:e.map(e=>new mb({x:-tz.OUT_OF_SCREEN,y:e.point.y},{x:tz.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){eF(this.use52WeekPrices())&&(this.traits[tz.AT_USE_52WEEK_PRICES]=!1)}getStyleForElement(e,t){let i=this.line2();if(1!==t||!eF(i))return super.getStyleForElement(e,t);let s=ez(this.traits);return s.line=i,i8(s)}getPriceScaleAdornments(){let e=this.allPoints();if(!this.showPrices||e===tz.EMPTY_ARRAY)return super.getPriceScaleAdornments();let t=this.traits.line,i=e.map(e=>({price:e.price,color:t.color})),s=this.line2();return eF(s)&&(i[1].color=s.color),i}getFlipAnchorIndices(){return null}}class go extends m_{helper;constructor(e,t,i){super(e,t),this.addPoints(i),this.helper=new mA(e)}get showTrendLine(){return this.traits[tz.AT_SHOW_TRENDLINE]}get hasAllPoints(){return eF(...this.points.map(e=>e.point))}get line2(){return this.traits[tz.AT_LINE_2]}get extendLeft(){return this.traits[tz.AT_EXTEND_LEFT]}get extendRight(){return this.traits[tz.AT_EXTEND_RIGHT]}get reverse(){return this.traits[tz.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[tz.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){let e=ez(this.traits);return e.line=this.line2,i8(e)}return super.getStyleForElement(e,t)}getKeyPoints(){let e=e=>e.map(e=>this.points[e]);return e(this.isExtended?this.reverse?[1,0,2]:[0,1,2]:this.reverse?[0,1,0]:[1,0,1])}getElements(){if(!this.hasAllPoints)return[];let[e,t,i]=this.getKeyPoints(),s=t.price-e.price,r=t.price/e.price,n=this.extendLeft,a=this.extendRight,o=this.leftPoint,l=this.rightPoint,u=(e,t,i=!1)=>{let s=new mb(e,t,!i&&n,!i&&a,this.axis);return s.isTrend=i,s},h=this.levelsRespectLogScale&&this.axis.scale===X.Logarithmic,c=({value:e})=>{let t=i.price+s*e,n=i.price*Math.pow(r,e);this.helper.update(h?n:t,i.time);let a=this.helper.point.y;return u({x:o.x,y:a},{x:l.x,y:a})},d=this.getColoredElements(c);return this.showTrendLine&&(d.push(u(e.point,t.point,!0)),this.isExtended&&d.push(u((this.reverse?e:t).point,i.point,!0))),d}getAdornPointAndAlign(e,t){let i=this.labels,s=(e,t,i)=>({pt:e,align:t,offset:i}),r=this.axis.pane.getBoundsWithoutScales();switch(i){case tz.AT_LABELS_LEFT:return this.extendLeft?s({x:r.x,y:e.anchor1.y},Q.Left,t):super.getAdornPointAndAlign(e,t);default:case tz.AT_LABELS_RIGHT:return this.extendRight?s({x:r.x+r.width,y:e.anchor2.y},Q.Right,-t):super.getAdornPointAndAlign(e,t);case tz.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,i)=>{let s=this.formatLevelPrice(i,t.anchor1.y);return{ref:t,spacing:5,offsetY:-5,text:s}}}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{let i=new Path2D;return null===e||(iN(i,e.p1),i.lineTo(t.p2.x,e.p1.y),iV(i,t.p2),i.lineTo(e.p1.x,t.p2.y)),i},this.getTextRef(),t)}getPriceScaleAdornments(){if(!this.pricesOnScale)return super.getPriceScaleAdornments();let e=this.getElements();if(0===e.length)return super.getPriceScaleAdornments();let t=this.traits.line.color;return this.factors.map((i,s)=>{let r=e[s++].p1,n=this.singleStyle?t:i.line.color;return{price:this.axis.toPrice(r.y),color:n}})}}class gl extends go{constructor(e,t){super(e,t,2)}}class gu extends go{constructor(e,t){super(e,t,3)}}let gh=(e,t)=>{let i=new Path2D;return null===e||(iN(i,e.p1),iV(i,e.p2),iV(i,t.p2)),i};class gc extends m_{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[tz.AT_REVERSE]}getElements(){let[e,t]=this.getScreenPoints(),i=t.y-e.y,s=({value:s})=>{let r=this.reverse?e.y+s*i:t.y-s*i;return new mb(e,{x:t.x,y:r},!1,!0,this.axis)};return this.getColoredElements(s)}getTextRef(){let[e,t]=this.getScreenPoints(),i=t.y-e.y,[s,r]=[this.leftPoint,this.rightPoint];return(n,a,o)=>{let l=this.reverse?e.y+o*i:t.y-o*i;return{ref:new mb({x:s.x,y:l},{x:r.x,y:l},!1,!1,this.axis),spacing:5,offsetY:!0,text:o.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,gh,this.getTextRef(),t)}}class gd extends gc{constructor(e,t){super(e,t)}}class gp{center;rim;radius;startAngle;endAngle;antiClockwise;axis;left;right;scale;clip;style;constructor(e,t,i,s,r,n,a){this.center=e,this.rim=t,this.radius=i,this.startAngle=s,this.endAngle=r,this.antiClockwise=n,this.axis=a,this.left=null,this.right=null,this.scale=null,this.clip=null,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})}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){let t=new DOMPointReadOnly(e.x,e.y),i=this.axis.pane.presenter.view.mouseContext;i.save(),i.resetTransform(),this.applyScale(i);let 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(iy(this.left,e),iy(this.right,e));else{let{x:i,y:s}=iA(this.hasScale?this.inverseScale(e):e,this.center);if(!this.hasRim){let{startAngle:e,endAngle:t,antiClockwise:r}=this,n=Math.PI/2;if(0===e&&t===n&&!r&&(i<0||s<0)||e===n&&t===Math.PI&&!r&&(i>0||s<0)||e===-n&&t===Math.PI&&r&&(i>0||s>0)||0===e&&t===-n&&r&&(i<0||s>0))return!1}t=Math.abs(Math.sqrt(i*i+s*s)-this.radius)}return t<=tz.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),iG(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}}let gf=(e,t)=>{let i=new Path2D,{center:s}=t;if(iN(i,s),i.arc(s.x,s.y,t.radius,t.startAngle,t.endAngle,t.isAntiClockwise??!1),null===e)return i;let r=new Path2D,{center:n}=e;return iN(r,n),r.arc(n.x,n.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),i.addPath(r),i};class gm extends m_{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){let[e,t]=this.getScreenPoints();if(!eF(e,t))return[];let i=iy(e,t),s=iA(t,e),r=s.y/i,n=s.x/i,a=({value:t})=>{let s=i*t,a={x:e.x+n*s,y:e.y+r*s};var o=this.axis;let l=iy(e,a);return new gp(e,a,l,0,Math.PI,null,o)},o=this.getColoredElements(a);if(this.showTrendLine){let i=new mb(e,t,!1,!1,this.axis);i.isTrend=!0,o.unshift(i)}return o}get showTrendLine(){return!0}getTextRef(){return(e,t,i)=>{let{center:s}=t,r=t.isAntiClockwise?-1:1;return{ref:{x:s.x,y:s.y+r*t.radius},spacing:0,offsetY:!0,text:i.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,gf,this.getTextRef(),t)}}class gg extends gm{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=ez(this.traits);return e.line=this.line2,i8(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[tz.AT_SHOW_TRENDLINE]}get line2(){return this.traits[tz.AT_LINE_2]}}class gy extends m_{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return tz.AT_ANGLES}getElements(){let[e,t]=this.getScreenPoints(),{x:i,y:s}=iA(t,e),r=({value:r})=>{let n=(t,i)=>new mb(e,{x:t,y:i},!1,!0,this.axis),a="1"!==r.charAt(0),o=Number(a?r.charAt(0):r.charAt(2));return a?n(t.x,e.y+s/o):n(e.x+i/o,t.y)};return this.getColoredElements(r)}getTextRef(){return(e,t,i)=>({ref:t.anchor2,spacing:0,offsetY:!0,text:i.toString()})}adornElements(e,t){this.adornElementsForColoredFactors(e,gh,this.getTextRef(),t)}}class gA extends gc{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}getElements(){let[e,t]=this.getScreenPoints();return[new mb(e,t,!1,!1,this.axis)].concat(super.getElements())}}class gS extends gm{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}}class gT extends mL{constructor(e,t){super(e,t),this.addPoints(3)}getElements(){let e=this.points[0].point,t=this.points[1].point,i=this.points[2].point,s=(t.x+i.x)/2-e.x,r=(t.y+i.y)/2-e.y,n=[];return n.push(new mb(t,{x:t.x+s,y:t.y+r},!1,!0,this.axis)),n.push(new mb(e,{x:e.x+s,y:e.y+r},!1,!0,this.axis)),n.push(new mb(i,{x:i.x+s,y:i.y+r},!1,!0,this.axis)),n.push(new mb(t,i,!1,!1,this.axis)),n}}class gv extends mO{constructor(e,t){super(e,t)}getEllipse(){let e=this.getRect();return null===e?null:new iR(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.visible)return!1;let t=this.getEllipse();return null!==t&&t.contains(e)}draw(e,t){var i;return!!super.draw(e,t)&&(i=this.getEllipse(),e.beginPath(),e.ellipse(i.cx,i.cy,i.radiusX,i.radiusY,0,0,2*Math.PI),e.stroke(),e.fill(),!0)}}class gP extends mL{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[tz.AT_EXTEND_PT_1]}get extend2(){return this.traits[tz.AT_EXTEND_PT_2]}getLastPoint(){let[e,t,i]=this.points;var s=iy(e.point,t.point),r=iT(e.point,t.point);return{x:i.point.x+s*Math.cos(r),y:i.point.y+s*Math.sin(r)}}getElements(){let[e,t,i]=this.points;var s=[];if(s.push(new mb(e.point,t.point,this.extend1,this.extend2,this.axis)),eF(i?.price)){var r=this.getLastPoint();s.push(new mb(i.point,r,this.extend1,this.extend2,this.axis))}return s}}class gC extends mO{kind;constructor(e,t,i){super(e,t),this.kind=i,this.adjustFill=!0}hitTest(e){if(!this.visible)return!1;let t=this.getRect();return null!==t&&t.contains(e)}get dimension(){let e="fish_hook"===this.kind?2:1;return tz.DEFAULT_SYMBOL_WIDTH_HEIGHT*e}updateOtherPoints(){this.points[1].price||this.setBottomRight()}setBottomRight(){let e=this.dimension,t=this.axis.pane.presenter.timeline,{price:i,time:s}=this.points[0],r=e_(t,s,Number,hN);if(-1!==r){let s=this.axis.pane.presenter.view.xAxis.xScale.bar.totalWidth,n=1;for(;(2*n+1)*s<e;)n++;this.points[0].update(i,t.at(r-n)),this.points[1].update(i,t.at(r+n));let a=iS(this.points[0].point,{x:0,y:-e/2}),o=iS(this.points[1].point,{x:0,y:e/2});this.points[0].updateFromPoint(a),this.points[1].updateFromPoint(o)}}draw(e,t){if(!super.draw(e,t))return!1;let i=this.getRect();switch(0===i.width&&(i.width=this.dimension),this.kind){case"zero":iK(e,i,"0");break;case"one":iK(e,i,"1");break;case"two":iK(e,i,"2");break;case"three":iK(e,i,"3");break;case"four":iK(e,i,"4");break;case"five":iK(e,i,"5");break;case"six":iK(e,i,"6");break;case"seven":iK(e,i,"7");break;case"eight":iK(e,i,"8");break;case"nine":iK(e,i,"9");break;case"question":iK(e,i,"?");break;case"fish_hook":var s=e,r=i;s.save(),s.translate(r.x,r.y);let n=Math.min(r.width,r.height)/560;s.scale(n,n),s.lineCap="butt",s.lineJoin="miter",s.miterLimit=4,s.save(),s.save(),s.miterLimit=10,s.beginPath(),s.moveTo(377.8,354.8),s.bezierCurveTo(377.8,354.8,401.8,517.8,290.6,507),s.bezierCurveTo(173.2,495.5,171.5,50.39,171.5,50.39),s.bezierCurveTo(171.5,50.39,191.7,252.59,212.3,351),s.bezierCurveTo(212.3,351,230.9,472.8,286.7,488.7),s.bezierCurveTo(350.4,507,369.5,452.7,377.8,354.79),s.closePath(),s.fill(),s.restore(),s.save(),s.miterLimit=10,s.beginPath(),s.moveTo(378.3,351.1),s.lineTo(341.1,446.6),s.lineTo(371.2,436.7),s.lineTo(378.3,351.1),s.closePath(),s.fill(),s.restore(),s.restore(),s.restore();break;case"arrow_up":var a=e,o=i;a.save();let{cx:l,cy:u,left:h,right:c,top:d,bottom:p,halfBaseSize:f}=iq(o);a.beginPath(),a.moveTo(c,u),a.lineTo(l,d),a.lineTo(h,u),a.lineTo(Math.floor(l-f),u),a.lineTo(Math.floor(l-f),p),a.lineTo(Math.floor(l+f),p),a.lineTo(Math.floor(l+f),u),a.closePath(),a.fill(),a.restore();break;case"arrow_down":var m=e,g=i;m.save();let{cx:y,cy:A,left:S,right:T,top:v,bottom:P,halfBaseSize:C}=iq(g);m.beginPath(),m.moveTo(T,A),m.lineTo(y,P),m.lineTo(S,A),m.lineTo(Math.floor(y-C),A),m.lineTo(Math.floor(y-C),v),m.lineTo(Math.floor(y+C),v),m.lineTo(Math.floor(y+C),A),m.closePath(),m.fill(),m.restore();break;case"arrow_right":var b=e,E=i;b.save();let{cx:L,cy:_,left:M,right:x,top:D,bottom:I,halfBaseSize:O}=iq(E);b.beginPath(),b.moveTo(L,D),b.lineTo(x,_),b.lineTo(L,I),b.lineTo(L,Math.floor(_+O)),b.lineTo(M,Math.floor(_+O)),b.lineTo(M,Math.floor(_-O)),b.lineTo(L,Math.floor(_-O)),b.closePath(),b.fill(),b.restore();break;case"arrow_left":var w=e,R=i;w.save();let{cx:N,cy:V,left:H,right:F,top:B,bottom:k,halfBaseSize:W}=iq(R);w.beginPath(),w.moveTo(N,B),w.lineTo(H,V),w.lineTo(N,k),w.lineTo(N,Math.floor(V+W)),w.lineTo(F,Math.floor(V+W)),w.lineTo(F,Math.floor(V-W)),w.lineTo(N,Math.floor(V-W)),w.closePath(),w.fill(),w.restore();break;case"arrow_horizontal":var U=e,$=i;U.save();let{cx:G,cy:z,left:Y,right:j,top:K,bottom:q,halfBaseSize:X}=iq($,1.5),Z=Math.floor(G-(G-Y)/3),J=Math.floor(G+(G-Y)/3);U.beginPath(),U.moveTo(Z,K),U.lineTo(Y,z),U.lineTo(Z,q),U.lineTo(Z,Math.floor(z+X)),U.lineTo(J,Math.floor(z+X)),U.lineTo(J,q),U.lineTo(j,z),U.lineTo(J,K),U.lineTo(J,Math.floor(z-X)),U.lineTo(Z,Math.floor(z-X)),U.lineTo(Z,K),U.closePath(),U.fill(),U.restore();break;case"arrow_vertical":var Q=e,ee=i;Q.save();let{cx:et,cy:ei,left:es,right:er,top:en,bottom:ea,halfBaseSize:eo}=iq(ee,2/3),el=Math.floor(ei-(ei-en)/3),eu=Math.floor(ei+(ei-en)/3);Q.beginPath(),Q.moveTo(er,el),Q.lineTo(et,en),Q.lineTo(es,el),Q.lineTo(Math.floor(et-eo),el),Q.lineTo(Math.floor(et-eo),eu),Q.lineTo(es,eu),Q.lineTo(et,ea),Q.lineTo(er,eu),Q.lineTo(Math.floor(et+eo),eu),Q.lineTo(Math.floor(et+eo),el),Q.lineTo(er,el),Q.closePath(),Q.fill(),Q.restore();break;case"arc_down":!function(e,t){let{cx:i,cy:s,left:r,right:n,deflection:a,arcWidth:o}=iX(t);e.save(),e.beginPath(),e.moveTo(n,s);let l=i+a,u=s+a,h=i-a,c=s+a;e.bezierCurveTo(l,u,h,c,r,s),e.lineTo(r,s+o),e.bezierCurveTo(h,c+o,l,u+o,n,s+o),e.closePath(),e.fill(),e.restore()}(e,i);break;case"arc_up":!function(e,t){let{cx:i,cy:s,left:r,right:n,deflection:a,arcWidth:o}=iX(t);e.save(),e.beginPath(),e.moveTo(n,s);let l=i+a,u=s-a,h=i-a,c=s-a;e.bezierCurveTo(l,u,h,c,r,s),e.lineTo(r,s-o),e.bezierCurveTo(h,c-o,l,u-o,n,s-o),e.closePath(),e.fill(),e.restore()}(e,i);break;case"thumbs_up":var eh=e,ec=i;eh.save(),eh.translate(ec.x,ec.y),eh.lineWidth=.05;let ed=Math.min(ec.width,ec.height)/18;eh.scale(ed,ed),eh.lineCap="butt",eh.save(),eh.save(),eh.beginPath(),eh.moveTo(3.23,8.96),eh.lineTo(4.17,8.96),eh.bezierCurveTo(4.73,8.81,5.91,6.45,6.45,5.82),eh.bezierCurveTo(6.88,5.33,7.66,5.09,8.48,3.7),eh.bezierCurveTo(9.11,2.78,8.38,1.49,10.06,1.17),eh.bezierCurveTo(10.9,1.01,11.86,2.61,11.58,4.11),eh.bezierCurveTo(11.49,4.6,11.25,5.14,11.07,5.54),eh.bezierCurveTo(10.63,6.5,10.05,6.58,10.17,7.23),eh.bezierCurveTo(10.98,7.25,11.79,7.32,12.67,7.27),eh.bezierCurveTo(14.33,7.17,15.55,9.08,14.43,10.38),eh.bezierCurveTo(14.9,11.12,14.79,12.33,14.14,12.81),eh.bezierCurveTo(14.42,13.58,14.25,14.45,13.67,14.8),eh.bezierCurveTo(14.13,16.77,12.36,16.87,11.77,16.84),eh.lineTo(4.65,16.84),eh.bezierCurveTo(3.87,16.77,3.95,16.28,3.5,16.27),eh.bezierCurveTo(3.39,16.26,3.3,16.26,3.3,16.26),eh.bezierCurveTo(3.18,16.26,3.19,15.7,3.28,15.7),eh.bezierCurveTo(3.36,15.69,3.61,15.68,3.87,15.71),eh.bezierCurveTo(4.03,15.79,4.4,16.26,4.75,16.27),eh.lineTo(12.12,16.26),eh.bezierCurveTo(13.13,16.27,13.67,15.11,12.8,14.56),eh.bezierCurveTo(13.85,14.53,13.98,12.98,13.19,12.6),eh.bezierCurveTo(14.35,12.49,14.5,10.65,13.44,10.41),eh.bezierCurveTo(14.8,9.97,14.39,7.59,12.35,7.83),eh.bezierCurveTo(11.42,7.77,9.87,7.94,9.68,7.62),eh.bezierCurveTo(9.41,6.82,9.684,6.45,10.17,5.88),eh.bezierCurveTo(10.5,5.46,11.02,4.6,11.04,3.64),eh.bezierCurveTo(11.05,2.5,10.41,1.23,9.58,1.98),eh.bezierCurveTo(9.38,2.21,9.36,3.47,8.94,4.02),eh.bezierCurveTo(8.09,5.52,7.3,5.66,6.95,6.15),eh.bezierCurveTo(6.27,6.86,4.93,9.52,4.36,9.52),eh.bezierCurveTo(3.98,9.52,3.243,9.52,3.24,9.52),eh.bezierCurveTo(3.12,9.52,3.08,8.98,3.22,8.95),eh.closePath(),eh.fill(),eh.restore(),eh.restore(),eh.restore();break;case"thumbs_down":var ep=e,ef=i;ep.save(),ep.translate(ef.x,ef.y),ep.lineWidth=.05;let em=Math.min(ef.width,ef.height)/18;ep.scale(em,em),ep.lineCap="butt",ep.save(),ep.save(),ep.beginPath(),ep.moveTo(14.77,9.04),ep.lineTo(13.82,9.04),ep.bezierCurveTo(13.27,9.18,12.09,11.55,11.54,12.17),ep.bezierCurveTo(11.12,12.66,10.34,12.9,9.52,14.29),ep.bezierCurveTo(8.88,15.21,9.62,16.51,7.93,16.82),ep.bezierCurveTo(7.1,16.98,6.13,15.39,6.42,13.88),ep.bezierCurveTo(6.51,13.4,6.75,12.855,6.93,12.46),ep.bezierCurveTo(7.37,11.49,7.95,11.41,7.82,10.76),ep.bezierCurveTo(7.02,10.75,6.21,10.68,5.33,10.73),ep.bezierCurveTo(3.66,10.83,2.44,8.91,3.57,7.62),ep.bezierCurveTo(3.09,6.88,3.2,5.67,3.85,5.19),ep.bezierCurveTo(3.57,4.42,3.74,3.55,4.33,3.2),ep.bezierCurveTo(3.87,1.22,5.64,1.13,6.22,1.16),ep.lineTo(13.35,1.16),ep.bezierCurveTo(14.12,1.22,14.04,1.71,14.49,1.73),ep.bezierCurveTo(14.6,1.73,14.7,1.73,14.7,1.73),ep.bezierCurveTo(14.82,1.74,14.8,2.29,14.72,2.3),ep.bezierCurveTo(14.63,2.31,14.39,2.32,14.12,2.28),ep.bezierCurveTo(13.96,2.21,13.6,1.74,13.25,1.73),ep.lineTo(5.88,1.73),ep.bezierCurveTo(4.86,1.73,4.33,2.88,5.19,3.44),ep.bezierCurveTo(4.14,3.47,4.01,5.02,4.8,5.39),ep.bezierCurveTo(3.64,5.5,3.49,7.35,4.55,7.58),ep.bezierCurveTo(3.19,8.02,3.6,10.4,5.64,10.16),ep.bezierCurveTo(6.57,10.23,8.12,10.05,8.32,10.37),ep.bezierCurveTo(8.58,11.17,8.32,11.54,7.82,12.11),ep.bezierCurveTo(7.49,12.54,6.97,13.39,6.96,14.36),ep.bezierCurveTo(6.94,15.49,7.59,16.76,8.41,16.01),ep.bezierCurveTo(8.62,15.78,8.63,14.52,9.05,13.97),ep.bezierCurveTo(9.9,12.47,10.69,12.33,11.04,11.84),ep.bezierCurveTo(11.72,11.13,13.06,8.47,13.637,8.47),ep.bezierCurveTo(14.01,8.47,14.75,8.47,14.75,8.47),ep.bezierCurveTo(14.87,8.47,14.91,9.01,14.77,9.04),ep.closePath(),ep.fill(),ep.restore(),ep.restore(),ep.restore();break;case"buy":iK(e,i,"B");break;case"sell":iK(e,i,"S")}return!0}}class gb extends m_{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new mA(e)}getElements(){let e=this.axis.pane.presenter.timeline,{price:t,time:i}=this.points[0],s=e_(e,i,Number,hN),r=e_(e,this.points[1].time,Number,hN),n=r-s;if(-1===s||-1===r)return[];let a=({value:i})=>{let r=e.at(s+i*n);return null===r?null:(this.helper.update(t,r),new my(this.helper.point,!0,this.axis))};return this.getColoredElements(a)}getTextRef(){return(e,t,i)=>({ref:t.anchor,spacing:3,offsetY:!0,text:i.toString()})}adornElements(e,t){let i=this.axis.pane.getBoundsWithoutScales();this.adornElementsForColoredFactors(e,(e,t)=>{let s=new Path2D;if(null===e)return s;let r=t.anchor.x-e.anchor.x;return s.rect(e.anchor.x,i.y,r,i.height),s},this.getTextRef(),t)}getTimeScaleAdornments(){let e=e=>({time:this.points[e].time,color:this.traits.line.color});return[e(0),e(1)]}}class gE{snapToSupported=!0;isDrawingAnnotation=!0;constructor(){}onMouseMove(e){let{point:t,view:i,offset:s}=e;i.drawCrosshair({ap:t,offset:s})}onMouseDown(e){if(eO()&&e.originalEvent instanceof TouchEvent)return;let{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(aS.CH_ANNPOINTPICKED,s),gQ(i,void 0)}}let gL="Closed";class g_ extends mL{isLong;twoDecMeta;_dataWindow;_metaData;isHit;constructor(e,t,i){super(e,t),this.isLong=i,this.isHit=!1,this.addPoints(4);let s=(e,t)=>this.points[e].moveDirection=t;s(1,es.Vertical),s(2,es.Vertical),s(3,es.Horizontal),this.twoDecMeta=new ii(2)}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}getDataWindow(e,t,i=!0,s=!0){let r=this.data(aA.DateTime),n=e_(r,+e,Number),a=e_(r,+t,Number),o={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[l,u,h]=[aA.High,aA.Low,aA.Close].map(e=>this.data(e)),c=e=>e-n;for(let e=n;e<=a;e++)i&&-1===o.refIndex&&eF(this.entryPrice)&&this.entryPrice>=u[e]&&this.entryPrice<=l[e]&&(o.refIndex=c(e)),(!i||o.refIndex>=0&&c(e)>=o.refIndex)&&((!eF(o.highest)||l[e]>o.highest)&&(o.highest=l[e]),(!eF(o.lowest)||u[e]<o.lowest)&&(o.lowest=u[e])),i&&-1!==o.refIndex&&(-1===o.highestIndex&&l[e]>this.upperPrice&&(o.highestIndex=c(e)),-1===o.lowestIndex&&u[e]<this.lowerPrice&&(o.lowestIndex=c(e))),s&&o.data.push({high:l[e],low:u[e],close:h[e],time:r[e]});if(s&&o.data&&o.data.length>0){o.state=eF(o.highest,o.lowest)&&(this.upperPrice<o.highest||this.lowerPrice>o.lowest)?gL:"Open",o.special=-1===o.highestIndex&&-1===o.lowestIndex||o.highestIndex===o.lowestIndex;let e=eC(o.data);if(o.toPrice=e.close,o.toTime=e.time,o.state===gL)if(o.special){if(-1!==o.refIndex){let e=o.data[o.refIndex];o.toTime=e.time;let t=this.isLong?this.lowerPrice<o.lowest:this.upperPrice<o.highest;o.toPrice=t?this.upperPrice:this.lowerPrice}}else{let e=-1!==o.highestIndex&&-1!==o.lowestIndex;e&&o.highestIndex<o.lowestIndex||-1===o.lowestIndex?(o.toPrice=this.upperPrice,o.toTime=o.data[o.highestIndex].time):(e&&o.lowestIndex<o.highestIndex||-1===o.highestIndex)&&(o.toPrice=this.lowerPrice,o.toTime=o.data[o.lowestIndex].time)}let t=this.isLong?o.toPrice-this.entryPrice:this.entryPrice-o.toPrice;o.pAndL=eB(t,2)}return o}get dataWindow(){return eF(this._dataWindow)||(this._dataWindow=this.getDataWindow(this.entryAnchor.time,this.exitAnchor.time)),this._dataWindow}getVisiblePriceRange(){let e=this.axis.yScale.domain();return e[1]-e[0]}getFutureTimestamp(){let e=this.axis.pane.presenter.timeline,t=e_(e,+this.points[0].time,Number,hN),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[tz.AT_ACCOUNT_SIZE]}get risk(){let e=this.traits[tz.AT_RISK_IS_PERCENT],t=this.traits[tz.AT_RISK];return eB(e?t/100*this.accountSize:t,2)}get pointValue(){return this._metaData||(this._metaData=this.presenter.mainPlot.metaData),this._metaData.pointValue}formatDollarValue(e){return Number.isFinite(e)?`${e<0?"-":""}$${this.twoDecMeta.format(Math.abs(e))}`:tz.NOT_APPLICABLE}get qty(){return Math.floor(this.risk/(this.isLong?this.entryPrice-this.lowerPrice:this.upperPrice-this.entryPrice))}get upperDiff(){return eB(this.upperPrice-this.entryPrice,2)}get amountMultiplier(){return this.isLong?1:-1}get upperAmount(){return eB(this.accountSize+this.amountMultiplier*this.qty*this.upperDiff,2)}get upperPandL(){return eB(this.amountMultiplier*this.upperDiff*this.pointValue,2)}get isCompact(){return this.traits[tz.AT_COMPACT]}get upper(){let e=hx(this.axis,this.priceMap(this.upperPrice)),t=`(${eB(this.upperDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get upperText(){let 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 eB(this.entryPrice-this.lowerPrice,2)}get lowerAmount(){return eB(this.accountSize-this.amountMultiplier*this.qty*this.lowerDiff,2)}get lowerPandL(){return eB(-this.amountMultiplier*this.lowerDiff*this.pointValue,2)}get lower(){let e=hx(this.axis,this.priceMap(this.lowerPrice)),t=`(${eB(this.lowerDiff/this.entryPrice*100,2).toFixed(2)}%)`;return this.isCompact,`${e} ${t}`}get lowerText(){let 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 eB(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(){let 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(tz.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(tz.AT_FILL)}get textStyle(){return this.fillOnlyStyle(tz.AT_FILL_TEXT)}get secondaryLineStyle(){return i8({line:{color:this.traits.line.color,dashStyle:"ShortDash"},fill:{color:tz.COLOR_TRANSPARENT}})}wasModifiedByTool(){eF(this.points[2].price)||this.positionPoints(),this._dataWindow=void 0}wasPointMovedByTool(e,t){let i=this.getVisiblePriceRange()/5e3;if(3>this.points.indexOf(e)){let t=t=>e.update(t,e.time);this.entryAnchor.price>this.upperAnchor.price&&t(e===this.entryAnchor?this.upperAnchor.price-i:this.entryAnchor.price+i),this.entryAnchor.price<this.lowerAnchor.price&&t(e===this.entryAnchor?this.lowerAnchor.price+i:this.entryAnchor.price-i)}if(e===this.entryAnchor){let 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(){let e=this.dataWindow;return this.isLong?e.pAndL>0:e.pAndL<=0}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){let e=new mb(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}),r=new mE(s(this.upperAnchor.point,t?-i:0),i,Math.abs(this.upperAnchor.point.y-this.entryAnchor.point.y),this.axis);r.style=this.upperStyle;let n=new mE(s(this.entryAnchor.point,t?-i:0),i,Math.abs(this.entryAnchor.point.y-this.lowerAnchor.point.y),this.axis);n.style=this.lowerStyle;let a=[e,r,n],o=this.dataWindow;if(-1!==o.refIndex){let e=o.data[o.refIndex],t=new mA(this.axis,this.entryPrice,e.time),i=new mA(this.axis,o.toPrice,o.toTime),s=new mb(t.point,i.point,!1,!1,this.axis);if(s.style=this.secondaryLineStyle,a.push(s),t.time!==i.time){let e=this.entryPrice<o.toPrice,s=new mE({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,a.push(s)}}return a}hitTest(e){if(!this.visible)return!1;let 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(){let e=e=>iC(this.traits[e].color);return[{price:this.upperPrice,color:e(tz.AT_FILL)},{price:this.entryPrice,color:e(tz.AT_LINE)},{price:this.lowerPrice,color:e(tz.AT_FILL2)}]}adornElements(e,t){let[i,s,r]=e;if(this.showTextAdornments){let[e,n]=[!0,!1].map(e=>iB(t,e)),{x:a,y:o,width:l}=s.rect,u=this.textStyle.fillStyle;iU(t,this.upperText,{x:a+l/2,y:o+e},Q.Center,u,iC(this.upperStyle.fillStyle));let{x:h,y:c,width:d,height:p}=r.rect;iU(t,this.lowerText,{x:h+d/2,y:c+p+Math.abs(n)},Q.Center,u,iC(this.lowerStyle.fillStyle));let{p1:f,p2:m}=i,{x:g,y:y}=f,{x:A}=m,S=this.state||tz.NOT_APPLICABLE,T=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${S} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.qty}`,v=this.isCompact?`${this.riskReward.toFixed(2)}`:`Risk/Reward Ratio: ${this.riskReward.toFixed(2)}`,P=e=>t.measureText(e).width,C=Math.abs(A-g)<1.25*Math.max(P(T),P(v))?y+Math.abs(n)+5:y+e+10,b=iC(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);iU(t,[T,v],{x:g+(A-g)/2,y:C},Q.Center,u,b)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}}var gM=["years","months","weeks","days","hours","minutes","seconds"];function gx(e,t){tt(2,arguments);var i=ts(e),s=ts(t),r=i.getTime()-s.getTime();return r<0?-1:r>0?1:r}function gD(e){return(gD="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e})(e)}function gI(e,t){if(tt(2,arguments),!t||"object"!==gD(t))return new Date(NaN);var i=t.years?te(t.years):0,s=t.months?te(t.months):0,r=t.weeks?te(t.weeks):0,n=t.days?te(t.days):0,a=t.hours?te(t.hours):0,o=t.minutes?te(t.minutes):0,l=t.seconds?te(t.seconds):0,u=ts(e),h=s||i?tr(u,s+12*i):u;return new Date((n||r?lU(h,n+7*r):h).getTime()+1e3*(l+60*(o+60*a)))}function gO(e,t,i){tt(2,arguments);var s=uM(e,t)/6e4;return uD(null==i?void 0:i.roundingMethod)(s)}class gw extends mM{markers;display=null;constructor(e,t){super(e,t),this.points=mI(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new gi]}isPointDrawn(e){return!!super.isPointDrawn(e)&&e.visible}makeLineArrow(e,t,i,s){let r=[ig(e,t),ig(i,s)];return[this.makeLine(r[0],r[1]),ge(r,"end",10)]}get rectColor(){return this.traits[tz.AT_FILL].color}get textColor(){return this.traits[tz.AT_FILL_TEXT].color}getMarkers(){return this.markers}formatDateDifference(e,t){return this.presenter.data.aggregation.isEndOfDay?`${lk(t,e)}d`:(function(e,t){if(arguments.length<1)throw TypeError("1 argument required, but only ".concat(arguments.length," present"));var i,s,r,n,a,o=null!=(i=null!=(s=null==t?void 0:t.locale)?s:nb.locale)?i:oQ,l=null!=(r=null==t?void 0:t.format)?r:gM,u=null!=(n=null==t?void 0:t.zero)&&n,h=null!=(a=null==t?void 0:t.delimiter)?a:" ";return o.formatDistance?l.reduce(function(t,i){var s="x".concat(i.replace(/(^.)/,function(e){return e.toUpperCase()})),r=e[i];return"number"==typeof r&&(u||e[i])?t.concat(o.formatDistance(s,r)):t},[]).join(h):""})(function(e){tt(1,arguments);var t=ts(e.start),i=ts(e.end);if(isNaN(t.getTime()))throw RangeError("Start Date is invalid");if(isNaN(i.getTime()))throw RangeError("End Date is invalid");var s={};s.years=Math.abs(function(e,t){tt(2,arguments);var i=ts(e),s=ts(t),r=gx(i,s),n=Math.abs(function(e,t){tt(2,arguments);var i=ts(e),s=ts(t);return i.getFullYear()-s.getFullYear()}(i,s));i.setFullYear(1584),s.setFullYear(1584);var a=gx(i,s)===-r,o=r*(n-Number(a));return 0===o?0:o}(i,t));var r=gx(i,t),n=gI(t,{years:r*s.years});s.months=Math.abs(function(e,t){tt(2,arguments);var i,s=ts(e),r=ts(t),n=gx(s,r),a=Math.abs(function(e,t){tt(2,arguments);var i=ts(e),s=ts(t);return 12*(i.getFullYear()-s.getFullYear())+(i.getMonth()-s.getMonth())}(s,r));if(a<1)i=0;else{1===s.getMonth()&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-n*a);var o=gx(s,r)===-n;(function(e){tt(1,arguments);var t=ts(e);return lW(t).getTime()===(function(e){tt(1,arguments);var t=ts(e),i=t.getMonth();return t.setFullYear(t.getFullYear(),i+1,0),t.setHours(23,59,59,999),t})(t).getTime()})(ts(e))&&1===a&&1===gx(e,r)&&(o=!1),i=n*(a-Number(o))}return 0===i?0:i}(i,n));var a=gI(n,{months:r*s.months});s.days=Math.abs(lk(i,a));var o=gI(a,{days:r*s.days});s.hours=Math.abs(function(e,t,i){tt(2,arguments);var s=uM(e,t)/36e5;return uD(null==i?void 0:i.roundingMethod)(s)}(i,o));var l=gI(o,{hours:r*s.hours});s.minutes=Math.abs(gO(i,l));var u=gI(l,{minutes:r*s.minutes});return s.seconds=Math.abs(uI(i,u)),s}({start:e,end:t}),{format:["days","hours","minutes","seconds"]}).replaceAll(/(days?)|(hours?)|(minutes?)|(seconds?)/g,e=>e[0])}computeState(){}get text(){return null===this.display&&this.computeState(),this.display}getTextCoord(e,t){let i=this.points[0].price<this.points[1].price,s=iB(t,i,this.text.length),{x:r,y:n,width:a,height:o}=e.rect;return{x:r+a/2,y:n+(i?0:o)+(i?s:Math.abs(s))}}adornElements(e,t){iU(t,this.text,this.getTextCoord(e[0],t),Q.Center,this.textColor,iC(this.rectColor))}getDateDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.time),i=Math.min(+e,+t),s=Math.max(+e,+t),r=this.data(aA.DateTime),n=e_(r,+i,Number),a=e_(r,+s,Number),o=em(this.data(aA.Volume).slice(n,a+1)),l=this.formatter.format(o,aA.Volume),u=a-n,h=0===u?"":this.formatDateDifference(i,s),c=e<t?"":"-";return[`${c}${u} bars, ${c}${h}`,`Vol ${l}`]}getPriceDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.price),i=t-e,s=this.formatter.format(i,aA.Close),r=this.formatter.format(i/e,aA.PercentChange);return[`${s} (${r})`]}resetComputedState(){this.display=null}getFlipAnchorIndices(){return[0,1]}}class gR extends gw{getElements(){this.points.slice(2).forEach(e=>e.toPoint());let[e,t,i,s]=this.getScreenPoints(),r=this.makeLine(e,s),n=this.makeLine(t,i),[a,o]=this.makeLineArrow(e,s,t,i);return this.markers[0]=o,[this.rect,r,n,a]}computeState(){this.display=this.getDateDifference()}}class gN extends gw{getElements(){this.points.slice(2).forEach(e=>e.toPoint());let[e,t,i,s]=this.getScreenPoints(),r=this.makeLine(e,i),n=this.makeLine(t,s),[a,o]=this.makeLineArrow(e,i,t,s);return this.markers[0]=o,[this.rect,r,n,a]}computeState(){this.display=this.getPriceDifference()}}class gV extends gw{get drawBorder(){return this.traits[tz.AT_DRAW_BORDER]}getBorderElements(){if(!this.drawBorder)return[];let[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());let[e,t,i,s]=this.getScreenPoints(),[r,n]=this.makeLineArrow(e,s,t,i),[a,o]=this.makeLineArrow(e,i,t,s);this.markers=[n,o];let l=this.getBorderElements();return[this.rect,r,a].concat(l)}computeState(){this.display=this.getPriceDifference().concat(this.getDateDifference())}}class gH extends mM{constructor(e,t){super(e,t),this.points=mI(e)}get priceLevels(){return i1(this.traits[tz.AT_PRICE_LEVELS])}get timeLevels(){return i1(this.traits[tz.AT_TIME_LEVELS])}get showAngles(){return this.traits[tz.AT_SHOW_ANGLES]}get reverse(){return this.traits[tz.AT_REVERSE]}get showLeftLabels(){return this.traits[tz.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[tz.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[tz.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[tz.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){let i=this.getScreenPoints(),s=this.lineOnlyStyle(tz.AT_LINE_2),r=[];e.concat(t).flatMap(e=>[e.p1,e.p2]).map(e=>{r.some(t=>e.x===t.x&&e.y===t.y)||r.push(e)});let n=i.map(e=>r.filter(t=>t.x!==e.x&&t.y!==e.y).map(t=>this.makeLine(e,t))).flat();return n.forEach(e=>e.style=s),n}getElements(){let 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){let i=this.singleStyle,s=this.showBackground,r=t.fillStyle,n=iF(t,1)/2,{x:a,y:o}=tz.DEFAULT_ADORN_OFFSET,l=(e,i,s,r,n)=>{let a=iS(e,i);iU(t,Number(s.toFixed(4)).toString(),a,r,n)},u=null;if(e.forEach(e=>{if(!e._data)return;let{level:h,isPrice:c}=e._data,d=i?r:e.style.strokeStyle,p=u&&s&&!i;c?(this.showLeftLabels&&l(e.p1,{x:a,y:n},h,Q.Right,d),this.showRightLabels&&l(e.p2,{x:-a,y:n},h,Q.Left,d)):(this.showTopLabels&&l(e.p1,{x:0,y:o},h,Q.Center,d),this.showBottomLabels&&l(e.p2,{x:0,y:-(2*o)},h,Q.Center,d)),p&&((e,i)=>{let s=new Path2D;iH(s,e.p1,i.p2),t.fillStyle=i.style.fillStyle,t.fill(s)})(u,e),u=e}),i&&s){let e=this.applyBackgroundOpacity(this.traits.line.color),i=new Path2D,[s,r]=this.getScreenPoints();iH(i,s,r),t.fillStyle=e,t.fill(i)}}resetComputedState(){this.lines=void 0}updateFrom(e,t,i,s,r){let n=e.reverse!==this.reverse;super.updateFrom(e,t,i,s,r),n&&this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}}let gF=e=>e.map(e=>({...e,dimensions:e.value.split("x").map(Number)})),gB=(e,t)=>1e-7>Math.abs(e-t);class gk extends mM{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=mI(e),this._parsedFans=this._parsedArcs=null}get levels(){return i1(this.traits[tz.AT_LEVELS])}setComputedAndTraits(e,t){let 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[tz.AT_SHOW_RANGES_RATIO]}get arcs(){return i1(this.traits[tz.AT_ARCS])}get fans(){return i1(this.traits[tz.AT_FANS])}get reverse(){return this.traits[tz.AT_REVERSE]}get parsedFans(){return null===this._parsedFans&&(this._parsedFans=gF(this.fans)),this._parsedFans}get computedFans(){let[,,e,t]=this.getReversedScreenPoints(),{dx:i,dy:s}=this.unit,{signX:r,signY:n}=this.getOrientation();return this.parsedFans.map(a=>{let[o,l]=a.dimensions;return this.setComputedAndTraits(a,o>=l?{x:e.x,y:e.y+l/o*n*5*s}:{x:t.x+o/l*5*r*i,y:t.y})})}get parsedArcs(){return null===this._parsedArcs&&(this._parsedArcs=gF(this.arcs)),this._parsedArcs}get computedArcs(){let{dx:e}=this.unit;return this.parsedArcs.map(t=>{let[i,s]=t.dimensions;return this.setComputedAndTraits(t,Math.sqrt(e**2*(i**2+s**2)))})}getReversedScreenPoints(){let[e,t,i,s]=this.getScreenPoints();return this.reverse?[t,e,s,i]:[e,t,i,s]}get unit(){let[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[tz.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[tz.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,i){let s=this.makeLine(e,t);return this.singleStyle||(s.style=i8(i)),s}getGridLines(e,t){let i=t.x-e.x,s=t.y-e.y;return this.computedLevels.map(({computed:r,traits:n})=>{let a=e.x+r*i,o=e.y+r*s;return[this.makeStyledLine({x:a,y:e.y},{x:a,y:t.y},n),this.makeStyledLine({x:e.x,y:o},{x:t.x,y:o},n)]}).flat()}getArcs(e){let{flipX:t,flipY:i,signY:s}=this.getOrientation(),{dx:r,dy:n}=this.unit,a=gB(r,n)?null:{x:1,y:n/r},o=this.getClipPath();return this.computedArcs.map(({computed:r,traits:n})=>{let l=new gp(e,null,r,t?s*Math.PI/2:0,t?Math.PI:s*Math.PI/2,i,this.axis);return null!==a&&(l.scale=a),l.clip=o,this.singleStyle||(l.style=i8(n)),l})}getFans(e){return this.computedFans.map(({computed:t,traits:i})=>this.makeStyledLine(e,t,i))}getElements(){if(null===this.unit)return[];let[e,t]=this.getReversedScreenPoints(),i=this.getGridLines(e,t);return[...i,...this.getArcs(e),...this.getFans(e)]}getOrientation(){let[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(){let[e,t]=this.getReversedScreenPoints(),i=new Path2D;return iH(i,e,t),i}adornElements(e,t){if(0===e.length)return;let i=(e,i,s)=>{t.fillStyle=s;let r=i.hasScale;r&&(t.save(),i.applyScale(t)),t.fill(e),r&&t.restore()};if(this.showBackground){let s=e.filter(e=>e.radius),r=this.getClipPath();if(t.save(),t.clip(r),this.singleStyle){let e=eC(s);i(gf(null,e),e,this.applyBackgroundOpacity(this.traits.line.color))}else{let e=null;s.forEach(t=>{let s=gf(e,t),r=t.style.fillStyle;i(s,t,r),e=t})}t.restore()}if(this.showRangesRatio&&null!==this.unit){let e=eC(this.computedLevels),i=(this.singleStyle?this:e).traits.line.color,[,s,r,n]=this.getReversedScreenPoints(),{x:a,y:o}=tz.DEFAULT_ADORN_OFFSET,{flipX:l,signX:u,signY:h}=this.getOrientation(),c=iS(r,{x:-a*u,y:o*h}),{priceDiff:d,barsDiff:p}=this.getLinesDataAtLevels(null,null),f=l?Q.Right:Q.Left;iU(t,p.toFixed(0),c,f,i);let m=iS(n,{x:2*a*u,y:-o*h}),g=l?Q.Left:Q.Right;iU(t,this.formatter.format(d,aA.Close),m,g,i);let y=iS(s,{x:-a*u,y:-o*h});iU(t,this.priceBarRatio.toFixed(6),y,f,i)}}resetComputedState(){if(this.lines=void 0,4===this.points.length&&null!==this.unit){let{priceDiff:e,barsDiff:t}=this.getLinesDataAtLevels(null,null);this.priceBarRatio=Math.abs(e/t)}}updateFrom(e,t,i,s,r){if(super.updateFrom(e,t,i,s,r),this._parsedFans=this._parsedArcs=null,!gB(e.priceBarRatio,this.priceBarRatio)){let[t,i,,]=this.points;this.reverse&&([t,i]=[i,t]);let{priceDiff:s,barsDiff:r}=this.getLinesDataAtLevels(null,null);i.update(t.price+Math.sign(s)*e.priceBarRatio*r,i.time),this.resetComputedState()}}getFlipAnchorIndices(){return[0,1]}}let gW=(e,t)=>{let i=new Path2D;return null===e||(iN(i,e.p1),iV(i,e.p2),iV(i,t.p2),iV(i,t.p1)),i};class gU extends m_{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[tz.AT_EXTEND_PT_1]}get extend2(){return this.traits[tz.AT_EXTEND_PT_2]}getElements(){let[e,t,i]=this.getScreenPoints(),{x:s,y:r}=iA(i,e),n=i=>{let[s,r]=[e,t].map(e=>iS(e,i));return new mb(s,r,this.extend1,this.extend2,this.axis)};return this.getColoredElements(({value:e})=>n({x:s*e,y:r*e}))}getTextRef(){return(e,t,i)=>{let s=this.formatLevelPrice(i,t.anchor1.y);return{ref:t,spacing:5,offsetY:!0,text:s}}}adornElements(e,t){this.adornElementsForColoredFactors(e,gW,this.getTextRef(),t)}}class g$ extends mL{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=e2(1,1e3,e.LevelSize),this.alignLeft="Left"===e.Position,this.totalVolume="Total"===e.Volume,this.widthPercent=e2(5,100,e.WidthPercent)/100,e.BarColoring){case"OpenToClose":this.useChange=!1;break;case"CloseToClose":this.useChange=!0;break;default:{let e=this.presenter.mainPlot?.mainCurve?.attributes;this.useChange=e?.includes(U.ChangeBased)??!1}}eH(e.PeriodType)&&(this.periodType=e.PeriodType),this.period=e.Period,this.valueRangePercent=e.ValueRangePercent/100;let t=er[AA()?.config.mode??"Unspecified"];this.usesFinerGrainedAgg=sB(t)}get isCountMode(){return"Count"===this.levelMode}updateLastBox(){if(this.boxes.length>0){let 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":{let e=this.studySeries.innCont(0),t=e?.getTimeData();if(!eF(t))return;let i=t[t.length-1],s=this.boxes.length>0?this.boxes[this.boxes.length-1]:null;if(eH(s)&&i.valueOf()<s.lastDate.valueOf())this.updateLastBox();else{let 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":{let t=this.axis.pane.presenter.view.xAxis.xScale.bar,i=this.axis.toY(e.min),s=this.axis.toY(e.max),r=this.axis.pane.presenter.view.toX(e.firstDate)-t.width/2,n=0;if("Days"===this.periodType){let i=e.lastDate,s=this.axis.pane.presenter.view.xAxis.xScale.timeline,a=s.at(s.lastSeriesIndex),o=a.valueOf()<i.valueOf(),l=o?a:i,u=(o?1:-2)*t.width/2;n=this.axis.pane.presenter.view.toX(l)+u-r}else n=this.period*t.width+(this.period-1)*t.spacing;return new iw(r,s,n,i-s)}default:throw Error("Unexpected period type for Volume At Price annotation")}}getElementsForBox(e){let t=this.getBoxRect(e),i=[];if(this.isPeriodic){let e=new mE({x:t.x,y:t.y},t.width,t.height,this.axis);e.style=this.backgroundStyle,i.push(e)}let{x:s,width:r}=t,n=r*this.widthPercent,a=e.bars[e.maxVolumeIndex];return e.bars.forEach((t,o)=>{let{upVolume:l,downVolume:u,totalVolume:h,isValue:c}=t;if(0===l&&0===u)return null;let d=this.axis.toY(e.min+o*e.zone),p=this.axis.toY(e.min+(o+1)*e.zone),f=Math.abs(d-p),m=(e,t,i=0)=>{let n=new mE({x:this.alignLeft?s+i:s+r-e-i,y:p},e,f,this.axis);return n.style=t,n},g=(e,t,i)=>e/t.totalVolume*i,y=this.studyPlot.curves[2].visible,A=y&&c?this.upValueStyle:this.upStyle,S=y&&c?this.downValueStyle:this.downStyle,T=y&&c?this.totalValueStyle:this.totalStyle;if(this.totalVolume){let e=g(h,a,n);i.push(m(e,T))}else{let e=g(u,a,n),t=g(l,a,n);i.push(m(t,A),m(e,S,t))}if(this.studyPlot.curves[1].visible&&o===e.maxVolumeIndex){let e=i[i.length-1].rect,t=this.alignLeft?e.x+e.width:s,n=(p+d)/2,a=this.alignLeft?s+r:e.x;i.push(new mb({x:t,y:n},{x:a,y:n},!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||0===this.boxes.length)return[];switch(this.periodType){case"VisibleScreen":{let e=this.boxes[0];if(!e||0===e.bars.length)return[];return this.getElementsForBox(e)}case"Bars":case"Days":{let[e,t]=this.presenter.view.xAxis.xScale.domain()||[];if(!oE(e)||!oE(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);let r=[];for(let e=i;e<=s;e++)r.push(...this.getElementsForBox(this.boxes[e]));return r}default:throw 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(tz.AT_FILL)}get upStyle(){return this.fillOnlyStyle(tz.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(tz.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(tz.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(tz.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(tz.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(tz.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(tz.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case"VisibleScreen":default:return null;case"Days":return o_(l1(G.Day,this.period)(e),1);case"Bars":{let t=this.axis.pane.presenter.data.aggregation;return o_(l1(t.unit,t.size*this.period)(e),1)}}}getData(){let e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!pz(e.spec))return;let[t,i]=this.presenter.view.xAxis.xScale.domain()||[];if(!oE(t)||!oE(i))return;let s=l1(e.unit,e.size);switch(this.periodType){case"VisibleScreen":{let e=this.boxes[0];if(e&&e.firstDate===t&&e.lastDate===i)this.gotData=!0;else{let e=this.getDataForRange(t,i);e&&(this.boxes[0]=e)}break}case"Bars":{let[e,t]=[0,1].map(e=>this.studySeries.innCont(e));if((e?.size??0)<1||(t?.size??0)<1)return;let i=e.getTimeData(),r=0;for(this.boxes=[];r<i.length;){let e=i[r],t=r+this.period,n=o_(t<i.length?i[t]:s(i[i.length-1]),1),a=this.getDataForRange(e,n);a&&this.boxes.push(a),r+=this.period}this.gotData=!0;break}case"Days":{if(e.isEndOfDay){this.boxes=[],this.gotData=!0;return}let[t,i]=[0,1].map(e=>this.studySeries.innCont(e));if((t?.size??0)<1||(i?.size??0)<1)return;let r=t.getTimeData(),n=t.getData(aA.TradingDay),a=e=>{let t=0,i=r[e],s=n[e];for(let a=e;a<r.length;a++)if(tu(r[a],i)>0&&n[a]!==s&&(t+=1,i=r[a],s=n[a],t===this.period))return a;return -1},o=0,l=r[0],u=a(o)-1;for(;(u<0||u===o)&&o<r.length;)o+=1,u=a(o)-1;for(this.boxes=[];o<r.length&&u<r.length&&o<u;){let e=o_(s(r[u]),1),t=this.getDataForRange(l,e);t&&this.boxes.push(t),l=r[o=u+1],u=a(o)-1}if(u<0&&o<r.length-1){let e=o_(s(r[r.length-1]),1),t=this.getDataForRange(r[o],e);t&&this.boxes.push(t)}this.gotData=!0}}}getBoxAt(e){if(0===this.boxes.length)return null;switch(this.periodType){case"VisibleScreen":{let t=this.boxes[0];if(t.firstDate>e||t.lastDate<e)return null;return t}case"Bars":case"Days":{let t=e.getTime(),i=this.boxes.find(e=>e.firstDate.getTime()<=t&&e.lastDate.getTime()>=t);if(!i)return null;return i}}}getValueAt(e,t,i){if(!this.isVisible)return null;let s=this.getBoxAt(t);if(!s)return null;let r=this.getBarIndex(s,i);if(r<0||r>=s.bars.length)return null;let n=s.bars[r];switch(e){case aA.UPVOL:return this.totalVolume?null:n.upVolume;case aA.DNVOL:return this.totalVolume?null:n.downVolume;case aA.TOTVOL:return this.totalVolume?n.totalVolume:null;case aA.POC:case aA.VAREA:case aA.BARBACK:return null;default:throw Error("Unexpected Volume At Price field")}}getBarIndex(e,t,i=!1){if(0===e.bars.length||0===e.zone)return -1;let 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:5e-324,zone:0,bars:[],maxVolumeIndex:-1,firstDate:e,lastDate:t}}findExtremes(e,t,i,s,r,n){let a=eH(r)&&eH(n);for(let o=t;o<=i;o++)if(a){let t=r[o];t>e.max&&(e.max=t);let i=n[o];i<e.min&&(e.min=i)}else{let t=s[o];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;let t=em(e.bars.map(e=>e.totalVolume))*this.valueRangePercent,i=e.bars[e.maxVolumeIndex].totalVolume,s=e.maxVolumeIndex,r=e.maxVolumeIndex;for(;i<t;){let n=[{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:r+1,endIdx:r+2},{dir:"upper",count:1,startIdx:r+1,endIdx:r+1}].filter(t=>t.startIdx>=0&&t.endIdx<e.bars.length).map(t=>{let s=em(e.bars.slice(t.startIdx,t.endIdx+1).map(e=>e.totalVolume));return{...t,volume:s,newTotal:i+s}});if(0===n.length)break;let a=(e,t)=>t.newTotal<e.newTotal?t:e,o=(e,t)=>t.volume>e.volume?t:e,l=n.filter(e=>e.newTotal>=t),u=l.length>0?l.reduce(a):n.reduce(o);for(let t=u.startIdx;t<=u.endIdx;t++)e.bars[t].isValue=!0;if("lower"===u.dir?s=u.startIdx:r=u.endIdx,(i=u.newTotal)>=t)break}}tallyVolume(e,t,i,s,r,n,a){let o=5e-324,l=!1;for(let u=t;u<=i;u++){let t=r[u],i=this.getBarIndex(e,t,!0);if(-1===i){l=!0;break}let h=a[u],c=this.useChange?n[u]>=0:s[u]<=r[u],d=e.bars[i];c?d.upVolume+=h:d.downVolume+=h,d.totalVolume=d.downVolume+d.upVolume,d.totalVolume>o&&(o=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){let i=this.makeBox(e,t),s=this.studySeries.innCont(1),r=s?.getTimeData();if(!eF(r))return null;let n=e=>e_(r,+e,Number),a=n(e),o=n(t);if(r[o].getTime()>t.getTime()&&(o-=1),a>o)return null;if(this.axis.pane.presenter.data.aggregation.unit===G.Day&&"Bars"===this.periodType){let e=s.getData(aA.TradingDay),t=e[a];for(;t===e[a]&&a>0;)a-=1;a+=1;let i=0;for(o=a;o<r.length&&i<this.period;)e[o]!==t&&(i+=1,t=e[o]),o+=1;o-=2}this.isVisibleScreen&&this.usesFinerGrainedAgg&&a<1e3&&this.studySeries.loadMoreData();let[l,u,h,c,d,p]=["Open","High","Low","Close","Change","Volume"].map(e=>{let t;return t=aA[e],s.getData(t)});this.findExtremes(i,a,o,c,u,h);let f=i.max-i.min,m=e=>({upVolume:0,downVolume:0,isValue:!1,totalVolume:0});if(this.isCountMode)i.zone=f/this.levelSize,i.bars=ex(this.levelSize,m);else{let e=Math.max(1,Math.ceil(f/((this.presenter.mainPlot?.metaData.minMovement??1)*this.levelSize)));i.zone=f/e,i.bars=ex(e,m)}return this.tallyVolume(i,a,o,l,c,d,p),this.gotData=!0,i}}class gG extends mL{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}getElements(){if(!this.studyPlot.visible||!this.studyPlot.mainCurve.visible)return[];let e=this.studySeries.getCurrentState();if(!e)return[];let t=e.confirmedPivots,i=Array.from(t.keys()).sort((e,t)=>e-t);if(0===i.length)return[];let s=this.presenter.mainPlot?.timeSeries?.container;if(!s||s.size<2)return[];let r=s.getTimeData();if(!r)return[];let n=this.presenter.view,[a,o]=n.xAxis.xScale.domain()||[];if(!a||!o)return[];let l=a.getTime(),u=o.getTime(),h=-1,c=-1;for(let e=0;e<i.length;e++){let t=r[i[e]].getTime();if(-1===h&&t>=l&&(h=Math.max(0,e-1)),t<=u)c=e;else if(-1!==h)break}if(-1===h){if(i.length>0&&r[i[0]].getTime()>u)return[];h=i.length-1,c=i.length-1}else -1===c&&(c=h);c=Math.min(i.length-1,c+1);let d=[];for(let e=h;e<c;e++){let s=i[e],a=i[e+1],o=n.toX(r[s]),l=this.axis.toY(t.get(s)),u=n.toX(r[a]),h=this.axis.toY(t.get(a));d.push(this.makeLine({x:o,y:l},{x:u,y:h}))}if(eF(e.pivotPrice)&&eF(e.candPrice)){let t=r[e.pivotIndex].getTime();if(r[e.candIndex].getTime()>=l&&t<=u){let t=n.toX(r[e.pivotIndex]),i=this.axis.toY(e.pivotPrice),s=n.toX(r[e.candIndex]),a=this.axis.toY(e.candPrice);d.push(this.makeLine({x:t,y:i},{x:s,y:a}))}}return d}}class gz extends mL{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}getStyleForElement(e,t){let i=[tz.AT_LINE,tz.AT_LINE_2,tz.AT_LINE_3][t],s=this.traits[i];return s?i8({line:s,fill:{color:tz.COLOR_TRANSPARENT}}):super.getStyleForElement(e,t)}getElements(){if(!this.studyPlot?.visible||!this.studyPlot?.mainCurve?.visible)return[];let e=this.studySeries.getCurrentState();if(!e||null===e.slope||null===e.intercept||null===e.stdDevWidth)return[];let{startIndex:t,endIndex:i,slope:s,intercept:r,stdDevWidth:n,extendLeft:a,extendRight:o}=e;if(null===t||null===i)return[];let l=this.presenter.mainPlot?.timeSeries?.container;if(!l||l.size<2)return[];let u=l.getTimeData();if(!u||u.length<=i)return[];let h=this.presenter.view,c=e=>r+s*(e+1),d=c(0),p=c(i-t+1-1),f=h.toX(u[t]),m=h.toX(u[i]),g=e=>{let t=this.axis.toY(d+e);return new mb({x:f,y:t},{x:m,y:this.axis.toY(p+e)},a,o,this.axis)};return[g(n),g(0),g(-n)]}adornElements(e,t){if(e.length<3||!e.every(e=>eF(e.p1,e.p2)))return;let i=(e,i,s)=>{t.fillStyle=s,t.fill(gW(e,i))};i(e[0],e[1],this.traits?.[tz.AT_FILL]?.color),i(e[1],e[2],this.traits?.[tz.AT_FILL2]?.color)}}function gY(e){let t=Math.abs(e)/Math.SQRT2,i=1/(1+.3275911*t);return .5*(1+(e<0?-1:1)*(1-((((1.061405429*i+-1.453152027)*i+1.421413741)*i+-.284496736)*i+.254829592)*i*Math.exp(-t*t)))}class gj extends mL{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(){let e=this.lineOnlyStyle(tz.AT_LINE),t=this.lineOnlyStyle(tz.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)+ +(0!==this.targetPrice2),this.pricesCount>1&&this.targetPrice1<this.targetPrice2){let 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 eH(this.mainCont)&&!this.mainCont.isEmpty&&this.studySeries.haveVolatility}get studySeries(){return this.studyPlot.timeSeries}getData(){let e=this.presenter.timeline;this.targetDate=e.at(e.lastSeriesIndex+this.periodTarget),this.points=[new mA(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new mA(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=f3(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(aA.Close),this.sigmaAnnualized=this.studySeries.getVolatilityPercent()}computeProbabilities(){let e=this.sigmaAnnualized*Math.sqrt(this.periodTarget/this.unitsPerYear),t=t=>(t-this.anchorPrice)/(this.anchorPrice*e),i=gY(t(this.targetPrice));if(this.pricesCount>1){let e=gY(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[];let e=[];return e.push(new my(this.points[0].point,!0,this.axis)),e.push(new my(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new my(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[];let 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){let[e,i]=[!0,!1].map(e=>Math.abs(iB(t,e))),s=this.pricesCount>1,r=this.points[0].point,n=s?this.points[1].point:r,a=this.traits.line2.color,o=iD(a),l=iF(t),u=["Above","Below","Between"],h=(e,t)=>`${eB(100*e,2).toFixed(2)}% Probability ${u[t]}`,c=(e,i)=>iU(t,e,i,Q.Right,o,a);if(c(h(this.probabilityAbove,0),{x:r.x-10,y:r.y-e}),s){let e=r.y+(n.y-r.y+l)/2;c(h(this.probabilityBetween,2),{x:r.x-10,y:e})}c(h(this.probabilityBelow,1),{x:n.x-10,y:n.y+i})}}}let gK=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=eV(aS.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,i){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,i)}activated(){}deactivated(){}findHit(e){let t;if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return tz.EVENT_PIN_HIT;let i=e.presenter.selectedAnnotation;void 0!==i&&(t=i.points.find(t=>t.hitTest(e.point)));let s=eC(e.axis.annotations.filter(t=>t.computed?null:t.hitTest(e.point)));return void 0!==t&&null==s&&(s=i),[s,t]}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}){let r=s.xAxis.viewBox.contains(t),n=!1;if(eF(e))this.resetVerticalAxis(e),n=!0;else if(r)this.resetHorizontalAxis(i),n=!0;else if(eO()){let e=i.selectedAnnotation;null!=e?m5(e,t):m6(i,t)}n&&s.redraw()}onMouseEnter(){this.previousTouchTimestamp=null}computePreviousTouchStartDuration(){if(!eO())return null;let e=new Date().getTime(),t=eF(this.previousTouchTimestamp)?e-this.previousTouchTimestamp:null;return this.previousTouchTimestamp=e,t}onMouseDown(e){let{point:t,button:i,splitter:s,offset:r,priceAxis:n,presenter:a,originalEvent:o}=e,l=window.navigator.platform.toLowerCase().startsWith("mac"),u=l?ei.Meta:ei.Control,h=i===et.Right||l&&i===et.Left&&e.getModifier(ei.Control);this.touchCrosshairMode&&eF(this.touchCrosshairTimeout)&&(clearTimeout(this.touchCrosshairTimeout),this.touchCrosshairTimeout=null);let c=this.computePreviousTouchStartDuration();if(eF(c)&&c<tz.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!h&&this.isLogoLink(r)&&a.notifyHost(aS.CH_LOGOCLICKED,{chart:a.accessor}),eF(t)&&a.allPlots.some(e=>e.tryHandleCustomEventClick(t.point)))return!0;if(eF(s))return this.resizingPanes=!0,this.lastResizingOffset=r,this.splitter=s,a.enableTooltip(!1),!0;if(eF(n))return eW(a.display.chart.zooming)[0]&&this.startAxisScaling(n,r),!0;if(null!=t){if(e.getModifier(u))return a.activeTool=new m4,a.activeTool.onMouseDown(e),!0;let[i,s]=this.findHit(t);if(a.clearSelection(),null!=i&&a.setSelection(i),null==i||i?.locked)return h?(this.hideCrosshairAndTooltips(a.view),null==i?m6(a,r,o):i?.locked&&m5(i,r),!0):!!this.touchCrosshairMode||(a.activeTool=new mQ(t),a.activeTool.startPan(r),mJ());let n=null!=s;return h?(m5(i,r),eO()):(!n||!!s.movable)&&(!!n||!!i.canMove(t.point))&&(a.activeTool=n&&-1!==i.points.indexOf(s)?new mg(i,s):new mm(i,t,r),eO())}return this.prevZoomingOffset=r,!1}onContextMenu(e){return!0}isLogoLink(e){let t=eH(m0)&&m0.logoClickable?m0.rect:null;return eF(t)&&t.contains(e)}onMouseMove(e){let{point:t,splitter:i,priceAxis:s,view:r,presenter:n,offset:a}=e;if(eF(e.pinchZoom)&&e.pinchZoom&&eF(e.pinchDistance))return eF(this.prevPinchDistance)&&(e.delta=this.prevPinchDistance-e.pinchDistance,this.onWheel(e)),this.prevPinchDistance=e.pinchDistance,eO();if(null!=i||this.resizingPanes)r.setCursor(ee.ResizeVertical),this.resizingPanes&&this.resizePanes(r,a);else if(eF(t)){let[e,i]=this.findHit(t);eF(i)?t.presenter.view.setCursor(ee.Crosshair):eF(e)?e.isSelected?t.presenter.view.setCursor(ee.Move):t.presenter.view.setCursor(ee.Hand):t.presenter.view.setCursor(ee.Arrow)}else if(eF(s))eW(n.display.chart.zooming)[0]&&(r.setCursor(ee.ResizeVertical),this.performAxisScaling(r,s,a));else{if(this.prevZoomingOffset){let{x:e}=this.prevZoomingOffset,{x:t}=a;this.applyZoom(r.presenter,-(e-t)),this.prevZoomingOffset=a}r.setCursor(ee.ResizeHorizontal)}return!t||this.resizingPanes?this.hideCrosshairAndTooltips(r):(this.isLogoLink(a)&&r.setCursor(ee.Hand),this.showCrosshairAndTooltips(r,t,a)),eO()}showCrosshairAndTooltips(e,t,i){t.time&&(!eO()||this.touchCrosshairMode)&&e.drawCrosshair({ap:t,offset:i})&&e.presenter.showTooltip&&mK(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&&mj(e.presenter)}onMouseLeave(e){let{view:t,offset:i}=e,s=t.presenter.accessor.getPaneBounds();s?.every(e=>!e.contains(i)||i.x===e.x||i.x===e.x+e.width||i.y===e.y||i.y===e.y+e.height)&&(this.hideCrosshairAndTooltips(t,!0),this.stopResizeZoom(t.presenter)),t.setCursor(ee.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),eO()){let t=function(){let e=AA().config.touchCrosshairTimeoutMillis;return eF(e)&&Number.isFinite(e)?e:tz.LONG_PRESS_TIMEOUT_MILLIS}();this.touchCrosshairTimeout=window.setTimeout(()=>{this.hideCrosshairAndTooltips(e.view,!0),this.touchCrosshairMode=!1},t)}}applyZoom(e,t,i=!0){if(!eW(e.display.chart.zooming)[1])return;let s=Math.sign(t)*(eO()?2:10),r=e.view;r.xAxis.zoom(s)&&(r.setPriceAxesDomains(),r.redraw(),i&&this.fireZoomChanged(e))}onWheel({view:e,presenter:t,getModifier:i,delta:s}){let{scrollBehavior:r}=t.display;return!!(eO()?"none"!==r:"wheel"===r||"wheel+shift"===r&&i(ei.Shift))&&0!==s&&(e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(),this.applyZoom(t,s),!0)}get useKeyboardShortcuts(){return AA().config.hostingModel!==eo[eo.Application]}onKeyDown(e){let{key:t,code:i,presenter:s}=e;if(eF(s.selectedAnnotation)&&("Backspace"===t||"Delete"===t||8===i||46===i)){let e=s.selectedAnnotation;e.axis.deleteAnnotation(e),s.onAnnotationModifiedByTool(e,el.Deleted)}if(eF(s.selectedAnnotation)&&(ew(t,i)?s.clearSelection():("F2"===t||113===i)&&s.selectedAnnotation instanceof mR&&s.selectedAnnotation.textEditable&&(s.activeTool=new mk(null,s.selectedAnnotation),s.activeTool.startEditing())),eR(t,i)||"ArrowRight"===t||39===i){let e=eR(t,i)?1:-1,r=s.view;r.xAxis.pan(e*r.xAxis.xScale.bar.totalWidth),this.hideCrosshairAndTooltips(r),r.redraw()}let r=window.navigator.platform.toLowerCase().startsWith("mac")?ei.Meta:ei.Control;if(e.getModifier(r)&&this.useKeyboardShortcuts){let e="z"===t||90===i,r="y"===t||89===i;return e&&s.undoRedoManager.undo(),r&&s.undoRedoManager.redo(),e||r}("r"===t||82===i)&&e.getModifier(ei.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){let i=t.y-this.lastResizingOffset.y;if(0===i)return;let s=e.presenter.panes,[r,n]=this.splitter,a=s.map((e,t)=>{let s=e.getBounds().height;return t===r?s+i:t===n?s-i:s});if(a.some(e=>e<tz.MINIMUM_PANE_HEIGHT))return;let o=(e,t)=>e+t,l=a.reduce(o,0),u=s.map(e=>e.height).reduce(o,0);s.forEach((e,t)=>e.height=eB(a[t]/l*u,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){let s=eO()?4:5,r=function(e,t,i,s=1,r=-1){let n=(i.y-t.y)/10,a=e.yScale.rangeWithPadding().reverse();return[a[0]+n*s,a[1]+n*r].map(t=>e.yScale.yToPrice(t))}(t,this.lastScaleResizingOffset,i,s,-s);this.lastScaleResizingOffset=i,t.isCustomDomain=!0,t.yScale.domain(r),e.redraw()}}},gq=e=>g1(m7,gC,1,e),gX=e=>g1(m7,mN,1,e),gZ={Default:()=>function(){return gK},Line:()=>g1(mH,gs,!1),DateRange:()=>g1(mH,gR,!1),PriceRange:()=>g1(mH,gN,!1),DatePriceRange:()=>g1(mH,gV,!1),GannBox:()=>g1(mH,gH,!1),GannSquare:()=>g1(mB,gk),Ray:()=>g1(mH,gs,!1),GannLine:()=>g1(mF,gs,!1),VerticalLine:()=>g1(m7,gr,1),HorizontalLine:()=>g1(m7,gn,1),LongPosition:()=>g1(m7,g_,1,!0),ShortPosition:()=>g1(m7,g_,1,!1),FiftyPercentLine:function(e,t){return eF(e)?g1(m8,ga,e.axis||t.mainAxis,e):g1(m7,ga,2)},FibonacciRetracement:()=>g1(mH,gl,!1),TrendBasedFibExtension:()=>g1(mH,gu,!0),FibonacciFan:()=>g1(mH,gd,!1),FibonacciArcs:()=>g1(mH,gg,!1),FibonacciChannel:()=>g1(mH,gU,!0),GannFan:()=>g1(mH,gy,!1),SpeedResistanceFan:()=>g1(mH,gA,!1),SpeedResistanceArcs:()=>g1(mH,gS,!1),AndrewsPitchfork:()=>g1(m7,gT,3),Rectangle:()=>g1(mH,m1,!1),Ellipse:()=>g1(mH,gv,!1),TrendChannel:()=>g1(mH,gP,!0),SymbolArrowUp:()=>gq("arrow_up"),SymbolArrowDown:()=>gq("arrow_down"),SymbolArrowRight:()=>gq("arrow_right"),SymbolArrowLeft:()=>gq("arrow_left"),SymbolArrowHorizontal:()=>gq("arrow_horizontal"),SymbolArrowVertical:()=>gq("arrow_vertical"),SymbolArcDown:()=>gq("arc_down"),SymbolArcUp:()=>gq("arc_up"),SymbolThumbsUp:()=>gq("thumbs_up"),SymbolThumbsDown:()=>gq("thumbs_down"),SymbolZero:()=>gq("zero"),SymbolOne:()=>gq("one"),SymbolTwo:()=>gq("two"),SymbolThree:()=>gq("three"),SymbolFour:()=>gq("four"),SymbolFive:()=>gq("five"),SymbolSix:()=>gq("six"),SymbolSeven:()=>gq("seven"),SymbolEight:()=>gq("eight"),SymbolNine:()=>gq("nine"),SymbolQuestion:()=>gq("question"),SymbolFishHook:()=>gq("fish_hook"),SymbolBuy:()=>gq("buy"),SymbolSell:()=>gq("sell"),FibonacciTimeZones:()=>g1(mH,gb,!1),Text:()=>g1(mk,mR,null),PickPoint:()=>function(){return new gE},ZoomIn:()=>function(){return new m4},ProfitLoss:gX,RewardRisk:gX,VolumeAtPrice:function(e){return g1(m7,g$,2,e)},ZigZag:function(e){return g1(m8,gG,null,e)},ProbabilityCones:function(e){return g1(m7,gj,2,e)},LinearRegressionChannel:function(e){return g1(m8,gz,null,e)}};function gJ(e,t=!1,i=null,s=null,r=null){let n=gZ[e];return(n=n(s,r))(e,t,i)}function gQ(e,t={}){e.enableTooltip(!0),e.resetActiveTool();let{axis:i,annotation:s,toolChange:r,annId:n}=t;eF(i)&&e.onAnnotationsUpdated(i),eF(s)&&e.onAnnotationModifiedByTool(s,r),[el.Cancelled,el.Executed,el.TextChanged].includes(r)&&e.onAnnotationDone(n,r)}function g0(e,t=!0,i=el.None){e.wasModifiedByTool();let s=e.axis;gQ(s.pane.presenter,t?{axis:s,annotation:e,toolChange:i}:void 0)}function g1(e,t,i,s){return function(r,n,a){let o=mC(r,t,s,a);return(o.annName=r,n)?o:new e(o,i)}}function g2(e){e.button===et.Right&&gQ(e.presenter)}function g3(e,t,i){let s={};s.source=aA[e.source],s.inputs=eK(e.inputs);let r=void 0!==e.target,n=eF(i)?i:e.curves;return s.outFields=function(e){let t=[];for(let i of e)t.includes(i)||t.push(i);return t}(r?[aA[e.target]]:n.map(e=>e.fields).flat()),s.target=r?aA[e.target]:s.outFields[0],s.aggregation=t,s}class g4 extends mh{model;basePlot;_hasEvents;_params;_shiftFmt;_title;range;shouldMaybePriceMap;annIndex;_canPriceMap;#e(e=3){let t=this.model.inputs||[],i=t.length;if(0===i)return"";let s="";i>e&&(t=t.slice(0,3),s=", ...");let r="AVWAP"===this.model.study;return 0===t.length?"":`(${t.map(e=>r&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value).join(", ")}${s})`}get params(){return eF(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(!eF(this._shiftFmt)){let 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(!eF(this._title)){let 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(){let e=sR(this.model.study),t=e.meta.decimals;this.metaData=void 0!==t?new ii(t):this.basePlot.metaData,eF(e.meta.range)&&(this.range=e.meta.range)}getDetachedScaleMargins(){return"VOL"===this.model?.study&&this.axis?.pane.isMain?tz.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){let t=this.model.study;!0===sR(t).meta.shiftable&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});let i=(e,t,i)=>this.curves[e].zones[t].value=this.model.levels[i].value;switch(t){case"ICHCLD":{let 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":{let t=Math.min(Math.max(0,e.inputs.Count),10);this.curves.forEach((e,i)=>e.visible=e.visible&&i<t);break}case"CRS":{let t="PercentChange"===e.inputs.Display;this.axis.comparison=t?q.Percent:q.None;break}case"PERF":{let t="VisibleStart"===e.inputs.Anchor;this.axis.comparison=t?q.Percent:q.None;break}case"JPI":case"CTTP":case"CTTI":{let t=ex(10,e=>(e+1)*.025),i=([e,i])=>[...t.map(t=>i_(t)(e)).reverse(),i,"#6a4a3a","#a000c8","#ffffff"];this.curves[0].colors=i(this.curves[0].colors),this.curves[1].colors=i(this.curves[1].colors);let s=this.curves[0].colors.length;this.curves[0].colors[s-1]=this.curves[1].colors[t.length],this.curves[1].colors[s-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,eF(this.annotations)||(this.annotations=[]);let t=this.curves[1],i=this.curves[2],s=gJ("VolumeAtPrice",!0,{[tz.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[tz.AT_FILL]:{color:this.curves[0].colors[0]},[tz.AT_FILL2]:{color:this.curves[0].colors[1]},[tz.AT_FILL3]:{color:this.curves[0].colors[2]},[tz.AT_FILL4]:{color:i.colors[0]},[tz.AT_FILL5]:{color:i.colors[1]},[tz.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,eF(this.annotations)||(this.annotations=[]);let t=this.curves[1],i=this.curves[2],s=this.curves[3],r=gJ("VolumeAtPrice",!0,{[tz.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[tz.AT_FILL]:{color:this.curves[0].colors[0]},[tz.AT_FILL2]:{color:this.curves[0].colors[1]},[tz.AT_FILL3]:{color:this.curves[0].colors[2]},[tz.AT_FILL4]:{color:i.colors[0]},[tz.AT_FILL5]:{color:i.colors[1]},[tz.AT_FILL6]:{color:i.colors[2]},[tz.AT_FILL7]:{color:s.colors[0]}},this.id)(this.axis,!1);r.setOptions(e.inputs),this.annIndex=this.annotations.push(r)-1;break}case"ZIGZAG":{this.customPlotValues=!0,eF(this.annotations)||(this.annotations=[]);let e=gJ("ZigZag",!0,{[tz.AT_LINE]:{color:this.curves[0].colors[0],width:this.curves[0].lineWidth,dashStyle:this.curves[0].dashStyle}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(e)-1;break}case"LINRCHN":{this.customPlotValues=!0,eF(this.annotations)||(this.annotations=[]);let e=this.curves[0],t=this.curves[1],i=this.curves[2],s=this.curves[3],r=this.curves[4],n=gJ("LinearRegressionChannel",!0,{[tz.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle},[tz.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[tz.AT_LINE_3]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle},[tz.AT_FILL]:{color:s.colors[0]},[tz.AT_FILL2]:{color:r.colors[0]}},this.id)(this.axis,!1);this.annIndex=this.annotations.push(n)-1;break}case"IVRANK":{let t=aA.ImplVolRank1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=aA.ImplVolRank5D;break;case"1-Month":t=aA.ImplVolRank1M;break;case"3-Month":t=aA.ImplVolRank3M;break;case"6-Month":t=aA.ImplVolRank6M;break;case"YTD":t=aA.ImplVolRankYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"IVPCTL":{let t=aA.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case"1-Year":default:break;case"5-Day":t=aA.ImplVolPerc5D;break;case"1-Month":t=aA.ImplVolPerc1M;break;case"3-Month":t=aA.ImplVolPerc3M;break;case"6-Month":t=aA.ImplVolPerc6M;break;case"YTD":t=aA.ImplVolPercYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case"OPTIV":{let t=[aA.WeighImplVolHigh,aA.WeighImplVol,aA.WeighImplVolLow];switch(e.inputs.TimeFrame){case"1-Day":default:break;case"5-Day":t=[aA.WeighImplVolHigh5D,aA.WeighImplVol5D,aA.WeighImplVolLow5D];break;case"1-Month":t=[aA.WeighImplVolHigh1M,aA.WeighImplVol1M,aA.WeighImplVolLow1M];break;case"3-Month":t=[aA.WeighImplVolHigh3M,aA.WeighImplVol3M,aA.WeighImplVolLow3M];break;case"6-Month":t=[aA.WeighImplVolHigh6M,aA.WeighImplVol6M,aA.WeighImplVolLow6M];break;case"1-Year":t=[aA.WeighImplVolHigh1Y,aA.WeighImplVol1Y,aA.WeighImplVolLow1Y];break;case"YTD":t=[aA.WeighImplVolHighYTD,aA.WeighImplVolYTD,aA.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":{let t=e.inputs.PeriodForecast-1;this.curves.forEach(e=>e.shift=t),eF(this.annotations)||(this.annotations=[]);let i=this.curves[11],s=this.curves[12],r=gJ("ProbabilityCones",!0,{[tz.AT_LINE]:{color:i.colors[0],width:i.lineWidth,dashStyle:i.dashStyle},[tz.AT_LINE_2]:{color:s.colors[0],width:s.lineWidth,dashStyle:s.dashStyle}},this.id)(this.axis,!1);r.setOptions(e.inputs),this.annIndex=this.annotations.push(r)-1}}}getValueAt(e,t,i){return this.isVolAP?this.annotations[this.annIndex].getValueAt(e,t,i):super.getValueAt(e,t,i)}getColorOf(e){if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;let t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case aA.UPVOL:return t[1];case aA.DNVOL:return t[0];case aA.TOTVOL:return t[2];case aA.POC:case aA.VAREA:case aA.BARBACK:return tz.COLOR_TRANSPARENT;case aA.LINRUP:return t[0];case aA.LINRMID:return this.curves[1].colors[0];case aA.LINRLOW:return this.curves[2].colors[0];default:throw Error("Unexpected Volume At Price field")}}isEmpty(){return!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel&&super.isEmpty()}setCurveAttributes(e,t){let i=t=>this.curves[e].attributes=[U[t]];switch(t){case"LikeMain":{let t=this.axis.pane.presenter.mainPlot.curves[0].attributes,s=AA().config.defaultVolumeBarColoring;eF(t)?this.curves[e].attributes=[t[0]]:i(eF(s)?"OpenToClose"===s?"OpenVsClose":"ChangeBased":"OpenVsClose");break}case"OpenToClose":i("OpenVsClose");break;case"CloseToClose":i("ChangeBased");break;default:throw Error(`Unexpected bar coloring choice: ${t}`)}}get hasEvents(){return this._hasEvents}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){let e=this.timeSeries.helpers;return e.includes(aA.Buy)||e.includes(aA.Sell)}getEventFor(e){switch(e){case aA.Buy:return{show:!0,title:"B",color:"#03c03c"};case aA.Sell:return{show:!0,title:"S",color:"#c23b22"};default:return null}}getEventFields(){return this.hasEvents?[aA.Buy,aA.Sell]:[]}async initialize(){if(this.model.basis!==tz.BASIS_MAIN)throw Error("Studies can currently only be based on the main (symbol) plot");return tU.call(this,async()=>{this.basePlot=this.axis.pane.presenter.mainPlot,await this.basePlot.initialize(),this.getMetaData();let e=this.axis.pane.presenter.data.aggregation,t=g3(this.model,e,this.curves);this.applySpecifics(t);let i=this.basePlot.timeSeries;i instanceof cT&&(i=i.actual),this.timeSeries=f_(this.model.study,t,i),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;let s=this.title,r=this.basePlot.timeSeries instanceof u0;return this.timeSeries.ready().then(e=>{e||r||this.timeSeries.computedServerSide||Ad(`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===aA.JPIB.id||e.id===aA.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;let s=(e,t)=>this.timeSeries.container.getData(e)[t],r=s(aA.JPIB,t),n=s(aA.JPIS,t);if(null===r&&i.id===aA.JPIB.id||null===n&&i.id===aA.JPIS.id)return null;let a=0,o=this.visFromIndex,l=this.timeSeries.helpers[0],u=this.timeSeries.helpers[2];for(;o<=t;)a+=1===s(u,o)?0:s(l,o),o++;return a}}let g5=[aA.Open,aA.High,aA.Low,aA.Close,aA.Volume];class g6 extends mh{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){let e=nX(this._expression);if(this.exprModel=null,this.symbols=null,nq(e))this.errorText=e.error;else{let{model:t,clean:i,symbols:s}=e;this.errorText=void 0,this.symbols=s,this.exprModel=t,this._expression=i}}get isValid(){return!eF(this.errorText)}#t(e){return{mapper:e=>e.query.symbol,loadMoreData:!0,recompute:B.Minimum,missing:F.UseNext,stretch:e=>!1,fieldMap:new Map(g5.map(e=>[e,e])),noDataApproach:k.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:e}}getTimeSeries(){let e=this.getInnerSeries(),t=this.axis?.pane.presenter.data?.exprSkipLeadingEmpty??!1,i=new pA(this.exprModel,e,this.#t(t));this.timeSeries=this.wrapIfAdvancedStyle(i);let s=this.title;this.timeSeries.ready().then(e=>{e||Ad(`Unable to calculate expression: ${s}`,"error")})}getInnerSeries(){let e=n0(this.exprModel),t=AA().getTimeSeriesDataSource();return e.map(e=>{let i=this.makeQuery();return i.symbol=e,t.getTimeSeries(i)})}getRecord(){if(eF(this.errorText))return;let e=this.metaData.inner.map(e=>[e.symbol,e.resolved]);this.record=new aN(e,ez(this.exprModel)),this.record.ready().then(e=>e)}getMetaData(){this.isValid&&(this.metaData=new ir(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(aS.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return tU.call(this,async()=>(await this.parseExpression(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}class g7 extends mh{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),this.offset=e.offset,this._forward=e.forward}async parseForward(){let e=nX(this.forward),t=nq(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=` (${ed(u_(this.offset),lz(tz.FMT_US_DATE_ONLY))(new Date)})`,this.outField=new am(`Close_${this.offset}`,Y.Number,K.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix="",this.outField=aA.Close);let{yes:t,no:i}=eS(e.symbols,e=>ty(`${e}*1`)),s=(await Promise.all(t.map(e=>tM(e)))).map(e=>e.map(e=>e.name));this.roots=t.reduce((e,t,i)=>(e[t]=s[i],e),{}),this.symbols=i}}get isValid(){return!eF(this.errorText)}getMetaData(){if(this.isValid){let e=Object.values(this.roots).flat();this.metaData=new ir(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(aS.MD_CHANGED,{plot:this})})}}getForwardPolicy(e){return{mapper:e=>e.query.root,loadMoreData:!1,recompute:B.Everything,missing:F.UseNext,stretch:e=>!1,fieldMap:new Map([[aA.Close,this.outField]]),noDataApproach:k.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1,valueProvider:e}}getTimeSeries(){let e=AA().getTimeSeriesDataSource(),t=Object.keys(this.roots),i=0===this.offset?J.Forward:J.HistoricalForward,s=t.map(t=>{let s={seriesKind:i,root:t,offset:this.offset,symbols:this.roots[t],getHashKey:()=>`${i}|${t}|${this.offset}`};return e.getTimeSeries(s)}),r=this.symbols.length>0?new u6(this.symbols):void 0;this.timeSeries=new pA(this.fwdModel,s,this.getForwardPolicy(r)),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:en.Unspecified};this.presenter?.notifyHost(aS.TS_MANYCHANGED,e)}})}async initialize(){return tU.call(this,async()=>(await this.parseForward(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}let g8=e=>e.substring(0,e.lastIndexOf("::"));class g9 extends mh{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),this.offset=e.offset,this.offsets=e.offsets,this.isAverage=e.offset<0,this._seasonal=this.refSeasonal=e.seasonal}constructSeasonal(e,t){return nQ(n2(e,e=>this.applyOffset(e,t)))}constructAverage(e,t=null){let i=null===t?null:t.map(e=>this.symbolToOffset[e]),s=null===i,r=this.offsets.filter(e=>!!s||i.includes(e)).map(t=>`(${this.constructSeasonal(e,t)})`);return`(${r.join("+")})/${r.length}`}prepareFields(){let e=this.isPlain?`${this.yearFromOffset(this.offset)}`:`${this.offset}Y`,t=this.isAverage?"Avg":e;this.suffix=0===this.offset?"":` (${t})`,this.outField=new am(`Close_${t}`,Y.Number,K.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){let i=this.isPlain?e:function(e,t){let i=ty(e),s=tv(e),r=tS(e);if(i)return tD(e,t);if(s){let i=tT.exec(e),s=Number.parseInt(i[2]),r=th(tn(new Date(s+(s>79?1900:2e3),0,1),t));return`${i[1]}${tC(r)}${i[3]}`}if(!r)return null;{let i=e.match(tA),s=tD(i[1],t),r=tD(i[2],t);return`_S_SP_${s}_${r}`}}(e,-t);return`${i}::${t}`}createSymbolToOffsetMapping(e){this.symbolToOffset={},e.forEach(e=>{this.offsets.forEach(t=>{this.symbolToOffset[this.applyOffset(e,t)]=t})})}async parseSeasonal(){let e=nX(this.seasonal,!0),t=nq(e),i=e=>(this.errorText=e,this.seaModel=null,null);if(t)return i(e.error);let{model:s,symbols:r}=e;this.prepareFields();let n=new Map;for(let e of r){let t=tb(await tm(e));n.set(e,t)}s=n2(s,e=>n.get(e));let a=(r=Array.from(n.values())).every(e=>ty(e)||tS(e)),o=r.every(e=>tv(e)),l=r.every(e=>!ty(e)&&!tv(e)&&!tS(e));if(!a&&!o&&!l)return i("Mixed types of symbols aren't supported yet");this.isPlain=l,this.isFutures=a,this.createSymbolToOffsetMapping(r),this.coreModel=this.isAverage?s:null,this.coreHasComputation=n1(s);let{model:u,symbols:h}=nX(this.isAverage?this.constructAverage(s):this.constructSeasonal(s,this.offset),!0);this.seaModel=u,this.hasComputation=n1(u),this._seasonal=nQ(n2(u,g8)),this.symbols=h,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!eF(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(g8))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){let e=g8(this.symbols[0]);if(this.isPlain)return`${e} ${new Date().getFullYear()-this.offset}`;if(this.isFutures)return tb(e,!0)}return this.title}getMetaData(){if(this.isValid){let e=this.getActualSymbols(),t=1===e.length&&!this.hasComputation&&!this.isAverage,i=AA().getMetaDataSource();this.metaData=t?i.getMetaData(e[0]):new ir(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(aS.MD_CHANGED,{plot:this})})}}getNoDataApproach(){return this.isAverage&&!this.coreHasComputation?k.ModelTransformRequired:this.hasComputation?k.NoAction:k.IgnoreTimelineOnly}get seasonalPolicy(){return{mapper:e=>e.query.surrogate||e.query.symbol,loadMoreData:!1,recompute:B.Everything,missing:this.hasComputation?F.UsePrevious:F.UseNone,stretch:e=>this.shouldStretch(e),fieldMap:new Map([[aA.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>0===t.length?this.seaModel:nX(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 tn(new Date,-e)}yearFromOffset(e){return th(this.shiftYears(e))}getCmdtyRange(e){let t=this.shiftYears(e);return[ta(t),function(e){tt(1,arguments);var t=ts(e),i=t.getFullYear();return t.setFullYear(i+1,0,0),t.setHours(23,59,59,999),t}(t)]}getTimeSeries(){if(!this.isValid)return;let e=AA().getTimeSeriesDataSource(),t=Object.keys(this.symbolToOffset).map(t=>{let i=this.makeQuery();return i.surrogate=t,i.symbol=g8(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&&eF(...i.range)&&(i.range=i.range.map(e=>tn(e,-i.offset))),i.offset>0&&(i.disableStreamingUpdates=!0),e.getTimeSeries(i)});this.timeSeries=new pA(this.seaModel,t,this.seasonalPolicy),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:en.Unspecified};this.presenter?.notifyHost(aS.TS_MANYCHANGED,e)}})}async initialize(){return tU.call(this,async()=>(await this.parseSeasonal(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}}let ye=["bottom","right","left"],yt={bottom:"center",right:"start",left:"end"};class yi{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,r,n){let a=eF(r);if(n=n||this.fontSize+this.padding+this.padding+(a?this.padding:0),!ye.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=yt[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=iC(this.backgroundColor),e.lineWidth=this.lineWidth;let o=Math.round(Math.max(...[s,r??""].map(t=>e.measureText(t).width))+("bottom"!==this.position?this.arrowLength:0)+this.padding+this.padding),l=Math.round(o/2),u=Math.round(n/2);e.setLineDash([]),e.beginPath(),e.moveTo(t,i);let h=i+u,c=i+2*u,d=i-u;if("right"===this.position){e.lineTo(t,h);let i=t+o;a&&(e.lineTo(t,c),e.lineTo(i,c)),e.lineTo(i,h),e.lineTo(i,d),e.lineTo(t,d)}else if("left"===this.position){e.lineTo(t,h);let s=t-o;a&&(e.lineTo(t,c),e.lineTo(s,c)),e.lineTo(s,h),e.lineTo(s,d),e.lineTo(t,i-u)}else if("bottom"===this.position){let s=t-l,r=t+l;e.lineTo(t,i),e.lineTo(r,i),e.lineTo(r,i+n),e.lineTo(s,i+n),e.lineTo(s,i),e.lineTo(t,i)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline="middle","bottom"===this.position)e.fillText(s,t,i+iF(e,1));else if("right"===this.position){let n=t+this.arrowLength+this.padding;e.fillText(s,n,i),a&&e.fillText(r,n,i+this.padding+u)}else if("left"===this.position){let n=t-this.arrowLength-this.padding;e.fillText(s,n,i),a&&e.fillText(r,n,i+this.padding+u)}}}let ys=(e,t)=>e-1-t-4,yr=(e,t)=>e+1+t+4,yn=Array.from(Array(6),(e,t)=>++t).reverse();function ya(e){return e.curves.filter(t=>t.visible&&(e.type!==Z.Study||t.style!==$.Ribbon)).map(t=>{let i=t.pickMainField(),[s,r]=function(e,t){let i=e.timeSeries.container;if(null===i||i.size<1)return[null,-1];let s=i.getLastDataPoint(t),r=i.getData(t),n=r.length-1,a=e.type===Z.Study&&["JPI","CTTP","CTTI"].includes(e.model.study);return null!=s||a||(s=-1!==(n=eT(r,e=>null!==e))?r[n]:null),[s,n]}(e,i);return{value:s,color:function(e){let t=e.plot.timeSeries.container;return null===t||t.size<1?null:e.getColor(t.size-1)}(t),field:i,index:r}})}class yo{pane;annotations;id;isCustomDomain;primary;onTheRight;viewBox;plots;comparison;scale;yScale;label;crosshairIndicator;ticks;lastUsedOptions;config;_fullDomain;constructor(e){this.pane=e,this.annotations=[],this.isCustomDomain=!1,this.primary=!1,this.onTheRight=!0,this.plots=[],this.label="",this.id=e1(),this.ticks=null,this.lastUsedOptions=null;let{chart:{fontSize:t},yAxis:{fontSize:i}}=this.pane.presenter.display;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:i||t||12},this.crosshairIndicator=new yi({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}makePlot(e){let t=null;switch(Z[e.type]){case Z.Symbol:t=new mc;break;case Z.Expression:t=new g6;break;case Z.Study:t=new g4;break;case Z.IncomeStatement:t=new md(J.IncomeStatement);break;case Z.BalanceSheet:t=new md(J.BalanceSheet);break;case Z.Forward:t=new g7;break;case Z.Seasonal:t=new g9;break;default:throw Error(`${e.type} isn't supported yet`)}return t.axis=this,t.fromModel(e),t}toPrice(e){let t=this.yScale.yToPrice(e);return this.comparison===q.None?t:this.pane.presenter.mainPlot.priceMap(t,void 0,aA.Close,!0)}toTime(e){return this.pane.presenter.view.toTime(e)}toAnnotationPoint(e){return new mA(this,this.toPrice(e.y),this.toTime(e.x)||void 0)}toX(e){return this.pane.presenter.view.toX(e)}priceMap(e){return this.comparison===q.None?e:this.pane.presenter.mainPlot.priceMap(e,void 0,aA.Close)}toY(e){let t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){let 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){let t={x:this.annTimeToX(e.time),y:this.toY(e.price)},i=this.pane.presenter,s=i.activeTool,r=s.annotation;return s.alignPointsMode&&r&&r.alignPointsSupported&&r.points.includes(e)?this.alignPoints(r,e,t):s.snapToSupported&&i.display.yAxis.snapAnnotationsToPrices&&!e.passive&&(e.moveDirection===es.Both||e.moveDirection===es.Vertical)&&this.snapToPrices(e,t),t}snapToPrices(e,t){let i=this.plots.find(e=>e.main);if(i&&i.timeSeries&&i.timeSeries.hasData){let s=i.timeSeries.container,r=e_(s.getTimeData(),+e.time,Number),n=[].concat(...i.curves.map(e=>e.fields)).filter(e=>s.hasField(e)).map(e=>{let i=s.getData(e)[r],n=this.toY(i),a=Math.abs(n-t.y);return{priceSnap:i,ySnap:n,dist:a}}).filter(e=>e.dist<=tz.SNAP_PROXIMITY_PIXELS).reduce((e,t)=>null===e||t.dist<e.dist?t:e,null);eF(n)&&(e.price=n.priceSnap,t.y=n.ySnap,e.time=s.getTimeData()[r],t.x=this.toX(e.time))}}alignPoints(e,t,i){let s=e.points.find(e=>e!==t);if(t!==s&&s&&s.point){let e=s.point,r=(360+-(180*iT(e,i))/Math.PI)%360;if(r>337.5||r<22.5||r>157.5&&r<202.5)i.y=e.y,t.price=this.toPrice(i.y);else if(r>67.5&&r<112.5||r>247.5&&r<292.5)i.x=e.x,t.time=this.toTime(i.x);else{let s=Math.abs(i.x-e.x),r=e.y>i.y?-1:1;i.y=e.y+s*r,t.price=this.toPrice(i.y)}}}toPoint(e){if(eF(this.pane.presenter.view))return this.snapTo(e)}makeAnnotation(e,t=!0){let i=gJ(e.id,!0,e.traits)(this,!1);t&&e.uid&&(i.uid=e.uid);let s=i.activePoints,r=e.points.length-s.length;return r>0&&i.addPoints(r),i.activePoints.forEach((t,i)=>{let s=e.points[i];ek(s.price)&&ek(s.time)&&t.update(s.price,s.time)}),i.visible=e.visible,i.locked=e.locked,i}expand(e){let t=[];switch(e.type){case"Forward":{let i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;for(let r=0;r<i.length;r++){let n=Object.assign({},e);n.curves=[i[r]],n.offset=s[r],t.push(n)}break}case"Seasonal":{let i=e.curves,s=e.offsets;delete e.curves,delete e.offsets;let r=s.filter(e=>e>=0);for(let n=0;n<i.length;n++){let a=Object.assign({},e);a.curves=[i[n]],a.offset=s[n];let o=a.offset<0;if(o){let e=-1===a.offset;a.offsets=e?r:ex(Math.abs(a.offset),e=>e+1)}else a.offsets=[a.offset];(!o||a.offsets.length>1)&&t.push(a)}break}default:t.push(e)}return t}fromModel(e){this.comparison=q[e.comparison??"None"],this.scale=X[e.scale??"Linear"],this.yScale=new mr(this.scale,this),this.label=e.label,this.plots=[].concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e));let t=e.annotations||[];this.annotations=t.map(e=>this.makeAnnotation(e));let{chart:{fontFamily:i,backgroundColor:s},yAxis:{textColor:r,crosshair:{color:n},primaryOnTheLeft:a}}=this.pane.presenter.display,o=a??!1;this.onTheRight=this.primary&&!o||!this.primary&&o,this.crosshairIndicator.configure({position:this.onTheRight?"right":"left",fontFamily:i,strokeColor:n,textColor:r,backgroundColor:i_(.15)(s)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){let 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();let 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){let t=e.axis,i=this.makeAnnotation(e.toModel(),!1);i.drawPoints(null,!0),i.offset({x:tz.ANN_DUPLICATE_OFFSET,y:tz.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(i),i.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&this.pane.presenter.clearSelection(),s8(e.name,t.traits),e.updateFrom(t.traits,t.extras,t.isUndoRedo?null:t.points,t.visible,t.locked),t.isUndoRedo&&eF(t.points)&&e.updateActivePoints(t.points),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(mT(e,el.Moved)),e.requestRedraw(),this.fireAnnotationsChanged()}setViewBox(e){this.viewBox=e;let{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 eF(this._fullDomain)||(this._fullDomain=this.getDataDomain().domain),this._fullDomain}updateFullDomain(e=null){if(null===e&&this.comparison!==q.None)return;let t=this.fullDomain;this._fullDomain=this.getDataDomain([e,e],t).domain}getPlotDataDomain(e,t,i){let s=e.timeSeries;if(!s.hasData)return{domain:null};let r=s.container,n=r.getTimeData(),a=e=>e_(n,+e,Number),o=eF(t),l=o?a(t):0,u=eF(i),h=u?a(i):n.length-1,c=e.curves.map(e=>e.fields).flat().filter(e=>e.id!==aA.Change.id),d=eF(e.targetFields);d&&c.push(...e.targetFields);let p={},f=t=>{let[i,s]=(t=>{let i=d?e.curves[0]:e.curves.find(e=>e.fields.includes(t));if(!eF(i)||0===i.shift)return[l,h];if(!eF(p[i.id])){let e=i.shiftedTimeDomain;if(!eF(e))return[l,h];p[i.id]=[a(e[0]),a(e[1])]}return p[i.id]})(t),n=r.getData(t),o=Math.max(i,0),u=Math.min(n.length-1,s);return n.slice(o,u+1).map((i,s)=>e.priceMapper(i,s,t))},m=[null,null],g=e=>e.id,y=new Set(eP(r.fields,c,g).map(g));e.curves.filter(e=>e.visible).map(e=>{let t=e.fields.filter(e=>y.has(e.id));e.isStackedColumn?eD(eM(t.map(e=>f(e)).reduce((e,t)=>t.map((t,i)=>(e[i]||0)+(t||0)),[])),m):t.map(e=>{eD(eM(f(e)),m)})});let A=eu.None,S=[$.Column,$.MultiColumn,$.StackedColumn];if(o&&u&&!e.main&&e.curves.some(e=>S.includes(e.style))){let e=m[0]>0,t=m[1]<0;e?(A=eu.Min,m[0]=0):t&&(A=eu.Max,m[1]=0)}return{domain:m,clamped:A}}getDataDomain([e,t]=[null,null],i=[null,null]){let s=ez(i),r=!1;for(let i of this.plots.filter(e=>!e.hasDetachedScale)){let{domain:n,clamped:a}=this.getPlotDataDomain(i,e,t);eF(n)&&(eD(n,s),r=r||a!==eu.None)}if(!eF(s))return{domain:null};let[n,a]=s;if(!eF(n,a))return{domain:null};let o=[Number(n),Number(a)];o[0]===o[1]&&(o[0]-=1,o[1]+=1);let l=eu.None;return r&&(0===o[0]?l=eu.Min:0===o[1]&&(l=eu.Max)),{domain:o,clamped:l}}setDomain(){let e=this.pane.presenter,t=e.view.xAxis.xScale.domain();if(!eF(t))return;for(let e of this.plots.filter(e=>e.hasDetachedScale)){let{domain:i}=this.getPlotDataDomain(e,t[0],t[1]);eF(i)&&e.yScale.domain(i)}if(this.isCustomDomain)return;let{domain:i,clamped:s}=this.getDataDomain(t);if(this===e.mainAxis&&e.mainPlot?.showPrevious){let t=e.mainPlot.getPreviousValue(),s=eG(e.display,!1,"chart","previous","forceVisible");eF(t,i)&&s&&(i[0]=Math.min(i[0],t),i[1]=Math.max(i[1],t))}if(this.yScale.domain(i),eF(i)){let e=this.getPadding(s);eF(e)&&this.yScale.padding(e)}}getInitialPadding(){let e=tO(this.pane.presenter.hostElement),t=tR(`#${tz.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!eF(t)){tN(t=tB(e,"div"),{display:"none"}),tV(t,{id:tz.HEADER_SIZE_PLACEHOLDER_ID,class:"bcharts-card bcharts-card-first"});let{lineHeight:i}=getComputedStyle(t);isNaN(Number.parseFloat(i))&&tN(t,{lineHeight:"120%"})}let{paddingTop:i,paddingBottom:s,marginTop:r,lineHeight:n}=getComputedStyle(t),a=this.pane.isMain?r:"0";return"cards"!==this.pane.presenter.display.tooltip.mode?Number.parseFloat(a):[i,s,a,n].map(Number.parseFloat).reduce((e,t)=>e+t,0)+tz.CARDS_Y_OFFSET}getPadding(e){let t=this.pane.presenter,i=t.display,s=eG(i,null,"yAxis","minPaddingPercent"),r=eG(i,null,"yAxis","maxPaddingPercent"),n=eF(s),a=eF(r),o=n||a?0:this.getInitialPadding(),l=n?s:tz.PANE_CAP_MIN_PADDING_PERCENT,u=a?r:tz.PANE_CAP_MAX_PADDING_PERCENT,h=l*this.viewBox.height,c=[a?u*this.viewBox.height:Math.max(h,Math.min(u*this.viewBox.height,o)),h];e===eu.Max?c[0]=tz.PANE_TINY_PADDING_PIXELS:e===eu.Min&&(c[1]=tz.PANE_TINY_PADDING_PIXELS);let d=t.mainPlot;return d&&d.hasEvents&&(c[0]+=3*t.view.getEventRadius()),c}clearTicks(){this.ticks=null}getTicks(e,t=0){let{height:i}=this.viewBox,s=iF(e,1.3),r={height:i,approxLineHeight:s,domain:this.yScale.domain()};if(eF(this.ticks)&&eF(r.domain)&&eF(this.lastUsedOptions)&&eF(this.lastUsedOptions.domain)&&r.height===this.lastUsedOptions.height&&r.approxLineHeight===this.lastUsedOptions.approxLineHeight&&r.domain[0]===this.lastUsedOptions.domain[0]&&r.domain[1]===this.lastUsedOptions.domain[1])return this.ticks;this.lastUsedOptions=r;let n=Math.floor((i+40)/(s+40)),a=this.yScale.getTicks(n),o=eG(AA().config,null,"overrides","yAxis","tickProvider");if(eF(o)&&"function"==typeof o&&r.height>0&&eF(r.domain)){let e=ez(r);e.autoTicks=ez(a),a=o(e)}let{innerTickSize:l,tickPadding:u,fontSize:h}=this.config,c=null,d=this.yScale?.checkTicks(),p=d?30:40;return this.ticks=a.map(i=>{let s=Math.round(this.yScale.priceToY(i)),r=Math.abs(s-(c??s));if(d&&null!==c&&r<p)return null;c=s;let n=hx(this,i),a=e.measureText(n).width,o={x1:0,x2:0,y1:s,y2:s,dy:0,label:n,labelX:0,labelY:s+.32*h};return this.onTheRight?(o.x1=t,o.x2=o.x1+l,o.labelX=o.x2+a+u):(o.x1=t-l,o.x2=o.x1+l,o.labelX=o.x1-u),o}).filter(e=>null!==e),this.ticks}widthNeeded(e){if(!eF(this.fullDomain))return tz.DEFAULT_PRICE_AXIS_WIDTH;e.save();let{fontWeight:t,fontSize:i}=this.config,{chart:{fontFamily:s}}=this.pane.presenter.display;e.font=`${t} ${i}px ${s}`;let r=t=>e.measureText(hx(this,t,!0)).width,n=Math.max(...this.fullDomain.map(r)),{innerTickSize:a,tickPadding:o}=this.config,l=eF(this.label)?iF(e,1.6):0;return e.restore(),n+a+2*o+l}draw(e){let{chart:{fontFamily:t},yAxis:{gridLines:i,textColor:s,visible:r}}=this.pane.presenter.display;if(!r||!this.viewBox)return;e.save();let{x:n,y:a,width:o,height:l}=this.viewBox,{fontWeight:u,fontSize:h}=this.config;if(iO(e,this.viewBox),e.font=`${u} ${h}px ${t}`,e.lineWidth=2,e.strokeStyle=i.color,e.textAlign="end",eF(this.label)){e.save(),e.fillStyle=iL(.4)(s),e.translate(0,0);let t=this.onTheRight?1:-1;e.rotate(t*Math.PI/2),e.textAlign="center";let i=iF(e),r=t*(a+l/2);this.onTheRight?e.fillText(this.label,r,-(n+o-i)):e.fillText(this.label,r,n+i),e.restore()}let c=this.onTheRight?n:o;e.setLineDash([]),iY(e,c,a,a+l);let d=this.getTicks(e,c);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;let i=this.onTheRight?this.viewBox.x:this.viewBox.width,s=hx(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){var t;let i=this.pane.presenter,{chart:{fontFamily:s,previous:r},yAxis:{showLastValue:n,preventLabelOverlap:a,includePercentChangeWithLastValue:o}}=i.display,l=i.view,u=[],h=(e,t,i,s,r,n)=>{if(null!=t){let a,l=t;t=e.priceMapper(t,n,r);let h=e.is(Z.Symbol)||e.is(Z.Expression);if(o&&h){let t=e.axis.comparison===q.Percent?q.None:q.Percent;a=e.priceMapper(l,n,r,t)}let c=e.hasDetachedScale?e.metaData.format(t,r):void 0,d=eF(a)?1:2;u.push({y:e.priceToY(t),formattedValue:c,value:t,auxValue:a,color:i,halfHeight:Math.round(this.indicatorHeight/d),priority:s})}};this.plots.forEach(e=>{if(e.timeSeries&&e.timeSeries.hasData){if("All"===n||"Main"===n&&e.main){let t=e.main?1:3;ya(e).filter(e=>null!=e.value&&-1!==e.index).forEach(i=>h(e,i.value,i.color,t,i.field,i.index))}e.showPrevious&&h(e,e.getPreviousValue(),r.color,2,aA.PreviousClose,void 0)}}),this.annotations.concat(this.plotAnnotations).forEach(e=>{u.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})))}),u.sort((e,t)=>e.y-t.y),a&&(t=this.viewBox,u.forEach((e,i,s)=>{if(0===i&&e.y-e.halfHeight<t.y)e.y=t.y+e.halfHeight+1;else if(i>0){let r=s[i-1],n=(({y:e,halfHeight:t})=>e-t)(e),a=(({y:e,halfHeight:t})=>e+t)(r);n<a&&(e.y=a+1+e.halfHeight),(({y:e,halfHeight:t})=>e+t)(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}}));let c=({y:t,value:i,formattedValue:r,color:n,auxValue:a})=>{let o,{leftOffset:u,rightOffset:h}=l,c=this.onTheRight?this.pane.viewBox.width-h:u,d=iD(n),p=new yi({position:this.onTheRight?"right":"left",fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:s,textColor:d,strokeColor:n,backgroundColor:n}),f=r||hx(this,i),m=this.comparison===q.Percent;eH(a)&&(o=m?hM(this,a):h_(a)),p.draw(e,c,t,f,o)};a?u.forEach(c):yn.forEach(e=>u.filter(t=>t.priority===e).forEach(c))}}let yl=Symbol.for("__dloacip__");class yu{presenter;id;axes;height;alignedToYear;viewBox;constructor(e){this.presenter=e,this.axes=[],this.height=0,this.alignedToYear=null,this.id=e1()}fromModel(e){this.height=e.height,!0===e.alignOnExpirations&&(this.alignedToYear=function(e){let t=e.map(e=>e.plots).flat().filter(e=>Z[e.type]==Z.Symbol).map(e=>e.symbol).map(e=>tx(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)=>{let i=new yo(this);return i.primary=0===t,i.fromModel(e),i},this)}getBounds(){return this.viewBox}setViewBox(e){this.viewBox=e}drawBackground(e){eF(this.viewBox)&&(this.drawAxes(e),e.save(),this.clipToNoScales(e),this.drawGrid(e),e.restore())}draw(e){eF(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[yl]&&function(e,{x:t,y:i,height:s,width:r}){if(!eH(m0))return;let{path:n,width:a,height:o,rect:l}=m0,u=Math.min(Math.max(50,r/8),a)/a;l.width=a*u,l.height=o*u,l.x=t+5,l.y=i+s-l.height-5,e.save();let 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(n),e.restore()}(e,this.getBoundsWithoutScales())}drawAxes(e){for(let t of this.axes)t.draw(e)}drawPrevious(e){let t=this.presenter.mainPlot;if(t.showPrevious&&this.isMain){let i=t.getPreviousValue();if(null!=(i=t.priceMapper(i,void 0,aA.PreviousClose))){let{leftOffset:s,rightOffset:r}=this.presenter.view,n=this.viewBox.width-r,a=t.axis.yScale.priceToY(i),{color:o,dashStyle:l,lineWidth:u}=this.presenter.display.chart.previous,h=iP(l);e.save(),e.strokeStyle=o,e.lineWidth=u,e.setLineDash(h),ij(e,a,s,n),e.restore()}}}getBoundsWithoutScales(){let e=this.viewBox.duplicate(),t=this.presenter.view;return e.x=t.leftOffset,e.width-=t.leftOffset+t.rightOffset,e}clipToNoScales(e){iO(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();let{chart:{fontFamily:t},yAxis:{fontSize:i}}=this.presenter.display;e.font=`${i??12}px ${t}`;let s=t=>t.draw(e,!0);this.axes.forEach(e=>{e.annotations.forEach(s),e.plotAnnotations.forEach(s)}),e.restore()}drawGrid(e){let{chart:{fontFamily:t},yAxis:{gridLines:i,visible:s,minorGridLines:r}}=this.presenter.display;if(!s||!i.visible)return;let{lineWidth:n,color:a,dashStyle:o}=i;e.save();let l=this.axes[0].plots?.length===0&&this.axes.length>1,u=this.axes[+!!l],{fontWeight:h,fontSize:c}=u.config;e.font=`${h} ${c}px ${t}`;let d=u.getTicks(e),{leftOffset:p,rightOffset:f}=this.presenter.view,m=this.viewBox.width-f,g=(t,i,s)=>{e.lineWidth=t,e.strokeStyle=i,e.setLineDash(iP(s)),e.beginPath()};if(g(n,a,o),d.forEach(t=>{e.moveTo(p,t.y1),e.lineTo(m,t.y2)}),e.stroke(),r&&r.visible&&d.length>=2){let{lineWidth:t,color:i,dashStyle:s}=r,n=(d[0].y1-d[1].y1)/5;g(t,i,s),d.forEach(t=>{for(let i=1;i<5;i++){let s=Math.ceil(t.y1+i*n);e.moveTo(p,s),e.lineTo(m,s)}}),e.stroke()}e.restore()}drawYCrosshair(e,t){let{yAxis:{crosshair:{enabled:i,showValue:s,color:r,dashStyle:n}}}=this.presenter.display;if(!i)return;let a=iP(n);e.strokeStyle=r,e.setLineDash(a);let o=this.presenter.view.leftOffset,l=this.viewBox.width-this.presenter.view.rightOffset,u=iZ();u.prolog(e),ij(e,u.adjust(t.y),u.adjust(o),u.adjust(l)),u.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",iU(e,AA().config.noDataText||tz.NO_DATA_TEXT,{x:this.viewBox.centerX,y:this.viewBox.centerY},Q.Center),e.restore()}get isMain(){let e=this.presenter.mainPlot;return this.axes.some(t=>t.plots.includes(e))}drawPlots(e){e.save();let t=this.presenter.mainPlot,i=this.presenter.display.chart.showNoDataText,s=!eF(i)||i,r=new Map,n=!0,a=i=>{for(let e of this.axes){for(let s of e.plots){let e=s.isEmpty();n=n&&s.main&&e,s===t||e||i(s)}e.plots.includes(t)&&!t.isEmpty()&&i(t)}s&&n&&this.drawNoData(e)};a(t=>t.draw(e)),a(t=>t.drawTopmost(e,r)),e.restore()}}function yh(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}class yc extends f8{timeline;aggregation;marginBars;bar;resetBar;wasZoomed;fitAllData;constructor(e,t){super(),this.timeline=e,this.aggregation=t;let i=e.presenter.display;this.marginBars=i.xAxis.marginBars||0,this.bar=yh(eG(i,tz.DEFAULT_BAR_WIDTH,"chart","bar","width"),eG(i,tz.DEFAULT_BAR_SPACING,"chart","bar","spacing")),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}extent(e){return f7.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);let e=this.display.xAxis.visibleRange;if(eF(e))return this.scaleBarToFitRange([e.from,e.to]);let t=this.display.density;if(Number.isFinite(t))return this.scaleBarToFitDensity(t);let i=this.display.period;if(Number.isFinite(i))return this.scaleBarToFitPeriod(i)}deriveExtentsFromBarWidth(e){if(!eF(this._range)||0===this.timeline.length)return null;let t=this._range[1]-this._range[0],i=Math.ceil(t/e.totalWidth);e.offset=t-i*e.totalWidth;let s=this.timeline.lastSeriesIndex+this.marginBars,r=this._domain&&this._domain[1];return r&&(s=e_(this.timeline,+r,Number,hN)),[s-i+1,s]}adjustDomain(){if(!eF(this._range))return;this.scaleBarToFit();let e=this.deriveExtentsFromBarWidth(this.bar);eF(e)&&(this.extent(e),this.setDomainFromExtent())}xToTime(e){if(!this.ready)return null;let t=Math.floor((e-this._range[0]-this.bar.offset)/this.bar.totalWidth),i=this._extent[0]+t;return this.timeline.at(i)}timeToIndex(e){return this.ready?(e="number"==typeof e?e:+e,e_(this.timeline,e,Number,hN)):null}indexToX(e){let 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;let t=this.timeToIndex(e);return this.indexToX(t)}zoom(e){let t=e*this.bar.width/100,i=this.bar.width-t,s=this.bar.spacing-e*this.bar.spacing/100;if(i>tz.MAXIMUM_BAR_WIDTH||i<tz.MINIMUM_BAR_WIDTH)return!1;let r=yh(i,s),n=this.deriveExtentsFromBarWidth(r);return!!this.isUsableExtent(n)&&(this.setBar(i,s),this.adjustDomain(),this.wasZoomed=!0,!0)}scaleBarToFitRange(e,t=!0){let i=(e,t,i,s)=>eF(e)?e_(this.timeline,e,Number,hN,i,s):t,{from:s,to:r}=this.presenter.data.range||{},n=+e[0]===s&&+e[1]===r,{firstSeriesIndex:a,lastSeriesIndex:o}=this.timeline,l=n?a:void 0,u=n?o:void 0,h=[i(e[0],a,l,u),i(e[1],o,l,u)];this.timeline.at(h[1])>e[1]&&(h[1]=Math.max(0,h[1]-1)),this.extent(h),this.scaleBarToFitDensity(h[1]-h[0]+1,t)}scaleBarToFitDensity(e,t=!0){let i=Math.max(tz.MINIMUM_BARS_VISIBLE,e),s=t&&this.display.xAxis.marginBars||0,r=(this._range[1]-this._range[0])/(i+s);this.setBar(2/3*r,1/3*r,!1)}scaleBarToFitPeriod(e){let t=this.timeline.lastSeriesIndex,i=this.timeline.at(t),s=i,r=t,n=this.presenter.data.aggregation;if(n.isEndOfDay||n.isIntraday&&e>=tz.INTRA_THRESHOLD)for(;r>0&&uM(i,s)<e;)r--,s=this.timeline.at(r);else if(!n.isTick){let t=Math.floor(e/tz.ONE_DAY_MILLIS),s=e=>gO(e,tl(e)),n=s(i),a=i;for(;r>0;){let e=this.timeline.at(r),i=nT(e,a);if(0===t){if(s(e)<=n||!i)break}else i||(t--,a=e);r--}}this.scaleBarToFitDensity(t-r+1)}setBar(e,t,i=!0){let[s,r]=e0(e,t,tz.MINIMUM_BAR_WIDTH,tz.MAXIMUM_BAR_WIDTH);this.bar.width=s,this.bar.spacing=r,this.wasZoomed||(this.resetBar={width:s,spacing:r}),i&&(this.presenter.model.display.chart.bar={width:e,spacing:t})}resetZoom(){eF(this.resetBar)?(this.bar.width=this.resetBar.width,this.bar.spacing=this.resetBar.spacing):(this.bar.width=tz.DEFAULT_BAR_WIDTH,this.bar.spacing=tz.DEFAULT_BAR_SPACING),delete this.presenter.model.display.chart.bar,this.adjustDomain()}isUsableExtent(e){return eF(e)&&eF(e[0],e[1])&&e[0]>=0&&e[1]<this.timeline.withPrologEpilogLength&&e[1]-e[0]>=tz.MINIMUM_BARS_VISIBLE}shiftBars(e,t=null){if(!this._extent)return;let i=this._extent.map(t=>t+e);this.isUsableExtent(i)&&(eF(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;let t=e%this.bar.totalWidth,i=this.bar.offset+t,s=Math.sign(e),r=-(e<0?Math.ceil:Math.floor)(e/this.bar.totalWidth);(i>this.bar.totalWidth||i<-this.bar.totalWidth)&&(r+=i>0?-1:1,i-=s*this.bar.totalWidth),this.shiftBars(r,i)}getSeriesThatCouldLoadMoreData(){let e=this.domain();if(!eF(e)||!eF(e[0]))return[];let t=e[0].getTime();return this.timeline.presenter.allPlots.map(e=>e.timeSeries).filter(e=>!!eF(e)&&!!e.hasData&&0!==e.container.size&&!0===e.canLoadMoreData&&t<=e.container.getTimeData()[0].getTime())}}function yd(e){return{date:e,priority:1,text:hL(e)}}class yp{view;xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;viewBox;overrideTickGetter;overrideFormatter;contractParityCache;contractParityCacheKey;constructor(e){this.view=e,this.contractParityCache=null,this.contractParityCacheKey=null,this.xScale=new yc(e.presenter.timeline,e.presenter.data.aggregation),this.ticks=null,this.lastUsedOptions=null,this.wasPanned=!1,this.panningXAxisAllowed=eG(e.presenter.display,!0,"xAxis","panning"),this.updateConfigFromModel();let t=e.presenter.renderTo.id,i=eG(AA().config,null,"overrides","xAxis","tickProvider");eF(i)&&"function"==typeof i&&(this.overrideTickGetter=eh(i,t));let s=eG(AA().config,null,"overrides","xAxis","formatter");eF(s)&&"function"==typeof s&&(this.overrideFormatter=eh(s,t))}updateConfigFromModel(){let{chart:{fontFamily:e,backgroundColor:t,fontSize:i},xAxis:{textColor:s,visible:r,fontSize:n,crosshair:{color:a}}}=this.view.presenter.display;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:n||i||12},this.isVisible=r,this.crosshairIndicator=new yi({position:"bottom",fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:a,textColor:s,backgroundColor:i_(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();let e=this.view.presenter.display.period===tz.FIFTY_YEARS_MILLIS;eF(this.xScale.extent())&&!e&&this.checkForMoreData()}zoom(e){let t=this.xScale.zoom(e);return this.checkForMoreData(),t}checkForMoreData(){this.xScale.getSeriesThatCouldLoadMoreData().forEach(e=>e.loadMoreData())}shouldScrollIntoView(e){let t=this.xScale.extent();return!!eF(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(){let e=this.xScale.timeline.lastSeriesIndex+this.getMaxCurveOffset(),t=this.xScale.extent(),i=t?t[1]:e;return e-i}canGoToLast(){return this.barsToLast>0}getMaxCurveOffset(){return Math.max(...this.view.presenter.allCurves.map(e=>e.shift))}goToLatest(e=!1){if(this.canGoToLast()||e){let 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;let{x:t,width:i}=this.viewBox;this.xScale.range([t,t+i])}heightNeeded(e){if(!this.isVisible)return 0;let t=this.view.presenter.display.chart.fontFamily,{fontWeight:i,fontSize:s}=this.config;e.save(),e.font=`${i} ${s}px ${t}`;let{innerTickSize:r,tickPadding:n,indicatorPadding:a}=this.config,o=iF(e,1)+r+n+a;return e.restore(),o}getTickGetter(e){if(this.overrideTickGetter)return this.overrideTickGetter;let t=this.view.presenter.display.xAxis.isOrdinal||!1,i=function(e){switch(e.agg.unit){case G.Tick:return new hT(e);case G.Intraday:return new hv(e,e.agg.size);case G.Day:return new hP(e);case G.Week:return new hC(e);case G.Month:case G.Quarter:return new hb(e);case G.Year:return new hE(e);default:throw Error(`Aggregation unit ${G[e.agg.unit]} not supported.`)}}(e);return t?yd:e=>i.getTick(e)}getTicks(e){let t,i;if(eF(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&&eF(this.ticks))return this.ticks;this.lastUsedOptions=e;let s=this.getTickGetter(e),r=Math.max(0,e.extent[0]),n=Math.min(this.xScale.timeline.withPrologEpilogLength-1,e.extent[1]+1);return this.ticks=this.view.presenter.timeline.slice(r,n).map((e,t)=>{if(!eF(e)||Number.isNaN(e.getTime()))return null;let i=s(e);return eF(i)&&(i.index=r+t),i}).filter(e=>eF(e)),this.ticks}normalizeDuration(e){let t=function(){let e=Object.keys(hd);return 1===hd.Day.Multipliers[0]&&e.forEach(e=>{let t=hd[e],i=eQ(t.Period);t.One=+i,t.Multipliers=t.Multipliers.map(e=>e*i)}),hd}(),i=t.Year,s=Object.keys(t);for(let r=0;r<s.length-1;++r){let n=t[s[r]].Multipliers,a=t[s[r+1]].Multipliers;if(e<=(eC(n)+eb(a))/2){i=t[s[r]];break}}let r=i.Multipliers,n=r.findIndex(t=>e<t),a=-1===n?eC(r):r[n];return"P1M"===i.Period?a*=.9:"P1W"===i.Period&&(a*=.84),a}draw(e){if(!this.isVisible)return;let{xAxis:{gridLines:t,textColor:i,minTickInterval:s,tickPixelInterval:r,format:n,forceTicksVisible:a},chart:{fontFamily:o}}=this.view.presenter.display,{fontWeight:l,fontSize:u,innerTickSize:h,tickPadding:c}=this.config,{x:d,y:p,width:f}=this.viewBox,{lineWidth:m,color:g,dashStyle:y}=t,A=iP(y);e.textAlign="center",e.font=`${l} ${u}px ${o}`,e.lineWidth=1,e.strokeStyle=g,e.fillStyle=i,e.setLineDash([]),ij(e,p,d,d+f);let S=this.xScale.extent(),T=e=>!eF(e)||!eF(e[0],e[1]);if(T(S))return;let v=t=>e.measureText(t).width,P=r>0?r:120,C=this.xScale.domain();if(T(C))return;let b=(C[1].getTime()-C[0].getTime())*P*.6/f,E=this.normalizeDuration(b),L=this.view.presenter.data.aggregation.isEndOfDay,_=d+f,M=({text:i,x:s,date:r,forced:n})=>{eF(r)&&(n||iY(e,s,p,p+h),e.fillText(i,s,p+h+c+.71*u),t.visible&&!n&&(e.save(),e.lineWidth=m,e.setLineDash(A),iY(e,s,0,p),e.restore()))},x={agg:this.view.presenter.data.aggregation,unitWidth:v("M"),barWidth:this.xScale.bar.width,extent:S,formatString:n,minTickInterval:s||0,duration:b},D=this.getTicks(x),I={date:tz.ZERO_DATE,priority:999,x:-999,text:"",index:-1,textWidth:0};D.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=v(e.text);let{x:t,textWidth:i}=e,r=t;if(a){let s=i/2;e.x=r=(r=t-s<d?d+s:t)+s>_?_-s:r,e.forced=t!==r}else e.forced=!1;((e,t)=>{let i,r;if(e.date.valueOf()===tz.ZERO_DATE.valueOf())return!0;if(i=e.date,r=t.date,(eF(i)?uM(r,i):tz.FIFTY_YEARS_MILLIS)<s)return!1;let n=t.x-e.x,a=t.date.getTime()-e.date.getTime();return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(n>P||!!L&&a>=E)})(I,e)?(M(I),I=e):e.priority<I.priority&&(I=e)}),M(I),this.drawTimeTransitions(e),this.drawTimeAdornments(e)}drawTransitionsFor(e,t,i,s,r){let n=this.xScale.domain(),a=this.view.presenter?.mainPlot?.timeSeries.container;if(!eH(a))return;let o=a.getTimeData(),l=null===t?o:a.getData(t);if(!eF(l))return;let u=e_(o,+n[0],Number),h=e_(o,+n[1],Number,eL,u);if(u<h){let t=this.viewBox.y,n=this.view.leftOffset,a=this.viewBox.x+this.viewBox.width;if(s.save(),r){s.fillStyle=e.fillColor;let c=l[u],d=Math.max(n,this.xScale.timeToX(o[u]));for(let e=u+1;e<=h;++e){let n=e<l.length?l[e]:null;if(e===h||i(n,c)){let i=e<o.length?o[e]:null,l=eH(i)?this.xScale.timeToX(i):a;l=Math.min(l,a),r(c)%2==0&&s.fillRect(d,0,l-d,t),c=n,d=l}}}let c=iZ();c.prolog(s),s.strokeStyle=e.color,s.lineWidth=e.width,s.setLineDash(iP(e.dashStyle));let d=null;for(let e=u;e<h;++e){let r=l[e];if(i(r,d)){let i=o[e],n=this.xScale.timeToX(i);eF(n,d)&&iY(s,n,0,t),d=r}}c.epilog(s),s.restore()}}drawTimeTransitions(e){let t=this.xScale.domain();if(!eH(t)||!eF(t[0],t[1]))return;let i=this.view.presenter,{xAxis:{contractTransition:s,cycleTransition:r}}=i.display,n=(e,t)=>e!==t;if(s.enabled&&i?.data?.aggregation.isMultiContract){let t=i?.mainPlot?.timeSeries.container,r=t?.getData(aA.Symbol);if(r&&r.length>0){let t=r[0];if(this.contractParityCacheKey!==t||!this.contractParityCache){let e=[...new Set(r)];e.sort((e,t)=>{let i=tx(e),s=tx(t);return(i?.getTime()??0)-(s?.getTime()??0)});let i=0;if(this.contractParityCache)for(let t=0;t<e.length;t++){let s=e[t],r=this.contractParityCache.get(s);if(void 0!==r){i=+((r-t)%2!=0);break}}this.contractParityCache=new Map,e.forEach((e,t)=>this.contractParityCache.set(e,t+i)),this.contractParityCacheKey=t}let i=e=>this.contractParityCache.get(e)??0;this.drawTransitionsFor(s,aA.Symbol,n,e,i)}}r.enabled&&(i?.data?.aggregation.isIntraday?this.drawTransitionsFor(r,aA.TradingDay,n,e,e=>e):i?.data?.aggregation.unit===G.Day?this.drawTransitionsFor(r,null,(e,t)=>!nv(e,t),e,e=>e.getMonth()):i?.data?.aggregation.unit===G.Week&&this.drawTransitionsFor(r,null,(e,t)=>!n_(e,t),e,e=>e.getFullYear()))}getAnnXScore(e,t){return[nT,nL,nv,n_].map((i,s)=>(4-s)*Number(i(e,t))).reduce((e,t)=>e+t,0)}annTimeToX(e){let t=this.xScale.timeToIndex(e);if(!eH(t))return null;let i=this.xScale.timeline.at(t),s=this.xScale.timeToX(e);if(!(t>0)||i.valueOf()===e.valueOf())return s;{let r=t-1,n=this.xScale.timeline.at(r),a=this.xScale.indexToX(r);if(!this.view.presenter.display?.xAxis?.isOrdinal){if(n.valueOf()>e.valueOf())return s;let t=this.getAnnXScore(n,e),r=this.getAnnXScore(i,e);return t>r?a:r>t?s:this.view.presenter?.data?.aggregation?.isIntraday?a:s}return a+(s-a)*((e.valueOf()-n.valueOf())/(i.valueOf()-n.valueOf()))}}drawTimeAdornments(e){e.save();let t=this.view.presenter,{chart:{fontFamily:i},xAxis:{preventLabelOverlap:s}}=t.display,r=[],n=t.mainPane?.getBoundsWithoutScales()??new iw(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).forEach(i=>{r.push(...i.getTimeScaleAdornments().map(i=>{let s=this.annTimeToX(i.time);if(s<n.x||s>n.x+n.width)return null;let r=hD(t,this.view.presenter?.display?.xAxis?.isOrdinal?i.time:this.xScale.xToTime(s)),a=e.measureText(r).width/2;return{x:s,value:r,color:i.color,halfWidth:a}}).filter(e=>null!=e))}),r.sort((e,t)=>e.x-t.x),s&&function(e,t){let i=e.length-1;e.forEach((e,s,r)=>{let n=0===s,a=n?null:r[s-1],o=(({x:e,halfWidth:t})=>e-t-4)(e),l=n?t.x:(({x:e,halfWidth:t})=>e+t+4)(a);if(e.x-e.halfWidth<t.x&&(e.x=yr(t.x,e.halfWidth)),o<l)e.x=yr(l,e.halfWidth+4);else{let t=(({x:e,halfWidth:t})=>e+t+4)(e),n=s<i?(({x:e,halfWidth:t})=>e-t-4)(r[s+1]):Number.MAX_SAFE_INTEGER;if(t>n){let i=ys(e.x,t-n),s=ys(e.x,e.halfWidth-2);e.x=Math.max(s,i,yr(l,a?.halfWidth??0))}}(({x:e,halfWidth:t})=>e+t+4)(e)>t.x+t.width&&(e.x=ys(t.x+t.width,e.halfWidth))})}(r,this.viewBox),r.forEach(t=>{let s=iD(t.color);new yi({position:"bottom",fontSize:this.config.fontSize,fontFamily:i,padding:this.config.indicatorPadding,strokeColor:tz.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}){let i=this.view.presenter,s=i.display.xAxis,{enabled:r,showValue:n,color:a,dashStyle:o,format:l}=s.crosshair,u=this.xScale.xToTime(t);if(!(eF(u)&&oE(u)))return!1;if(!r)return!0;t=this.xScale.timeToX(u);let h=iP(o);e.strokeStyle=a,e.setLineDash(h);let c=iZ();if(c.prolog(e),iY(e,c.adjust(t),0,c.adjust(this.viewBox.y)),c.epilog(e),!n||!s.visible)return!0;let d=hD(i,u,eF(s.format)?l:void 0);this.crosshairIndicator.draw(e,t,this.viewBox.y+1,d,void 0,this.viewBox.height-2);let{plotHover:p}=i.display.chart;return p&&i.allPlots.filter(e=>e.visible).forEach(i=>i.curves.forEach(i=>i.drawHover(e,u,t))),!0}}let yf={mousedown:"onMouseDown",mousemove:"onMouseMove",mouseup:"onMouseUp",dblclick:"onMouseDblClick",contextmenu:"onContextMenu",mouseover:"onMouseEnter",mouseout:"onMouseLeave",wheel:"onWheel",touchstart:"onMouseDown",touchmove:"onMouseMove",touchend:"onMouseUp",keydown:"onKeyDown"},ym={Shift:"shiftKey",Alt:"altKey",Control:"ctrlKey",Meta:"metaKey"};class yg{view;subscriptions;constructor(e){this.view=e,this.subscriptions=[]}init(e){let t=eO();Object.keys(yf).filter(e=>!e.startsWith("touch")||t).forEach(t=>{let i=e=>{let i=yf[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){let i=this.view.presenter;if(void 0===i||null===i.activeTool)return!1;let s=this.getPayload(t,i),r=i.activeTool,n=!1;return"function"==typeof r[e]&&(n=r[e](s)||!1),n}getPayload(e,t){let i=e instanceof MouseEvent,s=eO()&&e instanceof TouchEvent;if(i||s){let r={x:0,y:0};if(s&&1===e.touches.length){let t=e.touches[0],{left:i,top:s}=e.target.getBoundingClientRect();r.x=t.clientX-i,r.y=t.clientY-s}else i&&(r.x=e.offsetX,r.y=e.offsetY);let n={button:i?e.which:et.Left,offset:r,view:t.view,presenter:t,originalEvent:e,getModifier:t=>e[ym[ei[t]]]};if(e instanceof WheelEvent&&(n.delta=e.shiftKey?e.deltaX:e.deltaY),s&&2===e.touches.length){let t=e.touches[0],i=e.touches[1];n.pinchZoom=!0;let s=t.clientX-i.clientX,r=t.clientY-i.clientY;n.pinchDistance=Math.sqrt(s*s+r*r)}return this.view.splitters.forEach((e,t)=>{e.contains(r)&&(n.splitter=[t,t+1])}),t.panes.forEach(e=>{let t=e.getBounds();if(eF(t)&&t.contains(r)){let t=e.axes.find(e=>e.viewBox?.contains(r));t?n.priceAxis=t:n.point=e.axes.find(e=>e.primary).toAnnotationPoint(r)}}),n}if(e instanceof KeyboardEvent)return{key:e.key??e.keyIdentifier,code:e.keyCode||e.charCode,repeat:e.repeat,presenter:t,getModifier:t=>e.getModifierState(ei[t])}}}let yy=ug.concat(aA.PercentChange);class yA{view;id;isOptionsChart;constructor(e){this.view=e,this.isOptionsChart=!1,this.id=`bc-legend-${e1()}`}getLegendElem(){let e=this.view.el;return tH(this.id,e,"div")}update(){let e=this.getLegendElem(),t=hq(this.presenter.mainPane);if(!eF(t))return;this.isOptionsChart=this.mainPlot.title.startsWith(tz.FAKE_SYMBOL_PREFIX);let{left:i,right:s,top:r,width:n}=t;mq(e,"row",i,s,r,n),tF(e,{"bcharts-card":!0,"bcharts-legend":!0});let a=this.mainPlot,o=a.isSeasonal||this.isOptionsChart?this.getFirstColorBadge(a):"",l=this.getPlotTitle(a),u=this.maybeGetQuote(),h=this.div(`${o} ${l} `)+this.div(`${u}`),c=this.maybeGetAdditionalPlots();e.innerHTML=`${h} ${c}`}remove(){this.getLegendElem().remove()}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"";let i=Array.isArray(t)?t.join(" "):t;return`${e} = "${i}" `}).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){let t=yy.map(t=>e.getValue(t));if(ey(t)){let e=t[4],i=`field-${e>0?"up":e<0?"down":"same"}-value`,s=t.slice(0,-1).map((e,t)=>{let s=yy[t],r=this.format(e,s),n=hJ(s);return`${this.spanAsName(n)}${this.spanAsValue(r,i)}`}).join(" "),r=this.spanAsValue(`(${this.format(eC(t),eC(yy))})`,i);return`${s} ${r}`}return""}maybeGetQuote(){if(this.mainPlot.isSymbol&&this.mainPlot.timeSeries?.record?.isValid){let e=AA().getRecordSource().getRecord(this.mainPlot.timeSeries.record.symbol);return this.getQuoteFromRecord(e)}if(this.mainPlot.isExpression&&this.mainPlot.record.isValid){let e=this.mainPlot.record;return e.evaluate(),this.getQuoteFromRecord(e)}return""}getTitle(e,t,i){let s=this.span(`${e.name} (${e.symbol})`,{"data-plot-id":i,class:["value-title",t?"value-main":null]}),r=t?` ${this.span(e.exchange,{class:"value-subtitle"})}`:"";return`${s}${r}`}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))return this.span(e.title,{"data-plot-id":e.id,class:"value-title"});{let t=AA().getMetaDataSource().getMetaData(e.getActualSymbols()[0]);return this.getTitle(t,!0,e.id)}}getFirstColorBadge(e){return hU("rectangle",e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?"":ya(e).filter(e=>eF(e.value)).map(t=>{let 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(){let 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=>{let i=this.getFirstColorBadge(e),s=this.getPlotTitle(e),r=this.canBeDeleted(e)?hj(e.id):"",n="All"===t||e.isSeasonal?"":this.getLastValues(e);return this.div(`${r} ${i} ${s} ${n}`)}).join(" "):""}}class yS{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 yA(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=function(e,t=100){var i,s;let r;return i=t=>eN(e,t),s=t,r=!1,function(...e){r||(i.apply(this,e),r=!0,setTimeout(function(){r=!1},s))}}(aS.CH_CHTLAYOUTCHANGED,tz.LAYOUT_THROTTLE_DELAY)}get canShowLegend(){if(!this.presenter.hasLegend)return!1;let 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=>eF(e)&&e.className===t)}onNonToolHandledMouseDown(e){let t=this.presenter,i=e.target;if("string"==typeof i.className&&i.className.split(" ").includes("value-title"))t.onCardClicked(i);else{let s=this.findSvgParentWithClass(i,"move-pane");if(eH(s))return void t.onMovePaneClicked(s);let r=this.findSvgParentWithClass(i,"delete-plot");if(eH(r))return void t.deletePlotClicked(r);let n=this.findSvgParentWithClass(i,"show-hide-plot");if(eH(n))return void t.showHidePlotClicked(n);let a=this.findSvgParentWithClass(i,"more-actions");if(eH(a))return void t.plotMoreActionsClicked(a,e)}}initialize(e){this.presenter=e,this.el=this.presenter.hostElement;let t=new ResizeObserver(e=>{for(let t of e){let{width:e,height:i}=t.contentRect;this.setSize(e,i),eF(this.tooltip)&&this.tooltip.repositionAuto()}});t.observe(this.el.parentElement),this.listeners.push(()=>t.unobserve(this.el.parentElement));let i=e=>this.onNonToolHandledMouseDown(e);this.el.addEventListener("mousedown",i),this.listeners.push(()=>this.el.removeEventListener("mousedown",i)),tN(this.el,{flex:1,display:"flex",position:"relative","flex-direction":"column","touch-action":"pan-x pan-y"}),this.tooltip=new mY(this);let s=AA().config.getCustomEventPopup;this.customEventPopup=s?s(this):null;let{clientHeight:r,clientWidth:n}=this.el;this.width=n,this.height=r,this.canvasContainer=tB(this.el,"div"),tV(this.canvasContainer,{class:"chart-canvas-container"}),tN(this.canvasContainer,{flex:1,display:"flex","flex-direction":"column",position:"relative",height:"100%"}),this.mainCanvas=tB(this.canvasContainer,"canvas");let a={height:`${r}px`,width:`${n}px`,"z-index":2,position:"absolute",top:0,left:0};tN(this.mainCanvas,a),this.mouseCanvas=tB(this.canvasContainer,"canvas"),tV(this.mouseCanvas,{tabIndex:0}),a["z-index"]=3,a.outline="none",tN(this.mouseCanvas,a),this.goToLatestButton=tB(this.el,"button"),tW(this.goToLatestButton,`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
19
19
  <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>
20
- </svg>`),tN(this.goToLatestButton,{position:"absolute",right:0,bottom:0,"z-index":3}),tV(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 yp(this),this.eventCapture=new yg(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(n,r);let o=tO(this.el);eF(tR(`.${tz.SVG_ICONS_DOM_NODE}`,o))||function(e){let t=tB(e,"div");tV(t,{class:tz.SVG_ICONS_DOM_NODE});let i=Object.keys(hH).map(e=>`<symbol id="${hW(e)}" viewBox="0 0 1024 1024">${hH[e]}</symbol>`).join("");t.innerHTML=`<svg style="display:none" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>${i}</defs></svg>`}(o)}reinitialize(){this.el&&tk(".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 yp(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,i=!1){this.setChartSize(e,t),this.redraw(i)}setChartSize(e,t){let i={width:`${e}px`,height:`${t}px`};tN(this.el,i),this.width=e,this.height=t;let s=globalThis.devicePixelRatio||1,r={height:this.height*s,width:this.width*s};[this.mainCanvas,this.mouseCanvas].forEach(e=>{tV(e,r),tN(e,i)}),this.mainContext.scale(s,s),this.mouseContext.scale(s,s),this.recalculateLayout(),this.presenter&&mj(this.presenter)}widthNeeded(e,t){let 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;let e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),i=this.widthNeeded(this.mainContext,!1),s=this.height-e,r=this.presenter.panes,n=em(r.map(e=>e.height)),a=0,o=tz.PANE_SPLITTER_PERCENT_HEIGHT/100,l=Math.floor(o*s);n*=1+(r.length-1)*o;let u=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;this.presenter.display.yAxis.visible&&(r.some(e=>e.axes.length>1)?(this.leftOffset=i,this.rightOffset=t):u?this.leftOffset=i:this.rightOffset=t),r.forEach((e,i,r)=>{let o=i===r.length-1,u=Math.floor(s*e.height/n),h=new iw(0,a,this.width,u);e.setViewBox(h);let c=new iw(this.width-this.rightOffset,a,t,u),d=new iw(0,a,this.leftOffset,u),p=e=>e.setViewBox(e.onTheRight?c:d);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),a+=u,!o){let e=new iw(this.leftOffset,a,this.width-this.rightOffset-this.leftOffset,l);this.splitters.push(e),a+=l}});let h=new iw(this.leftOffset,a,this.width-this.rightOffset-this.leftOffset,e);this.xAxis.setViewBox(h),tN(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(){for(let e of(this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext),this.presenter.panes))e.drawBackground(this.mainContext);for(let e of(this.xAxis.draw(this.mainContext),this.presenter.panes))e.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext);let e=AA().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart,i=eF(e)?e:t;this.goToLatestButton.style.display=i&&this.xAxis.canGoToLast()?"block":"none",this.mainContext.restore()}get isHostElementVisible(){return eF(this.el)&&eF(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():AA().redraw(this.presenter.hostElement))}drawBackground(e){let 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}){let i=this.mouseContext;return i.clearRect(0,0,this.width,this.height),!!e&&!!this.xAxis.drawCrosshair(i,t)&&(this.presenter.display.yAxis.visible&&e.axis.pane.drawYCrosshair(i,t),!0)}drawSplitters(e){e.strokeStyle=(e=>{let t=iM(e);return iI(iE(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.lineWidth=2,this.splitters.forEach(t=>{let{x:i,y:s,width:r,height:n}=t,a=s+n/2;e.beginPath(),e.moveTo(i,a),e.lineTo(i+r,a),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){let t=function(e){switch(e){case ee.Arrow:default:return"default";case ee.Crosshair:return"crosshair";case ee.Hand:return"pointer";case ee.Move:return"move";case ee.ResizeVertical:return"ns-resize";case ee.Grabbing:return"grabbing";case ee.ResizeHorizontal:return"ew-resize"}}(e);tN(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&tk(".bcharts-card",this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){return Math.max(this.xAxis.xScale.bar.width/2,tz.MIN_EVENT_RADIUS)}}class yT{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=tB(this.view.el,"div"),tV(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),tN(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"});let e=tB(this.popupElement,"a");tV(e,{class:"custom-event-close-button"}),tN(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()),tN(this.popupElement,{visibility:"visible",top:`${e.y}px`,left:`${e.x}px`,width:"310px"}),this.visible=!0}hideValue(){}hide(){this.visible&&(this.hideValue(),tN(this.popupElement,{visibility:"hidden"}),this.visible=!1)}}function yv(e,t){if(!(e.annotations&&e.annotations.length>0))return;let i=t.annotations||[];t.annotations=i.concat(e.annotations)}let yP='..axes{..plots{.type==="Study"}}';var cm=N("c15IW");let yC={ok:!1,change:void 0,toApply:void 0};class yb{presenter;paused;undoStack;redoStack;initial;isPaused;constructor(e){this.presenter=e,this.paused=null,this.undoStack=[],this.redoStack=[],this.initial=new Map,this.isPaused=!1,this.clear()}clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,mT(e,el.Moved)))}done(e){if(this.isPaused){this.paused=e;return}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&&eH(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){let t={...e,id:"Delete"};this.presenter.handleAnnotationChange(t)}add(e){this.presenter.handleAnnotationChange({annotation:e,id:"Add"})}apply(e,t,i){if(!eF(e))return!1;switch(t){case el.None:case el.Undo:case el.Redo:Ad(`Unexpected tool change ${el[t]} for undo/redo`,"warn");break;case el.Created:i?this.delete(e):this.add(e);break;case el.Deleted:i?this.add(e):this.delete(e);break;default:{let t={...e,id:"Update"};this.presenter.handleAnnotationChange(t)}}let s=this.presenter.allAnnotations.find(t=>t.uid===e.uid),r=i?el.Undo:el.Redo;return eF(s)&&this.presenter.onAnnotationModifiedByTool(s,r),!0}can(e){let t=e?this.undoStack:this.redoStack;if(t.length<1)return yC;let i=eC(t),s=i.toolChange;if(!(e&&s!==el.Deleted&&s!==el.Created))return{ok:!0,change:s,toApply:i};let r=eE(t,e=>e.uid===i.uid,t.length-2),n=-1!==r?t[r]:null,a=null===n;return a&&!this.initial.has(i.uid)?yC:{ok:!0,change:s,toApply:a?this.initial.get(i.uid):n}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,i){let{ok:s,change:r,toApply:n}=this.can(i);if(!s)return;let a=e.pop();this.apply(n,r,i),t.push(a)}}class yE{presenter;text;align;verticalAlign;x;y;style;constructor(e){this.presenter=e,this.text=null,this.align="center",this.verticalAlign="top",this.x=0,this.y=0,this.style={color:"#333",fontSize:18}}update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;let{fontFamily:t}=this.presenter.display.chart,{fontSize:i,color:s,fontWeight:r}=this.style,{x:n,y:a,width:o,height:l}=this.presenter.mainPlot.axis.pane.getBounds(),u=n+this.presenter.view.leftOffset,h=n+o-this.presenter.view.rightOffset,c=u;c="center"===this.align?o/2:"right"===this.align?h:u;let d=a+i;"middle"===this.verticalAlign?d=a+i+l/2:"bottom"===this.verticalAlign&&(d=a+l),c+=this.x,d+=this.y,e.save(),e.font=`${r||"normal"} ${i}px ${t}`,e.textAlign=this.align,e.textBaseline="bottom",e.fillStyle=s,e.fillText(this.text,c,d),e.restore()}}function yL(e={}){let t=this.allPlots;if(!t.every(e=>eF(e.timeSeries)&&e.timeSeries.hasData))return"No data to export";let i=e.excludeHeader??!1,s=e.numDecimals??null,r=e.excludeFields??[],n=e=>{let t=new Map;return e.main&&(t.set(aA.DateTime,0),this.data.aggregation.isMultiContract&&!e.isExpression&&t.set(aA.Symbol,0)),e.curves.forEach(e=>{e.fields.forEach(i=>{r.includes(i.id)||t.set(i,e.shift)})}),Array.from(t)},a=this.data.aggregation.isEndOfDay?tz.FMT_ISO_DATE_ONLY:tz.FMT_EXPORT_ALL_BUT_MILLIS,o=(e,t)=>e===aA.DateTime?o5(t,a):(eF(s,t)?eB(t,s):t)?.toString()??"",l={},u=this.timeline.lastSeriesIndex,h=eb(this.mainPlot.timeSeries.container.getTimeData()),c=e_(this.timeline,+h,Number,hN),d=(e,t)=>{let i=this.timeline.at(e),s=t.timeSeries.container,r=s.getTimeData(),u=e_(r,+i,Number,eL,l[t.id]||0),h=+i==+r[u];return h&&(l[t.id]=u),n(t).map(([t,n])=>{if(0===n)if(h)return o(t,s.getData(t)[u]);else if(t===aA.DateTime)return o5(i,a);else return"";{let i=this.timeline.at(e-n),a=e_(r,+i,Number,eL,0);return+i==+r[a]?o(t,s.getData(t)[a]):""}})},p=e=>{let i=t.map(e).flat();return i.slice(1).every(e=>0===e.length)?null:i.join(",")},f=[];i||(f.push(p(e=>{let t=Array(n(e).length).fill("");return t[0]=`"${Z[e.type]}: ${e.title}"`,t})),f.push(p(e=>n(e).map(([e,t])=>`"${e.name}"`))));let m=[0,0];this.allCurves.forEach(e=>{!e.fields.every(e=>r.includes(e.id))&&(e.shift<0&&(m[0]=Math.min(m[0],e.shift)),e.shift>0&&(m[1]=Math.max(m[1],e.shift)))});for(let e=c+m[0];e<=u+m[1];e++){let t=p(eh(d,e));null!==t&&f.push(t)}return f.join("\n")}function y_(e={}){let t=this.view.mainCanvas,{width:i,height:s}=t,{width:r,height:n,title:a}=e,o=(e,t)=>{let i=document.createElement("canvas");return i.width=e,i.height=t,i.getContext("2d")},l=o(i,s),u=globalThis.devicePixelRatio;if(l.drawImage(t,0,0),l.scale(u,u),eH(a)){let e=new yE(this);e.update(a),e.draw(l)}let h=this.mainPlot?.timeSeries.container?.getLastDataPoint(aA.DateTime);if(eH(h)){let{fontFamily:e}=this.display.chart,{fontWeight:i,fontSize:s}=this.mainAxis.config;l.font=`${i} ${1.2*s}px ${e}`,l.textBaseline="top";let r=1.5*s,n=getComputedStyle(t),a=n.getPropertyValue("--app-hc-color"),o=n.getPropertyValue("--app-color-pl"),u={x:tz.CARDS_X_OFFSET,y:tz.CARDS_Y_OFFSET},c=hK(this,h,u,void 0,!1,0),d=`${c.date} ${c.time??""}`.trim(),[p,f]=[1,5],m=(e,t)=>l.measureText(e).width+t,g=(e,t,i,s,r)=>(l.fillStyle=s,l.fillText(e,t,i),m(e,r)),y=(e,t)=>e.type===Z[t];c.panes.forEach(e=>{let{top:t,left:i,width:s,right:n}=e.bounds,l=i+s-n-f,h=i+u.x,c=t+u.y;e.plots.some(e=>e.isMain)&&(h+=g(d,h,c,a,f)),e.plots.forEach((e,t)=>{let s,n=(s=e.name,e.isMain&&y(e,"Symbol")?s=`${e.description} (${e.name}) [${e.exchange}]`:y(e,"Study")&&(s=`${e.description} ${e.name.substring(e.name.indexOf(" "))}`),s),d=!y(e,"Study")&&e.values.length>1;if(!e.isMain&&t>0){let t=h+m(n,f);e.values.forEach(e=>{d&&(t+=m(e.abbreviation,p)),t+=m(e.value,f)}),t>=l&&(h=i+u.x,c+=r)}h+=g(n,h,c,a,f),e.values.forEach(e=>{d&&(h+=g(e.abbreviation,h,c,o,p)),h+=g(e.value,h,c,e.color,f)})})})}let c=e=>({width:r??i,height:n??s,data:e.toDataURL("image/png")});if(!(eH(r)&&eH(n)))return c(l.canvas);{let e=o(r,n);return e.drawImage(l.canvas,0,0,r,n),c(e.canvas)}}let yM=Symbol.for("__ias__");class yx{accessor;view;defaultTool;_activeTool;tooltipEnabled;timeline;sentInitialLoadNotification;_hostElement;undoRedoManager;title;display;model;data;panes;_hasLegend;renderTo;seriesChangedToken;metaChangedToken;streamingSubscription;_previousMask;_ohlcMask;selectedAnnotation;forceResetVisibleRange;_maxOffset;_isShutdown;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.tooltipEnabled=!0,this.sentInitialLoadNotification=!1,this._hostElement=null,this.panes=[],this.seriesChangedToken="",this.metaChangedToken="",this.streamingSubscription=null,this._previousMask=0,this.forceResetVisibleRange=!1,this._maxOffset=0,this._isShutdown=!1,this.defaultTool=gJ("Default"),this._activeTool=this.defaultTool,this.timeline=new hV(this),this.undoRedoManager=new yb(this),this.title=new yE(this),this.notifySelectionChanged=eV(aS.CH_ANNSELECTIONCHANGED),this.notifyRecreated=eV(aS.CH_RECREATED),this.notifyDefinitionChanged=eV(aS.CH_DEFINITION_CHANGED)}getModel(){return this.model}get isEmpty(){return!eF(this.model)}notifyHost(e,t){eN(e,t)}async fromModel(e,t){if(this._isShutdown)return;eF(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearSelection(),this.model=e;let i=ez(e);this.data=i.data,this.data.aggregation=nx(i.data.aggregation),this.display=i.display,eF(this.display.period)&&(this.display.period=eQ(this.display.period)),this.panes=i.panes.map(e=>{let t=new yu(this);return t.fromModel(e),t},this);let s=this.allPlots.map(e=>e.initialize());await Promise.all(s),this._isShutdown||(this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),eF(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{let i=!t||function(e,t,i){let s={id:"Aggregation",context:{id:"Get"}};if(yO(nM(Ae(s,t,i)),nM(Ae(s,e,i)))||!yD(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!yD(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;let r=n5(t),n=n5(e);if(function(e,t){let i=e=>e.curves[0],s=i(e),r=i(t),n=yI.includes(s.style),a=yI.includes(r.style);if(n!==a)return!0;if(!a)return!1;if(s.style!==r.style)return!0;if(t.inputs&&yO(eK(e.inputs),eK(t.inputs)))return!0;return!1}(r,n))return!0;let a=e=>{let t=e.toLowerCase();return n.type===e&&r.type===e&&r[t]!==n[t]},o=r.type!==n.type,l=a("Forward"),u=a("Expression"),h=a("Symbol");return o||l||u||h}(e,t,this);this.view.resetZoomAndVisibleRange=i,i&&(this._maxOffset=0)}}closeView(){eF(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(eF(this.view)?this.view.reinitialize():(this.view=new yS,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){eF(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,eF(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(aS.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(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let 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(){let 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(){let 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;let i=t.series,s=e=>e.timeSeries===i||e.eventsSeries===i,r=this.allPlots.find(s);if(!eF(r))return;let n=eF(r)&&r.main,a=!1,o=!1;if(e===aS.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;a=!0}let l=eF(t.index)?i.container.getTimeData()[t.index]:null,u=e===aS.TS_EVENTSCHANGED,h=this.view.xAxis,c=h.xScale;if(e===aS.TS_MANYCHANGED||u){if(n&&this.data.checkRange)if(eF(this.display.xAxis.visibleRange)){let e={id:"Period",context:{range:this.display.xAxis.visibleRange}};e[yM]=!0,this.accessor.change(e);return}else delete this.data.checkRange;r.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;if(r.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,h.goToLatest(!0)),r.invalidateAssociatedAnnotations("NewChunkArrived")),(r.isSeasonal&&!h.wasVisibleRangeChanged||this.display?.xAxis?.isOrdinal)&&h.goToLatest(!0),t.part===en.Tail){let e=e_(this.timeline,l,Number,hN);h.shouldScrollIntoView(e)&&c.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),a=!0}else if(e===aS.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(l);-1!=e&&h.shouldScrollIntoView(e)?(c.shiftBars(1),a=!0):o=!0,r.isStudy&&r.invalidateAssociatedAnnotations("DataPointAdded")}else e===aS.TS_DATAPOINTCHANGED&&(o=!0,r.isStudy&&r.invalidateAssociatedAnnotations("DataPointChanged"));if(!u&&s(this.mainPlot)&&i.hasData&&0===i.container.size&&this.notifyHost(aS.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),a&&this.view.recalculateLayout(),o&&(a&&Ad("Performance : redundant call to recompute price domains (layout recalculation took care of this)","warn"),this.allAxes.filter(e=>e.plots.includes(r)).forEach(e=>{e.setDomain(),eF(l)&&e.updateFullDomain(l)})),!this.sentInitialLoadNotification&&e===aS.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(aS.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),mj(this);let e=this.display.period===tz.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(c.fitAllData=!0,c.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===aS.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){let t=this.panes.indexOf(e.pane),i=e.pane.axes.indexOf(e),s={chart:this.accessor,paneIndex:t,axisIndex:i};this.notifyHost(aS.CH_AXISSCALECHANGED,s)}get previousMask(){return eF(this._previousMask)||(this._previousMask=av(aA.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return eF(this._hasLegend)||(this._hasLegend=AA().config.mode===er[er.cmdtyView]),this._hasLegend}onStreamingUpdates(e){eF(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 eF(this._ohlcMask)||(this._ohlcMask=av(aA.Open,aA.High,aA.Low,aA.Close,aA.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)==0)return!1;let i=(e,t)=>eH(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 AA().getRecordSource().subject.pipe(uL(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return eF(this._hostElement)?this._hostElement.id:null}initialize(t){if(this._hostElement=t instanceof HTMLElement?t:tR(`#${t}`),!this._hostElement)throw Error(`There is no element ${t} in the DOM`);this.renderTo=t,this.seriesChangedToken=e(cm).subscribe(aS.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=e(cm).subscribe(aS.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return e(cm).unsubscribe(this.seriesChangedToken),e(cm).unsubscribe(this.metaChangedToken),eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(aS.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(){eF(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(ee.Arrow)}print(e={}){let t=tB(document.body,"iframe");t.src="",t.style.display="none",t.onload=()=>{let{title:i}=e,s=y_.call(this,{title:i}),r=new Image;r.src=s.data,r.style.width="100%",t.contentDocument.body.appendChild(r),new Promise(e=>{let t=()=>{r&&void 0!==r.naturalWidth&&0!==r.naturalWidth&&r.complete?e():setTimeout(t,150)};t()}).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),eF(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===tz.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,i=eO();!e&&t.visible&&t.mode===tz.TOOLTIP_CARDS&&tk(".bcharts-card",this.hostElement).forEach(e=>{let t=e.classList.contains("bcharts-card-move");i&&t||e.classList.contains("bcharts-legend")||(e.style.display="none")})}handleAnnotationChange(e){let 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 sz(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);let i=this.allAnnotations.find(t=>t.uid===e.uid);if(void 0!==i){let t=i.axis,s=t[`${e.id.toLowerCase()}Annotation`];if("function"==typeof s){s.call(t,i,e),"Delete"!==e.id||e.isUndoRedo||this.onAnnotationModifiedByTool(i,el.Deleted);return}}throw Error(`Unknown sub-action ${e.id} for action ${tz.ANN_ACTION_ID}`)}getPlotInfoFromDomId(e){let t=e.attributes.getNamedItem("data-plot-id").value,i=this.allPlots,s=i.findIndex(e=>e.id===t);return{type:Z[i[s].type],index:s}}getSimplePlot(e,t){return this.accessor.change({id:"Plot",context:{id:tz.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index),s={chart:this.accessor,plot:i};this.notifyHost(aS.CH_CARDPLOTCLICKED,s)}deletePlotClicked(e){let 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}});let s={chart:this.accessor,plot:i};this.notifyHost(aS.CH_CARDPLOTREMOVED,s)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let 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}});let s=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:s,visible:i};this.notifyHost(aS.CH_CARDPLOTVISIBILITYCHANGED,r)}plotMoreActionsClicked(e,t){let i=this.getPlotInfoFromDomId(e),s=this.getSimplePlot(i.type,i.index),r={x:t.clientX,y:t.clientY},n={chart:this.accessor,plot:s,offset:r,originalEvent:t};this.notifyHost(aS.CH_PLOTNEEDSCONTEXTMENU,n)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem("data-pane").value),i="Down"===e.attributes.getNamedItem("data-dir").value,s=t+ +!!i,r=t-!i;setTimeout(()=>{this.accessor.change({id:"MovePane",context:{from:s,to:r}}),this.notifyHost(aS.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){var i,s;let r=this.allAxes.indexOf(e),n=e.annotations.map(e=>e.toModel()),a=(i=this.model,s={axisIndex:r,annotations:n},sY(i,`..axes[${s.axisIndex}]`,e=>(e.annotations=s.annotations,e)));try{this.model=ad(a,tz.CHART_SCHEMA)}catch(e){Ad(`Cannot update annotation (corrupts definition), error is: ${e.message}`,"error")}t&&this.view.draw(),this.notifyHost(aS.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,i=!0){if(t!==el.None){if(i&&t!==el.Undo&&t!==el.Redo){let i=mT(e,t);this.undoRedoManager.done(i)}let s=mv(e);s.toolChange=el[t],this.notifyHost(aS.CH_ANNMODIFIEDBYTOOL,s)}}onAnnotationDone(e,t){let i={id:e,chart:this.accessor,toolChange:el[t]};this.notifyHost(aS.CH_ANNMODIFIEDBYTOOL,i)}onPaneHeightsUpdated(){var e,t;let i,s=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=(e=this.model,t={paneHeights:s},i=e,t.paneHeights.forEach(e=>{let t;i=sY(i,(t=e.index,`..panes[${t}]`),t=>(t.height=e.relativeHeight,t))}),i),this.notifyHost(aS.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!eF(e)||0===e.size)return null;let t=e.getTimeData();return{dataRange:{from:eb(t).getTime(),to:eC(t).getTime()},barCount:e.size}}}function yD(e,t){return e?.from===t?.from&&e?.to===t?.to}let yI=["Renko","Range","LineBreak","Kagi","PointAndFigure"];function yO(e,t){for(let i of Object.keys(e))if(e[i]!==t[i])return!0}let yw="MARKED_FOR_DELETION";function yR(e,t){if(0===t.plots.length)return e;let i=e;return t.plots.forEach(e=>{let t=yH(e.index),s=yF(i,t);eF(s)&&s.type===e.type&&(i=sY(i,t,e=>(e[yw]=!0,e)))}),ap(i=sY(i,`..plots{.${yw} === true}`,e=>tz.NULL_OBJECT))}function yN(e,{main:t,type:i,index:s},r){let n="..plots{.main === true}",a=sz(e,"..panes").map((e,t)=>{let i=1===sz(e,n).length;return sz(e,"..axes").map((e,s)=>{let a=1===sz(e,n).length;return sz(e,"..plots").map(e=>{let n=function(e,t,i,s){let r=Z[e.type],n={curves:ez(e.curves),type:e.type};n.precision=e.precision,n.visible=e.visible;let a=(e,t)=>{eF(e[t])?n[t]=e[t].map(e=>ez(e)):n[t]=[]},o=(e,t,i=!1)=>{!0===t.main&&(e.main=!0,e.showPrevious=t.showPrevious,i&&null!=t.events&&(e.events=ez(t.events)))},l=(e,t=e=>!0)=>{eF(s)&&(e.subtitles=s.allPlots.filter(e=>e.type===r).filter(t).map(e=>e.title))};switch(r){case Z.Symbol:{n.title=e.symbol;let t=n.curves[0].style,i=t=>{a(e,"inputs"),0===n.inputs.length&&(n.inputs=ez(t))};switch(t){case"Renko":i(tz.DEFAULT_RENKO_INPUTS);break;case"Kagi":i(tz.DEFAULT_KAGI_INPUTS);break;case"PointAndFigure":i(tz.DEFAULT_PNF_INPUTS);break;case"LineBreak":i(tz.DEFAULT_LINEBREAK_INPUTS);break;case"Baseline":i(tz.DEFAULT_BASELINE_INPUTS)}o(n,e,!0);break}case Z.Study:{a(e,"inputs");let s=sR(e.study),r=n.inputs,o="AVWAP"===e.study,l=0===r.length?"":` (${r.map(e=>o&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value).join(", ")})`,u=n.curves.map(e=>Number(e.shift)).filter(e=>e>0),h=0===u.length?"":` [${u.join(", ")}]`;n.title=`${s.id}${l}${h}`,n.studyId=s.id,a(e,"levels"),a(e,"bands"),n.placement=t?i?"overlay":"withMain":"standalone",n.detachedScale=e.detachedScale;break}case Z.BalanceSheet:case Z.IncomeStatement:{let t=aA[e.curves[0].fields[0]];n.title=`${t.name} (${e.fundamental.substring(0,1)})`,n.fundamentalId=t.id,n.frequency=e.fundamental;break}case Z.Expression:n.title=e.expression,o(n,e);break;case Z.Forward:n.title=e.forward,a(e,"offsets"),l(n),o(n,e);break;case Z.Seasonal:n.title=e.seasonal,l(n,e=>e.refSeasonal===n.title),a(e,"offsets"),o(n,e);break;default:throw Error("Unexpected plot type")}return n}(e,i,a,r);return n.paneIndex=t,n.axisIndex=s,n})})}).flat(2).map((e,t)=>(e.index=t,e));if(t)return a.filter(e=>e.main);if(!eF(i))return a;{let e=a.filter(e=>e.type===i);return eF(s)?e.filter(e=>e.index===s):e}}function yV(e,t){"Study"===e.type&&t.curves?.forEach(e=>delete e.varyColorPerBar),function(e){let t=Z[e.type];return t===Z.Forward||t===Z.Seasonal}(e)?eF(t.curves)&&(e.curves=t.curves):function(e,t){if(void 0!==t&&t.length===e.length)for(let i=0;i<e.length;++i){let s=t[i],r=e[i];for(let e of(eY(r,s),["shift","dashStyle","lineSmoothing","lineMarker"])){let t=s[e];eF(t)&&(r[e]=t)}}}(e.curves,t.curves);let i=Z[t.type];eF(t.precision)?e.precision=t.precision:delete e.precision,i===Z.Symbol?e.symbol=t.symbol:i===Z.Study?(function(e,t,i){let s=eK(e),r=eK(t);eY(s,r);let n=Object.keys(r).map(e=>({name:e,value:r[e]}));n.length>0&&(i.inputs=n)}(e.inputs,t.inputs,e),["bands","levels","detachedScale"].forEach(i=>{t[i]&&(e[i]=t[i])})):(i===Z.BalanceSheet||i===Z.IncomeStatement)&&t.frequency?e.fundamental=t.frequency:i===Z.Expression?eF(t.expression)&&(e.expression=t.expression):i===Z.Forward?(eF(t.offsets)&&(e.offsets=t.offsets),eF(t.forward)&&(e.forward=t.forward)):i===Z.Seasonal&&(eF(t.offsets)&&(e.offsets=t.offsets),eF(t.seasonal)&&(e.seasonal=t.seasonal),eF(t.usesInAverage)&&(e.usesInAverage=t.usesInAverage),rs(e))}let yH=e=>`..plots[${e}]`;function yF(e,t){let i=sz(e,t);return 1!==i.length?null:i[0]}let yB=["withMain","overlay","standalone","clone"];function yk(){return{plots:[]}}function yW(e){let t=e.display.chart.newPaneHeight??1;return{axes:[yk()],height:t}}function yU(e){let t=yW(e);return e.panes.push(t),t}function y$(e,t){let i=eH(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:yU(e),s=i.axes[0];return t.oppositeScale?yQ(i,s):s}function yG(e,t,i){let s=null,{mainPane:r,mainAxis:n}=n6(e);switch(t){case"withMain":s=yQ(r,n);break;case"overlay":s=n;break;case"standalone":s=yU(e).axes[0];break;case"clone":if("number"==typeof i){let t={main:!1,index:i,type:Z[Z.Study]},r=yN(e,t).find(e=>e.index===t.index);s=sz(e,`..panes[${r.paneIndex}]..axes[${r.axisIndex}]`)[0]}}return s}let yz=[{fields:[aA.Close.id],colors:["#888"],style:"Line",lineWidth:2,varyColorPerBar:!1,visible:!0}];function yY(e){return"Symbol"===e.type}let yj={attributes:["OpenVsClose"],colors:["#b63400","#007f3e","#1664db"],fields:["Open","High","Low","Close","Change"],style:"Candlestick",varyColorPerBar:!0,lineWidth:1},yK=0,yq=["#0d223a","#8abc21","#910000","#2f7ed8","#42ccdc","#bf95df","#860262","#e5daa3","#4682e8","#aaa9c1","#fcccdc","#f66b00","#d875be","#e84b46"],yX="Symbol";function yZ(e,t){let i={curves:[{attributes:[],colors:yq.slice(yK,yK+1),fields:e?[aA.Last.id]:[aA.Close.id],style:"Line",dashStyle:"Solid",varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0}]};return delete t.oppositeScale,ej(i,t),eF(t.curves)&&eY(i.curves,t.curves),yK=(yK+1)%yq.length,i}let yJ='..plots{(.type === "Symbol" || .type === "Expression") && .main !== true}';function yQ(e,t){let i=e.axes.find(e=>e!==t);return eF(i)||(i=yk(),e.axes.push(i)),i}let y0=()=>tz.NULL_OBJECT;function y1(e){return sY(e,"..axes.annotations",y0)}function y2(e){return ap(sY(e,'..plots{.type === "Symbol" && .main !== true}',y0))}let y3=".display.chart.previous";function y4(e,t,i){let s=[],r=i.allPlots[t.index];if(r?.type!==Z[t.type])return s;let n=i.panes.indexOf(r.axis.pane),a=n===i.panes.length-1,o=1===i.panes[n].axes.reduce((e,t)=>e+t.plots.length,0);return 0!==n&&s.push("ExistingAbove"),o||s.push("NewAbove"),a||s.push("ExistingBelow"),o||s.push("NewBelow"),s}function y5(e,t,i){let s=[],r=i.allPlots[t.index];if(r?.type!==Z[t.type])return s;let n=r.axis.pane,a=r.axis===n.axes[0],o=n.axes.some(e=>e.plots.some(e=>r!==e&&!e.hasDetachedScale)),l=r.hasDetachedScale;return(a||l)&&s.push("SecondaryAxis"),(!a||l)&&s.push("PrimaryAxis"),o&&s.push("NoAxis"),s}function y6(e,t){let i=e.panes[t],s=i.axes.map(e=>e.plots.reduce((e,t)=>e+ +!!t.detachedScale,0)),r=i.axes.length;return i.axes.forEach((e,t)=>{let n=s[t],a=e.plots.length;if(0!==n&&!(n<a)&&n===a)if(r>1&&1===n){let n=(t+1)%r;if(s[n]<i.axes[n].plots.length){let t=e.plots.find(e=>e.detachedScale);t&&(i.axes[n].plots.push(t),e.plots=e.plots.filter(e=>!e.detachedScale),s[n]++)}}else{let t=e.plots.find(e=>e.detachedScale);t&&(t.detachedScale=!1)}}),e}function y7(e,t){let i=e.allPlots[t],s=e.panes.indexOf(i.axis.pane),r=e.panes[s].axes.indexOf(i.axis),n=e.panes[s].axes[r].plots.findIndex(e=>e===i);return{pane:s,axis:r,plot:n}}let y8={MainPlot:as,Aggregation:{Update:aa,Get:function(e,t,i){return ez(e.data.aggregation)}},Period:{Update:function(e,t,i){let s=eF(t.period),r=eF(t.range),n=eF(t.density);if(+!!s+ +!!r+ +!!n>1)throw Error("Cannot set more than one of: period, range, density.");if(s&&(e.display.period=t.period,nH(e),nB(e)),r)if((!eF(e.display.period)||au(e.display.period))&&(e.display.xAxis.visibleRange=t.range),nF(e),nB(e),eF(i)){let s=function(e){let t=e.getDataStats();return null===t?null:t.dataRange}(i),r=nx(e.data.aggregation),n=i.data.aggregation,a=r.unit!==n.unit||r.size!==n.size||r.spec!==n.spec||!eF(s)||e.data.checkRange,o=a;if(!a){let{from:e,to:i}=s,{from:r,to:n}=t.range;o=r<e||r>i||n<e||n>i}o&&(e.data.range=t.range),delete e.data.checkRange}else e.data.checkRange=!0;return n&&(e.display.density=t.density,nH(e),nF(e)),(s||r||n)&&(nV(e),i&&(i.forceResetVisibleRange=!0)),e},Delete:function(e,t,i){return eF(t.period)&&t.period&&(delete e.display.period,ar(e),i&&(i.forceResetVisibleRange=!0)),e}},Crosshair:{Update:function(e,t){let[i,s]=eW(t.crosshair),{color:r,dashStyle:n}=t.horizontal||{},{color:a,dashStyle:o}=t.vertical||{},l=(e,t,i)=>{t&&(e.color=t),i&&(e.dashStyle=i)},u=sY(e,".display.xAxis.crosshair",e=>(e.enabled=i,l(e,a,o),e));return u=sY(u,".display.yAxis.crosshair",e=>(e.enabled=s,l(e,r,n),e)),eF(t.haloTracking)&&"boolean"==typeof t.haloTracking&&(u=sY(u,".display.chart",e=>(e.plotHover=t.haloTracking,e))),u},Get:function(e,t,i){let s=t=>sz(e,t)[0],r=s(".display.chart"),n=s(".display.xAxis.crosshair"),a=s(".display.yAxis.crosshair"),o="none";return n.enabled&&a.enabled?o="both":n.enabled?o="vertical":a.enabled&&(o="horizontal"),{crosshair:o,horizontal:{color:a.color,dashStyle:a.dashStyle},vertical:{color:n.color,dashStyle:n.dashStyle},haloTracking:r.plotHover}}},Tooltip:{Update:function(e,t){return sY(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){let s=sz(e,".display.tooltip")[0];return{visible:s.visible,mode:s.mode,showMainTitle:s.showMainTitle,mainTitle:s.mainTitle}}},Events:function(e,t){let i=ez(t);return Object.keys(t).forEach(e=>{tz.EVENTS.includes(e)||delete i[e];let s=t[e];"boolean"==typeof s?s={show:t[e]}:Object.keys(s).forEach(e=>{tz.EVENT_PROPERTIES.includes(e)||delete s[e]}),i[e]=s}),sY(e,n4,e=>("Symbol"===e.type&&(e.events=e.events||{},Object.keys(i).forEach(t=>{e.events[t]=e.events[t]||{},eY(e.events[t],i[t],!1)})),e))},Scale:{Update:function(e,t){let i=sY(e,"..panes[0]..axes",e=>(eH(t.scale)&&(e.scale=t.scale),e));return i=sY(i,".display.xAxis",e=>(eH(t.marginBars)&&(e.marginBars=t.marginBars),eH(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),eH(t.ordinalName)&&(e.ordinalName=t.ordinalName),eH(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e)),i=sY(i,".display.yAxis",e=>{(eF(t.minPadding)||eF(t.maxPadding))&&Ad("The 'minPadding' and 'maxPadding' are deprecated (ignored)","warn");let i=eH(t.preventLabelOverlap)&&!eH(t.preventVerticalLabelOverlap);i&&Ad("The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'","warn");let s=i?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return eH(s)&&(e.preventLabelOverlap=s),eF(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),eF(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),e}),eF(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:s,index:r,paneIndex:n}=e;eF(t,s,r)&&"vertical"===t&&Number.isInteger(r)&&(i=sY(i,`..panes[${n??0}]..axes[${r}]`,e=>eF(e)?(e.label=s,e):tz.NULL_OBJECT))}),eH(t.contractTransition)&&(i=sY(i,".display.xAxis",e=>(eY(e.contractTransition,t.contractTransition),e))),eH(t.cycleTransition)&&(i=sY(i,".display.xAxis",e=>(eY(e.cycleTransition,t.cycleTransition),e))),i},Get:function(e,t,i){let{mainAxis:s}=n6(e),r=sz(e,".display.xAxis")[0],n=sz(e,".display.yAxis")[0];return{scale:s.scale,marginBars:r.marginBars??0,preventLabelOverlap:n.preventLabelOverlap,preventVerticalLabelOverlap:n.preventLabelOverlap,preventHorizontalLabelOverlap:r.preventLabelOverlap,snapAnnotationsToPrices:n.snapAnnotationsToPrices,nonEodLabelWithDate:r.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:n.includePercentChangeWithLastValue??!1,ordinalName:r.ordinalName??"",contractTransition:r.contractTransition,cycleTransition:r.cycleTransition}}},Other:{Update:function(e,t,i){let s=e;if(eF(t.comparisonMode)&&"string"==typeof t.comparisonMode&&e$(q,t.comparisonMode)&&(s=sY(s,`..panes{${n4}}.axes`,e=>(e.comparison=t.comparisonMode,e))),eF(t.gridLines)){let[e,i]=eW(t.gridLines);s=sY(s,".display.xAxis.gridLines",t=>(t.visible=e,t)),s=sY(s,".display.yAxis.gridLines",e=>(e.visible=i,e))}if(eF(t.minorGridLines)){let[,e]=eW(t.minorGridLines);s=sY(s,".display.yAxis.minorGridLines",t=>(t.visible=e,t))}eF(t.newPaneHeight)&&"number"==typeof t.newPaneHeight&&(s=sY(s,".display.chart{.newPaneHeight > 0}",e=>(e.newPaneHeight=t.newPaneHeight,e))),eF(t.showNavigator)&&"boolean"==typeof t.showNavigator&&(s=sY(s,".display.scrollbar",e=>(e.visible=t.showNavigator,e))),eF(t.plotHover)&&"boolean"==typeof t.plotHover&&(s=sY(s,".display.chart",e=>(e.plotHover=t.plotHover,e))),eF(t.showLastValue)&&"string"==typeof t.showLastValue&&(s=sY(s,".display.yAxis",e=>(e.showLastValue=t.showLastValue,e))),eF(t.showMinMaxArc)&&"boolean"==typeof t.showMinMaxArc&&(s=sY(s,".display.chart",e=>(e.showMinMaxArc=t.showMinMaxArc,e))),eF(t.showGoToLatest)&&"boolean"==typeof t.showGoToLatest&&(s=sY(s,".display.chart",e=>(e.showGoToLatest=t.showGoToLatest,e))),eF(t.showLegend)&&"boolean"==typeof t.showLegend&&(s=sY(s,".display.chart",e=>(e.showLegend=t.showLegend,e)),t.showLegend||i.view.removeLegend()),eF(t.allAnnotationsLocked)&&"boolean"==typeof t.allAnnotationsLocked&&(s=sY(s,".display",e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),eF(t.exprSkipLeadingEmpty)&&"boolean"==typeof t.exprSkipLeadingEmpty&&(s=sY(s,".data",e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));let r=[];if(eF(t.extendedHours)&&"boolean"==typeof t.extendedHours&&(s=sY(s,".data",e=>(e.extendedHours=t.extendedHours,e))),eF(t.realTimeCboeBzx)&&"boolean"==typeof t.realTimeCboeBzx&&(s=sY(s,".data",e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&r.push("realTimeCboeBzx"),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),eF(t.buildContinuation)&&"boolean"==typeof t.buildContinuation&&(s=sY(s,".data",e=>(e.buildContinuation=t.buildContinuation,e))),r.length>0){let e={chart:i.accessor,hostPropsChanged:r};i.notifyHost(aS.CH_HOST_PROPS_CHANGED,e)}return s},Get:function(e,t,i){let s=sz(e,`..panes{${n4}}.axes.comparison`)[0],r=e.display,n=(e,t)=>eG(e,!1,t,"visible"),a=e=>(function(e,t){let i=e=>eF(e)&&"boolean"==typeof e&&e,s=i(e),r=i(t);return s&&r?"both":s?"vertical":r?"horizontal":"none"})(n(r.xAxis,e),n(r.yAxis,e)),o=eG(r.chart,!0,"showLegend");return{comparison:s,gridLines:a("gridLines"),minorGridLines:a("minorGridLines"),newPaneHeight:r.chart.newPaneHeight,showLastValue:r.yAxis.showLastValue,showLegend:o,showMinMaxArc:r.chart.showMinMaxArc,allAnnotationsLocked:r.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){let i=sR(t.studyId);if(!eH(i))return Ad(`Unknown or unavailable study with the id '${t.studyId}'`,"error"),e;let s=n5(e),r=sF(i);if(s.type===Z[Z.Expression]&&r)return Ad(`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;let n=t.placement||(i.meta.overlay?"overlay":"standalone"),a={type:"Study",study:t.studyId,visible:!0};"overlay"===n&&"VOL"===t.studyId&&(a.detachedScale=!0),void 0!==t.curves&&(a.curves=i.defaults.curves),yV(a,t);let o=yG(e,n,t.cloneIndex);eF(o)&&o.plots.push(a);let l=e.data.aggregation;return an(e,"Tick"===l.unit&&"None"===l.spec)}(e,t);case"IncomeStatement":case"BalanceSheet":return function(e,t){let i=n5(e);if(i.type!==Z[Z.Symbol])throw Error("Cannot add fundamental to the chart whose main plot is not a Symbol plot.");let s=i.symbol,r={curves:[{fields:[t.fundamentalId],lineWidth:2,style:"Line",varyColorPerBar:!1,visible:!0,colors:["#888"]}],fundamental:"Quarter",symbol:s,type:K[aA[t.fundamentalId].category],visible:!0};return yV(r,t),e.panes.push({axes:[{plots:[r]}]}),e}(e,t);case"Expression":let i=n5(e),s={curves:ez(yY(i)?i.curves:yz),expression:"",type:"Expression",visible:!0};return yV(s,t),y$(e,t).plots.push(s),e;case"Symbol":return function(e,t){let i=n5(e),s=AA().getDefaultMultiFieldCurve(),r=eF(s)?s:yj,n=i.curves?.length,a={curves:n===t.curves.length&&1===n?ez(yY(i)?i.curves:[r]):t.curves,symbol:"",type:"Symbol",visible:!0};return yV(a,t),y$(e,t).plots.push(a),e}(e,t);case"Seasonal":let r={curves:ez(yz),offsets:[0],seasonal:"",type:"Seasonal",visible:!0,main:!1};return yV(r,t),t.paneIndex=t.paneIndex??0,y$(e,t).plots.push(r),e;default:throw Error("Unexpected plot type '${type}', not supported currently")}},Get:yN,Delete:yR,Update:function(e,t,i){if(eF(t.placement)&&!yB.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let s=t.main?n4:yH(t.index),r=yF(e,s);if(!eH(r)||eH(t.type)&&r.type!==t.type)return e;if(eH(t.visible))return r.visible=t.visible,e;if(r.main&&function(e){let t=Z[e.type];return t===Z.Symbol||t===Z.Expression}(r)){if(t.curves){let i=e=>e.curves[0].style===$[$.Range],[s,n]=[i(r),i(t)];s&&!n?e=aa(e,{unit:"Day",size:1,spec:"None"}):!s&&n&&(e=aa(e,{unit:"Intraday",size:100,spec:"PerRange"}))}return t.type||(t.type=r.type),eF(t.precision)?r.precision=t.precision:delete r.precision,eF(t.showPrevious)&&(e=sY(e,n4,e=>(e.showPrevious=t.showPrevious,e))),t.curves?n$(e,t):e}{let r=sY(e,s,e=>(yV(e,t),e)),n=yN(r,t,i).find(e=>e.index===t.index);if(!eF(n))return e;if(!(t.type===Z[Z.Study]&&eF(t.placement)&&t.placement!==n.placement))return r;let a=yF(r,s),o=yG(r=yR(r,{id:"Delete",plots:[{index:t.index,type:t.type}]}),t.placement);return null!==o&&o.plots.push(a),r}}},Compare:{Update:function(e,t){let{yes:i,no:s}=eS((eF(t.symbols)&&(Ad("Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types","warn"),t.plots=t.symbols.map(e=>(e.type=yX,e))),t.plots?.some(e=>eF(e.leftScale)))?(Ad("Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'","warn"),t.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):t.plots,e=>e.oppositeScale??!1),{mainPane:r,mainAxis:n}=n6(e);r.alignOnExpirations=t.alignOnExpirations||!1;let a=yQ(r,n),o=e=>![yX,"Expression"].includes(e.type);a.plots=a.plots.filter(o);let l=n.plots.filter(e=>e.main||o(e)),u="Tick"===e.data.aggregation.unit;yK=0;let h=eh(yZ,u);return n.plots=l.concat(s.map(h)),i.length>0&&(a.plots.push(...i.map(h)),a.comparison=n.comparison,a.scale=n.scale),ap(e)},Get:function(e,t){let i=sz(e,yJ),{mainPane:s,mainAxis:r}=n6(e),n=[];for(let e of i){let t=r.plots.includes(e),i=e.type.toLowerCase(),s={curves:ez(e.curves),type:e.type,[i]:e[i],leftScale:!t};n.push(s)}return{plots:n,alignOnExpirations:s.alignOnExpirations}}},Annotation:{Get:function(e,t,i){let s=sz(e,"..panes").map((e,t)=>sz(e,"..axes").map((e,i)=>sz(e,".annotations").map(e=>({...e,paneIndex:t,axisIndex:i})))).flat(2).map((e,t)=>({...e,index:t}));return eF(t.index)&&Number.isFinite(t.index)?t.index<s.length?[s[t.index]]:tz.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=ez(e);if(t.strip.main){let e=n5(i),t=e.type.toLowerCase();e[t]=tz.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(i=y1(i)),t.strip.compare&&(i=y2(i)),i=sY(i,".data",e=>(e.range&&(delete e.range,e.checkRange=!0),e))},Outline:function(e,t,i){let s=yN(e,{main:!0},i)[0],r=s.title===tz.PLACEHOLDER_SYMBOL_NAME,n="Symbol"===s.type,a="Expression"===s.type,o=nX(s.title),l=[];return a&&!nq(o)?l=o.symbols:r||(l=[s.title]),{isTemplate:r,isDefinition:!r,main:{isSymbol:n,isExpression:a,symbols:l,title:r?null:s.title},compare:sz(e,yJ).map(e=>e.symbol),annotations:sz(e,"..annotations").map(e=>e.id),studies:yN(e,{type:"Study"},i).map(e=>e.title)}},Theme:{Update:function(e,t){let i=e,{backgroundColor:s,axis:{gridLinesColor:r,textColor:n,crosshairColor:a,gridLinesStyle:o},fontSize:l}=t,{chart:u,xAxis:h,yAxis:c}=l||{};if((s||u)&&(i=sY(e,".display.chart",e=>(s&&(e.backgroundColor=s),u&&(e.fontSize=u),e))),r){let e=e=>(e.color=r,e);i=sY(i,".display.xAxis.gridLines",e),i=sY(i,".display.yAxis.gridLines",e),i=sY(i,".display.yAxis.minorGridLines",e)}if(o){let e=e=>(e.dashStyle=o,e);i=sY(i,".display.xAxis.gridLines",e),i=sY(i,".display.yAxis.gridLines",e),i=sY(i,".display.yAxis.minorGridLines",e)}if(n){let e=e=>(e.textColor=n,e);i=sY(i,".display.xAxis",e),i=sY(i,".display.yAxis",e)}if(a){let e=e=>(e.color=a,e);i=sY(i,".display.xAxis.crosshair",e),i=sY(i,".display.yAxis.crosshair",e)}if(h||c){let e=e=>t=>(t.fontSize=e,t);h&&(i=sY(i,".display.xAxis",e(h))),c&&(i=sY(i,".display.yAxis",e(c)))}return i},Get:function(e,t,i){let{chart:s,xAxis:r,yAxis:n}=e.display||{},{fontSize:a,backgroundColor:o}=s||{},{fontSize:l,gridLines:u,textColor:h,crosshair:c}=r||{},{color:d,dashStyle:p}=u||{},{fontSize:f}=n||{},{color:m}=c||{};return{backgroundColor:o,axis:{gridLinesColor:d,textColor:h,crosshairColor:m,gridLinesStyle:p},fontSize:{chart:a,xAxis:l,yAxis:f}}}},Clear:function(e,t,i){let{paneIndex:s,annotations:r,studies:n}=t||{},a=Number.isInteger(s)?`[${s}]`:"",o=`..panes${a}`,l=e,u=e=>tz.NULL_OBJECT;return!0===r&&(i.allAnnotations.forEach(e=>i.onAnnotationModifiedByTool(e,el.Deleted,!1)),l=sY(l,`${o}..annotations`,u)),!0===n&&(l=sY(l,`${o}..plots{.type=="Study"}`,u)),l=ap(l)},Previous:{Update:function(e,t,i){return sY(e,y3,e=>(eY(e,t),e))},Get:function(e,t,i){return sz(e,y3)[0]}},MovePlot:{Update:function(e,t,i){if(!y4(e,t,i).includes(t.targetPane))return e;let s=y7(i,t.index),r=yF(e,yH(t.index));e.panes[s.pane].axes[s.axis].plots.splice(s.plot,1);let n=s.pane,a=!0;switch(t.targetPane){case"ExistingAbove":n--;break;case"NewAbove":e.panes.splice(n,0,yW(e)),a=!1;break;case"ExistingBelow":n++;break;case"NewBelow":n++,a=!1,e.panes.splice(n,0,yW(e))}a&&i.panes[n].isMain&&r?.type==="Study"&&"VOL"===r.study&&(r.detachedScale=!0);let o=e.panes[n];o.axes.length<2&&o.axes[0].plots.length>0&&o.axes.push(yk());let l=o.axes.findIndex(e=>0===e.plots.length),u=-1===l?o.axes.length-1:l;o.axes[u].plots.push(r);let h=y6(e,s.pane);return ap(h=y6(h,n))},Get:y4},PinPlot:{Update:function(e,t,i){if(!y5(e,t,i).includes(t.targetAxis))return e;let s=y7(i,t.index),r=e.panes[s.pane],n=yF(e,yH(t.index)),a=-1;switch(t.targetAxis){case"PrimaryAxis":a=0;break;case"SecondaryAxis":a=1;break;case"NoAxis":n.detachedScale=!0}if(-1!==a)if(a!==s.axis)delete n.detachedScale,r.axes.length<2&&a>0&&r.axes.push(yk()),r.axes[a].plots.push(n),r.axes[+(0===a)].plots.splice(s.plot,1);else{let e=r.axes[s.axis].plots[s.plot];delete e.detachedScale}return ap(y6(e,s.pane))},Get:y5}};function y9(e){return"function"==typeof e}function Ae(e,t,i){return(function(e,t){let i=y8[e];if(y9(i))return i;{let e=void 0!==t?i[t]:void 0;if(!y9(e)&&!y9(e=i[tz.DEFAULT_ACCESSOR_SUBACTION]))throw Error("Invalid accesor id and/or sub id");return e}})(e.id,e.context.id)(t,e.context,i)}function At(e){return{id:"MainPlot",context:e}}let Ai={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},As=Symbol.for("__ias__");class Ar{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new yx(this)}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)return void console.error("You cannot initialize a headless chart.");if(this.presenter.initialize(e),eH(t)){let e="string"==typeof t;e?Ad("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);let i=e?{symbol:t}:t;this.change(At(i))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,i=null){if(!this.headless)if(eF(e)){s9(e,t),s8(e,t);let s=gJ(e,!1,t,i,this.presenter);s.isDrawingAnnotation&&this.presenter.view.setCursor(ee.Crosshair),this.presenter.activeTool=s,eO()||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 AS()}get model(){return(this.headless?this._model:this.presenter.getModel())||AS()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:tz.ACTION_TEMPLATE,context:{strip:e}})}change(...e){let t={chart:this,actions:e.filter(e=>!e[As])};t.actions.length>0&&this.presenter?.notifyHost(aS.CH_API_ACTIONS_RECEIVED,t);let i=AA().config.validateInput,s=e.map(e=>i?ad(e,tz.ACCESSOR_SCHEMA):e);if(1===s.length){let e=s[0];if(e.id===tz.ACTION_TEMPLATE||e.context.id===tz.ACTION_GET)return Ae(e,this.model,this.presenter);if(!this.headless&&e.id===tz.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:r,no:n}=eS(s,e=>e.id===tz.ACTION_PLOT&&eF(e.context)&&e.context.id===tz.ACTION_DELETE),a=ez(this.model),o=ez(this.model);r.length>0&&n.push({id:tz.ACTION_PLOT,context:{id:tz.ACTION_DELETE,plots:r.map(e=>e.context)}}),n.forEach(e=>{if(!eF(o=Ae(e,o,this.presenter)))throw Error("Forgot to return model from accessor")}),this.fromModel(o,a)}async fromModel(e,t){let i=ad(e,tz.CHART_SCHEMA);this.headless?this._model=i:await this.presenter?.fromModel(i,t)}async load(e,t){let i={...Ai,...t},s=ad(JSON.parse(e),tz.CHART_SCHEMA),r=this.model,n=ez(r);if(eF(r)){if(s=function(e,t,i){let s=n5(t),r=s.type.toLowerCase();if(s[r]===tz.PLACEHOLDER_SYMBOL_NAME){let s=n5(e),{mainAxis:r}=n6(t),n=r.annotations,a=as(t,s);if(i){let{mainAxis:e}=n6(a);e.annotations=n}return a}return t}(r,s,i.keepNewAnnotations),i.keepNewAnnotations||(s=y1(s)),i.keepOldAnnotations&&(s=function(e,t){let{mainAxis:i}=n6(e),{mainAxis:s}=n6(t);yv(i,s);let r=e=>sz(e,'..plots{.type==="Study"}.study')[0],n=sz(e,yP).filter(e=>e!==i),a=sz(t,yP).filter(e=>e!==s);return n.forEach(e=>{let t=r(e),i=a.find(e=>t===r(e));eF(i)&&yv(e,i)}),t}(r,s)),i.keepNewCompare||(s=y2(s)),i.keepOldCompare&&(s=function(e,t){let i=sz(e,yJ),s=sz(t,yJ),r=Math.max(0,4-s.length);if(0===r)return t;let n=i.filter(e=>!s.find(t=>e.symbol===t.symbol)).slice(0,r);if(0===n.length)return t;let{mainPane:a,mainAxis:o}=n6(t),{mainAxis:l}=n6(e);return n.forEach(e=>{l.plots.includes(e)?o.plots.push(e):yQ(a,o).plots.push(e)}),t}(r,s)),i.keepOldAggregation){let e={id:tz.ACTION_AGGREGATION,context:r.data.aggregation},t=s.display.density;s=Ae(e,s,this.presenter),i.keepNewBarWidth&&eF(t)&&(s.display.density=t)}await this.fromModel(s,n),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){this.headless||this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=AS();if(this.headless)this._model=t;else if(this.presenter.getModel()){let i=this.presenter.mainPlot,s=null;if(i.isSymbol?s={symbol:i.symbol}:i.isExpression?s={expression:i.expression}:i.isForward?s={forward:i.forward}:i.isSeasonal&&(s={seasonal:i.seasonal}),eF(s)){let i=Ae({id:"Theme",context:{id:"Get"}},this.model,this.presenter),r=Ae(At(s),t,this.presenter);e&&(r=Ae({id:"Theme",context:i},r,this.presenter)),this.presenter?.fromModel(r)}}this.clearUndoRedo(),this.presenter?.notifyHost(aS.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){Ad("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:yL.call(this.presenter,e)}exportImage(e={}){return this.headless?null:y_.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){let s=this.presenter;if(this.headless||t<0||i<0||t>s.panes.length)return null;let r=s.panes[t];return i>r.axes.length?null:r.axes[i].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[i,s]of t.panes.entries()){let t=s.getBounds();if(eF(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(aS.CH_DIDBECOMEACTIVE,{chart:this})}}var cm=N("c15IW");function An(e,t,i,s,r){void 0===s&&(s=0),void 0===r&&(r=!1);var n=t.schedule(function(){i(),r?e.add(this.schedule(null,s)):this.unsubscribe()},s);if(e.add(n),!r)return n}function Aa(e,t){return e+Math.random()*(t-e)}let Ao=Function(atob("Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg")),Al=Function("f",atob("Zi5yZW1vdmVBbGxDaGFydHMoKTsg")),Au=Function("m",atob("cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw=="));async function Ah(e,t){if(t&&!Au(e.mode))return;let i=!1,s=0,r=25;for(;!i&&s<5;){let t=function(){let e=globalThis.parent?.location?.hostname||"";return["","localhost","127.0.0.1"].includes(e)||function(e){let t=e.split(".");if(!t||4!==t.length)return!1;let i=t.map(Number);if(!i.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[s,r]=i;return 10===s||172===s&&r>=16&&r<=31||192===s&&168===r}(e)}()||"FreeWidget"===e.mode,n=t?e.apiKey:"";try{let r=t?"":function(){let e=document.domain,t=e.split("."),i="__tld"+new Date().getTime(),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}(),a=function(e,t=""){return function(e,t){Object.keys(t).forEach(e=>!eF(t[e])&&delete t[e]);let i=new URLSearchParams(t);return`${e}/?${i.toString()}`}(atob("aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ=="),{module:atob("YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy"),secret:t,referer:e})}(r,n),o=await fetch(a);if(o.ok){let 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++,r*=2,await new Promise(e=>setTimeout(e,r))}i&&e.knownSite||(setTimeout(Ao,Aa(2e3,3e3)),setTimeout(()=>Al(AA()),Aa(4e3,5e3)))}var Ac={};function Ad(e,t="info",i=""){let s=globalThis.console,r=void 0!==s[t];s[r?t:"log"](e,i)}Ac=JSON.parse('{"major":2,"minor":361,"patch":0,"prerelease":false}');let Ap={environment:"Browser",validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${tz.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){let i=this.baseUrl[e],s=`${i}${t}`;if(Au(this.mode)&&this.knownSite){let{username:r,password:n}=this.credentials||{},a=eF(r,n),o=("timeseries"===e||"timeseriesNew"===e)&&a&&this.allowCredentials?`&username=${r}&password=${n}`:"";s=`https://${this.dataEndpoint}${i}${t}${o}`}let r=await fetch(s);return await r.text()},getCustomEventPopup:e=>null};async function Af(e,t){let i=AA()?.config;if(!i||!i.fetch)throw 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 Am=!1,Ag=null;function Ay(t,i={}){if(Am)throw Error("You should only call initFeed once during page's lifetime");Am=!0;let s=Object.assign(Ap);return eY(s,i),eH(s.logo)&&function(e,t){let i=new DOMParser().parseFromString(e,"image/svg+xml"),s=i.querySelector("svg")?.getAttribute("viewBox"),r=i.querySelector("path")?.getAttribute("d");if(eH(s)&&eH(r)){let e=s.split(" ").map(Number);4===e.length&&e.every(Number.isFinite)&&(m0={path:new Path2D(r),width:e[2],height:e[3],rect:new iw(0,0,0,0),logoClickable:t})}}(s.logo,s.logoClickable??!1),!function(e){var t;let i=e.extensions?.studyProvider;if(!eF(i))return;let s=i.getFields(),r=i.getStudies(),n=ez(s_(tz.CHART_SCHEMA)),a=n.definitions,o=a.studyField.enum,l=a.study.enum;for(let e of s)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(l.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...s.map(e=>e.id)),l.push(...r.map(e=>e.id)),t=tz.CHART_SCHEMA,ac.addSchema(t,n),ay(s),sI(r)}(s),(Ag=new t(s)).version=function(){let t=e(Ac),i=t.prerelease?`-${t.prerelease.identifier}.${t.prerelease.ordinal}`:"";return`${t.major}.${t.minor}.${t.patch}${i}`}(),Ad(`%cBarchart Chart version ${Ag.version}`,"info","font-size: larger"),Ag.cachesData&&(Ag.subject?.subscribe(Ag.onPerformInternalGc.bind(Ag)),e(cm).subscribe(aS.CH_ALL,Ag.onChartChanged.bind(Ag))),Ag}function AA(){return Ag}function AS(){return ez(AA()?.template)}function AT(){eH(Ag)&&(Ag.shutdown(),Am=!1,Ag=null)}function Av(e){let t=new Ar(!0);return t.load(e),t.change({id:"Outline",context:{id:"Get"}})}function AP(e,t,i,s=null){return new Proxy(e,{get:function(e,r,n){return r===t?function(t){let n=s?t[s]:t;return(i.handlesRequestsFor(n)?i:e)[r](t)}:Reflect.get(e,r,n)}})}class AC{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed;constructor(e){this.config=e,this._mainFeed=null,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=new Map,this.pendingRedraw=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=e1()}get subject(){return this.isAuxiliary||eH(this._subject)||(this._subject=new og().pipe(function(e){for(var t,i,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var n=null!=(t=op(s[s.length-1])?s.pop():void 0)?t:a3,a=null!=(i=s[0])?i:null,o=s[1]||1/0;return oA(function(t,i){var s=[],r=!1,l=function(e){var t=e.buffer;e.subs.unsubscribe(),aj(s,e),i.next(t),r&&u()},u=function(){if(s){var t=new aK;i.add(t);var r={buffer:[],subs:t};s.push(r),An(t,n,function(){return l(r)},e)}};null!==a&&a>=0?An(i,n,u,a,!0):r=!0,u();var h=oS(i,function(e){var t,i,r=s.slice();try{for(var n=ak(r),a=n.next();!a.done;a=n.next()){var u=a.value,h=u.buffer;h.push(e),o<=h.length&&l(u)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(t)throw t.error}}},function(){for(;null==s?void 0:s.length;)i.next(s.shift().buffer);null==h||h.unsubscribe(),i.complete(),i.unsubscribe()},void 0,function(){return s=null});t.subscribe(h)})}(tz.INTERNAL_GC_MILLIS),oC(e=>e.length>0))),this._subject}get isAuxiliary(){return null!==window.opener}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=AP(this.timeSeriesSource,"getTimeSeries",e,"symbol"),this.metaDataSource=AP(this.metaDataSource,"getMetaData",e),this.recordSource=AP(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(!eH(this.timeSeriesSource))throw Error("No time series source defined");return this.timeSeriesSource}getMetaDataSource(){if(!eH(this.metaDataSource))throw Error("No metadata source defined");return this.metaDataSource}getRecordSource(){if(!eH(this.recordSource))throw Error("No record source defined");return this.recordSource}async ready(){return tU.call(this,async()=>{await Ah(this.config,this instanceof AM||this instanceof Ab||this instanceof AI);let e=this.config.defaultTemplate;if(!e)throw Error("Must provide a default template");if("string"==typeof e){let t=await fetch(e);e=await t.json()}return this.template=ad(e,tz.CHART_SCHEMA),!0})}getHeadlessChart(){return new Ar(!0)}fixupRenderTo(e){if(!eH(e))return null;if(e instanceof HTMLElement)return e;let t=tR(`#${e}`);if(eH(t))return t;let i=[...this.charts.keys()].find(t=>t.id===e);return eH(i)?i:null}checkChart(e,t){let i=this.fixupRenderTo(e),s=eH(i)&&this.charts.has(i);return eH(t)&&t!==s&&Ad(`There is ${t?"no":"already a"} chart inside the element ${e}`,"error"),i}addChart(e,t=null){let i=this.checkChart(e,!1),s=new Ar;return this.charts.set(i,s),s.initialize(e,t),s}removeChart(e){let t=this.checkChart(e,!0);eH(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return eH(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);eH(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),eH(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!eH(t?.presenter?.view))return;let i=t.presenter.view;i.isHostElementVisible&&i.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:new Set,records:new Set,timeSeries:new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{eH(t)&&(eH(t.record)?e.records.add(t.record):eF(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){this.getTimeSeriesDataSource().refresh(),eN(aS.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.evictUnused(e)}triggerGc(){this.subject?.next()}onChartChanged(e,t){(e===aS.CH_RECREATED||e===aS.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc():this.triggerGc())}getDefaultMultiFieldCurve(){if(!eH(this.template))return null;if(!this.knowDefaultCurve){let e=n5(this.template);1===e.curves.length&&function(e){switch($[e]){case $.OHLC:case $.HLC:case $.Candlestick:case $.HollowCandles:case $.HeikinAshi:case $.ElderImpulseSystem:case $.Range:case $.MultiColumn:return!0;default:return!1}}(e.curves[0].style)?this.defaultOhlcCurve=ez(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=ez(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 Ab extends AC{constructor(e){super(e),this.timeSeriesSource=new he(!1),this.metaDataSource=new io,this.recordSource=new lN}}class AE extends AC{constructor(e){super(e),this.timeSeriesSource=new he(!0),this.metaDataSource=new io,this.recordSource=new lV}}class AL extends AC{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new he(!0),this.metaDataSource=new io,this.recordSource=new lN}}let A_=["drazen.dotlic@barchart.com","princec","b.hebert24@barchart.com"];class AM extends AC{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new he(!0),this.metaDataSource=new il,this.recordSource=new lH,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,eH(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){eH(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&&A_.includes(this.connection._username)&&Ad(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===tz.BC_EVENT_DISCONNECTED||e===tz.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===tz.BC_EVENT_LOGGED_IN||e===tz.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),eH(this._connection)&&(this.connection.off("timestamp",this.onTimestamp),this.connection.off("events",this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}}function Ax(e,t){return new AD(e,t)}class AD{_client;_subscriptions=new Map;_listeners=new Set;constructor(e,t){this._client=e;let i=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let s=e.marketSnapshot;if(eH(s)){let e=i(t);null!==e&&this._listeners.forEach(t=>t.onSnapshot?.(s,e))}let r=e.marketUpdate;if(eH(r)){let e=i(t);null!==e&&this._listeners.forEach(t=>t.onUpdate?.(r,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 eH(await this._client.connection)}shutdown(){eH(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!eH(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!eH(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){let t=await this._client.connection;return await t?.getInstrument(e)??[]}}class AI extends AC{_adapter=null;_auxFeeds=[];constructor(t){super(t),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new he(!0),this.metaDataSource=new iu,this.recordSource=new lF,e(cm).subscribe(aS.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let i of this._auxFeeds)i.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&eN(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error("Cannot set adapter on auxiliary feed");this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let 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){let 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(let t of this._auxFeeds)t.getAllCacheableEntities(e)}}var cm=N("c15IW");let AO=e(cm);export{AO as PubSub,Ay as initFeed,AA as getFeed,AT as shutdownFeed,Av as getChartOutline,AC as BaseDataFeed,Ab as BarchartSiteDataFeed,AL as MiniWidgetDataFeed,AM as MarketDataFeed,AI as OpenFeed,AE as SnapshotDataFeed,Ax as adaptOpenFeedClient,l8 as OHLCDataPointBuilder,nX as parseExpression,nZ as evaluateExpression,nQ as formatExpression,n0 as getExpressionSymbols,n2 as replaceExpressionSymbols,pA as ExpressionSeries,py as makeExpression,u1 as ContainerWrapperTimeSeries,t4 as formatPriceWithDecimals,t5 as getCombinedMetaData,lR as BaseRecordSource,aE as EmptyRecord,am as Field,aA as Fields,ue as TimeSeriesContainer,cf as TimeSeriesQuery,nN as Aggregation,tU as asyncReady,tL as hasOpenInterest,l3 as optionValueToDate,e1 as generateUid,s$ as getTaxonomies,sH as doesStudyExist,sN as getAnnotationTraits,g3 as getStudyOptions,cA as StudySeries,cy as makeHelperField,f_ as makeStudy,fY as convertSeries,fj as mapSeries,fD as movAvg,fI as movExp,fO as movSmo,fw as movWei,fR as movHul,fz as linReg,fF as trueRange,fk as typical,fW as roc,fG as stdDev,aS as Topics,ix as getLightness,en as ChunkPart,J as SeriesKind,z as AggregationSpec,G as AggregationUnit,B as ExpressionRecompute,k as ExpressionNoDataApproach,F as ExpressionMissingBar,Y as FieldValueType,K as FieldCategory,j as FieldFormat,yT as CustomEventPopup,tB as appendDOMElement,tN as styleDOMElement,tV as setAttributesDOMElement};
20
+ </svg>`),tN(this.goToLatestButton,{position:"absolute",right:0,bottom:0,"z-index":3}),tV(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 yp(this),this.eventCapture=new yg(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(n,r);let o=tO(this.el);eF(tR(`.${tz.SVG_ICONS_DOM_NODE}`,o))||function(e){let t=tB(e,"div");tV(t,{class:tz.SVG_ICONS_DOM_NODE});let i=Object.keys(hH).map(e=>`<symbol id="${hW(e)}" viewBox="0 0 1024 1024">${hH[e]}</symbol>`).join("");t.innerHTML=`<svg style="display:none" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>${i}</defs></svg>`}(o)}reinitialize(){this.el&&tk(".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 yp(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,i=!1){this.setChartSize(e,t),this.redraw(i)}setChartSize(e,t){let i={width:`${e}px`,height:`${t}px`};tN(this.el,i),this.width=e,this.height=t;let s=globalThis.devicePixelRatio||1,r={height:this.height*s,width:this.width*s};[this.mainCanvas,this.mouseCanvas].forEach(e=>{tV(e,r),tN(e,i)}),this.mainContext.scale(s,s),this.mouseContext.scale(s,s),this.recalculateLayout(),this.presenter&&mj(this.presenter)}widthNeeded(e,t){let 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;let e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),i=this.widthNeeded(this.mainContext,!1),s=this.height-e,r=this.presenter.panes,n=em(r.map(e=>e.height)),a=0,o=tz.PANE_SPLITTER_PERCENT_HEIGHT/100,l=Math.floor(o*s);n*=1+(r.length-1)*o;let u=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;this.presenter.display.yAxis.visible&&(r.some(e=>e.axes.length>1)?(this.leftOffset=i,this.rightOffset=t):u?this.leftOffset=i:this.rightOffset=t),r.forEach((e,i,r)=>{let o=i===r.length-1,u=Math.floor(s*e.height/n),h=new iw(0,a,this.width,u);e.setViewBox(h);let c=new iw(this.width-this.rightOffset,a,t,u),d=new iw(0,a,this.leftOffset,u),p=e=>e.setViewBox(e.onTheRight?c:d);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),a+=u,!o){let e=new iw(this.leftOffset,a,this.width-this.rightOffset-this.leftOffset,l);this.splitters.push(e),a+=l}});let h=new iw(this.leftOffset,a,this.width-this.rightOffset-this.leftOffset,e);this.xAxis.setViewBox(h),tN(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(){for(let e of(this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext),this.presenter.panes))e.drawBackground(this.mainContext);for(let e of(this.xAxis.draw(this.mainContext),this.presenter.panes))e.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext);let e=AA().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart,i=eF(e)?e:t;this.goToLatestButton.style.display=i&&this.xAxis.canGoToLast()?"block":"none",this.mainContext.restore()}get isHostElementVisible(){return eF(this.el)&&eF(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():AA().redraw(this.presenter.hostElement))}drawBackground(e){let 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}){let i=this.mouseContext;return i.clearRect(0,0,this.width,this.height),!!e&&!!this.xAxis.drawCrosshair(i,t)&&(this.presenter.display.yAxis.visible&&e.axis.pane.drawYCrosshair(i,t),!0)}drawSplitters(e){e.strokeStyle=(e=>{let t=iM(e);return iI(iE(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.lineWidth=2,this.splitters.forEach(t=>{let{x:i,y:s,width:r,height:n}=t,a=s+n/2;e.beginPath(),e.moveTo(i,a),e.lineTo(i+r,a),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){let t=function(e){switch(e){case ee.Arrow:default:return"default";case ee.Crosshair:return"crosshair";case ee.Hand:return"pointer";case ee.Move:return"move";case ee.ResizeVertical:return"ns-resize";case ee.Grabbing:return"grabbing";case ee.ResizeHorizontal:return"ew-resize"}}(e);tN(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&tk(".bcharts-card",this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){return Math.max(this.xAxis.xScale.bar.width/2,tz.MIN_EVENT_RADIUS)}}class yT{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=tB(this.view.el,"div"),tV(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),tN(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"});let e=tB(this.popupElement,"a");tV(e,{class:"custom-event-close-button"}),tN(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()),tN(this.popupElement,{visibility:"visible",top:`${e.y}px`,left:`${e.x}px`,width:"310px"}),this.visible=!0}hideValue(){}hide(){this.visible&&(this.hideValue(),tN(this.popupElement,{visibility:"hidden"}),this.visible=!1)}}function yv(e,t){if(!(e.annotations&&e.annotations.length>0))return;let i=t.annotations||[];t.annotations=i.concat(e.annotations)}let yP='..axes{..plots{.type==="Study"}}';var cm=N("c15IW");let yC={ok:!1,change:void 0,toApply:void 0};class yb{presenter;paused;undoStack;redoStack;initial;isPaused;constructor(e){this.presenter=e,this.paused=null,this.undoStack=[],this.redoStack=[],this.initial=new Map,this.isPaused=!1,this.clear()}clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,mT(e,el.Moved)))}done(e){if(this.isPaused){this.paused=e;return}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&&eH(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){let t={...e,id:"Delete"};this.presenter.handleAnnotationChange(t)}add(e){this.presenter.handleAnnotationChange({annotation:e,id:"Add"})}apply(e,t,i){if(!eF(e))return!1;switch(t){case el.None:case el.Undo:case el.Redo:Ad(`Unexpected tool change ${el[t]} for undo/redo`,"warn");break;case el.Created:i?this.delete(e):this.add(e);break;case el.Deleted:i?this.add(e):this.delete(e);break;default:{let t={...e,id:"Update"};this.presenter.handleAnnotationChange(t)}}let s=this.presenter.allAnnotations.find(t=>t.uid===e.uid),r=i?el.Undo:el.Redo;return eF(s)&&this.presenter.onAnnotationModifiedByTool(s,r),!0}can(e){let t=e?this.undoStack:this.redoStack;if(t.length<1)return yC;let i=eC(t),s=i.toolChange;if(!(e&&s!==el.Deleted&&s!==el.Created))return{ok:!0,change:s,toApply:i};let r=eE(t,e=>e.uid===i.uid,t.length-2),n=-1!==r?t[r]:null,a=null===n;return a&&!this.initial.has(i.uid)?yC:{ok:!0,change:s,toApply:a?this.initial.get(i.uid):n}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,i){let{ok:s,change:r,toApply:n}=this.can(i);if(!s)return;let a=e.pop();this.apply(n,r,i),t.push(a)}}class yE{presenter;text;align;verticalAlign;x;y;style;constructor(e){this.presenter=e,this.text=null,this.align="center",this.verticalAlign="top",this.x=0,this.y=0,this.style={color:"#333",fontSize:18}}update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;let{fontFamily:t}=this.presenter.display.chart,{fontSize:i,color:s,fontWeight:r}=this.style,{x:n,y:a,width:o,height:l}=this.presenter.mainPlot.axis.pane.getBounds(),u=n+this.presenter.view.leftOffset,h=n+o-this.presenter.view.rightOffset,c=u;c="center"===this.align?o/2:"right"===this.align?h:u;let d=a+i;"middle"===this.verticalAlign?d=a+i+l/2:"bottom"===this.verticalAlign&&(d=a+l),c+=this.x,d+=this.y,e.save(),e.font=`${r||"normal"} ${i}px ${t}`,e.textAlign=this.align,e.textBaseline="bottom",e.fillStyle=s,e.fillText(this.text,c,d),e.restore()}}function yL(e={}){let t=this.allPlots;if(!t.every(e=>eF(e.timeSeries)&&e.timeSeries.hasData))return"No data to export";let i=e.excludeHeader??!1,s=e.numDecimals??null,r=e.excludeFields??[],n=e=>{let t=new Map;return e.main&&(t.set(aA.DateTime,0),this.data.aggregation.isMultiContract&&!e.isExpression&&t.set(aA.Symbol,0)),e.curves.forEach(e=>{e.fields.forEach(i=>{r.includes(i.id)||t.set(i,e.shift)})}),Array.from(t)},a=this.data.aggregation.isEndOfDay?tz.FMT_ISO_DATE_ONLY:tz.FMT_EXPORT_ALL_BUT_MILLIS,o=(e,t)=>e===aA.DateTime?o5(t,a):(eF(s,t)?eB(t,s):t)?.toString()??"",l={},u=this.timeline.lastSeriesIndex,h=eb(this.mainPlot.timeSeries.container.getTimeData()),c=e_(this.timeline,+h,Number,hN),d=(e,t)=>{let i=this.timeline.at(e),s=t.timeSeries.container,r=s.getTimeData(),u=e_(r,+i,Number,eL,l[t.id]||0),h=+i==+r[u];return h&&(l[t.id]=u),n(t).map(([t,n])=>{if(0===n)if(h)return o(t,s.getData(t)[u]);else if(t===aA.DateTime)return o5(i,a);else return"";{let i=this.timeline.at(e-n),a=e_(r,+i,Number,eL,0);return+i==+r[a]?o(t,s.getData(t)[a]):""}})},p=e=>{let i=t.map(e).flat();return i.slice(1).every(e=>0===e.length)?null:i.join(",")},f=[];i||(f.push(p(e=>{let t=Array(n(e).length).fill("");return t[0]=`"${Z[e.type]}: ${e.title}"`,t})),f.push(p(e=>n(e).map(([e,t])=>`"${e.name}"`))));let m=[0,0];this.allCurves.forEach(e=>{!e.fields.every(e=>r.includes(e.id))&&(e.shift<0&&(m[0]=Math.min(m[0],e.shift)),e.shift>0&&(m[1]=Math.max(m[1],e.shift)))});for(let e=c+m[0];e<=u+m[1];e++){let t=p(eh(d,e));null!==t&&f.push(t)}return f.join("\n")}function y_(e={}){let t=this.view.mainCanvas,{width:i,height:s}=t,{width:r,height:n,title:a}=e,o=(e,t)=>{let i=document.createElement("canvas");return i.width=e,i.height=t,i.getContext("2d")},l=o(i,s),u=globalThis.devicePixelRatio;if(l.drawImage(t,0,0),l.scale(u,u),eH(a)){let e=new yE(this);e.update(a),e.draw(l)}let h=this.mainPlot?.timeSeries.container?.getLastDataPoint(aA.DateTime);if(eH(h)){let{fontFamily:e}=this.display.chart,{fontWeight:i,fontSize:s}=this.mainAxis.config;l.font=`${i} ${1.2*s}px ${e}`,l.textBaseline="top";let r=1.5*s,n=getComputedStyle(t),a=n.getPropertyValue("--app-hc-color"),o=n.getPropertyValue("--app-color-pl"),u={x:tz.CARDS_X_OFFSET,y:tz.CARDS_Y_OFFSET},c=hK(this,h,u,void 0,!1,0),d=`${c.date} ${c.time??""}`.trim(),[p,f]=[1,5],m=(e,t)=>l.measureText(e).width+t,g=(e,t,i,s,r)=>(l.fillStyle=s,l.fillText(e,t,i),m(e,r)),y=(e,t)=>e.type===Z[t];c.panes.forEach(e=>{let{top:t,left:i,width:s,right:n}=e.bounds,l=i+s-n-f,h=i+u.x,c=t+u.y;e.plots.some(e=>e.isMain)&&(h+=g(d,h,c,a,f)),e.plots.forEach((e,t)=>{let s,n=(s=e.name,e.isMain&&y(e,"Symbol")?s=`${e.description} (${e.name}) [${e.exchange}]`:y(e,"Study")&&(s=`${e.description} ${e.name.substring(e.name.indexOf(" "))}`),s),d=!y(e,"Study")&&e.values.length>1;if(!e.isMain&&t>0){let t=h+m(n,f);e.values.forEach(e=>{d&&(t+=m(e.abbreviation,p)),t+=m(e.value,f)}),t>=l&&(h=i+u.x,c+=r)}h+=g(n,h,c,a,f),e.values.forEach(e=>{d&&(h+=g(e.abbreviation,h,c,o,p)),h+=g(e.value,h,c,e.color,f)})})})}let c=e=>({width:r??i,height:n??s,data:e.toDataURL("image/png")});if(!(eH(r)&&eH(n)))return c(l.canvas);{let e=o(r,n);return e.drawImage(l.canvas,0,0,r,n),c(e.canvas)}}let yM=Symbol.for("__ias__");class yx{accessor;view;defaultTool;_activeTool;tooltipEnabled;timeline;sentInitialLoadNotification;_hostElement;undoRedoManager;title;display;model;data;panes;_hasLegend;renderTo;seriesChangedToken;metaChangedToken;streamingSubscription;_previousMask;_ohlcMask;selectedAnnotation;forceResetVisibleRange;_maxOffset;_isShutdown;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.tooltipEnabled=!0,this.sentInitialLoadNotification=!1,this._hostElement=null,this.panes=[],this.seriesChangedToken="",this.metaChangedToken="",this.streamingSubscription=null,this._previousMask=0,this.forceResetVisibleRange=!1,this._maxOffset=0,this._isShutdown=!1,this.defaultTool=gJ("Default"),this._activeTool=this.defaultTool,this.timeline=new hV(this),this.undoRedoManager=new yb(this),this.title=new yE(this),this.notifySelectionChanged=eV(aS.CH_ANNSELECTIONCHANGED),this.notifyRecreated=eV(aS.CH_RECREATED),this.notifyDefinitionChanged=eV(aS.CH_DEFINITION_CHANGED)}getModel(){return this.model}get isEmpty(){return!eF(this.model)}notifyHost(e,t){eN(e,t)}async fromModel(e,t){if(this._isShutdown)return;eF(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearSelection(),this.model=e;let i=ez(e);this.data=i.data,this.data.aggregation=nx(i.data.aggregation),this.display=i.display,eF(this.display.period)&&(this.display.period=eQ(this.display.period)),this.panes=i.panes.map(e=>{let t=new yu(this);return t.fromModel(e),t},this);let s=this.allPlots.map(e=>e.initialize());await Promise.all(s),this._isShutdown||(this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),eF(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{let i=!t||function(e,t,i){let s={id:"Aggregation",context:{id:"Get"}};if(yO(nM(Ae(s,t,i)),nM(Ae(s,e,i)))||!yD(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!yD(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;let r=n5(t),n=n5(e);if(function(e,t){let i=e=>e.curves[0],s=i(e),r=i(t),n=yI.includes(s.style),a=yI.includes(r.style);if(n!==a)return!0;if(!a)return!1;if(s.style!==r.style)return!0;if(t.inputs&&yO(eK(e.inputs),eK(t.inputs)))return!0;return!1}(r,n))return!0;let a=e=>{let t=e.toLowerCase();return n.type===e&&r.type===e&&r[t]!==n[t]},o=r.type!==n.type,l=a("Forward"),u=a("Expression"),h=a("Symbol");return o||l||u||h}(e,t,this);this.view.resetZoomAndVisibleRange=i,i&&(this._maxOffset=0)}}closeView(){eF(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(eF(this.view)?this.view.reinitialize():(this.view=new yS,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){eF(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,eF(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(aS.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(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let 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(){let 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(){let 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;let i=t.series,s=e=>e.timeSeries===i||e.eventsSeries===i,r=this.allPlots.find(s);if(!eF(r))return;let n=eF(r)&&r.main,a=!1,o=!1;if(e===aS.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;a=!0}let l=eF(t.index)?i.container.getTimeData()[t.index]:null,u=e===aS.TS_EVENTSCHANGED,h=this.view.xAxis,c=h.xScale;if(e===aS.TS_MANYCHANGED||u){if(n&&this.data.checkRange)if(eF(this.display.xAxis.visibleRange)){let e={id:"Period",context:{range:this.display.xAxis.visibleRange}};e[yM]=!0,this.accessor.change(e);return}else delete this.data.checkRange;r.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;if(r.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,h.goToLatest(!0)),r.invalidateAssociatedAnnotations("NewChunkArrived")),(r.isSeasonal&&!h.wasVisibleRangeChanged||this.display?.xAxis?.isOrdinal)&&h.goToLatest(!0),t.part===en.Tail){let e=e_(this.timeline,l,Number,hN);h.shouldScrollIntoView(e)&&c.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),a=!0}else if(e===aS.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(l);-1!=e&&h.shouldScrollIntoView(e)?(c.shiftBars(1),a=!0):o=!0,r.isStudy&&r.invalidateAssociatedAnnotations("DataPointAdded")}else e===aS.TS_DATAPOINTCHANGED&&(o=!0,r.isStudy&&r.invalidateAssociatedAnnotations("DataPointChanged"));if(!u&&s(this.mainPlot)&&i.hasData&&0===i.container.size&&this.notifyHost(aS.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),a&&this.view.recalculateLayout(),o&&(a&&Ad("Performance : redundant call to recompute price domains (layout recalculation took care of this)","warn"),this.allAxes.filter(e=>e.plots.includes(r)).forEach(e=>{e.setDomain(),eF(l)&&e.updateFullDomain(l)})),!this.sentInitialLoadNotification&&e===aS.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(aS.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),mj(this);let e=this.display.period===tz.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(c.fitAllData=!0,c.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===aS.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){let t=this.panes.indexOf(e.pane),i=e.pane.axes.indexOf(e),s={chart:this.accessor,paneIndex:t,axisIndex:i};this.notifyHost(aS.CH_AXISSCALECHANGED,s)}get previousMask(){return eF(this._previousMask)||(this._previousMask=av(aA.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){return eF(this._hasLegend)||(this._hasLegend=AA().config.mode===er[er.cmdtyView]),this._hasLegend}onStreamingUpdates(e){eF(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 eF(this._ohlcMask)||(this._ohlcMask=av(aA.Open,aA.High,aA.Low,aA.Close,aA.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)==0)return!1;let i=(e,t)=>eH(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 AA().getRecordSource().subject.pipe(uL(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),oC(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return eF(this._hostElement)?this._hostElement.id:null}initialize(t){if(this._hostElement=t instanceof HTMLElement?t:tR(`#${t}`),!this._hostElement)throw Error(`There is no element ${t} in the DOM`);this.renderTo=t,this.seriesChangedToken=e(cm).subscribe(aS.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=e(cm).subscribe(aS.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return e(cm).unsubscribe(this.seriesChangedToken),e(cm).unsubscribe(this.metaChangedToken),eF(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(aS.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(){eF(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(ee.Arrow)}print(e={}){let t=tB(document.body,"iframe");t.src="",t.style.display="none",t.onload=()=>{let{title:i}=e,s=y_.call(this,{title:i}),r=new Image;r.src=s.data,r.style.width="100%",t.contentDocument.body.appendChild(r),new Promise(e=>{let t=()=>{r&&void 0!==r.naturalWidth&&0!==r.naturalWidth&&r.complete?e():setTimeout(t,150)};t()}).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),eF(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===tz.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,i=eO();!e&&t.visible&&t.mode===tz.TOOLTIP_CARDS&&tk(".bcharts-card",this.hostElement).forEach(e=>{let t=e.classList.contains("bcharts-card-move");i&&t||e.classList.contains("bcharts-legend")||(e.style.display="none")})}handleAnnotationChange(e){let 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 sz(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);let i=this.allAnnotations.find(t=>t.uid===e.uid);if(void 0!==i){let t=i.axis,s=t[`${e.id.toLowerCase()}Annotation`];if("function"==typeof s){s.call(t,i,e),"Delete"!==e.id||e.isUndoRedo||this.onAnnotationModifiedByTool(i,el.Deleted);return}}throw Error(`Unknown sub-action ${e.id} for action ${tz.ANN_ACTION_ID}`)}getPlotInfoFromDomId(e){let t=e.attributes.getNamedItem("data-plot-id").value,i=this.allPlots,s=i.findIndex(e=>e.id===t);return{type:Z[i[s].type],index:s}}getSimplePlot(e,t){return this.accessor.change({id:"Plot",context:{id:tz.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDomId(e),i=this.getSimplePlot(t.type,t.index),s={chart:this.accessor,plot:i};this.notifyHost(aS.CH_CARDPLOTCLICKED,s)}deletePlotClicked(e){let 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}});let s={chart:this.accessor,plot:i};this.notifyHost(aS.CH_CARDPLOTREMOVED,s)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let 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}});let s=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:s,visible:i};this.notifyHost(aS.CH_CARDPLOTVISIBILITYCHANGED,r)}plotMoreActionsClicked(e,t){let i=this.getPlotInfoFromDomId(e),s=this.getSimplePlot(i.type,i.index),r={x:t.clientX,y:t.clientY},n={chart:this.accessor,plot:s,offset:r,originalEvent:t};this.notifyHost(aS.CH_PLOTNEEDSCONTEXTMENU,n)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem("data-pane").value),i="Down"===e.attributes.getNamedItem("data-dir").value,s=t+ +!!i,r=t-!i;setTimeout(()=>{this.accessor.change({id:"MovePane",context:{from:s,to:r}}),this.notifyHost(aS.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){var i,s;let r=this.allAxes.indexOf(e),n=e.annotations.map(e=>e.toModel()),a=(i=this.model,s={axisIndex:r,annotations:n},sY(i,`..axes[${s.axisIndex}]`,e=>(e.annotations=s.annotations,e)));try{this.model=ad(a,tz.CHART_SCHEMA)}catch(e){Ad(`Cannot update annotation (corrupts definition), error is: ${e.message}`,"error")}t&&this.view.draw(),this.notifyHost(aS.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,i=!0){if(t!==el.None){if(i&&t!==el.Undo&&t!==el.Redo){let i=mT(e,t);this.undoRedoManager.done(i)}let s=mv(e);s.toolChange=el[t],this.notifyHost(aS.CH_ANNMODIFIEDBYTOOL,s)}}onAnnotationDone(e,t){let i={id:e,chart:this.accessor,toolChange:el[t]};this.notifyHost(aS.CH_ANNMODIFIEDBYTOOL,i)}onPaneHeightsUpdated(){var e,t;let i,s=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=(e=this.model,t={paneHeights:s},i=e,t.paneHeights.forEach(e=>{let t;i=sY(i,(t=e.index,`..panes[${t}]`),t=>(t.height=e.relativeHeight,t))}),i),this.notifyHost(aS.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!eF(e)||0===e.size)return null;let t=e.getTimeData();return{dataRange:{from:eb(t).getTime(),to:eC(t).getTime()},barCount:e.size}}}function yD(e,t){return e?.from===t?.from&&e?.to===t?.to}let yI=["Renko","Range","LineBreak","Kagi","PointAndFigure"];function yO(e,t){for(let i of Object.keys(e))if(e[i]!==t[i])return!0}let yw="MARKED_FOR_DELETION";function yR(e,t){if(0===t.plots.length)return e;let i=e;return t.plots.forEach(e=>{let t=yH(e.index),s=yF(i,t);eF(s)&&s.type===e.type&&(i=sY(i,t,e=>(e[yw]=!0,e)))}),ap(i=sY(i,`..plots{.${yw} === true}`,e=>tz.NULL_OBJECT))}function yN(e,{main:t,type:i,index:s},r){let n="..plots{.main === true}",a=sz(e,"..panes").map((e,t)=>{let i=1===sz(e,n).length;return sz(e,"..axes").map((e,s)=>{let a=1===sz(e,n).length;return sz(e,"..plots").map(e=>{let n=function(e,t,i,s){let r=Z[e.type],n={curves:ez(e.curves),type:e.type};n.precision=e.precision,n.visible=e.visible;let a=(e,t)=>{eF(e[t])?n[t]=e[t].map(e=>ez(e)):n[t]=[]},o=(e,t,i=!1)=>{!0===t.main&&(e.main=!0,e.showPrevious=t.showPrevious,i&&null!=t.events&&(e.events=ez(t.events)))},l=(e,t=e=>!0)=>{eF(s)&&(e.subtitles=s.allPlots.filter(e=>e.type===r).filter(t).map(e=>e.title))};switch(r){case Z.Symbol:{n.title=e.symbol;let t=n.curves[0].style,i=t=>{a(e,"inputs"),0===n.inputs.length&&(n.inputs=ez(t))};switch(t){case"Renko":i(tz.DEFAULT_RENKO_INPUTS);break;case"Kagi":i(tz.DEFAULT_KAGI_INPUTS);break;case"PointAndFigure":i(tz.DEFAULT_PNF_INPUTS);break;case"LineBreak":i(tz.DEFAULT_LINEBREAK_INPUTS);break;case"Baseline":i(tz.DEFAULT_BASELINE_INPUTS)}o(n,e,!0);break}case Z.Study:{a(e,"inputs");let s=sR(e.study),r=n.inputs,o="AVWAP"===e.study,l=0===r.length?"":` (${r.map(e=>o&&"Anchor"===e.name?new Date(e.value).toLocaleString():e.value).join(", ")})`,u=n.curves.map(e=>Number(e.shift)).filter(e=>e>0),h=0===u.length?"":` [${u.join(", ")}]`;n.title=`${s.id}${l}${h}`,n.studyId=s.id,a(e,"levels"),a(e,"bands"),n.placement=t?i?"overlay":"withMain":"standalone",n.detachedScale=e.detachedScale;break}case Z.BalanceSheet:case Z.IncomeStatement:{let t=aA[e.curves[0].fields[0]];n.title=`${t.name} (${e.fundamental.substring(0,1)})`,n.fundamentalId=t.id,n.frequency=e.fundamental;break}case Z.Expression:n.title=e.expression,o(n,e);break;case Z.Forward:n.title=e.forward,a(e,"offsets"),l(n),o(n,e);break;case Z.Seasonal:n.title=e.seasonal,l(n,e=>e.refSeasonal===n.title),a(e,"offsets"),o(n,e);break;default:throw Error("Unexpected plot type")}return n}(e,i,a,r);return n.paneIndex=t,n.axisIndex=s,n})})}).flat(2).map((e,t)=>(e.index=t,e));if(t)return a.filter(e=>e.main);if(!eF(i))return a;{let e=a.filter(e=>e.type===i);return eF(s)?e.filter(e=>e.index===s):e}}function yV(e,t){"Study"===e.type&&t.curves?.forEach(e=>delete e.varyColorPerBar),function(e){let t=Z[e.type];return t===Z.Forward||t===Z.Seasonal}(e)?eF(t.curves)&&(e.curves=t.curves):function(e,t){if(void 0!==t&&t.length===e.length)for(let i=0;i<e.length;++i){let s=t[i],r=e[i];for(let e of(eY(r,s),["shift","dashStyle","lineSmoothing","lineMarker"])){let t=s[e];eF(t)&&(r[e]=t)}}}(e.curves,t.curves);let i=Z[t.type];eF(t.precision)?e.precision=t.precision:delete e.precision,i===Z.Symbol?e.symbol=t.symbol:i===Z.Study?(function(e,t,i){let s=eK(e),r=eK(t);eY(s,r);let n=Object.keys(r).map(e=>({name:e,value:r[e]}));n.length>0&&(i.inputs=n)}(e.inputs,t.inputs,e),["bands","levels","detachedScale"].forEach(i=>{t[i]&&(e[i]=t[i])})):(i===Z.BalanceSheet||i===Z.IncomeStatement)&&t.frequency?e.fundamental=t.frequency:i===Z.Expression?eF(t.expression)&&(e.expression=t.expression):i===Z.Forward?(eF(t.offsets)&&(e.offsets=t.offsets),eF(t.forward)&&(e.forward=t.forward)):i===Z.Seasonal&&(eF(t.offsets)&&(e.offsets=t.offsets),eF(t.seasonal)&&(e.seasonal=t.seasonal),eF(t.usesInAverage)&&(e.usesInAverage=t.usesInAverage),rs(e))}let yH=e=>`..plots[${e}]`;function yF(e,t){let i=sz(e,t);return 1!==i.length?null:i[0]}let yB=["withMain","overlay","standalone","clone"];function yk(){return{plots:[]}}function yW(e){let t=e.display.chart.newPaneHeight??1;return{axes:[yk()],height:t}}function yU(e){let t=yW(e);return e.panes.push(t),t}function y$(e,t){let i=eH(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:yU(e),s=i.axes[0];return t.oppositeScale?yQ(i,s):s}function yG(e,t,i){let s=null,{mainPane:r,mainAxis:n}=n6(e);switch(t){case"withMain":s=yQ(r,n);break;case"overlay":s=n;break;case"standalone":s=yU(e).axes[0];break;case"clone":if("number"==typeof i){let t={main:!1,index:i,type:Z[Z.Study]},r=yN(e,t).find(e=>e.index===t.index);s=sz(e,`..panes[${r.paneIndex}]..axes[${r.axisIndex}]`)[0]}}return s}let yz=[{fields:[aA.Close.id],colors:["#888"],style:"Line",lineWidth:2,varyColorPerBar:!1,visible:!0}];function yY(e){return"Symbol"===e.type}let yj={attributes:["OpenVsClose"],colors:["#b63400","#007f3e","#1664db"],fields:["Open","High","Low","Close","Change"],style:"Candlestick",varyColorPerBar:!0,lineWidth:1},yK=0,yq=["#0d223a","#8abc21","#910000","#2f7ed8","#42ccdc","#bf95df","#860262","#e5daa3","#4682e8","#aaa9c1","#fcccdc","#f66b00","#d875be","#e84b46"],yX="Symbol";function yZ(e,t){let i={curves:[{attributes:[],colors:yq.slice(yK,yK+1),fields:e?[aA.Last.id]:[aA.Close.id],style:"Line",dashStyle:"Solid",varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0}]};return delete t.oppositeScale,ej(i,t),eF(t.curves)&&eY(i.curves,t.curves),yK=(yK+1)%yq.length,i}let yJ='..plots{(.type === "Symbol" || .type === "Expression") && .main !== true}';function yQ(e,t){let i=e.axes.find(e=>e!==t);return eF(i)||(i=yk(),e.axes.push(i)),i}let y0=()=>tz.NULL_OBJECT;function y1(e){return sY(e,"..axes.annotations",y0)}function y2(e){return ap(sY(e,'..plots{.type === "Symbol" && .main !== true}',y0))}let y3=".display.chart.previous";function y4(e,t,i){let s=[],r=i.allPlots[t.index];if(r?.type!==Z[t.type])return s;let n=i.panes.indexOf(r.axis.pane),a=n===i.panes.length-1,o=1===i.panes[n].axes.reduce((e,t)=>e+t.plots.length,0);return 0!==n&&s.push("ExistingAbove"),o||s.push("NewAbove"),a||s.push("ExistingBelow"),o||s.push("NewBelow"),s}function y5(e,t,i){let s=[],r=i.allPlots[t.index];if(r?.type!==Z[t.type])return s;let n=r.axis.pane,a=r.axis===n.axes[0],o=n.axes.some(e=>e.plots.some(e=>r!==e&&!e.hasDetachedScale)),l=r.hasDetachedScale;return(a||l)&&s.push("SecondaryAxis"),(!a||l)&&s.push("PrimaryAxis"),o&&s.push("NoAxis"),s}function y6(e,t){let i=e.panes[t],s=i.axes.map(e=>e.plots.reduce((e,t)=>e+ +!!t.detachedScale,0)),r=i.axes.length;return i.axes.forEach((e,t)=>{let n=s[t],a=e.plots.length;if(0!==n&&!(n<a)&&n===a)if(r>1&&1===n){let n=(t+1)%r;if(s[n]<i.axes[n].plots.length){let t=e.plots.find(e=>e.detachedScale);t&&(i.axes[n].plots.push(t),e.plots=e.plots.filter(e=>!e.detachedScale),s[n]++)}}else{let t=e.plots.find(e=>e.detachedScale);t&&(t.detachedScale=!1)}}),e}function y7(e,t){let i=e.allPlots[t],s=e.panes.indexOf(i.axis.pane),r=e.panes[s].axes.indexOf(i.axis),n=e.panes[s].axes[r].plots.findIndex(e=>e===i);return{pane:s,axis:r,plot:n}}let y8={MainPlot:as,Aggregation:{Update:aa,Get:function(e,t,i){return ez(e.data.aggregation)}},Period:{Update:function(e,t,i){let s=eF(t.period),r=eF(t.range),n=eF(t.density);if(+!!s+ +!!r+ +!!n>1)throw Error("Cannot set more than one of: period, range, density.");if(s&&(e.display.period=t.period,nH(e),nB(e)),r)if((!eF(e.display.period)||au(e.display.period))&&(e.display.xAxis.visibleRange=t.range),nF(e),nB(e),eF(i)){let s=function(e){let t=e.getDataStats();return null===t?null:t.dataRange}(i),r=nx(e.data.aggregation),n=i.data.aggregation,a=r.unit!==n.unit||r.size!==n.size||r.spec!==n.spec||!eF(s)||e.data.checkRange,o=a;if(!a){let{from:e,to:i}=s,{from:r,to:n}=t.range;o=r<e||r>i||n<e||n>i}o&&(e.data.range=t.range),delete e.data.checkRange}else e.data.checkRange=!0;return n&&(e.display.density=t.density,nH(e),nF(e)),(s||r||n)&&(nV(e),i&&(i.forceResetVisibleRange=!0)),e},Delete:function(e,t,i){return eF(t.period)&&t.period&&(delete e.display.period,ar(e),i&&(i.forceResetVisibleRange=!0)),e}},Crosshair:{Update:function(e,t){let[i,s]=eW(t.crosshair),{color:r,dashStyle:n}=t.horizontal||{},{color:a,dashStyle:o}=t.vertical||{},l=(e,t,i)=>{t&&(e.color=t),i&&(e.dashStyle=i)},u=sY(e,".display.xAxis.crosshair",e=>(e.enabled=i,l(e,a,o),e));return u=sY(u,".display.yAxis.crosshair",e=>(e.enabled=s,l(e,r,n),e)),eF(t.haloTracking)&&"boolean"==typeof t.haloTracking&&(u=sY(u,".display.chart",e=>(e.plotHover=t.haloTracking,e))),u},Get:function(e,t,i){let s=t=>sz(e,t)[0],r=s(".display.chart"),n=s(".display.xAxis.crosshair"),a=s(".display.yAxis.crosshair"),o="none";return n.enabled&&a.enabled?o="both":n.enabled?o="vertical":a.enabled&&(o="horizontal"),{crosshair:o,horizontal:{color:a.color,dashStyle:a.dashStyle},vertical:{color:n.color,dashStyle:n.dashStyle},haloTracking:r.plotHover}}},Tooltip:{Update:function(e,t){return sY(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){let s=sz(e,".display.tooltip")[0];return{visible:s.visible,mode:s.mode,showMainTitle:s.showMainTitle,mainTitle:s.mainTitle}}},Events:function(e,t){let i=ez(t);return Object.keys(t).forEach(e=>{tz.EVENTS.includes(e)||delete i[e];let s=t[e];"boolean"==typeof s?s={show:t[e]}:Object.keys(s).forEach(e=>{tz.EVENT_PROPERTIES.includes(e)||delete s[e]}),i[e]=s}),sY(e,n4,e=>("Symbol"===e.type&&(e.events=e.events||{},Object.keys(i).forEach(t=>{e.events[t]=e.events[t]||{},eY(e.events[t],i[t],!1)})),e))},Scale:{Update:function(e,t){let i=sY(e,"..panes[0]..axes",e=>(eH(t.scale)&&(e.scale=t.scale),e));return i=sY(i,".display.xAxis",e=>(eH(t.marginBars)&&(e.marginBars=t.marginBars),eH(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),eH(t.ordinalName)&&(e.ordinalName=t.ordinalName),eH(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e)),i=sY(i,".display.yAxis",e=>{(eF(t.minPadding)||eF(t.maxPadding))&&Ad("The 'minPadding' and 'maxPadding' are deprecated (ignored)","warn");let i=eH(t.preventLabelOverlap)&&!eH(t.preventVerticalLabelOverlap);i&&Ad("The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'","warn");let s=i?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return eH(s)&&(e.preventLabelOverlap=s),eF(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),eF(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),e}),eF(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:s,index:r,paneIndex:n}=e;eF(t,s,r)&&"vertical"===t&&Number.isInteger(r)&&(i=sY(i,`..panes[${n??0}]..axes[${r}]`,e=>eF(e)?(e.label=s,e):tz.NULL_OBJECT))}),eH(t.contractTransition)&&(i=sY(i,".display.xAxis",e=>(eY(e.contractTransition,t.contractTransition),e))),eH(t.cycleTransition)&&(i=sY(i,".display.xAxis",e=>(eY(e.cycleTransition,t.cycleTransition),e))),i},Get:function(e,t,i){let{mainAxis:s}=n6(e),r=sz(e,".display.xAxis")[0],n=sz(e,".display.yAxis")[0];return{scale:s.scale,marginBars:r.marginBars??0,preventLabelOverlap:n.preventLabelOverlap,preventVerticalLabelOverlap:n.preventLabelOverlap,preventHorizontalLabelOverlap:r.preventLabelOverlap,snapAnnotationsToPrices:n.snapAnnotationsToPrices,nonEodLabelWithDate:r.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:n.includePercentChangeWithLastValue??!1,ordinalName:r.ordinalName??"",contractTransition:r.contractTransition,cycleTransition:r.cycleTransition}}},Other:{Update:function(e,t,i){let s=e;if(eF(t.comparisonMode)&&"string"==typeof t.comparisonMode&&e$(q,t.comparisonMode)&&(s=sY(s,`..panes{${n4}}.axes`,e=>(e.comparison=t.comparisonMode,e))),eF(t.gridLines)){let[e,i]=eW(t.gridLines);s=sY(s,".display.xAxis.gridLines",t=>(t.visible=e,t)),s=sY(s,".display.yAxis.gridLines",e=>(e.visible=i,e))}if(eF(t.minorGridLines)){let[,e]=eW(t.minorGridLines);s=sY(s,".display.yAxis.minorGridLines",t=>(t.visible=e,t))}eF(t.newPaneHeight)&&"number"==typeof t.newPaneHeight&&(s=sY(s,".display.chart{.newPaneHeight > 0}",e=>(e.newPaneHeight=t.newPaneHeight,e))),eF(t.showNavigator)&&"boolean"==typeof t.showNavigator&&(s=sY(s,".display.scrollbar",e=>(e.visible=t.showNavigator,e))),eF(t.plotHover)&&"boolean"==typeof t.plotHover&&(s=sY(s,".display.chart",e=>(e.plotHover=t.plotHover,e))),eF(t.showLastValue)&&"string"==typeof t.showLastValue&&(s=sY(s,".display.yAxis",e=>(e.showLastValue=t.showLastValue,e))),eF(t.showMinMaxArc)&&"boolean"==typeof t.showMinMaxArc&&(s=sY(s,".display.chart",e=>(e.showMinMaxArc=t.showMinMaxArc,e))),eF(t.showGoToLatest)&&"boolean"==typeof t.showGoToLatest&&(s=sY(s,".display.chart",e=>(e.showGoToLatest=t.showGoToLatest,e))),eF(t.showLegend)&&"boolean"==typeof t.showLegend&&(s=sY(s,".display.chart",e=>(e.showLegend=t.showLegend,e)),t.showLegend||i.view.removeLegend()),eF(t.allAnnotationsLocked)&&"boolean"==typeof t.allAnnotationsLocked&&(s=sY(s,".display",e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),eF(t.exprSkipLeadingEmpty)&&"boolean"==typeof t.exprSkipLeadingEmpty&&(s=sY(s,".data",e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e)));let r=[];if(eF(t.extendedHours)&&"boolean"==typeof t.extendedHours&&(s=sY(s,".data",e=>(e.extendedHours=t.extendedHours,e))),eF(t.realTimeCboeBzx)&&"boolean"==typeof t.realTimeCboeBzx&&(s=sY(s,".data",e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&r.push("realTimeCboeBzx"),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),eF(t.buildContinuation)&&"boolean"==typeof t.buildContinuation&&(s=sY(s,".data",e=>(e.buildContinuation=t.buildContinuation,e))),r.length>0){let e={chart:i.accessor,hostPropsChanged:r};i.notifyHost(aS.CH_HOST_PROPS_CHANGED,e)}return s},Get:function(e,t,i){let s=sz(e,`..panes{${n4}}.axes.comparison`)[0],r=e.display,n=(e,t)=>eG(e,!1,t,"visible"),a=e=>(function(e,t){let i=e=>eF(e)&&"boolean"==typeof e&&e,s=i(e),r=i(t);return s&&r?"both":s?"vertical":r?"horizontal":"none"})(n(r.xAxis,e),n(r.yAxis,e)),o=eG(r.chart,!0,"showLegend");return{comparison:s,gridLines:a("gridLines"),minorGridLines:a("minorGridLines"),newPaneHeight:r.chart.newPaneHeight,showLastValue:r.yAxis.showLastValue,showLegend:o,showMinMaxArc:r.chart.showMinMaxArc,allAnnotationsLocked:r.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){let i=sR(t.studyId);if(!eH(i))return Ad(`Unknown or unavailable study with the id '${t.studyId}'`,"error"),e;let s=n5(e),r=sF(i);if(s.type===Z[Z.Expression]&&r)return Ad(`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;let n=t.placement||(i.meta.overlay?"overlay":"standalone"),a={type:"Study",study:t.studyId,visible:!0};"overlay"===n&&"VOL"===t.studyId&&(a.detachedScale=!0),void 0!==t.curves&&(a.curves=i.defaults.curves),yV(a,t);let o=yG(e,n,t.cloneIndex);eF(o)&&o.plots.push(a);let l=e.data.aggregation;return an(e,"Tick"===l.unit&&"None"===l.spec)}(e,t);case"IncomeStatement":case"BalanceSheet":return function(e,t){let i=n5(e);if(i.type!==Z[Z.Symbol])throw Error("Cannot add fundamental to the chart whose main plot is not a Symbol plot.");let s=i.symbol,r={curves:[{fields:[t.fundamentalId],lineWidth:2,style:"Line",varyColorPerBar:!1,visible:!0,colors:["#888"]}],fundamental:"Quarter",symbol:s,type:K[aA[t.fundamentalId].category],visible:!0};return yV(r,t),e.panes.push({axes:[{plots:[r]}]}),e}(e,t);case"Expression":let i=n5(e),s={curves:ez(yY(i)?i.curves:yz),expression:"",type:"Expression",visible:!0};return yV(s,t),y$(e,t).plots.push(s),e;case"Symbol":return function(e,t){let i=n5(e),s=AA().getDefaultMultiFieldCurve(),r=eF(s)?s:yj,n=i.curves?.length,a={curves:n===t.curves.length&&1===n?ez(yY(i)?i.curves:[r]):t.curves,symbol:"",type:"Symbol",visible:!0};return yV(a,t),y$(e,t).plots.push(a),e}(e,t);case"Seasonal":let r={curves:ez(yz),offsets:[0],seasonal:"",type:"Seasonal",visible:!0,main:!1};return yV(r,t),t.paneIndex=t.paneIndex??0,y$(e,t).plots.push(r),e;default:throw Error("Unexpected plot type '${type}', not supported currently")}},Get:yN,Delete:yR,Update:function(e,t,i){if(eF(t.placement)&&!yB.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let s=t.main?n4:yH(t.index),r=yF(e,s);if(!eH(r)||eH(t.type)&&r.type!==t.type)return e;if(eH(t.visible))return r.visible=t.visible,e;if(r.main&&function(e){let t=Z[e.type];return t===Z.Symbol||t===Z.Expression}(r)){if(t.curves){let i=e=>e.curves[0].style===$[$.Range],[s,n]=[i(r),i(t)];s&&!n?e=aa(e,{unit:"Day",size:1,spec:"None"}):!s&&n&&(e=aa(e,{unit:"Intraday",size:100,spec:"PerRange"}))}return t.type||(t.type=r.type),eF(t.precision)?r.precision=t.precision:delete r.precision,eF(t.showPrevious)&&(e=sY(e,n4,e=>(e.showPrevious=t.showPrevious,e))),t.curves?n$(e,t):e}{let r=sY(e,s,e=>(yV(e,t),e)),n=yN(r,t,i).find(e=>e.index===t.index);if(!eF(n))return e;if(!(t.type===Z[Z.Study]&&eF(t.placement)&&t.placement!==n.placement))return r;let a=yF(r,s),o=yG(r=yR(r,{id:"Delete",plots:[{index:t.index,type:t.type}]}),t.placement);return null!==o&&o.plots.push(a),r}}},Compare:{Update:function(e,t){let{yes:i,no:s}=eS((eF(t.symbols)&&(Ad("Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types","warn"),t.plots=t.symbols.map(e=>(e.type=yX,e))),t.plots?.some(e=>eF(e.leftScale)))?(Ad("Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'","warn"),t.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):t.plots,e=>e.oppositeScale??!1),{mainPane:r,mainAxis:n}=n6(e);r.alignOnExpirations=t.alignOnExpirations||!1;let a=yQ(r,n),o=e=>![yX,"Expression"].includes(e.type);a.plots=a.plots.filter(o);let l=n.plots.filter(e=>e.main||o(e)),u="Tick"===e.data.aggregation.unit;yK=0;let h=eh(yZ,u);return n.plots=l.concat(s.map(h)),i.length>0&&(a.plots.push(...i.map(h)),a.comparison=n.comparison,a.scale=n.scale),ap(e)},Get:function(e,t){let i=sz(e,yJ),{mainPane:s,mainAxis:r}=n6(e),n=[];for(let e of i){let t=r.plots.includes(e),i=e.type.toLowerCase(),s={curves:ez(e.curves),type:e.type,[i]:e[i],leftScale:!t};n.push(s)}return{plots:n,alignOnExpirations:s.alignOnExpirations}}},Annotation:{Get:function(e,t,i){let s=sz(e,"..panes").map((e,t)=>sz(e,"..axes").map((e,i)=>sz(e,".annotations").map(e=>({...e,paneIndex:t,axisIndex:i})))).flat(2).map((e,t)=>({...e,index:t}));return eF(t.index)&&Number.isFinite(t.index)?t.index<s.length?[s[t.index]]:tz.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=ez(e);if(t.strip.main){let e=n5(i),t=e.type.toLowerCase();e[t]=tz.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(i=y1(i)),t.strip.compare&&(i=y2(i)),i=sY(i,".data",e=>(e.range&&(delete e.range,e.checkRange=!0),e))},Outline:function(e,t,i){let s=yN(e,{main:!0},i)[0],r=s.title===tz.PLACEHOLDER_SYMBOL_NAME,n="Symbol"===s.type,a="Expression"===s.type,o=nX(s.title),l=[];return a&&!nq(o)?l=o.symbols:r||(l=[s.title]),{isTemplate:r,isDefinition:!r,main:{isSymbol:n,isExpression:a,symbols:l,title:r?null:s.title},compare:sz(e,yJ).map(e=>e.symbol),annotations:sz(e,"..annotations").map(e=>e.id),studies:yN(e,{type:"Study"},i).map(e=>e.title)}},Theme:{Update:function(e,t){let i=e,{backgroundColor:s,axis:{gridLinesColor:r,textColor:n,crosshairColor:a,gridLinesStyle:o},fontSize:l}=t,{chart:u,xAxis:h,yAxis:c}=l||{};if((s||u)&&(i=sY(e,".display.chart",e=>(s&&(e.backgroundColor=s),u&&(e.fontSize=u),e))),r){let e=e=>(e.color=r,e);i=sY(i,".display.xAxis.gridLines",e),i=sY(i,".display.yAxis.gridLines",e),i=sY(i,".display.yAxis.minorGridLines",e)}if(o){let e=e=>(e.dashStyle=o,e);i=sY(i,".display.xAxis.gridLines",e),i=sY(i,".display.yAxis.gridLines",e),i=sY(i,".display.yAxis.minorGridLines",e)}if(n){let e=e=>(e.textColor=n,e);i=sY(i,".display.xAxis",e),i=sY(i,".display.yAxis",e)}if(a){let e=e=>(e.color=a,e);i=sY(i,".display.xAxis.crosshair",e),i=sY(i,".display.yAxis.crosshair",e)}if(h||c){let e=e=>t=>(t.fontSize=e,t);h&&(i=sY(i,".display.xAxis",e(h))),c&&(i=sY(i,".display.yAxis",e(c)))}return i},Get:function(e,t,i){let{chart:s,xAxis:r,yAxis:n}=e.display||{},{fontSize:a,backgroundColor:o}=s||{},{fontSize:l,gridLines:u,textColor:h,crosshair:c}=r||{},{color:d,dashStyle:p}=u||{},{fontSize:f}=n||{},{color:m}=c||{};return{backgroundColor:o,axis:{gridLinesColor:d,textColor:h,crosshairColor:m,gridLinesStyle:p},fontSize:{chart:a,xAxis:l,yAxis:f}}}},Clear:function(e,t,i){let{paneIndex:s,annotations:r,studies:n}=t||{},a=Number.isInteger(s)?`[${s}]`:"",o=`..panes${a}`,l=e,u=e=>tz.NULL_OBJECT;return!0===r&&(i.allAnnotations.forEach(e=>i.onAnnotationModifiedByTool(e,el.Deleted,!1)),l=sY(l,`${o}..annotations`,u)),!0===n&&(l=sY(l,`${o}..plots{.type=="Study"}`,u)),l=ap(l)},Previous:{Update:function(e,t,i){return sY(e,y3,e=>(eY(e,t),e))},Get:function(e,t,i){return sz(e,y3)[0]}},MovePlot:{Update:function(e,t,i){if(!y4(e,t,i).includes(t.targetPane))return e;let s=y7(i,t.index),r=yF(e,yH(t.index));e.panes[s.pane].axes[s.axis].plots.splice(s.plot,1);let n=s.pane,a=!0;switch(t.targetPane){case"ExistingAbove":n--;break;case"NewAbove":e.panes.splice(n,0,yW(e)),a=!1;break;case"ExistingBelow":n++;break;case"NewBelow":n++,a=!1,e.panes.splice(n,0,yW(e))}a&&i.panes[n].isMain&&r?.type==="Study"&&"VOL"===r.study&&(r.detachedScale=!0);let o=e.panes[n];o.axes.length<2&&o.axes[0].plots.length>0&&o.axes.push(yk());let l=o.axes.findIndex(e=>0===e.plots.length),u=-1===l?o.axes.length-1:l;o.axes[u].plots.push(r);let h=y6(e,s.pane);return ap(h=y6(h,n))},Get:y4},PinPlot:{Update:function(e,t,i){if(!y5(e,t,i).includes(t.targetAxis))return e;let s=y7(i,t.index),r=e.panes[s.pane],n=yF(e,yH(t.index)),a=-1;switch(t.targetAxis){case"PrimaryAxis":a=0;break;case"SecondaryAxis":a=1;break;case"NoAxis":n.detachedScale=!0}if(-1!==a)if(a!==s.axis)delete n.detachedScale,r.axes.length<2&&a>0&&r.axes.push(yk()),r.axes[a].plots.push(n),r.axes[+(0===a)].plots.splice(s.plot,1);else{let e=r.axes[s.axis].plots[s.plot];delete e.detachedScale}return ap(y6(e,s.pane))},Get:y5}};function y9(e){return"function"==typeof e}function Ae(e,t,i){return(function(e,t){let i=y8[e];if(y9(i))return i;{let e=void 0!==t?i[t]:void 0;if(!y9(e)&&!y9(e=i[tz.DEFAULT_ACCESSOR_SUBACTION]))throw Error("Invalid accesor id and/or sub id");return e}})(e.id,e.context.id)(t,e.context,i)}function At(e){return{id:"MainPlot",context:e}}let Ai={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},As=Symbol.for("__ias__");class Ar{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new yx(this)}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)return void console.error("You cannot initialize a headless chart.");if(this.presenter.initialize(e),eH(t)){let e="string"==typeof t;e?Ad("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);let i=e?{symbol:t}:t;this.change(At(i))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,i=null){if(!this.headless)if(eF(e)){s9(e,t),s8(e,t);let s=gJ(e,!1,t,i,this.presenter);s.isDrawingAnnotation&&this.presenter.view.setCursor(ee.Crosshair),this.presenter.activeTool=s,eO()||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 AS()}get model(){return(this.headless?this._model:this.presenter.getModel())||AS()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:tz.ACTION_TEMPLATE,context:{strip:e}})}change(...e){let t={chart:this,actions:e.filter(e=>!e[As])};t.actions.length>0&&this.presenter?.notifyHost(aS.CH_API_ACTIONS_RECEIVED,t);let i=AA().config.validateInput,s=e.map(e=>i?ad(e,tz.ACCESSOR_SCHEMA):e);if(1===s.length){let e=s[0];if(e.id===tz.ACTION_TEMPLATE||e.context.id===tz.ACTION_GET)return Ae(e,this.model,this.presenter);if(!this.headless&&e.id===tz.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:r,no:n}=eS(s,e=>e.id===tz.ACTION_PLOT&&eF(e.context)&&e.context.id===tz.ACTION_DELETE),a=ez(this.model),o=ez(this.model);r.length>0&&n.push({id:tz.ACTION_PLOT,context:{id:tz.ACTION_DELETE,plots:r.map(e=>e.context)}}),n.forEach(e=>{if(!eF(o=Ae(e,o,this.presenter)))throw Error("Forgot to return model from accessor")}),this.fromModel(o,a)}async fromModel(e,t){let i=ad(e,tz.CHART_SCHEMA);this.headless?this._model=i:await this.presenter?.fromModel(i,t)}async load(e,t){let i={...Ai,...t},s=ad(JSON.parse(e),tz.CHART_SCHEMA),r=this.model,n=ez(r);if(eF(r)){if(s=function(e,t,i){let s=n5(t),r=s.type.toLowerCase();if(s[r]===tz.PLACEHOLDER_SYMBOL_NAME){let s=n5(e),{mainAxis:r}=n6(t),n=r.annotations,a=as(t,s);if(i){let{mainAxis:e}=n6(a);e.annotations=n}return a}return t}(r,s,i.keepNewAnnotations),i.keepNewAnnotations||(s=y1(s)),i.keepOldAnnotations&&(s=function(e,t){let{mainAxis:i}=n6(e),{mainAxis:s}=n6(t);yv(i,s);let r=e=>sz(e,'..plots{.type==="Study"}.study')[0],n=sz(e,yP).filter(e=>e!==i),a=sz(t,yP).filter(e=>e!==s);return n.forEach(e=>{let t=r(e),i=a.find(e=>t===r(e));eF(i)&&yv(e,i)}),t}(r,s)),i.keepNewCompare||(s=y2(s)),i.keepOldCompare&&(s=function(e,t){let i=sz(e,yJ),s=sz(t,yJ),r=Math.max(0,4-s.length);if(0===r)return t;let n=i.filter(e=>!s.find(t=>e.symbol===t.symbol)).slice(0,r);if(0===n.length)return t;let{mainPane:a,mainAxis:o}=n6(t),{mainAxis:l}=n6(e);return n.forEach(e=>{l.plots.includes(e)?o.plots.push(e):yQ(a,o).plots.push(e)}),t}(r,s)),i.keepOldAggregation){let e={id:tz.ACTION_AGGREGATION,context:r.data.aggregation},t=s.display.density;s=Ae(e,s,this.presenter),i.keepNewBarWidth&&eF(t)&&(s.display.density=t)}await this.fromModel(s,n),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){this.headless||this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=AS();if(this.headless)this._model=t;else if(this.presenter.getModel()){let i=this.presenter.mainPlot,s=null;if(i.isSymbol?s={symbol:i.symbol}:i.isExpression?s={expression:i.expression}:i.isForward?s={forward:i.forward}:i.isSeasonal&&(s={seasonal:i.seasonal}),eF(s)){let i=Ae({id:"Theme",context:{id:"Get"}},this.model,this.presenter),r=Ae(At(s),t,this.presenter);e&&(r=Ae({id:"Theme",context:i},r,this.presenter)),this.presenter?.fromModel(r)}}this.clearUndoRedo(),this.presenter?.notifyHost(aS.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){Ad("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:yL.call(this.presenter,e)}exportImage(e={}){return this.headless?null:y_.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){let s=this.presenter;if(this.headless||t<0||i<0||t>s.panes.length)return null;let r=s.panes[t];return i>r.axes.length?null:r.axes[i].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[i,s]of t.panes.entries()){let t=s.getBounds();if(eF(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(aS.CH_DIDBECOMEACTIVE,{chart:this})}}var cm=N("c15IW");function An(e,t,i,s,r){void 0===s&&(s=0),void 0===r&&(r=!1);var n=t.schedule(function(){i(),r?e.add(this.schedule(null,s)):this.unsubscribe()},s);if(e.add(n),!r)return n}function Aa(e,t){return e+Math.random()*(t-e)}let Ao=Function(atob("Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg")),Al=Function("f",atob("Zi5yZW1vdmVBbGxDaGFydHMoKTsg")),Au=Function("m",atob("cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiOw=="));async function Ah(e,t){if(t&&!Au(e.mode))return;let i=!1,s=0,r=25;for(;!i&&s<5;){let t=function(){let e=globalThis.parent?.location?.hostname||"";return["","localhost","127.0.0.1"].includes(e)||function(e){let t=e.split(".");if(!t||4!==t.length)return!1;let i=t.map(Number);if(!i.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[s,r]=i;return 10===s||172===s&&r>=16&&r<=31||192===s&&168===r}(e)}()||"FreeWidget"===e.mode,n=t?e.apiKey:"";try{let r=t?"":function(){let e=document.domain,t=e.split("."),i="__tld"+new Date().getTime(),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}(),a=function(e,t=""){return function(e,t){Object.keys(t).forEach(e=>!eF(t[e])&&delete t[e]);let i=new URLSearchParams(t);return`${e}/?${i.toString()}`}(atob("aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ=="),{module:atob("YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy"),secret:t,referer:e})}(r,n),o=await fetch(a);if(o.ok){let 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++,r*=2,await new Promise(e=>setTimeout(e,r))}i&&e.knownSite||(setTimeout(Ao,Aa(2e3,3e3)),setTimeout(()=>Al(AA()),Aa(4e3,5e3)))}var Ac={};function Ad(e,t="info",i=""){let s=globalThis.console,r=void 0!==s[t];s[r?t:"log"](e,i)}Ac=JSON.parse('{"major":2,"minor":361,"patch":1,"prerelease":false}');let Ap={environment:"Browser",validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${tz.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){let i=this.baseUrl[e],s=`${i}${t}`;if(Au(this.mode)&&this.knownSite){let{username:r,password:n}=this.credentials||{},a=eF(r,n),o=("timeseries"===e||"timeseriesNew"===e)&&a&&this.allowCredentials?`&username=${r}&password=${n}`:"";s=`https://${this.dataEndpoint}${i}${t}${o}`}let r=await fetch(s);return await r.text()},getCustomEventPopup:e=>null};async function Af(e,t){let i=AA()?.config;if(!i||!i.fetch)throw 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 Am=!1,Ag=null;function Ay(t,i={}){if(Am)throw Error("You should only call initFeed once during page's lifetime");Am=!0;let s=Object.assign(Ap);return eY(s,i),eH(s.logo)&&function(e,t){let i=new DOMParser().parseFromString(e,"image/svg+xml"),s=i.querySelector("svg")?.getAttribute("viewBox"),r=i.querySelector("path")?.getAttribute("d");if(eH(s)&&eH(r)){let e=s.split(" ").map(Number);4===e.length&&e.every(Number.isFinite)&&(m0={path:new Path2D(r),width:e[2],height:e[3],rect:new iw(0,0,0,0),logoClickable:t})}}(s.logo,s.logoClickable??!1),!function(e){var t;let i=e.extensions?.studyProvider;if(!eF(i))return;let s=i.getFields(),r=i.getStudies(),n=ez(s_(tz.CHART_SCHEMA)),a=n.definitions,o=a.studyField.enum,l=a.study.enum;for(let e of s)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(l.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...s.map(e=>e.id)),l.push(...r.map(e=>e.id)),t=tz.CHART_SCHEMA,ac.addSchema(t,n),ay(s),sI(r)}(s),(Ag=new t(s)).version=function(){let t=e(Ac),i=t.prerelease?`-${t.prerelease.identifier}.${t.prerelease.ordinal}`:"";return`${t.major}.${t.minor}.${t.patch}${i}`}(),Ad(`%cBarchart Chart version ${Ag.version}`,"info","font-size: larger"),Ag.cachesData&&(Ag.subject?.subscribe(Ag.onPerformInternalGc.bind(Ag)),e(cm).subscribe(aS.CH_ALL,Ag.onChartChanged.bind(Ag))),Ag}function AA(){return Ag}function AS(){return ez(AA()?.template)}function AT(){eH(Ag)&&(Ag.shutdown(),Am=!1,Ag=null)}function Av(e){let t=new Ar(!0);return t.load(e),t.change({id:"Outline",context:{id:"Get"}})}function AP(e,t,i,s=null){return new Proxy(e,{get:function(e,r,n){return r===t?function(t){let n=s?t[s]:t;return(i.handlesRequestsFor(n)?i:e)[r](t)}:Reflect.get(e,r,n)}})}class AC{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed;constructor(e){this.config=e,this._mainFeed=null,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=new Map,this.pendingRedraw=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=e1()}get subject(){return this.isAuxiliary||eH(this._subject)||(this._subject=new og().pipe(function(e){for(var t,i,s=[],r=1;r<arguments.length;r++)s[r-1]=arguments[r];var n=null!=(t=op(s[s.length-1])?s.pop():void 0)?t:a3,a=null!=(i=s[0])?i:null,o=s[1]||1/0;return oA(function(t,i){var s=[],r=!1,l=function(e){var t=e.buffer;e.subs.unsubscribe(),aj(s,e),i.next(t),r&&u()},u=function(){if(s){var t=new aK;i.add(t);var r={buffer:[],subs:t};s.push(r),An(t,n,function(){return l(r)},e)}};null!==a&&a>=0?An(i,n,u,a,!0):r=!0,u();var h=oS(i,function(e){var t,i,r=s.slice();try{for(var n=ak(r),a=n.next();!a.done;a=n.next()){var u=a.value,h=u.buffer;h.push(e),o<=h.length&&l(u)}}catch(e){t={error:e}}finally{try{a&&!a.done&&(i=n.return)&&i.call(n)}finally{if(t)throw t.error}}},function(){for(;null==s?void 0:s.length;)i.next(s.shift().buffer);null==h||h.unsubscribe(),i.complete(),i.unsubscribe()},void 0,function(){return s=null});t.subscribe(h)})}(tz.INTERNAL_GC_MILLIS),oC(e=>e.length>0))),this._subject}get isAuxiliary(){return null!==window.opener}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=AP(this.timeSeriesSource,"getTimeSeries",e,"symbol"),this.metaDataSource=AP(this.metaDataSource,"getMetaData",e),this.recordSource=AP(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(!eH(this.timeSeriesSource))throw Error("No time series source defined");return this.timeSeriesSource}getMetaDataSource(){if(!eH(this.metaDataSource))throw Error("No metadata source defined");return this.metaDataSource}getRecordSource(){if(!eH(this.recordSource))throw Error("No record source defined");return this.recordSource}async ready(){return tU.call(this,async()=>{await Ah(this.config,this instanceof AM||this instanceof Ab||this instanceof AI);let e=this.config.defaultTemplate;if(!e)throw Error("Must provide a default template");if("string"==typeof e){let t=await fetch(e);e=await t.json()}return this.template=ad(e,tz.CHART_SCHEMA),!0})}getHeadlessChart(){return new Ar(!0)}fixupRenderTo(e){if(!eH(e))return null;if(e instanceof HTMLElement)return e;let t=tR(`#${e}`);if(eH(t))return t;let i=[...this.charts.keys()].find(t=>t.id===e);return eH(i)?i:null}checkChart(e,t){let i=this.fixupRenderTo(e),s=eH(i)&&this.charts.has(i);return eH(t)&&t!==s&&Ad(`There is ${t?"no":"already a"} chart inside the element ${e}`,"error"),i}addChart(e,t=null){let i=this.checkChart(e,!1),s=new Ar;return this.charts.set(i,s),s.initialize(e,t),s}removeChart(e){let t=this.checkChart(e,!0);eH(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return eH(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);eH(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),eH(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!eH(t?.presenter?.view))return;let i=t.presenter.view;i.isHostElementVisible&&i.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:new Set,records:new Set,timeSeries:new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{eH(t)&&(eH(t.record)?e.records.add(t.record):eF(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){this.getTimeSeriesDataSource().refresh(),eN(aS.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.evictUnused(e)}triggerGc(){this.subject?.next()}onChartChanged(e,t){(e===aS.CH_RECREATED||e===aS.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc():this.triggerGc())}getDefaultMultiFieldCurve(){if(!eH(this.template))return null;if(!this.knowDefaultCurve){let e=n5(this.template);1===e.curves.length&&function(e){switch($[e]){case $.OHLC:case $.HLC:case $.Candlestick:case $.HollowCandles:case $.HeikinAshi:case $.ElderImpulseSystem:case $.Range:case $.MultiColumn:return!0;default:return!1}}(e.curves[0].style)?this.defaultOhlcCurve=ez(e.curves[0]):this.defaultOhlcCurve=null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=ez(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 Ab extends AC{constructor(e){super(e),this.timeSeriesSource=new he(!1),this.metaDataSource=new io,this.recordSource=new lN}}class AE extends AC{constructor(e){super(e),this.timeSeriesSource=new he(!0),this.metaDataSource=new io,this.recordSource=new lV}}class AL extends AC{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new he(!0),this.metaDataSource=new io,this.recordSource=new lN}}let A_=["drazen.dotlic@barchart.com","princec","b.hebert24@barchart.com"];class AM extends AC{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new he(!0),this.metaDataSource=new il,this.recordSource=new lH,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,eH(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){eH(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&&A_.includes(this.connection._username)&&Ad(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===tz.BC_EVENT_DISCONNECTED||e===tz.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===tz.BC_EVENT_LOGGED_IN||e===tz.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),eH(this._connection)&&(this.connection.off("timestamp",this.onTimestamp),this.connection.off("events",this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}}function Ax(e,t){return new AD(e,t)}class AD{_client;_subscriptions=new Map;_listeners=new Set;constructor(e,t){this._client=e;let i=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let s=e.marketSnapshot;if(eH(s)){let e=i(t);null!==e&&this._listeners.forEach(t=>t.onSnapshot?.(s,e))}let r=e.marketUpdate;if(eH(r)){let e=i(t);null!==e&&this._listeners.forEach(t=>t.onUpdate?.(r,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 eH(await this._client.connection)}shutdown(){eH(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!eH(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!eH(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){let t=await this._client.connection;return await t?.getInstrument(e)??[]}}class AI extends AC{_adapter=null;_auxFeeds=[];constructor(t){super(t),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new he(!0),this.metaDataSource=new iu,this.recordSource=new lF,e(cm).subscribe(aS.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let i of this._auxFeeds)i.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&eN(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error("Cannot set adapter on auxiliary feed");this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let 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){let 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(let t of this._auxFeeds)t.getAllCacheableEntities(e)}}var cm=N("c15IW");let AO=e(cm);export{AO as PubSub,Ay as initFeed,AA as getFeed,AT as shutdownFeed,Av as getChartOutline,AC as BaseDataFeed,Ab as BarchartSiteDataFeed,AL as MiniWidgetDataFeed,AM as MarketDataFeed,AI as OpenFeed,AE as SnapshotDataFeed,Ax as adaptOpenFeedClient,l8 as OHLCDataPointBuilder,nX as parseExpression,nZ as evaluateExpression,nQ as formatExpression,n0 as getExpressionSymbols,n2 as replaceExpressionSymbols,pA as ExpressionSeries,py as makeExpression,u1 as ContainerWrapperTimeSeries,t4 as formatPriceWithDecimals,t5 as getCombinedMetaData,lR as BaseRecordSource,aE as EmptyRecord,am as Field,aA as Fields,ue as TimeSeriesContainer,cf as TimeSeriesQuery,nN as Aggregation,tU as asyncReady,tL as hasOpenInterest,l3 as optionValueToDate,e1 as generateUid,s$ as getTaxonomies,sH as doesStudyExist,sN as getAnnotationTraits,g3 as getStudyOptions,cA as StudySeries,cy as makeHelperField,f_ as makeStudy,fY as convertSeries,fj as mapSeries,fD as movAvg,fI as movExp,fO as movSmo,fw as movWei,fR as movHul,fz as linReg,fF as trueRange,fk as typical,fW as roc,fG as stdDev,aS as Topics,ix as getLightness,en as ChunkPart,J as SeriesKind,z as AggregationSpec,G as AggregationUnit,B as ExpressionRecompute,k as ExpressionNoDataApproach,F as ExpressionMissingBar,Y as FieldValueType,K as FieldCategory,j as FieldFormat,yT as CustomEventPopup,tB as appendDOMElement,tN as styleDOMElement,tV as setAttributesDOMElement};
21
21
  //# sourceMappingURL=barchart.chart.js.map
chart-lib/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@barchart/chart-lib",
3
- "version": "2.361.0",
3
+ "version": "2.361.1",
4
4
  "description": "Barchart HTML5 Streaming Chart",
5
5
  "main": "barchart.chart.js",
6
6
  "types": "barchart.chart.d.ts",