@tradecanvas/core 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -21,6 +21,6 @@ Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=requi
21
21
  cursor: pointer;
22
22
  color: ${n?`#1fa874`:`#e8505b`};
23
23
  transition: background 0.1s;
24
- `,t.addEventListener(`mouseenter`,()=>{t.style.background=`#1f2630`}),t.addEventListener(`mouseleave`,()=>{t.style.background=`transparent`}),t.addEventListener(`click`,()=>{this.onItemSelect?.(e.intent),this.hide()}),s.appendChild(t)}n.appendChild(s),this.menuElement=s;let l=e=>{(e instanceof KeyboardEvent&&e.key===`Escape`||e instanceof MouseEvent&&!s.contains(e.target))&&this.hide()};document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l),this.removeHandler=()=>{document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)}}hide(){this.menuElement?.remove(),this.menuElement=null,this.removeHandler?.(),this.removeHandler=null}destroy(){this.hide(),this.onItemSelect=null}};function Yx(e,t,n={}){let r=Math.max(Math.abs(t)*(n.riskFraction??.01),1e-8),i=r*(n.riskReward??2);return e===`buy`?{side:e,entry:t,stopLoss:t-r,takeProfit:t+i}:{side:e,entry:t,stopLoss:t+r,takeProfit:t-i}}function Xx(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var Zx=6,Qx=.12,$x=[6,3],eS=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Yx(e,t,this.defaults),this.dragging=null}cancel(){this.draft=null,this.dragging=null}isActive(){return this.draft!==null}getDraft(){return this.draft?{...this.draft}:null}hitTest(t,n,r=Zx){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.k(this.priceOf(r),n),s=Math.abs(i-t.y);s<=o&&(o=s,a=r)}return a}beginDrag(e,t,n){let r=this.hitTest(e,t,n);return r!==null&&this.beginDragOn(r)}beginDragOn(e){return this.draft?(this.dragging=e,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=null,this.dragStart=null}drag(t,n){if(!this.draft||!this.dragging)return!1;let r=e.I(t.y,n);return this.draft=nS(this.draft,this.dragging,r),!0}endDrag(){this.dragging=null,this.dragStart=null}isDragging(){return this.dragging!==null}priceOf(e){let t=this.draft;return e===`entry`?t.entry:e===`sl`?t.stopLoss:t.takeProfit}render(e,t,n,r){this.renderLines(e,t,n),xx(e,this.tags(t,n),t,n,[])}renderLines(t,n,r){let i=this.draft;if(!i)return;let{chartRect:a}=n,o=e.k(i.entry,n),s=e.k(i.stopLoss,n),c=e.k(i.takeProfit,n),{profit:l,loss:u}=tS(r);t.save(),t.globalAlpha=Qx,t.fillStyle=l,t.fillRect(a.x,Math.min(o,c),a.width,Math.abs(c-o)),t.fillStyle=u,t.fillRect(a.x,Math.min(o,s),a.width,Math.abs(s-o)),t.globalAlpha=1,Yb(t,n,o,r.text,$x),Yb(t,n,c,l,[]),Yb(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=tS(n),o=r.side===`buy`?1:-1,s=e=>{let t=r.entry===0?0:(e-r.entry)/r.entry*100*o;return`${t>=0?`+`:``}${t.toFixed(2)}%`};return[{y:e.k(r.entry,t),color:n.text,grab:{kind:`bracket`,handle:`entry`},cells:[{kind:`stamp`,text:r.side===`buy`?`Long`:`Short`},{kind:`text`,text:`${Xx(r).toFixed(2)}R`}]},{y:e.k(r.takeProfit,t),color:i,grab:{kind:`bracket`,handle:`tp`},cells:[{kind:`stamp`,text:`TP`},{kind:`text`,text:s(r.takeProfit),color:i}]},{y:e.k(r.stopLoss,t),color:a,grab:{kind:`bracket`,handle:`sl`},cells:[{kind:`stamp`,text:`SL`},{kind:`text`,text:s(r.stopLoss),color:a}]}].filter(e=>Z(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))wx(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let{profit:o,loss:s}=tS(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.k(l,n);Z(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function tS(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function nS(e,t,n){let r=e.side===`buy`;if(t===`entry`){let t=n-e.entry;return{side:e.side,entry:n,stopLoss:e.stopLoss+t,takeProfit:e.takeProfit+t}}if(t===`sl`){let t=r?Math.min(n,e.entry):Math.max(n,e.entry);return{...e,stopLoss:t}}let i=r?Math.max(n,e.entry):Math.min(n,e.entry);return{...e,takeProfit:i}}function rS(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var iS=6,aS=[6,3],oS=class{draft=null;dragStart=null;dragging=!1;start(e,t,n=1){this.draft={side:e,price:t,quantity:n},this.dragging=!1}cancel(){this.draft=null,this.dragging=!1}isActive(){return this.draft!==null}isDragging(){return this.dragging}getDraft(){return this.draft?{...this.draft}:null}setPrice(e){return this.draft?(this.draft={...this.draft,price:e},!0):!1}toIntent(e){return this.draft?{side:this.draft.side,type:rS(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=iS){return this.draft?Math.abs(e.k(this.draft.price,n)-t.y)<=r:!1}beginDrag(e,t,n){return this.hitTest(e,t,n)&&this.beginDragOn()}beginDragOn(){return this.draft?(this.dragging=!0,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=!1,this.dragStart=null}drag(t,n){return!this.draft||!this.dragging?!1:this.setPrice(e.I(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(e,t,n,r,i){this.renderLines(e,t,n),xx(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Yb(t,n,e.k(i.price,n),sS(i.side,r),aS),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.k(i.price,t);if(!Z(a,t))return[];let o=rS(i.side,i.price,r);return[{y:a,color:sS(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:kx({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))wx(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let o=e.k(a.price,n);return Z(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:sS(a.side,r)}]:[]}};function sS(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var cS=2;function lS(e,t){return e.type===t.type?e.type===`cancelOrder`?e.orderId===t.orderId:e.type===`removeStop`?e.positionId===t.positionId&&e.which===t.which:e.positionId===t.positionId:!1}function uS(e,t,n=cS){let r=(e,n)=>t.x>=e.x-n&&t.x<=e.x+e.size+n&&t.y>=e.y-n&&t.y<=e.y+e.size+n;for(let t=e.length-1;t>=0;t--)if(r(e[t],0))return e[t];let i=null,a=1/0;for(let o of e){if(!r(o,n))continue;let e=Math.hypot(t.x-(o.x+o.size/2),t.y-(o.y+o.size/2));e<a&&(a=e,i=o)}return i}var dS=5,fS=7,pS=2;function mS(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function hS(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r,o=i.orderColors?.buy??`#1fa874`,s=i.orderColors?.sell??`#e8505b`;t.lineWidth=1.5;for(let i of n){let n=e.M(mS(i.time,r),r),c=e.k(i.price,r);if(n<a.x||n>a.x+a.width||c<a.y||c>a.y+a.height)continue;let l=i.side===`buy`,u=l?c+pS:c-pS,d=l?u+fS:u-fS;t.beginPath(),t.moveTo(n,u),t.lineTo(n-dS,d),t.lineTo(n+dS,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function gS(e){for(let t in e)if(e[t]!==null)return!0;return!1}function _S(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function vS(e,t){let n=t.style?.trading;return!n||!gS(n)?e:{...e,orderColors:{...e.orderColors,..._S({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,..._S({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function yS(e,t){let n=t.style?.markers;return!n||!gS(n)?e:{...e,..._S(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function bS(e,t){let n=t.style?.tradeZones;return!n||!gS(n)?e:{...e,..._S(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var xS=1e3,SS=class{orders=[];positions=[];currentPrice=null;config;orderRenderer=new Nx;positionRenderer=new Gx;dragHandler;contextMenu=new Jx;bracket=new eS;orderDraft=new oS;buttons=[];tagBoxes=[];tagInset=0;drawnTags=[];grabOffset=0;fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new qx(this.config.dragThreshold),this.contextMenu.onItemSelect=e=>{this.eventCallback?.(`orderPlace`,e)}}setContainer(e){this.container=e}setRequestRender(e){this.requestRender=e}setEventCallback(e){this.eventCallback=e}setOrders(e){this.orders=e,this.requestRender?.()}setPositions(e){this.positions=e,this.requestRender?.()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}getCurrentPrice(){return this.currentPrice}setCurrentPrice(e){this.currentPrice=e,this.requestRender?.()}setConfig(e){Object.assign(this.config,e),this.requestRender?.()}addFill(e){this.fills=[...this.fills.slice(-(xS-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-xS),this.realisedPnl=e.reduce((e,t)=>e+(t.pnl??0),0),this.requestRender?.()}getRealisedPnl(){return this.realisedPnl}getFills(){return[...this.fills]}armed=null;isOverButton(e){return this.config.enabled&&uS(this.buttons,e)!==null}runButton(e){switch(e.type){case`cancelOrder`:this.eventCallback?.(`orderCancel`,{orderId:e.orderId});break;case`closePosition`:this.eventCallback?.(`positionClose`,{positionId:e.positionId});break;case`reversePosition`:this.eventCallback?.(`positionReverse`,{positionId:e.positionId});break;case`removeStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,[e.which]:null});break;case`trailStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,trailingStop:e.distance});break}}startBracket(e,t){this.bracket.start(e,t),this.requestRender?.()}cancelBracket(){this.bracket.isActive()&&(this.bracket.cancel(),this.requestRender?.())}confirmBracket(){let e=this.bracket.getDraft();return e?(this.eventCallback?.(`bracketPlace`,{side:e.side,entry:e.entry,stopLoss:e.stopLoss,takeProfit:e.takeProfit,riskReward:Xx(e)}),this.bracket.cancel(),this.requestRender?.(),!0):!1}isBracketActive(){return this.bracket.isActive()}startOrderDraft(e,t){this.orderDraft.start(e,t),this.requestRender?.()}cancelOrderDraft(){this.orderDraft.isActive()&&(this.orderDraft.cancel(),this.requestRender?.())}confirmOrderDraft(){let e=this.orderDraft.toIntent(this.currentPrice);return e?(this.eventCallback?.(`orderPlace`,e),this.orderDraft.cancel(),this.requestRender?.(),!0):!1}isOrderDraftActive(){return this.orderDraft.isActive()}isOverDraggableLine(t,n,r=8){if(!this.config.enabled)return!1;if(gx(this.tagBoxes,t.x,t.y)&&!uS(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.k(i,n);return Z(a,n)&&Math.abs(t.y-a)<=r};for(let e of this.orders)if(e.draggable!==!1&&i(e.price))return!0;for(let e of this.positions)if(i(e.stopLoss)||i(e.takeProfit))return!0;return!1}onPointerDown(e,t,n){if(!this.config.enabled)return!1;let r=uS(this.buttons,e,n?.button),i=r?null:gx(this.tagBoxes,e.x,e.y);return i&&this.grabTag(i,e)||(this.grabOffset=0,this.bracket.isActive()&&this.bracket.beginDrag(e,t,n?.handle))||this.orderDraft.isActive()&&this.orderDraft.beginDrag(e,t,n?.handle)?(this.requestRender?.(),!0):r?(this.armed=r.action,!0):this.dragHandler.onPointerDown(e,this.orders,this.positions,t,n?.order??8)}grabTag(e,t){this.grabOffset=e.lineY-t.y;let n=e.grab;switch(n.kind){case`bracket`:return this.bracket.beginDragOn(n.handle);case`draft`:return this.orderDraft.beginDragOn();case`order`:{let t=this.orders.find(e=>e.id===n.orderId);return t!==void 0&&this.dragHandler.beginOrder(t,e.lineY)}case`stop`:{let t=this.positions.find(e=>e.id===n.positionId);return t!==void 0&&this.dragHandler.beginStop(t,n.which,e.lineY)}}}onPointerMove(e,t){if(this.armed)return!0;let n=this.grabOffset===0?e:{x:e.x,y:Jb(e.y+this.grabOffset,t)};if(this.bracket.isDragging()){let e=this.bracket.drag(n,t);return e&&this.requestRender?.(),e}if(this.orderDraft.isDragging()){let e=this.orderDraft.drag(n,t);return e&&this.requestRender?.(),e}if(!this.dragHandler.isActive())return!1;let r=this.dragHandler.onPointerMove(n,t);return r&&this.requestRender?.(),r}onPointerUp(e){if(this.grabOffset=0,this.armed){let t=this.armed;this.armed=null;let n=e?uS(this.buttons,e):null;return n&&lS(n.action,t)&&this.runButton(t),!0}if(this.bracket.isDragging())return this.bracket.endDrag(),this.requestRender?.(),!0;if(this.orderDraft.isDragging())return this.orderDraft.endDrag(),this.requestRender?.(),!0;let t=this.dragHandler.onPointerUp();return t?(t.sourceType===`order`?this.eventCallback?.(`orderModify`,{orderId:t.id,newPrice:t.newPrice,previousPrice:t.previousPrice}):this.eventCallback?.(`positionModify`,{positionId:t.id,[t.sourceType]:t.newPrice}),this.requestRender?.(),!0):!1}cancelPointer(){this.grabOffset=0;let e=!1;return this.armed&&(this.armed=null,e=!0),this.bracket.isDragging()&&(this.bracket.cancelDrag(),e=!0),this.orderDraft.isDragging()&&(this.orderDraft.cancelDrag(),e=!0),this.dragHandler.cancel()&&(e=!0),e&&this.requestRender?.(),e}onContextMenu(n,r){if(!this.config.enabled||!this.config.contextMenu?.enabled||!this.container)return!1;let i=e.I(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}tagRects(){return this.drawnTags}setTagInset(e){this.tagInset=Math.max(0,e)}render(e,t,n){if(this.buttons=[],this.tagBoxes=[],this.drawnTags=[],!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.renderInPlot(e,t,n)}finally{e.restore()}}renderInPlot(e,t,n){let r=vS(this.config,n);r.fillMarks!==!1&&hS(e,this.fills,t,r);let i=this.dragHandler.getDragState();this.positionRenderer.renderLines(e,this.positions,this.currentPrice,t,r,i),this.orderRenderer.renderLines(e,this.orders,t,r,i),this.bracket.renderLines(e,t,n),this.orderDraft.renderLines(e,t,n),xx(e,[...this.bracket.tags(t,n),...this.orderDraft.tags(t,n,this.currentPrice),...this.positionRenderer.tags(this.positions,this.currentPrice,t,r,i),...this.orderRenderer.tags(this.orders,t,r,i)],t,n,this.buttons,this.tagBoxes,this.tagInset,this.drawnTags)}renderAxisBadges(e,t,n,r){if(this.config.enabled){if(r){let{chartRect:i}=t;this.sortedAxisBadges(t,n).forEach((a,o)=>{let s=r[o]??a.y;!Number.isFinite(s)||s-16/2<i.y-.5||s+16/2>i.y+i.height+.5||wx(e,s,a.text,a.color,t,n)});return}for(let r of Cx(this.axisBadges(t,n),t))wx(e,r.at,r.text,r.color,t,n)}}axisBadgeLines(e,n=t.DARK_THEME){return this.config.enabled?this.sortedAxisBadges(e,n).map(e=>e.y):[]}sortedAxisBadges(e,t){return this.axisBadges(e,t).sort((e,t)=>e.y-t.y)}axisBadges(e,t){let n=vS(this.config,t);return[...this.positionRenderer.axisBadges(this.positions,e,n,this.dragHandler.getDragState()),...this.orderRenderer.axisBadges(this.orders,e,n,this.dragHandler.getDragState()),...this.bracket.axisBadges(e,t,this.config.pricePrecision),...this.orderDraft.axisBadges(e,t,this.config.pricePrecision)]}axisTagYs(e,n=t.DARK_THEME){return this.config.enabled?Cx(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},CS=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n,r){this.manager.renderAxisBadges(e,t,n,r)}axisBadgeLines(e,t){return this.manager.axisBadgeLines(e,t)}tagRects(){return this.manager.tagRects()}axisTagYs(e,t){return this.manager.axisTagYs(e,t)}},wS=`rgba(31, 168, 116,0.15)`,TS=`rgba(232, 80, 91,0.15)`,ES=`#1fa874`,DS=`#e8505b`,OS=100;function kS(e,t=`cumulative`){let n=(e,n)=>{let r=e.filter(e=>Number.isFinite(e.price)&&Number.isFinite(e.volume)&&e.volume>0);r.sort((e,t)=>n(e.price,t.price));let i=0;return r.map(e=>(i+=e.volume,{price:e.price,value:t===`cumulative`?i:e.volume}))},r=n(e.bids,(e,t)=>t-e),i=n(e.asks,(e,t)=>e-t),a=0;for(let e of r)a=Math.max(a,e.value);for(let e of i)a=Math.max(a,e.value);return{bids:r,asks:i,max:a}}function AS(t,n){if(t.length<2)return 1/0;let r=Math.abs(e.k(t[0].price,n)-e.k(t[1].price,n));return r>0?r:1/0}var jS=class{cache=null;invalidate(){this.cache=null}render(t,n,r,i){if(!i.enabled)return;let a=i.mode===`level`?`level`:`cumulative`;(!this.cache||this.cache.depth!==n||this.cache.mode!==a)&&(this.cache={depth:n,mode:a,bars:kS(n,a)});let{bids:o,asks:s,max:c}=this.cache.bars;if(c===0)return;let{chartRect:l}=r,u=Math.min(Math.max(i.maxWidth??OS,0),l.width),d=l.x+l.width,f=Math.min(AS(o,r),AS(s,r)),p=Number.isFinite(f)?f:4,m=Math.max(1,a===`level`?p-1:p),h=(n,i)=>{t.fillStyle=i;for(let{price:i,value:a}of n){let n=e.k(i,r);if(n<l.y||n>l.y+l.height)continue;let o=a/c*u;t.fillRect(d-o,n-m/2,o,m)}};if(h(o,i.bidColor??wS),h(s,i.askColor??TS),i.markBest){let n=(n,i)=>{if(!n)return;let a=e.k(n.price,r);a<l.y||a>l.y+l.height||(t.fillStyle=i,t.fillRect(d-u,a-.5,u,1))};n(o[0],i.bestBidColor??ES),n(s[0],i.bestAskColor??DS)}}},MS=class{data=null;config={};overlay=new jS;setData(e){this.data=e,this.overlay.invalidate()}setConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}isActive(){return!!this.config.enabled&&this.data!==null}render(e,t,n){if(!this.data||!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.overlay.render(e,this.data,t,this.config)}finally{e.restore()}}};function NS(e,t){let n=e.trailingStop;if(n===void 0||!(n>0)||!Number.isFinite(t)||!(t>0))return e;let r=e.side===`buy`,i=r?t-n:t+n,a=e.stopLoss;return a!==void 0&&(r?i<=a:i>=a)?e:{...e,stopLoss:i}}var PS=class{name=`paper`;state=`disconnected`;listeners=new Map;orders=[];positions=[];markPrice;markTime;seq=0;constructor(e={}){this.markPrice=e.markPrice??0}connect(e){this.state=`connected`,this.emit(`connectionChange`,this.state),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}disconnect(){this.state=`disconnected`,this.emit(`connectionChange`,this.state)}getConnectionState(){return this.state}setMarkPrice(e,t){this.markPrice=e,this.markTime=t!==void 0&&Number.isFinite(t)?t:void 0,this.checkPendingOrders(),this.checkStops()}fillTime(){return this.markTime??Date.now()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}async placeOrder(e){let t={id:this.nextId(`ord`),side:e.side,type:e.type,price:e.price,stopPrice:e.stopPrice,quantity:e.quantity??1,label:e.type===`market`?void 0:IS(e.type),draggable:!0,stopLoss:e.stopLoss,takeProfit:e.takeProfit,timeInForce:e.timeInForce};return e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(t.trailingStop=e.trailingStop),e.type===`market`?this.fill(t,this.markPrice||e.price):(this.orders=[...this.orders,t],this.emit(`orders`,this.orders)),t}async modifyOrder(e){this.orders=this.orders.map(t=>t.id===e.orderId?{...t,price:e.newPrice}:t),this.emit(`orders`,this.orders)}async cancelOrder(e){this.orders=this.orders.filter(t=>t.id!==e.orderId),this.emit(`orders`,this.orders)}async modifyPosition(e){let t=(e,t)=>e===void 0?t:e??void 0;this.positions=this.positions.map(n=>{if(n.id!==e.positionId)return n;let r={...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)};return e.trailingStop===null?delete r.trailingStop:e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(r.trailingStop=e.trailingStop),e.stopLoss===null&&delete r.trailingStop,typeof e.stopLoss==`number`?r:NS(r,this.markPrice)}),this.emit(`positions`,this.positions)}async closePosition(e){let t=this.positions.find(t=>t.id===e.positionId);t&&(this.close(t,this.markPrice||t.entryPrice,`close`),this.emit(`positions`,this.positions))}async reversePosition(e){let t=this.positions.find(t=>t.id===e.positionId);if(!t)return;let n=this.markPrice||t.entryPrice;this.close(t,n,`reverse`);let r=t.quantity-(t.closedQuantity??0),i={id:this.nextId(`ord`),side:FS(t.side),type:`market`,price:n,quantity:r};this.fill(i,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear(),this.orders=[],this.positions=[]}fill(e,t){this.orders=this.orders.filter(t=>t.id!==e.id);let n={id:this.nextId(`pos`),side:e.side,entryPrice:t,quantity:e.quantity,stopLoss:e.stopLoss,takeProfit:e.takeProfit};e.trailingStop!==void 0&&(n.trailingStop=e.trailingStop),this.positions=[...this.positions,n];let r={orderId:e.id,side:e.side,price:t,quantity:e.quantity,time:this.fillTime(),positionId:n.id,reason:`order`};this.emit(`fill`,r),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}close(e,t,n){this.positions=this.positions.filter(t=>t.id!==e.id);let r=e.quantity-(e.closedQuantity??0),i=e.side===`buy`?1:-1;this.emit(`fill`,{orderId:this.nextId(`ord`),side:FS(e.side),price:t,quantity:r,time:this.fillTime(),positionId:e.id,reason:n,pnl:(t-e.entryPrice)*r*i})}checkPendingOrders(){let e=this.orders.filter(e=>this.isTriggered(e));for(let t of e)this.fill(t,t.type===`limit`?t.price:t.stopPrice??t.price)}isTriggered(e){if(e.type===`limit`)return e.side===`buy`?this.markPrice<=e.price:this.markPrice>=e.price;if(e.type===`stop`||e.type===`stopLimit`){let t=e.stopPrice??e.price;return e.side===`buy`?this.markPrice>=t:this.markPrice<=t}return!1}trailStops(){let e=!1;return this.positions=this.positions.map(t=>{let n=NS(t,this.markPrice);return n!==t&&(e=!0),n}),e}checkStops(){let e=!1;for(let t of[...this.positions]){let n=t.stopLoss!==void 0&&(t.side===`buy`?this.markPrice<=t.stopLoss:this.markPrice>=t.stopLoss),r=t.takeProfit!==void 0&&(t.side===`buy`?this.markPrice>=t.takeProfit:this.markPrice<=t.takeProfit);!n&&!r||(this.close(t,n?t.stopLoss:t.takeProfit,n?`stopLoss`:`takeProfit`),e=!0)}this.trailStops()&&(e=!0),e&&this.emit(`positions`,this.positions)}nextId(e){return`${e}-${++this.seq}`}emit(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function FS(e){return e===`buy`?`sell`:`buy`}function IS(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var LS=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>n.delete(t)}once(e,t){let n=this.on(e,e=>{n(),t(e)});return n}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let e of n)e(t)}removeAllListeners(){this.listeners.clear()}},RS=6e4,zS=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),BS=class extends LS{currentBar=null;newest=-1/0;builtFromTrades=!1;lastTradeAt=null;timeframe;timeframeMs;dateFrame;bucket={};dateStamps=!1;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.reset()}seed(e){this.builtOffTheBuckets()&&(this.currentBar=null,this.newest=-1/0,this.lastTradeAt=null),Number.isFinite(e)&&(this.newest=Math.max(this.newest,(0,t.normalizeBarTime)(e)))}resume(e){if(!zS(e))return;let n=(0,t.normalizeBarTime)(e.time);n<this.newest||(this.newest=n,this.currentBar={time:n,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume??0,closed:!1,tickCount:0},this.builtFromTrades=!0,this.lastTradeAt=null)}setTimeZone(e,t=!1){this.bucket={timeZone:e??void 0},this.dateStamps=t}processTick(e){let n=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[n]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let r=this.barFor(e.time);r!==null&&(this.newest=(0,t.normalizeBarTime)(r),this.lastTradeAt=e.time,!this.currentBar||this.currentBar.time!==r?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:r,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1},this.builtFromTrades=!0):(this.currentBar.high=Math.max(this.currentBar.high,e.price),this.currentBar.low=Math.min(this.currentBar.low,e.price),this.currentBar.close=e.price,this.currentBar.volume+=e.volume,this.currentBar.tickCount++),this.emit(`bar`,this.currentBar))}processBar(e,n){let r=(0,t.normalizeBarTime)(e.time);if(r<this.newest){n&&this.emit(`correction`,{...e});return}if(this.newest=r,this.builtFromTrades=!1,n&&this.currentBar&&(0,t.normalizeBarTime)(this.currentBar.time)===r)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!n)this.currentBar={...e,closed:!1,tickCount:(this.currentBar?.tickCount??0)+1},this.emit(`bar`,this.currentBar);else{let t={...e,closed:!0,tickCount:1};this.emit(`barClose`,t),this.currentBar=null}}getCurrentBar(){return this.currentBar?{...this.currentBar}:null}getTickBuffer(){let e=Array(this.ringCount);for(let t=0;t<this.ringCount;t++)e[t]=this.tickRing[(this.ringHead+t)%this.ringCapacity];return e}reset(){this.currentBar=null,this.newest=-1/0,this.builtFromTrades=!1,this.lastTradeAt=null,this.ringHead=0,this.ringCount=0}barFor(e){let n=this.alignToTimeframe(e);if((0,t.normalizeBarTime)(n)>=this.newest)return n;if((0,t.normalizeBarTime)(e)<this.instantOf(this.newest))return null;let r=this.currentBar;return r!==null&&(0,t.normalizeBarTime)(r.time)===this.newest?r.time:this.newest}instantOf(e){return!this.dateStamps||!this.dateFrame?e:e-(0,t.offsetAt)(this.bucket.timeZone??0,e)*RS}builtOffTheBuckets(){let e=this.currentBar;return e===null||!this.builtFromTrades?!1:this.lastTradeAt===null?!this.startsABucket((0,t.normalizeBarTime)(e.time)):this.alignToTimeframe(this.lastTradeAt)!==e.time}startsABucket(e){return this.timeframeMs>0?this.dateStamps&&this.dateFrame?(0,t.timeframeBucketStart)(e,this.timeframe)===e:this.alignToTimeframe(e)===e:!0}alignToTimeframe(e){if(!(this.timeframeMs>0))return e;let n=(0,t.timeframeBucketStart)(e,this.timeframe,this.bucket);return!this.dateStamps||!this.dateFrame?n:n+(0,t.offsetAt)(this.bucket.timeZone??0,n)*RS}},VS=class extends LS{config;attempt=0;timer=null;active=!1;constructor(e){super(),this.config={...t.DEFAULT_RECONNECT,...e}}schedule(e){if(!this.config.enabled||!this.active)return;if(this.cancel(),this.attempt++,this.attempt>this.config.maxRetries){this.emit(`giveUp`,{attempts:this.attempt-1}),this.active=!1;return}let t=this.computeDelay();this.emit(`attempt`,{attempt:this.attempt,delay:t}),this.timer=setTimeout(()=>{this.timer=null,this.active&&e()},t)}onConnected(){this.attempt=0,this.cancel(),this.emit(`success`,void 0)}start(){this.active=!0}stop(){this.active=!1,this.cancel(),this.attempt=0}cancel(){this.timer&&=(clearTimeout(this.timer),null)}getAttempt(){return this.attempt}isActive(){return this.active}computeDelay(){let e=this.config.baseDelay,t=this.config.backoffMultiplier**(this.attempt-1),n=Math.min(e*t,this.config.maxDelay),r=n*.25*(Math.random()*2-1);return Math.max(0,Math.round(n+r))}},HS=20,US=class{price=null;previousClose=null;visible=!0;flashUntil=0;pricePrecision=null;locale=`en-US`;tag=null;setLocale(e){this.locale=e}setPrice(e,t){this.price!==null&&e!==this.price&&(this.flashUntil=Date.now()+300),t===void 0?e!==this.price&&(this.previousClose=this.price??e):this.previousClose=t,this.price=e}setVisible(e){this.visible=e}isVisible(){return this.visible}setPricePrecision(e){this.pricePrecision=e}getPrice(){return this.price}getTag(){return this.tag}render(e,t,n){this.renderLine(e,t,n),this.renderTag(e,t,n)}placed(t,n){let r=n.style?.lastPrice;if(!this.visible||this.price===null||r?.visible===!1)return null;let i=e.k(this.price,t),{chartRect:a}=t;return i<a.y||i>a.y+a.height?null:{y:i,color:this.previousClose===null||this.price>=this.previousClose?r?.up??n.candleUp??`#1fa874`:r?.down??n.candleDown??`#e8505b`}}renderLine(n,r,i){let a=this.placed(r,i);if(!a)return;let{y:o,color:s}=a,{chartRect:c}=r,l=i.style?.lastPrice,u=Date.now()<this.flashUntil,d=l?.width??1;n.setLineDash((0,t.lineDash)(l?.style??`dotted`,[4,3],d)),n.strokeStyle=s,n.lineWidth=d,n.globalAlpha=u?1:.7,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(o)+.5,d),n.stroke(),n.setLineDash([]),n.globalAlpha=1}renderTag(e,n,r){this.tag=null;let i=this.placed(n,r);if(!i||this.price===null)return;let{y:a,color:o}=i,{chartRect:s}=n,c=s.x+s.width+1,l=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),u=n.formatPrice?n.formatPrice(this.price):(0,t.formatPrice)(this.price,l,this.locale);e.font=`bold 11px ${r.font.family}`;let d=(n.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2;e.fillStyle=o,A(e,c,a-HS/2,d,HS,r),this.tag={x:c,y:a-HS/2,width:d,height:HS,color:o},e.fillStyle=ne(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+7,a)}},WS=1e3,GS=10,KS=1440,qS=5e3,JS=2,YS=864e5,XS=6e4,ZS=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],QS=new WeakMap;function $S(e){if(e instanceof aC||!e.supportedTimeframes?.length)return e;let t=QS.get(e);return t||(t=new aC(e,e.supportedTimeframes),QS.set(e,t)),t}function eC(e,n,r){if(n.includes(e))return e;let i=(0,t.pickBaseTimeframe)(e,n,{timeZone:r});return i&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(i))<=1440?i:null}function tC(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||eC(n,r)!==null}function nC(e,n,r){let i=(0,t.parseTimeframe)(n),a=r!==void 0&&(0,t.timeframeSpansDays)(n)&&e%YS!==0,o=a?e+(0,t.offsetAt)(r,e)*XS:e,s;if(i?.unit===`M`){let e=new Date(o);s=Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+i.count,1)}else s=o+(0,t.timeframeToMs)(n);return a?(0,t.wallToUtc)(s,r):s}function rC(e,t){let n=t[0],r={time:e,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume};for(let e=1;e<t.length;e++){let n=t[e];n.high>r.high&&(r.high=n.high),n.low<r.low&&(r.low=n.low),r.close=n.close,r.volume+=n.volume}return r}function iC(e,t){return rC(e,[...t.values()].sort((e,t)=>e.time-t.time))}var aC=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;closedBuckets=new Map;tail=null;generation=0;zones=new Map;resolving=new Map;unanswered=new Map;constructor(e,t){this.inner=e,this.baseTimeframes=t,this.name=e.name,e.fetchHistoryBefore&&(this.fetchHistoryBefore=(e,t,n,r)=>this.historyBefore(e,t,n,r)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e=>this.resolveShared(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),e.fetchTrades&&(this.fetchTrades=e.fetchTrades.bind(e)),e.subscribeTrades&&(this.subscribeTrades=e.subscribeTrades.bind(e)),this.listen(`bar`,e=>this.onBar(e));for(let e of ZS)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=eC(e,this.baseTimeframes);if(!t)throw RangeError(`${this.name} cannot serve the ${e} timeframe`);return t}connect(e){let t=this.baseFor(e.timeframe);this.generation++,this.resetBucket(),this.closedBuckets.clear(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,...this.planFor(e.timeframe,this.keptZone(e.symbol))},this.live&&this.resumeFromHistory(this.live),this.inner.connect({...e,timeframe:this.live?.base??t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.closedBuckets.clear(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){if(this.baseFor(t)===t)return this.inner.fetchHistory(e,t,n);let r=this.generation,{plan:i,bars:a}=await this.baseBarsWithZone(e,t,async i=>{let a=this.baseBarsFor(t,i,n),o=await this.inner.fetchHistory(e,i,Math.min(a,WS));return this.extendBack(e,i,o,a,r)});return this.rememberTail(e,t,a,i),this.toTarget(a,t,n,i)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.generation++;for(let e of this.unsubscribe)e();this.unsubscribe.length=0,this.listeners.clear(),this.inner.dispose()}bucketFor(e,t){let n=eC(t,this.baseTimeframes);return n===null||n===t?null:{...this.planFor(t,this.keptZone(e)).bucket}}waitsForZone(e){return typeof this.inner.resolveSymbol==`function`&&(0,t.timeframeFollowsDays)(e)}keptZone(e){return this.zones.get(e)??void 0}renewZone(e){let t=this.unanswered.get(e);if(!t)return;let n=t.zone,r=t.asked!==void 0&&this.resolving.get(e)===t.asked;n===void 0&&r||(this.unanswered.delete(e),n===void 0?this.zones.delete(e):this.zones.set(e,n))}async zoneFor(e){if(this.zones.has(e))return this.keptZone(e);let t,n=new Promise(e=>{t=setTimeout(()=>e(),qS)});try{await Promise.race([this.resolveShared(e),n])}catch{}finally{clearTimeout(t)}return this.zones.has(e)||(this.zones.set(e,null),this.unanswered.set(e,{asked:this.resolving.get(e)})),this.keptZone(e)}resolveShared(e){let t=this.resolving.get(e);if(t)return t;let n=this.inner.resolveSymbol.bind(this.inner),r=Promise.resolve().then(()=>n(e));this.resolving.set(e,r);let i=()=>{this.resolving.get(e)===r&&this.resolving.delete(e)};return r.then(t=>{this.keepZone(e,t),i()},i),r}keepZone(e,n){let r=(0,t.symbolTimeZone)(n),i=r&&(0,t.isValidTimeZone)(r)&&!(0,t.isUtcTimeZone)(r)?r:null,a=this.unanswered.get(e);a?this.unanswered.set(e,{...a,zone:i}):this.zones.has(e)||this.zones.set(e,i)}planFor(e,n){let r=this.baseFor(e),i=n!==void 0&&r!==e&&(0,t.timeframeFollowsDays)(e)?eC(e,this.baseTimeframes,n):null,a=i??r,o=i?n:void 0;return{base:a,zone:o,bucket:{timeZone:o,dates:(0,t.timeframeSpansDays)(a)}}}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner);if(this.baseFor(t)===t)return i(e,t,n,r);let a=this.generation,{plan:o,bars:s}=await this.baseBarsWithZone(e,t,async o=>{let s=this.baseBarsFor(t,o,r),c=await i(e,o,n,Math.min(s,WS));return this.extendBack(e,o,c.filter(e=>e.time<n),s,a,1)});return this.toTarget(s,t,r,o)}async baseBarsWithZone(e,t,n){if(!this.waitsForZone(t)||this.zones.has(e)){let r=this.planFor(t,this.keptZone(e));return{plan:r,bars:await n(r.base)}}let r=this.planFor(t,void 0).base,i=n(r);i.catch(()=>{});let a=this.planFor(t,await this.zoneFor(e));return{plan:a,bars:await(a.base===r?i:n(a.base))}}baseBarsFor(e,n,r){return(r+1)*Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(n))}async extendBack(e,t,n,r,i,a=1){let o=this.inner.fetchHistoryBefore?.bind(this.inner),s=n,c=a;for(;o&&s.length>0&&s.length<r&&c<10&&i===this.generation;){let n=s[0].time,i=await o(e,t,n,Math.min(r-s.length,WS));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r,i){if(e.length===0)return[];let a=(0,t.resampleBars)(e,n,i.bucket);return a.length>1&&a[0].time!==e[0].time&&a.shift(),a.length>r?a.slice(a.length-r):a}rememberTail(e,n,r,i){if(r.length===0)return;let a=(0,t.timeframeBucketStart)(r[r.length-1].time,n,i.bucket),o=r.length;for(;o>0&&(0,t.timeframeBucketStart)(r[o-1].time,n,i.bucket)===a;)o--;this.tail={symbol:e,target:n,zone:i.zone,bucket:a,bars:r.slice(o)}}resumeFromHistory(e){let t=this.tail;if(!(!t||t.symbol!==e.symbol||t.target!==e.target||t.zone!==e.zone)){this.bucket=t.bucket;for(let e of t.bars)this.parts.set(e.time,e)}}onBar(e){let n=this.live;if(!n){this.emit(`bar`,e.data);return}let{bar:r,closed:i}=e.data,a=(0,t.timeframeBucketStart)(r.time,n.target,n.bucket);if(this.bucket!==null&&a<this.bucket){i&&this.correctClosed(a,r);return}if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.keepClosed(),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=(0,t.timeframeBucketStart)(nC(r.time,n.base,n.zone),n.target,n.bucket),c=i&&s!==a;this.emit(`bar`,{bar:o,closed:c}),c&&(this.keepClosed(),this.resetBucket(),this.bucket=s)}composed(){return this.bucket===null||this.parts.size===0?null:iC(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:iC(e,n),closed:!0}))}keepClosed(){if(!(this.bucket===null||this.parts.size===0)){this.closedBuckets.set(this.bucket,this.parts);for(let e of this.closedBuckets.keys()){if(this.closedBuckets.size<=2)break;this.closedBuckets.delete(e)}}}resetBucket(){this.bucket=null,this.parts=new Map}listen(e,t){let n=e=>t(e);this.inner.on(e,n),this.unsubscribe.push(()=>this.inner.off(e,n))}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},oC=1e3,sC=15e3,cC=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],lC=class{bar=null;count=0;lastTime=-1/0;constructor(e){this.tradesPerBar=e}push(e){let t=[],n=!1;for(let r of e){if(this.bar)this.bar={...this.bar,high:Math.max(this.bar.high,r.price),low:Math.min(this.bar.low,r.price),close:r.price,volume:this.bar.volume+r.volume};else{let e=Math.max(r.time,this.lastTime+1);this.lastTime=e,this.bar={time:e,open:r.price,high:r.price,low:r.price,close:r.price,volume:r.volume},this.count=0}this.count++,n=!0,this.count>=this.tradesPerBar&&(t.push({bar:this.bar,closed:!0}),this.bar=null,n=!1)}return n&&this.bar&&t.push({bar:this.bar,closed:!1}),t}build(e){return this.bar=null,this.count=0,this.lastTime=-1/0,this.push(e).map(e=>e.bar)}},uC=class{name;supportedTimeframes;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;tick=null;stopTrades=null;keepAlive=null;tickMode=!1;state=`disconnected`;constructor(e){this.inner=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes,e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),this.fetchTrades=e.fetchTrades.bind(e),this.subscribeTrades=e.subscribeTrades.bind(e);for(let t of cC)e.on(t,e=>{this.tickMode||this.emit(t,e.data)})}async fetchHistory(e,n,r){let i=(0,t.tickBarCount)(n);if(i===null)return this.inner.fetchHistory(e,n,r);let a=(await this.inner.fetchTrades(e,oC)).filter(mC).sort((e,t)=>e.time-t.time),o=new lC(i),s=o.build(a);return this.tick={symbol:e,builder:o,after:a.length?a[a.length-1].time:-1/0},r!==void 0&&r>0?s.slice(-r):s}fetchHistoryBefore(e,n,r,i){return(0,t.tickBarCount)(n)!==null||!this.inner.fetchHistoryBefore?Promise.resolve([]):this.inner.fetchHistoryBefore(e,n,r,i)}connect(e){this.disconnect();let n=(0,t.tickBarCount)(e.timeframe);if(n===null){this.tickMode=!1,this.inner.connect(e);return}this.tickMode=!0;let r=this.tick?.symbol===e.symbol?this.tick:{symbol:e.symbol,builder:new lC(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>mC(e)&&e.time>=r.after);for(let{bar:e,closed:n}of r.builder.push(t))this.emit(`bar`,{bar:e,closed:n}),this.emit(`tick`,{time:e.time,price:e.close,volume:e.volume})}),this.state=`connected`,this.emit(`connectionChange`,`connected`),this.keepAlive=setInterval(()=>this.emit(`connectionChange`,`connected`),sC)}disconnect(){this.tickMode?(this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.state=`disconnected`):this.inner.disconnect()}getConnectionState(){return this.tickMode?this.state:this.inner.getConnectionState()}dispose(){this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.listeners.clear(),this.inner.dispose()}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},dC=new WeakMap;function fC(e){if(e instanceof uC||!pC(e))return e;let t=dC.get(e);return t||(t=new uC(e),dC.set(e,t)),t}function pC(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function mC(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var hC=Symbol(`tradecanvas.sourceAdapter`),gC=new WeakSet;function _C(e){return gC.has(e)}var vC=(e,t)=>`${e}\u0000${t}`;function yC(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function bC(e){if(e.adapter&&e.feed)throw TypeError(`A stream takes an adapter or a feed, not both`);if(e.adapter)return e.adapter;if(e.feed)return CC(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function xC(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var SC=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function CC(e){let t=e[hC];if(t)return t;let n=new wC(e);return gC.add(n),n}var wC=class{name;supportedTimeframes;fetchHistoryBefore;state=`disconnected`;listeners=new Map;unsubscribe=null;requests=new Map;streamed=null;constructor(e){this.feed=e,this.name=e.name,e.supportedTimeframes&&(this.supportedTimeframes=e.supportedTimeframes),e.pagesBack!==!1&&(this.fetchHistoryBefore=(e,t,n,r)=>this.feed.getBars({symbol:e,timeframe:t,countBack:r,before:n,signal:this.signalFor(e,t)})),xC(this,e,SC)}fetchHistory(e,t,n=500){return this.feed.getBars({symbol:e,timeframe:t,countBack:n,signal:this.signalFor(e,t)})}fetchStreamHistory(e,t){return this.streamed=vC(e.symbol,e.timeframe),this.fetchHistory(e.symbol,e.timeframe,t)}connect(e){this.subscribe({symbol:e.symbol,timeframe:e.timeframe})}subscribe(e,t){this.stopSubscription(),this.streamed=vC(e.symbol,e.timeframe);let n=!0,r=!1,i=null;this.unsubscribe=()=>{n=!1,i?.()};let a=e=>{this.setState(e),t?.connection(e)},o=this.feed.subscribeBars(e,{bar:(e,r)=>{n&&(this.emit(`bar`,{bar:e,closed:r}),t?.bar(e,r))},tick:e=>{n&&(this.emit(`tick`,e),t?.tick(e))},connection:e=>{n&&(r=!0,a(e))},symbolInfo:e=>{n&&(this.emit(`symbolInfo`,e),t?.symbolInfo(e))},error:e=>{n&&(this.emit(`error`,{message:e}),t?.error(e))}});if(!n){o();return}i=o,r||a(`connected`)}disconnect(){this.stopSubscription(),this.streamed!==null&&(this.requests.get(this.streamed)?.abort(),this.requests.delete(this.streamed),this.streamed=null),this.state=`disconnected`}getConnectionState(){return this.state}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}signalFor(e,t){let n=vC(e,t),r=this.requests.get(n);return r||(r=new AbortController,this.requests.set(n,r)),r.signal}stopSubscription(){let e=this.unsubscribe;this.unsubscribe=null,e?.()}setState(e){this.state=e,this.emit(`connectionChange`,e)}emit(e,t){let n={type:e,data:t,timestamp:Date.now()};for(let t of[...this.listeners.get(e)??[]])t(n)}};function TC(e){let t={name:e.name,...e.supportedTimeframes?{supportedTimeframes:e.supportedTimeframes}:{},pagesBack:typeof e.fetchHistoryBefore==`function`,getBars:async({symbol:t,timeframe:n,countBack:r,before:i})=>i===void 0?e.fetchHistory(t,n,r):e.fetchHistoryBefore?e.fetchHistoryBefore(t,n,i,r):[],subscribeBars:(t,n)=>EC(e,t,n),[hC]:e};return xC(t,e,SC),t}function EC(e,t,n){let r=[[`bar`,e=>{let{bar:t,closed:r}=e.data;n.bar(t,r)}],[`tick`,e=>n.tick(e.data)],[`connectionChange`,e=>n.connection(e.data)],[`symbolInfo`,e=>n.symbolInfo(e.data)],[`error`,e=>n.error(e.data?.message??`Adapter error`)]];for(let[t,n]of r)e.on(t,n);return e.connect({symbol:t.symbol,timeframe:t.timeframe}),()=>{for(let[t,n]of r)e.off(t,n);e.disconnect()}}function DC(e){let t=bC(e),n=!_C(t),r=$S(t),i=r instanceof aC?r:null,a=fC(r);return a instanceof wC?new OC(a,i,n):new kC(a,i,n)}var OC=class{subscriber=null;constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.subscriber=e}getBars(e,t){return this.adapter.fetchStreamHistory(e,t)}subscribeBars(e){this.adapter.subscribe(e,this.subscriber??void 0)}unsubscribe(){this.adapter.disconnect()}release(){this.subscriber=null}},kC=class{unlisten=[];constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.hear(`connectionChange`,t=>e.connection(t.data)),this.hear(`tick`,t=>e.tick(t.data)),this.hear(`bar`,t=>{let{bar:n,closed:r}=t.data;e.bar(n,r)}),this.hear(`error`,t=>e.error(t.data?.message??`Adapter error`));try{this.hear(`symbolInfo`,t=>e.symbolInfo(t?.data))}catch{}}getBars(e,t){return this.adapter.fetchHistory(e.symbol,e.timeframe,t)}subscribeBars(e){this.adapter.connect({symbol:e.symbol,timeframe:e.timeframe})}unsubscribe(){this.adapter.disconnect()}release(){for(let e of this.unlisten)e();this.unlisten=[]}hear(e,t){this.adapter.on(e,t),this.unlisten.push(()=>this.adapter.off(e,t))}},AC=2e4,jC=6e4,MC=3e4,NC=500,PC=864e5;function FC(e,n){if(!n)return e;let{time:r,open:i,high:a,low:o,close:s,volume:c}=n;return[...e,{time:(0,t.normalizeBarTime)(r)/(0,t.barTimeUnit)(e),open:i,high:a,low:o,close:s,volume:c}]}function IC(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var LC=class extends LS{config=null;source=null;aggregator=null;reconnector;priceLine=new US;state=`disconnected`;lastPrice=null;previousClose=null;sentPreviousClose=null;previousCloseTime=null;heartbeatTimer=null;lastMessageTime=0;connectSeq=0;timeZone=null;historyEnd=null;constructor(){super(),this.reconnector=new VS,this.wireReconnector()}async connect(e){this.disconnect();let n=DC(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new BS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new VS(e.reconnect??t.DEFAULT_RECONNECT),this.wireReconnector(),this.aggregator.on(`bar`,e=>{this.emit(`barUpdate`,e),this.updatePrice(e.close)}),this.aggregator.on(`barClose`,e=>{this.setPreviousClose(e),this.emit(`barClose`,e)}),this.aggregator.on(`correction`,e=>{(0,t.normalizeBarTime)(e.time)===this.previousCloseTime&&(this.previousClose=e.close),this.emit(`barCorrection`,e)}),n.listen(this.subscriber()),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat(),this.source&&=(this.source.release(),this.source.unsubscribe(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.historyEnd=null,this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.source||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,(e!==this.config.symbol||t!==this.config.timeframe)&&this.source.resampler?.renewZone(e),this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}setTimeZone(e){if(e!==null&&!(0,t.isValidTimeZone)(e))throw RangeError(`Unknown time zone: ${e}`);this.timeZone=e,this.applyTickZone()}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}applyTickZone(){let e=this.config;if(!this.aggregator||!e)return;let t=this.historyEnd,n=t!==null&&t%PC===0,r=this.source?.resampler?.bucketFor(e.symbol,e.timeframe);if(r){let e=r.dates===!0&&n;this.aggregator.setTimeZone(r.timeZone??(e?this.timeZone:null),e);return}this.aggregator.setTimeZone(this.tickZone(e.timeframe,t),n)}tickZone(e,n){let r=this.timeZone;return r===null||(0,t.timeframeSpansDays)(e)||n!==null&&IC(n,e,r)?r:null}async doConnect(){if(!this.config||!this.source)return;let e=++this.connectSeq,n={symbol:this.config.symbol,timeframe:this.config.timeframe};this.setState(`connecting`);try{let r=await this.source.getBars(n,this.config.historyLimit??NC);if(e!==this.connectSeq||!this.source)return;let i=r.length>0?r[r.length-1]:null;this.historyEnd=i?(0,t.normalizeBarTime)(i.time):null,this.applyTickZone(),this.seedAggregator(i);let a=this.formingAfter(i);i&&!a&&(this.setPreviousClose(i),this.updatePrice(i.close)),this.emit(`snapshot`,FC(r,a)),this.source.subscribeBars(n),this.startHeartbeat()}catch(t){if(e!==this.connectSeq)return;let n=t instanceof Error?t.message:String(t);this.emit(`error`,{message:n,code:`CONNECT_FAILED`}),this.setState(`error`),this.reconnector.schedule(()=>this.doConnect())}}wireReconnector(){this.reconnector.on(`attempt`,({attempt:e,delay:t})=>{this.state=`reconnecting`,this.emit(`connectionChange`,{state:`reconnecting`,reconnectAttempt:e,lastMessageTime:this.lastMessageTime})}),this.reconnector.on(`giveUp`,({attempts:e})=>{this.setState(`error`),this.emit(`error`,{message:`Reconnection failed after ${e} attempts`,code:`RECONNECT_EXHAUSTED`})})}subscriber(){return{connection:e=>this.onConnection(e),tick:e=>this.onTick(e),bar:(e,t)=>this.onBar(e,t),error:e=>this.emit(`error`,{message:e??`Adapter error`}),symbolInfo:e=>{e&&typeof e==`object`&&this.emit(`symbolInfo`,e)}}}onConnection(e){this.lastMessageTime=Date.now(),e===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(e===`disconnected`||e===`error`)&&this.reconnector.schedule(()=>this.doConnect())}onTick(e){this.lastMessageTime=Date.now(),this.emit(`tick`,e),(e.bid!==void 0||e.ask!==void 0)&&this.emit(`quote`,{bid:e.bid,ask:e.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(e):this.updatePrice(e.price)}onBar(e,t){this.lastMessageTime=Date.now(),this.aggregator?.processBar(e,t)}setPreviousClose(e){this.previousClose=e.close,this.previousCloseTime=(0,t.normalizeBarTime)(e.time)}seedAggregator(e){this.aggregator&&(this.aggregator.seed(e?e.time:-1/0),e&&this.config?.aggregateTicks&&this.aggregator.resume(e))}formingAfter(e){let n=this.aggregator?.getCurrentBar()??null;return!n||e&&(0,t.normalizeBarTime)(n.time)<=(0,t.normalizeBarTime)(e.time)?null:n}updatePrice(e){e===this.lastPrice&&this.previousClose===this.sentPreviousClose||(this.lastPrice=e,this.sentPreviousClose=this.previousClose,this.priceLine.setPrice(e,this.previousClose??void 0),this.emit(`priceChange`,{price:e,previousClose:this.previousClose}))}setState(e){this.state!==e&&(this.state=e,this.emit(`connectionChange`,{state:e,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}))}wake(e){!this.source||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&(!this.source.watchSilence||Date.now()-this.lastMessageTime<=AC)||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.source?.watchSilence===!0&&Date.now()-this.lastMessageTime>jC&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},MC)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},RC=class extends LS{data;speed;index;status=`idle`;timer=null;constructor(e){if(super(),e.data.length===0)throw Error(`ReplayController requires non-empty data`);this.data=e.data,this.speed=Math.max(.01,e.speed??1),this.index=Math.max(0,Math.min(e.startIndex??0,e.data.length)),e.autoStart&&this.start()}getStatus(){return this.status}getIndex(){return this.index}getTotal(){return this.data.length}getPrefix(){return this.data.slice(0,this.index)}start(){if(this.status!==`playing`){if(this.index>=this.data.length){this.transition(`finished`);return}this.transition(`playing`),this.scheduleNext()}}pause(){this.status===`playing`&&(this.clearTimer(),this.transition(`paused`))}resume(){this.status===`paused`&&this.start()}stop(){this.clearTimer(),this.index=0,this.transition(`idle`)}step(e=1){if(!(e<=0)){this.clearTimer();for(let t=0;t<e;t++)if(!this.emitNext())return;this.status!==`finished`&&this.transition(`paused`)}}seek(e){let t=Math.max(0,Math.min(e,this.data.length));this.clearTimer(),this.index=t;let n=t>=this.data.length?`finished`:`paused`;this.transition(n)}setSpeed(e){this.speed=Math.max(.01,e),this.status===`playing`&&(this.clearTimer(),this.scheduleNext())}destroy(){this.clearTimer(),this.removeAllListeners()}scheduleNext(){let e=1e3/this.speed;this.timer=setTimeout(()=>{this.timer=null,this.status===`playing`&&this.emitNext()&&this.scheduleNext()},e)}emitNext(){if(this.index>=this.data.length)return this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1;let e=this.data[this.index],t=this.index;return this.index++,this.emit(`bar`,{bar:e,index:t,total:this.data.length}),this.index>=this.data.length?(this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1):!0}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}transition(e){this.status!==e&&(this.status=e,this.emit(`stateChange`,{status:e,index:this.index,total:this.data.length}))}};function zC(e){if(!Array.isArray(e)||e.length<6)return null;let t=e[0];if(typeof t!=`number`||!Number.isFinite(t))return null;let n=VC(e[1]),r=VC(e[2]),i=VC(e[3]),a=VC(e[4]),o=VC(e[5]);return n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}function BC(e){if(!HC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=VC(e.o),r=VC(e.h),i=VC(e.l),a=VC(e.c),o=VC(e.v);if(n===null||r===null||i===null||a===null||o===null)return null;let s=typeof e.x==`boolean`?e.x:!1;return{bar:{time:t,open:n,high:r,low:i,close:a,volume:o},closed:s}}function VC(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function HC(e){return typeof e==`object`&&!!e}function Q(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function UC(e){let n=e&&typeof e==`object`&&`data`in e?e.data:e;if(!n||typeof n!=`object`)return null;let r=n;return r.e===`24hrMiniTicker`?(0,t.readQuote)({symbol:r.s,last:Q(r.c),open:Q(r.o),high:Q(r.h),low:Q(r.l),volume:Q(r.v),time:Q(r.E)}):null}function WC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Q(n.lastPrice),change:Q(n.priceChange),changePercent:Q(n.priceChangePercent),open:Q(n.openPrice),high:Q(n.highPrice),low:Q(n.lowPrice),prevClose:Q(n.prevClosePrice),volume:Q(n.volume),bid:Q(n.bidPrice),ask:Q(n.askPrice),time:Q(n.closeTime)})}function GC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Q(t.T),r=Q(t.p),i=Q(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var KC=64,qC=(e,t)=>`${e}|${t}`,JC=class{last=new Map;serve(e,t,n){if(!Array.isArray(n)||n.length===0)return;let r=n[n.length-1],i=Number(r?.time);if(!Number.isFinite(i))return;let a=qC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>KC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(qC(e,t))}},YC=class{newest=-1/0;servedClose=null;served=new JC;serve(e,t,n){this.served.serve(e,t,n)}reset(e,n){let r=this.served.lastBar(e,n);this.newest=r===void 0?-1/0:(0,t.normalizeBarTime)(r.time),this.servedClose=r?.close??null}admit(e,n=!1){let r=(0,t.normalizeBarTime)(e.time);return Number.isFinite(r)?r<this.newest||r===this.newest&&n&&e.close===this.servedClose?!1:(this.servedClose=null,this.newest=r,!0):!0}},XC={"1s":`1s`,"1m":`1m`,"3m":`3m`,"5m":`5m`,"15m":`15m`,"30m":`30m`,"1h":`1h`,"2h":`2h`,"4h":`4h`,"6h":`6h`,"8h":`8h`,"12h":`12h`,"1d":`1d`,"3d":`3d`,"1w":`1w`,"1M":`1M`},ZC=1e3,QC=200,$C=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function ew(e){let t=e.currency?$C.indexOf(e.currency):-1;return t<0?0:40-t*3}function tw(e){if(typeof e.symbol!=`string`||e.status!==`TRADING`)return null;let n=typeof e.baseAsset==`string`?e.baseAsset:``,r=typeof e.quoteAsset==`string`?e.quoteAsset:``,i=Array.isArray(e.filters)?e.filters.find(e=>typeof e==`object`&&!!e&&e.filterType===`PRICE_FILTER`&&typeof e.tickSize==`string`):void 0,a={symbol:e.symbol,description:n&&r?`${n} / ${r}`:e.symbol,exchange:`Binance`,type:`crypto`};return i&&(a.pricePrecision=(0,t.stepDecimals)(i.tickSize),a.minTick=Number(i.tickSize)),a.timeZone=`UTC`,r&&(a.currency=r),a}function nw(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=tw(e);t&&n.push(t)}return n}var rw=class{name=`binance`;supportedTimeframes=Object.keys(XC);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;newestBar=new YC;constructor(e){this.restBase=e?.restBase??`https://api.binance.com/api/v3`,this.wsBase=e?.wsBase??`wss://stream.binance.com:9443/ws`}connect(e){this.config=e,this.newestBar.reset(e.symbol,e.timeframe),this.connectWs()}disconnect(){if(this.ws){let e=this.ws;e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,e.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n=500){let r=await this.fetchKlines(e,t,n,``);return this.newestBar.serve(e,t,r),r}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,ew)}async resolveSymbol(e){if(this.symbolList){let t=(await this.symbolList.catch(()=>null))?.find(t=>t.symbol===e);if(t)return t}let t=await fetch(`${this.restBase}/exchangeInfo?symbol=${encodeURIComponent(e)}`);return t.ok?nw(await t.json())[0]??null:null}loadSymbols(){return this.symbolList||(this.symbolList=(async()=>{let e=await fetch(`${this.restBase}/exchangeInfo`);if(!e.ok)throw Error(`Binance REST error: ${e.status}`);return nw(await e.json())})(),this.symbolList.catch(()=>{this.symbolList=null})),this.symbolList}subscribeQuotes(e,t){let n=[...new Set(e.map(e=>e.trim().toUpperCase()))].filter(e=>/^[A-Z0-9]{2,30}$/.test(e)).slice(0,QC);if(n.length===0)return()=>{};let r=!1,i=null,a=null,o=0,s=new Set,c=new AbortController;(async()=>{let e=await fetch(`${this.restBase}/ticker/24hr?symbols=${encodeURIComponent(JSON.stringify(n))}`,{signal:c.signal});if(e.ok)return e.json();let t=await fetch(`${this.restBase}/ticker/24hr`,{signal:c.signal});if(!t.ok)return[];let r=await t.json(),i=new Set(n);return Array.isArray(r)?r.filter(e=>i.has(e?.symbol)):[]})().then(e=>{if(r||!Array.isArray(e))return;let n=e.map(WC).filter(e=>e!==null&&!s.has(e.symbol));n.length>0&&t(n)}).catch(()=>{});let l=this.wsBase.replace(/\/ws\/?$/,``),u=()=>{if(!r){try{i=new WebSocket(`${l}/stream?streams=${n.map(e=>`${e.toLowerCase()}@miniTicker`).join(`/`)}`)}catch{d();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=UC(n);!i||r||(s.add(i.symbol),t([i]))},i.onclose=()=>{i=null,d()}}},d=()=>{r||(a=setTimeout(u,Math.min(3e4,1e3*2**o++)))};return u(),()=>{r=!0,c.abort(),a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=await fetch(`${this.restBase}/aggTrades?symbol=${encodeURIComponent(e.toUpperCase())}&limit=${n}`);if(!r.ok)throw Error(`Binance aggTrades ${r.status}`);let i=await r.json();return Array.isArray(i)?i.map(GC).filter(e=>e!==null):[]}subscribeTrades(e,t){let n=`${e.trim().toLowerCase()}@aggTrade`;if(!/^[a-z0-9]{2,30}@aggTrade$/.test(n))return()=>{};let r=!1,i=null,a=null,o=0,s=()=>{if(!r){try{i=new WebSocket(`${this.wsBase}/${n}`)}catch{c();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=GC(n);i&&!r&&t([i])},i.onclose=()=>{i=null,c()}}},c=()=>{r||(a=setTimeout(s,Math.min(3e4,1e3*2**o++)))};return s(),()=>{r=!0,a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}fetchHistoryBefore(e,t,n,r=500){return this.fetchKlines(e,t,Math.min(r,ZC),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=XC[t]??`15m`,a=`${this.restBase}/klines?symbol=${e}&interval=${i}&limit=${n}${r}`,o=await fetch(a);if(!o.ok)throw Error(`Binance REST error: ${o.status}`);let s=await o.json();if(!Array.isArray(s))return[];let c=[];for(let e of s){let t=zC(e);t&&c.push(t)}return c}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}connectWs(){if(!this.config)return;let e=`${this.config.symbol.toLowerCase()}@kline_${XC[this.config.timeframe]??`15m`}`,t=`${this.wsBase}/${e}`;this.setState(`connecting`);try{this.ws=new WebSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws.onopen=()=>{this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`)},this.ws.onmessage=e=>{let t;try{t=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}typeof t==`object`&&t&&t.e===`kline`&&this.handleKline(t.k)},this.ws.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},this.ws.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}handleKline(e){let t=BC(e);if(!t)return;let{bar:n,closed:r}=t,i=this.newestBar.admit(n,r);this.emitEvent(`bar`,{bar:n,closed:r}),i&&this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume})}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},iw=class{name=`mock`;state=`disconnected`;listeners=new Map;config=null;options;tickTimer=null;currentPrice;oldestOpen=new Map;forming=null;formingTimeframe=null;constructor(e){this.options={basePrice:100,volatility:1.5,tickInterval:2e3,historySize:500,...e},this.currentPrice=this.options.basePrice}connect(e){this.config=e,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startTicking()}disconnect(){this.stopTicking(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}subscribeQuotes(e,t){let n=[...new Set(e)].map(e=>{let t=this.options.basePrice*(.5+aw(e)%1e3/1e3);return{symbol:e,open:t,last:t,high:t,low:t,volume:0}});if(n.length===0)return()=>{};let r=this.options.volatility/100,i=()=>t(n.map(e=>({symbol:e.symbol,last:e.last,open:e.open,high:e.high,low:e.low,volume:e.volume,change:e.last-e.open,changePercent:(e.last-e.open)/e.open*100,time:Date.now()})));i();let a=setInterval(()=>{for(let e of n)e.last=Math.max(e.open*.01,e.last*(1+(Math.random()-.5)*r)),e.high=Math.max(e.high,e.last),e.low=Math.min(e.low,e.last),e.volume+=Math.random()*100;i()},this.options.tickInterval);return()=>clearInterval(a)}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=Date.now(),i=this.options.volatility/1e3,a=this.options.basePrice*(.5+aw(e)%1e3/1e3),o=[];for(let e=n-1;e>=0;e--)a=Math.max(a*.5,a*(1+(Math.random()-.5)*i)),o.push({time:r-e*1e3,price:a,volume:Math.random()*5});return o}subscribeTrades(e,t){let n=this.options.volatility/1e3,r=this.options.basePrice*(.5+aw(e)%1e3/1e3),i=setInterval(()=>{let e=[];for(let t=0;t<3;t++)r=Math.max(r*.5,r*(1+(Math.random()-.5)*n)),e.push({time:Date.now(),price:r,volume:Math.random()*5});t(e)},this.options.tickInterval);return()=>clearInterval(i)}async fetchHistory(e,t,n){let r=this.options.historyGenerator?this.options.historyGenerator(e,t,n??this.options.historySize):this.generateHistory(t,n??this.options.historySize);return r.length>0&&this.oldestOpen.set(e,r[0].open),this.forming=r.length>0?{...r[r.length-1]}:null,this.formingTimeframe=t,r}async fetchHistoryBefore(e,n,r,i){let a=(0,t.timeframeToMs)(n),o=this.options.volatility/100,s=Array(Math.max(0,i)),c=this.oldestOpen.get(e)??this.options.basePrice;for(let e=0;e<i;e++){let t=c/(1+(Math.random()-.52)*o),n=Math.max(t,c)+Math.random()*c*o*.3,l=Math.max(0,Math.min(t,c)-Math.random()*c*o*.3),u=Math.floor(1e4+Math.random()*1e5);s[i-1-e]={time:r-(e+1)*a,open:t,high:n,low:l,close:c,volume:u},c=t}return this.oldestOpen.set(e,c),s}async searchSymbols(e,n){return(0,t.rankSymbols)(this.options.symbols??[],e,n?.limit??50)}async resolveSymbol(e){return this.options.symbols?.find(t=>t.symbol===e)??null}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}generateHistory(e,n){let r=[],i=(0,t.timeframeToMs)(e),a=Math.floor(Date.now()/i)*i,o=this.options.basePrice,s=this.options.volatility/100;for(let e=n-1;e>=0;e--){let t=a-e*i,n=(Math.random()-.48)*o*s,c=o;o+=n;let l=Math.max(c,o)+Math.random()*o*s*.3,u=Math.min(c,o)-Math.random()*o*s*.3,d=Math.floor(1e4+Math.random()*1e5);r.push({time:t,open:c,high:l,low:u,close:o,volume:d})}return this.currentPrice=o,r}startTicking(){this.stopTicking();let e=this.options.tickInterval??2e3;this.tickTimer=setInterval(()=>{if(this.state!==`connected`||!this.config)return;let e=this.options.volatility/100,t=(Math.random()-.48)*this.currentPrice*e*.3;this.currentPrice+=t;let n=Date.now(),r=this.tickBar(n,t,Math.floor(100+Math.random()*5e3));this.emitEvent(`bar`,{bar:r,closed:!1}),this.emitEvent(`tick`,{time:n,price:this.currentPrice,volume:r.volume})},e)}tickBar(e,n,r){let i=this.config.timeframe,a=(0,t.timeframeToMs)(i),o=Math.floor(e/a)*a,s=this.currentPrice,c=this.formingTimeframe===i?this.forming:null,l=Math.abs(n)*.2,u;if(c&&c.time===o)u={time:o,open:c.open,high:Math.max(c.high,s+l),low:Math.min(c.low,s-l),close:s,volume:c.volume+r};else{let e=c?.close??s-n;u={time:o,open:e,high:Math.max(e,s)+l,low:Math.min(e,s)-l,close:s,volume:r}}return this.forming=u,this.formingTimeframe=i,{...u}}stopTicking(){this.tickTimer&&=(clearInterval(this.tickTimer),null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function aw(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var ow=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;newestBar=new YC;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.newestBar.reset(e.symbol,e.timeframe),this.openSocket()}disconnect(){let e=this.config;if(this.ws){if(this.opts.unsubscribeMessage&&e)try{this.sendMessage(this.opts.unsubscribeMessage(e))}catch{}let t=this.ws;t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){let r=this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500);return Promise.resolve(r).then(n=>(this.newestBar.serve(e,t,n),n))}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}openSocket(){let e=this.config;if(!e)return;let t=this.opts.wsUrl(e);this.setState(`connecting`);let n;try{n=this.createSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws=n,n.onopen=()=>{if(this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`),this.opts.subscribeMessage)try{this.sendMessage(this.opts.subscribeMessage(e))}catch{}},n.onmessage=t=>{let n=this.decode(t.data);if(n===void 0)return;let r;try{r=this.opts.parseMessage(n,e)}catch{return}if(!r)return;let i=r.bar?this.newestBar.admit(r.bar,r.closed??!1):!1;r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&i&&this.emitEvent(`tick`,{time:Date.now(),price:r.bar.close,volume:r.bar.volume})},n.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},n.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}sendMessage(e){e===void 0||!this.ws||this.ws.send(typeof e==`string`?e:JSON.stringify(e))}decode(e){if(this.opts.decode)try{return this.opts.decode(e)}catch{return}if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}createSocket(e){if(this.opts.socketFactory)return this.opts.socketFactory(e);let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);return new t(e)}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},sw=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new JC;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.lastBarTime=this.served.lastBar(e.symbol,e.timeframe)?.time??0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n){let r=await this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500);return this.served.serve(e,t,r),r}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}async poll(){let e=this.config;if(!e||this.state!==`connected`)return;let t;try{t=await this.opts.fetchBars(e.symbol,e.timeframe,this.opts.pollLimit??2)}catch(e){this.emitEvent(`error`,{message:`Poll failed`,cause:e});return}if(t.length===0)return;let n=t[t.length-1];if(!(n.time<this.lastBarTime)){if(this.lastBarTime>0&&n.time>this.lastBarTime){let e=t.find(e=>e.time===this.lastBarTime);e&&this.emitEvent(`bar`,{bar:e,closed:!0})}this.emitEvent(`bar`,{bar:n,closed:!1}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume}),this.lastBarTime=n.time}}startPolling(){this.stopPolling(),this.poll();let e=this.opts.setInterval??((e,t)=>setInterval(e,t));this.timer=e(()=>{this.poll()},this.opts.intervalMs??5e3)}stopPolling(){this.timer!==null&&((this.opts.clearInterval??(e=>clearInterval(e)))(this.timer),this.timer=null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function $(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function cw(e){return typeof e==`object`&&!!e}var lw={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function uw(e){return lw[e]??3600}var dw=class extends sw{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(lw),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>fw(t,e,n)})}};async function fw(e,t,n){let r=`${e}/products/${t}/candles?granularity=${uw(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return pw(await i.json())}function pw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=mw(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function mw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:i,high:r,low:n,close:a,volume:o}}var hw={"1m":`1`,"3m":`3`,"5m":`5`,"15m":`15`,"30m":`30`,"1h":`60`,"2h":`120`,"4h":`240`,"6h":`360`,"12h":`720`,"1d":`D`,"1w":`W`,"1M":`M`};function gw(e){return hw[e]??`1`}var _w=class extends ow{constructor(e={}){let t=e.restBase??`https://api.bybit.com`,n=e.wsBase??`wss://stream.bybit.com/v5/public/spot`,r=e.category??`spot`;super({name:`bybit`,wsUrl:()=>n,subscribeMessage:e=>({op:`subscribe`,args:[`kline.${gw(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${gw(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(hw),parseMessage:vw,fetchHistory:(e,n,i)=>yw(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>yw(t,r,e,n,a,Math.floor(i)-1)})}};function vw(e){if(!cw(e)||typeof e.topic!=`string`||!e.topic.startsWith(`kline.`))return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!cw(n))return null;let r=$(n.start),i=$(n.open),a=$(n.high),o=$(n.low),s=$(n.close),c=$(n.volume);if(r===null||i===null||a===null||o===null||s===null||c===null)return null;let l=typeof n.confirm==`boolean`?n.confirm:!1;return{bar:{time:r,open:i,high:a,low:o,close:s,volume:c},closed:l}}async function yw(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${gw(r)}&limit=${Math.min(Math.max(i,1),1e3)}${a===void 0?``:`&end=${a}`}`,s=await fetch(o);if(!s.ok)throw Error(`Bybit REST error: ${s.status}`);return bw(await s.json())}function bw(e){if(!cw(e)||!cw(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=xw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function xw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}var Sw={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function Cw(e){return Sw[e]??1}var ww=class extends ow{constructor(e={}){let t=e.restBase??`https://api.kraken.com`,n=e.wsBase??`wss://ws.kraken.com/v2`;super({name:`kraken`,wsUrl:()=>n,subscribeMessage:e=>({method:`subscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Cw(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Cw(e.timeframe)}}),supportedTimeframes:Object.keys(Sw),parseMessage:Tw,fetchHistory:(e,n)=>Ew(t,e,n)})}};function Tw(e){if(!cw(e)||e.channel!==`ohlc`)return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!cw(n))return null;let r=$(n.open),i=$(n.high),a=$(n.low),o=$(n.close),s=$(n.volume),c=typeof n.interval_begin==`string`?Date.parse(n.interval_begin):NaN;return r===null||i===null||a===null||o===null||s===null||!Number.isFinite(c)?null:{bar:{time:c,open:r,high:i,low:a,close:o,volume:s},closed:!1}}async function Ew(e,t,n){let r=Cw(n),i=t.replace(`/`,``),a=`${e}/0/public/OHLC?pair=${encodeURIComponent(i)}&interval=${r}`,o=await fetch(a);if(!o.ok)throw Error(`Kraken REST error: ${o.status}`);return Dw(await o.json())}function Dw(e){if(!cw(e)||!cw(e.result))return[];let t=null;for(let[n,r]of Object.entries(e.result))if(n!==`last`&&Array.isArray(r)){t=r;break}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Ow(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function Ow(e){if(!Array.isArray(e)||e.length<7)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[6]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:n,high:r,low:i,close:a,volume:o}}var kw=200,Aw={"1m":`minutes/1`,"3m":`minutes/3`,"5m":`minutes/5`,"15m":`minutes/15`,"30m":`minutes/30`,"1h":`minutes/60`,"4h":`minutes/240`,"1d":`days`,"1w":`weeks`,"1M":`months`},jw={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function Mw(e){return Aw[e]??null}function Nw(e){return jw[e]??null}var Pw=class extends ow{constructor(e={}){let t=e.restBase??`https://api.upbit.com`,n=e.wsUrl??`wss://api.upbit.com/websocket/v1`;super({name:`upbit`,wsUrl:()=>n,socketFactory:e.socketFactory??Fw,decode:Lw,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:Nw(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys(jw),parseMessage:Rw,fetchHistory:(e,n,r)=>Vw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>Vw(t,e,n,i,r)})}};function Fw(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var Iw=null;function Lw(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((Iw??=new TextDecoder).decode(e))}function Rw(e){if(!cw(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=Bw(e,e.candle_date_time_utc,e.candle_acc_trade_volume);return t?{bar:t,closed:!1}:null}if(e.type===`ticker`&&typeof e.trade_date==`string`&&/^\d{8}$/.test(e.trade_date)){let t=e.trade_date,n=Bw(e,`${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)}T00:00:00`,e.acc_trade_volume);return n?{bar:n,closed:!1}:null}return null}function zw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=cw(n)?Bw(n,n.candle_date_time_utc,n.candle_acc_trade_volume):null;e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function Bw(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=$(e.opening_price),a=$(e.high_price),o=$(e.low_price),s=$(e.trade_price),c=$(n);return!Number.isFinite(r)||i===null||a===null||o===null||s===null||c===null?null:{time:r,open:i,high:a,low:o,close:s,volume:c}}async function Vw(e,t,n,r,i){let a=Mw(n);if(!a)throw Error(`Upbit has no ${n} candles`);let o=new URLSearchParams({market:t,count:String(Math.min(Math.max(Math.floor(r),1),200))});i!==void 0&&o.set(`to`,new Date(i).toISOString().replace(/\.\d{3}Z$/,`Z`));let s=await fetch(`${e}/v1/candles/${a}?${o}`);if(!s.ok)throw Error(`Upbit REST error: ${s.status}`);return zw(await s.json())}var Hw=(e,t)=>`${e}\u0000${t}`,Uw=class{name;series=new Map;subscribers=new Map;constructor(e={}){this.name=e.name??`manual`}setBars(e,t,n){let r=n.map(e=>({...e})).sort((e,t)=>e.time-t.time);this.series.set(Hw(e,t),r)}pushBar(e,t,n,r=!1){let i=Hw(e,t),a=this.series.get(i)??[],o=a[a.length-1],s={...n},c=r;if(!o||s.time>o.time)this.series.set(i,[...a,s]);else{let n=a.findIndex(e=>e.time===s.time);if(n<0)throw RangeError(`ManualFeed: no ${e} ${t} bar at ${s.time} to replace`);n<a.length-1&&(c=!0),this.series.set(i,a.map((e,t)=>t===n?s:e))}for(let e of[...this.subscribers.get(i)??[]])e.bar({...s},c)}async getBars(e){let t=this.series.get(Hw(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:Ww(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=Hw(e.symbol,e.timeframe),r=this.subscribers.get(n);return r||(r=new Set,this.subscribers.set(n,r)),r.add(t),()=>{r.delete(t),r.size===0&&this.subscribers.delete(n)}}};function Ww(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].time<t?n=i+1:r=i}return n}var Gw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},Kw=class{config={...Gw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=Jw;top=qw;lineGap=Yw;pricePrecision=null;reportedHeight=null;resizeListener=null;setResizeListener(e){this.resizeListener=e}forgetHeight(){this.drawnHeight=null,this.reportedHeight=null}reportResize(){let e=this.getHeight();e!==this.reportedHeight&&(this.reportedHeight=e,this.resizeListener?.())}setConfig(e){Object.assign(this.config,e),this.forgetHeight()}getConfig(){return{...this.config}}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){e!==this.symbol&&(this.symbol=e,this.forgetHeight())}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.forgetHeight())}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){e!==this.statusText&&(this.statusText=e,this.forgetHeight())}setExchange(e){e!==this.exchange&&(this.exchange=e,this.forgetHeight())}title(){return this.config.showSymbol?[(0,t.tickerOf)(this.symbol),this.timeframe,this.exchange].filter(Boolean).join(` · `):``}titleCells(e,t,n,r,i){let a=[],o=this.title();if(o){let i=`600 ${t}px ${n}`;e.font=i,a.push({label:``,labelWidth:0,value:o,width:e.measureText(o).width,color:r,font:i})}if(this.statusText){let r=`${t}px ${n}`;e.font=r,a.push({label:``,labelWidth:0,value:this.statusText,width:e.measureText(this.statusText).width,color:i,font:r})}return a}priceCells(e,n,r,i,a,o,s,c){let l=`${o}px ${s}`;e.font=l;let u=i.close>=i.open,d=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),f=e=>n.formatPrice?.(e)??(0,t.formatPrice)(e,d,this.locale),p=[{label:`O`,value:f(i.open),color:c},{label:`H`,value:f(i.high),color:c},{label:`L`,value:f(i.low),color:c},{label:`C`,value:f(i.close),color:u?r.candleUp:r.candleDown}];if(this.config.showChange){let e=i.close-a.close,n=a.close===0?0:e/a.close*100,o=e>=0?`+`:``,s=(0,t.formatPrice)(n,2,this.locale);p.push({label:``,value:`${o}${f(e)} (${o}${s}%)`,color:e>=0?r.candleUp:r.candleDown})}return p.map(t=>({...t,labelWidth:t.label?e.measureText(t.label+` `).width:0,width:eT(e,t.value),font:l}))}setSpacing(e){e.inset===this.inset&&e.top===this.top&&e.lineGap===this.lineGap||(this.inset=e.inset,this.top=e.top,this.lineGap=e.lineGap,this.drawnHeight=null)}getInset(){return this.inset}getHeight(){if(!this.config.visible||this.config.position!==`top-left`)return 0;if(this.drawnHeight!==null)return this.drawnHeight;let e=this.config.fontSize,t=this.top;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+this.lineGap),this.config.showVolume&&(t+=e+2),t}getWidth(){return!this.config.visible||this.config.position!==`top-left`?0:this.drawnWidth}render(e,n,r,i){if(!this.config.visible)return this.reportResize();if(i.length===0)return;let a=this.hoverBar??i[i.length-1],o=this.hoverBar?this.hoverPrev??a:i.length>1?i[i.length-2]:a,{chartRect:s}=n,c=this.config.fontSize,l=this.config.fontFamily??r.font.family,u=r.style?.legend.text??r.text,d=r.style?.legend.label??r.textSecondary,f=this.config.position===`top-left`,p=f?s.x+this.inset:s.x+s.width-this.inset,m=s.y+this.top;e.textAlign=f?`left`:`right`,e.textBaseline=`top`;let h=0,g=this.titleCells(e,c,l,u,d);if(this.config.showOHLC&&g.push(...this.priceCells(e,n,r,a,o,c,l,u)),g.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width;for(let n of $w(g,t,s.width-2*this.inset)){let i=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t);h=Math.max(h,i);let a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=d,e.fillText(r.label,a,m),a+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,a,m),a+=r.width+t;m+=c+this.lineGap}e.textAlign=f?`left`:`right`}if(this.config.showVolume){e.font=`${c}px ${l}`,e.fillStyle=d;let n=(0,t.formatVolumeLoc)(a.volume,this.locale),i=e.measureText(`Vol ${n}`).width;this.drawGround(e,r,f?p:p-i,m,i,c),e.fillStyle=d,e.fillText(`Vol ${n}`,p,m),h=Math.max(h,i),m+=c+2}if(this.drawnHeight=f?m-s.y:null,this.drawnWidth=f?this.inset+h:0,this.reportResize(),this.indicators.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:eT(e,n)}}),i=n.reduce((e,n)=>e+n.width+t,-t),a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let{entry:r,color:i,width:o}of n)e.fillStyle=i,e.fillText(r,a,m),a+=o+t}}drawGround(e,t,n,r,i,a){!this.config.ground||i<=0||(e.save(),e.globalAlpha=Xw,e.fillStyle=t.background,e.fillRect(n-Zw,r-Qw,i+2*Zw,a+this.lineGap),e.restore())}},{legendTop:qw,legendInset:Jw,legendLineGap:Yw}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],Xw=.72,Zw=3,Qw=1;function $w(e,t,n){let r=[],i=[],a=0;for(let o of e){let e=o.labelWidth+o.width;i.length>0&&a+t+e>n&&(r.push(i),i=[],a=0),a+=(i.length>0?t:0)+e,i.push(o)}return i.length>0&&r.push(i),r}function eT(e,t){let n=t.replace(/\d/g,`0`);return Math.max(e.measureText(t).width,e.measureText(n.replace(/[-−]/g,`+`)).width,e.measureText(n.replace(/\+/g,`-`)).width)}var tT=class{static toDataURL(e,t){return this.compose(e,t)?.toDataURL(`image/png`)??``}static async toBlob(e,t){let n=this.compose(e,t);return n?new Promise(e=>n.toBlob(e,`image/png`)):null}static download(e,t=`chart.png`,n){let r=this.toDataURL(e,n);if(!r)return;let i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i)}static compose(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return null;let r=n[0],i=r.width,a=r.height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);t&&(s.fillStyle=t,s.fillRect(0,0,i,a));let c=Array.from(n).sort((e,t)=>(parseInt(e.style.zIndex)||0)-(parseInt(t.style.zIndex)||0));for(let e of c)s.drawImage(e,0,0);return o}},nT=class{config=null;setConfig(e){this.config=e}isVisible(){return!!this.config?.text}render(e,t,n){if(!this.config?.text)return;let{chartRect:r}=t,i=this.config.fontSize??48,a=n.style?.watermark.color??this.config.color??n.textSecondary;e.save(),e.globalAlpha=.07,e.font=`bold ${i}px ${n.font.family}`,e.fillStyle=a,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(this.config.text,r.x+r.width/2,r.y+r.height/2),e.restore()}},rT={solid:null,dashed:[6,4],dotted:[2,3]},iT=6;function aT(e,t){let n=[...e].sort((e,t)=>t.rank-e.rank||e.px-t.px),r=[],i=[];for(let e of n){let n=0,a=r.length;for(;n<a;){let t=n+a>>1;r[t]<e.px?n=t+1:a=t}n>0&&e.px-r[n-1]<t||n<r.length&&r[n]-e.px<t||(r.splice(n,0,e.px),i.push(e))}return i.sort((e,t)=>e.px-t.px)}var oT=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;firstTime=NaN;lastTime=NaN;tz=null;setConfig(e){Object.assign(this.config,e)}setTimezone(e){e!==this.tz&&(this.tz=e,this.invalidateCache())}isVisible(){return this.config.visible}setVisible(e){this.config.visible=e}computeBreaksTyped(e){if(e.length<2)return[];let n=this.lastDataLength,r=this.cacheValid&&e.length>=n&&e[0].time===this.firstTime&&e[n-1].time===this.lastTime;if(r&&e.length===n)return this.cachedBreaksTyped;let i=r?this.cachedBreaksTyped.slice():[],a=(0,t.barTimeUnit)(e),o=r?n:1,s=(0,t.timeParts)(e[o-1].time*a,this.tz);for(let n=o;n<e.length;n++){let r=(0,t.timeParts)(e[n].time*a,this.tz);if(r.year!==s.year)i.push({idx:n,kind:`year`});else if(r.month!==s.month)i.push({idx:n,kind:`month`});else if(r.day!==s.day){let e=new Date(Date.UTC(r.year,r.month-1,r.day)).getUTCDay()===1;i.push({idx:n,kind:e?`week`:`day`})}s=r}return this.lastDataLength=e.length,this.firstTime=e[0].time,this.lastTime=e[e.length-1].time,this.cachedBreaksTyped=i,r||(this.cachedMedianStep=sT(e)),this.cacheValid=!0,i}render(e,t,n,r){this.renderLines(e,t,n,r)}renderLines(e,t,n,r){let i=this.lineMarks(t,r,n);if(i.length===0)return;let{chartRect:a}=t,o=this.look(n),s=rT[o.style];e.save(),s&&e.setLineDash(s),e.strokeStyle=o.color;for(let t of i)e.globalAlpha=t.alpha,e.lineWidth=t.width,e.beginPath(),e.moveTo(t.px,a.y),e.lineTo(t.px,a.y+a.height),e.stroke();e.restore()}lineRects(e,t,n){let r=this.lineMarks(e,n,t);if(r.length===0)return[];let{color:i,style:a}=this.look(t),o=rT[a]??void 0,{y:s,height:c}=e.chartRect;return r.map(e=>({x:e.px-e.width/2,y:s,width:e.width,height:c,color:i,alpha:e.alpha,...o?{dash:o}:{}}))}look(e){let t=e.style?.sessionBreaks;return{color:t?.color??this.config.color??e.axisLine,style:t?.style??this.config.lineStyle??`dashed`,width:t?.width??this.config.lineWidth??1}}lineMarks(e,t,n){return aT(this.marks(e,t,n),iT)}marks(t,n,r){if(!this.config.visible||n.length<2)return[];let i=this.computeBreaksTyped(n);if(i.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:a}=t,o=this.look(r).width,s=[];for(let n of i){let r=e.w(n.idx,t)-(t.barWidth+t.barSpacing)/2;if(r<a.x-1||r>a.x+a.width+1)continue;let i=Math.round(r)+.5,c=.25,l=o,u=3;n.kind===`day`?(c=.22,u=0):n.kind===`week`?(c=.34,u=1):n.kind===`month`?(c=.5,u=2,l=o+.5):(c=.7,l=o+1),s.push({px:i,width:l,alpha:c,rank:u})}return s}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}};function sT(e){if(e.length<2)return 0;let n=Math.min(50,e.length-1),r=(0,t.barTimeUnit)(e),i=[];for(let t=1;t<=n;t++)i.push((e[t].time-e[t-1].time)*r);return i.sort((e,t)=>e-t),i[Math.floor(i.length/2)]}var cT=864e5;function lT(e,t){let n={...e,...t};return t.tzOffsetMinutes!==void 0&&t.timeZone===void 0&&delete n.timeZone,n.windows?n.windows=n.windows.map(e=>({...e})):delete n.windows,n}function uT(e,t){let n=((e+t*6e4)%cT+cT)%cT;return Math.floor(n/6e4)}function dT(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function fT(e,n){let r=uT(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>dT(r,e.startMinute,e.endMinute)):dT(r,n.startMinute,n.endMinute)}var pT={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},mT=class{visible=!1;config={...pT};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=lT(this.config,e)}replaceConfig(e){this.config=lT(e,{})}getConfig(){return{...this.config,windows:this.config.windows?.map(e=>({...e}))}}render(e,t,n,r){let i=this.rects(t,n,r);if(i.length!==0){e.save(),e.fillStyle=i[0].color;for(let t of i)e.fillRect(t.x,t.y,t.width,t.height);e.restore()}}rects(t,n,r){if(!this.visible||t.length===0)return[];let{chartRect:i}=n,{from:a,to:o}=n.visibleRange,s=Math.max(0,a),c=Math.min(o,t.length-1);if(c<s)return[];let l=n.barWidth+n.barSpacing,u=r.name===`light`?`rgba(0,0,0,0.045)`:`rgba(0,0,0,0.28)`,d=[],f=-1,p=(t,r)=>{let a=e.w(t,n)-l/2,o=e.w(r,n)+l/2;d.push({x:a,y:i.y,width:o-a,height:i.height,color:u,alpha:1})};for(let e=s;e<=c;e++){let n=!fT(t[e].time,this.config);n&&f===-1?f=e:!n&&f!==-1&&(p(f,e-1),f=-1)}return f!==-1&&p(f,c),d}},hT=[2,3],gT=16,_T=class{highLow=!1;quote=null;quoteShown=!0;priceText=null;setPriceText(e){this.priceText=e}setQuoteShown(e){this.quoteShown=e}setHighLow(e){this.highLow=e}isHighLowVisible(){return this.highLow}setBidAsk(e){this.quote=e?{...e}:null}getBidAsk(){return this.quote?{...this.quote}:null}levels(e,t){let n=[];if(this.highLow){let r=Math.max(0,t.visibleRange.from),i=Math.min(e.length-1,t.visibleRange.to),a=-1/0,o=1/0;for(let t=r;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);Number.isFinite(a)&&n.push({kind:`high`,price:a}),Number.isFinite(o)&&n.push({kind:`low`,price:o})}let{bid:r,ask:i}=(this.quoteShown?this.quote:null)??{};return r!==void 0&&Number.isFinite(r)&&n.push({kind:`bid`,price:r}),i!==void 0&&Number.isFinite(i)&&n.push({kind:`ask`,price:i}),n}render(t,n,r,i){let{chartRect:a}=n;t.save(),t.setLineDash(hT),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.k(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=vT(o.kind,r),t.beginPath(),e.y(t,a.x,a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a,o){let{chartRect:s}=r,c=s.x+s.width+1,l=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,u=(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max);n.save(),n.font=`${i.font.sizeSmall}px ${i.font.family}`,n.textBaseline=`middle`,n.textAlign=`left`;for(let d of this.levels(a,r)){let a=e.k(d.price,r);if(a<s.y||a>s.y+s.height)continue;let f=o?.get(d.kind)??a;if(Number.isNaN(f))continue;n.fillStyle=vT(d.kind,i),A(n,c,f-gT/2,l,gT,i),n.fillStyle=i.background;let p=r.formatPrice?.(d.price)??this.priceText?.(d.price)??(0,t.formatPrice)(d.price,u);n.fillText(p,c+7,f)}n.restore()}};function vT(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var yT=12,bT=3,xT=500,ST=2,CT=[`movesUp`,`movesDown`];function wT(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!CT.includes(e.condition)}function TT(e,t,n,r){switch(r){case`crossingUp`:return e!==void 0&&e<n&&t>=n;case`crossingDown`:return e!==void 0&&e>n&&t<=n;case`crossing`:return e!==void 0&&(e<n&&t>=n||e>n&&t<=n);case`greaterThan`:return t>n;case`lessThan`:return t<n;default:return!1}}var ET=[`crossing`,`crossingUp`,`crossingDown`];function DT(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var OT=1,kT=2**31-1,AT=class extends LS{alerts=[];lastValues=new Map;drawingSides=new Map;drawingLevels=null;requestRender=null;pricePrecision=null;barTime=null;expiryTimer=null;history=new Map;lastDiffs=new Map;setBarTime(e){this.barTime=e}setRequestRender(e){this.requestRender=e}setPricePrecision(e){this.pricePrecision=e}addAlert(e,t=`crossing`,n,r=!1,i=`price`,a,o={}){let s=jT(t,i,o),c=`tc_alert_${OT++}`,l={id:c,price:e,condition:t,message:n,triggered:!1,repeating:r,channel:i,label:a,...s};return this.alerts.push(l),s.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`added`,l),this.requestRender?.(),c}setDrawingLevels(e){this.drawingLevels=e}addDrawingAlert(e,t=`crossing`,n,r=!1,i){if(!ET.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${OT++}`,o={id:a,price:this.drawingLevels?.(e)?.[0]??NaN,condition:t,message:n,triggered:!1,repeating:r,channel:`price`,label:i,drawingId:e};return this.alerts.push(o),this.emit(`added`,o),a}removeDrawingAlerts(e){for(let t of this.alerts.filter(t=>t.drawingId===e))this.removeAlert(t.id)}takeDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId===e);for(let e of t)this.removeAlert(e.id);return t.map(e=>({...e}))}restoreAlerts(e){for(let t of e){if(this.alerts.some(e=>e.id===t.id))continue;let e={...t};this.alerts.push(e),this.emit(`added`,e)}this.scheduleExpiry(),this.requestRender?.()}pruneDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId!==void 0&&!e.has(t.drawingId));for(let e of t)this.removeAlert(e.id);return t.length}removeAlert(e){this.drawingSides.delete(e),this.lastDiffs.delete(e);let t=this.alerts.some(t=>t.id===e&&t.expiresAt!==void 0);this.alerts=this.alerts.filter(t=>t.id!==e),t&&this.scheduleExpiry(),this.emit(`removed`,e),this.requestRender?.()}getAlerts(){return[...this.alerts]}getAlertAtPoint(t,n,r=6){let{chartRect:i}=n;if(t.y<i.y||t.y>i.y+i.height)return null;let a=null,o=r;for(let r of this.alerts){if(!wT(r))continue;let i=Math.abs(e.k(r.price,n)-t.y);i<=o&&(o=i,a=r)}return a}updateAlertPrice(e,t){let n=this.alerts.find(t=>t.id===e);!n||!Number.isFinite(t)||(n.price=t,n.triggered=!1,n.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`updated`,{...n}),this.requestRender?.())}clearAlerts(){this.alerts=[],this.lastDiffs.clear(),this.drawingSides.clear(),this.scheduleExpiry(),this.requestRender?.()}checkPrice(e){this.checkChannel(`price`,e),this.checkDrawingAlerts(e)}checkDrawings(e){this.checkDrawingAlerts(e)}expire(){let e=Date.now(),t=this.alerts.filter(t=>!t.expired&&t.expiresAt!==void 0&&e>=t.expiresAt&&!(t.triggered&&!t.repeating));if(t.length!==0){for(let e of t)e.expired=!0;try{for(let e of t)this.emit(`expired`,{...e}),this.emit(`updated`,{...e})}finally{this.requestRender?.(),this.scheduleExpiry()}}}scheduleExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null;let e=Math.min(...this.alerts.filter(e=>!e.expired&&e.expiresAt!==void 0&&!(e.triggered&&!e.repeating)).map(e=>e.expiresAt));if(!Number.isFinite(e))return;let t=Math.min(Math.max(0,e-Date.now()),kT);this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.expire(),this.expiryTimer||this.scheduleExpiry()},t)}dispose(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null}checkDrawingAlerts(e){if(!(!this.drawingLevels||!Number.isFinite(e)))for(let t of this.alerts){if(!t.drawingId||t.expired)continue;let n=this.drawingLevels(t.drawingId);if(!n||n.length===0){this.drawingSides.delete(t.id);continue}t.price=n[0];let r=n.map(t=>Math.sign(e-t)),i=this.drawingSides.get(t.id);this.drawingSides.set(t.id,r),!(!i||i.length!==r.length)&&(r.some((e,n)=>DT(i[n],e,t.condition))?t.triggered||(t.triggered=!0,this.emit(`triggered`,{...t})):t.repeating&&(t.triggered=!1))}}checkChannel(e,t){this.checkChannels(new Map([[e,t]]))}checkChannels(e,t={}){let n=(e instanceof Map?[...e.entries()]:Object.entries(e)).filter(([,e])=>Number.isFinite(e));if(n.length===0)return;this.expire();let r=new Map,i=new Map;for(let[e,t]of n){r.set(e,this.lastValues.get(e));let n=this.recordBar(e,t);n&&i.set(e,n),this.lastValues.set(e,t)}for(let e of this.alerts){if(e.drawingId||e.expired)continue;let n=r.has(e.channel),a=e.target!==void 0&&r.has(e.target);if(!n&&!a||e.target!==void 0&&t.together&&!(n&&a))continue;let o;if(e.onBarClose){let t=i.get(e.channel)??(e.target?i.get(e.target):void 0);if(!t)continue;o=this.closedBarMet(e,t)}else if(e.target)o=this.targetMet(e);else if(CT.includes(e.condition)){if(!n)continue;o=this.moveMet(e,this.history.get(e.channel)??[])}else{let t=r.get(e.channel);if(!n||t===void 0)continue;o=TT(t,this.lastValues.get(e.channel),e.price,e.condition)}this.settle(e,o)}}settle(e,t){t?e.triggered||(e.triggered=!0,this.emit(`triggered`,{...e})):e.repeating&&(e.triggered=!1)}targetMet(e){let t=this.lastValues.get(e.channel),n=e.target?this.lastValues.get(e.target):void 0;if(t===void 0||n===void 0)return!1;let r=t-n,i=this.lastDiffs.get(e.id);return this.lastDiffs.set(e.id,r),e.price=n,TT(i,r,0,e.condition)}moveMet(e,t,n=t.length){let r=e.bars??1,i=t.slice(Math.max(0,n-r),n);if(i.length<2||e.percent===void 0)return!1;let a=i[i.length-1].value,o=i.map(e=>e.value);if(e.condition===`movesUp`){let t=Math.min(...o);return t!==0&&(a-t)/Math.abs(t)*100>=e.percent}let s=Math.max(...o);return s!==0&&(s-a)/Math.abs(s)*100>=e.percent}closedBarMet(e,t){let n=this.history.get(e.channel)??[],r=n.findIndex(e=>e.time===t.time);if(r<0)return!1;if(CT.includes(e.condition))return this.moveMet(e,n,r+1);let i=(e,t)=>{let r=this.history.get(e)??[],i=n[t]?.time;return i===void 0?void 0:r.find(e=>e.time===i)?.value},a=n[r].value,o=r>0?n[r-1].value:void 0,s=e.price;if(e.target){let t=i(e.target,r),n=r>0?i(e.target,r-1):void 0;if(t===void 0)return!1;a-=t,o=o!==void 0&&n!==void 0?o-n:void 0,s=0,e.price=t}return TT(o,a,s,e.condition)}recordBar(e,t){let n=this.barTime;if(n===null)return null;let r=this.history.get(e)??[],i=r[r.length-1];if(i&&n<i.time)return r=r.filter(e=>e.time<n),r.push({time:n,value:t}),this.history.set(e,r),null;if(i&&i.time===n)return r[r.length-1]={time:n,value:t},null;i=r[r.length-1],r.push({time:n,value:t});let a=Math.min(502,Math.max(3,...this.alerts.map(e=>(e.bars??1)+2)));return r.length>a&&r.splice(0,r.length-a),this.history.set(e,r),i?{channel:e,time:i.time}:null}seedLastValue(e,t){Number.isFinite(t)&&this.lastValues.set(e,t)}clearLastValues(){this.lastValues.clear(),this.drawingSides.clear(),this.history.clear(),this.lastDiffs.clear()}saveToStorage(e){try{let t=this.alerts.map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,repeating:e.repeating,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}));localStorage.setItem(e,JSON.stringify(t))}catch{}}loadFromStorage(e){try{let t=localStorage.getItem(e);if(!t)return;let n=JSON.parse(t);if(!Array.isArray(n))return;for(let e of n){if(typeof e.drawingId==`string`&&e.condition&&!e.triggered){ET.includes(e.condition)&&this.addDrawingAlert(e.drawingId,e.condition,e.message,e.repeating??!1,e.label);continue}if(!e.condition||e.triggered||e.expired)continue;let t=MT(e),n=!t.target&&!CT.includes(e.condition),r=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:NaN;if(!(n&&Number.isNaN(r)))try{this.addAlert(r,e.condition,e.message,e.repeating??!1,e.channel??`price`,e.label,t)}catch{}}}catch{}}render(n,r,i){let{chartRect:a}=r;for(let o of this.alerts){if(!wT(o))continue;let s=e.k(o.price,r);if(s<a.y||s>a.y+a.height)continue;let c=o.expired?`#8a93a3`:o.triggered?`#f2a93b`:`#4c8dff`;n.setLineDash([2,6]),n.strokeStyle=c,n.lineWidth=1,n.beginPath(),e.y(n,a.x,a.x+a.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=`10px ${i.font.family}`,n.fillStyle=c,n.textBaseline=`bottom`,n.textAlign=`right`;let l=`${(0,t.priceTagText)(o.price,r,this.pricePrecision??void 0)}${o.message?` - ${o.message}`:``}`,u=a.x+a.width-4;n.fillText(l,u,s-2);let d=u-n.measureText(l).width-bT-yT;d>=a.x&&fx(n,t.UI_ICONS.bell,d,s-2-yT,yT,c)}}};function jT(e,t,n){let r={},i=CT.includes(e);if(n.target!==void 0){if(i)throw RangeError(`An alert on a move takes no other line`);if(n.target===t)throw RangeError(`An alert can’t compare a line with itself`);r.target=n.target}if(i){let{percent:e,bars:t}=n;if(e===void 0||!Number.isFinite(e)||e<=0)throw RangeError(`An alert on a move needs a percent above 0`);if(t===void 0||!Number.isInteger(t)||t<2||t>500)throw RangeError(`An alert on a move needs 2 to 500 bars`);r.percent=e,r.bars=t}return n.onBarClose&&(r.onBarClose=!0),n.expiresAt!==void 0&&Number.isFinite(n.expiresAt)&&(r.expiresAt=n.expiresAt),r}function MT(e){let t={};return typeof e.target==`string`&&e.target&&(t.target=e.target),typeof e.percent==`number`&&Number.isFinite(e.percent)&&(t.percent=e.percent),typeof e.bars==`number`&&Number.isInteger(e.bars)&&(t.bars=e.bars),e.onBarClose===!0&&(t.onBarClose=!0),typeof e.expiresAt==`number`&&Number.isFinite(e.expiresAt)&&(t.expiresAt=e.expiresAt),t}var NT=16,PT=3*NT,FT=1e3/30,IT=1e-9,LT=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),RT={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>LT()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,NT)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},zT=class extends LS{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=RT){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1,this.owedMs=0}play(e){if(this.data.length===0)return;if(e){let{startIndex:t,paused:n,duration:r,...i}=e;this.config={...this.config,...i};let a=t===void 0?null:this.clamp(t);if(n){this.clearTimer(),this.seekTo(a??Math.max(0,this.cursor)),this.setPace(r),this.setState(`paused`);return}a!==null&&(this.cursor=a-1,this.owedMs=0),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.stepMs();if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),this.config.animate?this.runForming(t):t<NT||this.paceMs!==null?this.runFrames(t):this.timer=setInterval(()=>this.advance(1),t)}pause(){this.clearTimer(),this.setState(`paused`)}resume(){this.state===`paused`&&this.play()}stop(){this.clearTimer(),this.cursor=-1,this.owedMs=0,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.owedMs=0,this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){let t=this.getFraction();this.config={...this.config,speed:e},this.paceMs=null;let n=this.stepMs();this.owedMs=n>0&&Number.isFinite(n)?t*n:0,this.state===`playing`&&this.play()}getState(){return this.state}isAtEnd(){return this.data.length>0&&this.cursor>=this.data.length-1}getProgress(){let e=this.data.length;return{current:Math.max(0,this.cursor),total:e,percent:e>0?(this.cursor+1)/e*100:0}}remainingMs(){return this.paceMs===null?null:this.paceMs*Math.max(0,this.data.length-1-this.cursor)}getStepMs(){return this.stepMs()}getFraction(){let e=this.stepMs();return e>0&&Number.isFinite(e)?Math.min(1,this.owedMs/e):0}dispose(){this.stop(),this.removeAllListeners(),this.data=[]}setPace(e){this.paceMs=e!==void 0&&e>0&&Number.isFinite(e)?e/Math.max(1,this.data.length-1-this.cursor):null}runFrames(e){let t=this.run,n=this.clock.now(),r=0,i=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let a=this.clock.now();r+=Math.min(50,Math.max(0,a-n)),n=a;let o=Math.floor(r/e);try{o>0&&(r-=o*e,this.advance(o))}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(i))}};this.frameHandle=this.clock.frame(i)}stepMs(){return this.paceMs??this.config.interval/this.config.speed}runForming(e){let t=this.run,n=e>=PT,r=this.clock.now(),i=-1/0,a=r=>{!n||this.isAtEnd()||t!==this.run||this.state!==`playing`||(i=r,this.emit(`phase`,{index:this.cursor+1,fraction:Math.min(1,this.owedMs/e)}))},o=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let n=this.clock.now();this.owedMs+=Math.min(50,Math.max(0,n-r)),r=n;let s=Math.floor((this.owedMs+IT)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+NT/2>=FT&&a(n)}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(o))}};a(r),this.frameHandle=this.clock.frame(o)}advance(e){if(this.isAtEnd()){this.finish();return}this.cursor=Math.min(this.data.length-1,this.cursor+e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}),this.isAtEnd()&&this.finish()}finish(){this.clearTimer(),this.setState(`paused`),this.emit(`complete`,void 0)}clamp(e){return Number.isFinite(e)?Math.max(0,Math.min(Math.floor(e),this.data.length-1)):0}clearTimer(){this.run++,this.timer&&=(clearInterval(this.timer),null),this.frameHandle!==null&&(this.clock.cancel(this.frameHandle),this.frameHandle=null)}setState(e){this.state!==e&&(this.state=e,this.emit(`stateChange`,e))}},BT=64,VT=3,HT=3;function UT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function WT(e){return Array.isArray(e)?e:[]}function GT(e,t){return typeof e==`string`?e:t}function KT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function qT(e){if(!UT(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>JT||!UT(e.style))return null;let n=[];for(let t of e.anchors){if(!UT(t)||typeof t.time!=`number`||typeof t.price!=`number`||!Number.isFinite(t.time)||!Number.isFinite(t.price))return null;n.push({time:t.time,price:t.price})}let r=(0,t.sanitizeDrawingStyle)(e.style);return r.color===void 0||r.lineWidth===void 0?null:{id:e.id,type:e.type,anchors:n,style:{lineStyle:`solid`,...r,color:r.color,lineWidth:r.lineWidth},visible:typeof e.visible==`boolean`?e.visible:!0,locked:typeof e.locked==`boolean`?e.locked:!1,options:UT(e.options)?e.options:void 0,intervals:ja(e.intervals)??void 0,group:QT(e.group),...tm(e.name)===void 0?{}:{name:tm(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=YT?{paneId:e.paneId}:{},meta:UT(e.meta)?e.meta:void 0}}var JT=5e3,YT=200,XT=64,ZT=80;function QT(e){if(!(!UT(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>XT))return{id:e.id,name:e.name.slice(0,ZT)}}function $T(e){return!UT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function eE(e){if(!UT(e))return;let n={},r=WT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=WT(e.lineWidths).filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);i.length>0&&(n.lineWidths=i),typeof e.opacity==`number`&&Number.isFinite(e.opacity)&&(n.opacity=Math.min(1,Math.max(0,e.opacity)));let a=(0,t.readIndicatorPlotStyles)(e.plots);return a&&(n.plots=a),Object.keys(n).length>0?n:void 0}var tE=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function nE(e){if(!UT(e)||typeof e.id!=`string`)return null;let t=typeof e.drawingId==`string`?e.drawingId:void 0,n=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:null,r=tE.find(t=>t===e.condition)??`crossing`,i=MT(e),a=i.target!==void 0||r===`movesUp`||r===`movesDown`;return n===null&&!t&&!a?null:{id:e.id,price:n??NaN,drawingId:t,condition:r,message:typeof e.message==`string`?e.message:void 0,triggered:e.triggered===!0,repeating:e.repeating===!0,channel:GT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function rE(e){return!UT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var iE=4e3;function aE(e){if(!UT(e))return;let n={},r=[];for(let[i,a]of Object.entries(e)){let e=(0,t.readChartStyleOverrides)(a);r.push(...e.rejected);let o=Object.fromEntries(Object.entries(e.overrides).filter(([,e])=>e!==null));Object.keys(o).length>0&&(n[i.slice(0,BT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function oE(e){if(!UT(e))return sE();typeof e.version==`number`&&e.version>HT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=UT(e.viewport)?e.viewport:{},r=[];for(let n of WT(e.indicators))UT(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||UT(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:eE(n.style),visible:typeof n.visible==`boolean`?n.visible:void 0,levels:Array.isArray(n.levels)?n.levels.filter(e=>typeof e==`number`&&Number.isFinite(e)):void 0,pane:typeof n.pane==`string`?n.pane:void 0,scale:n.scale===`left`?`left`:void 0,intervals:ja(n.intervals)??void 0,paneStyle:(0,t.readPaneStyle)(n.paneStyle)??void 0,paneSize:typeof n.paneSize==`number`&&Number.isFinite(n.paneSize)&&n.paneSize>0?Math.min(n.paneSize,iE):void 0,paneOrder:typeof n.paneOrder==`number`&&Number.isInteger(n.paneOrder)&&n.paneOrder>=0?n.paneOrder:void 0,paneCollapsed:n.paneCollapsed===!0?!0:void 0,paneMaximized:n.paneMaximized===!0?!0:void 0,paneLog:n.paneLog===!0?!0:void 0,paneInvert:n.paneInvert===!0?!0:void 0,panePercent:n.panePercent===!0?!0:void 0}));let i=[];for(let t of WT(e.drawings)){let e=qT(t);e&&i.push(e)}let a=[];for(let t of WT(e.orders)){let e=$T(t);e&&a.push(e)}let o=[];for(let t of WT(e.positions)){let e=rE(t);e&&o.push(e)}let s=[];for(let t of WT(e.alerts)){let e=nE(t);e&&s.push(e)}let c=aE(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:KT(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:GT(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:KT(n.barWidth,8),barSpacing:KT(n.barSpacing,2),offset:KT(n.offset,0)},theme:typeof e.theme==`string`?e.theme:void 0,...c?{overrides:c}:{},locale:typeof e.locale==`string`?e.locale:void 0,indicators:r,drawings:i,orders:a,positions:o,alerts:s}}function sE(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var cE=class{static capture(e,t){return{version:e.getIndicators?HT:1,timestamp:Date.now(),chartType:t?.chartType??`candlestick`,...t?.chartTypeOptions&&Object.keys(t.chartTypeOptions).length>0?{chartTypeOptions:t.chartTypeOptions}:{},symbol:t?.symbol,timeframe:t?.timeframe,viewport:{barWidth:8,barSpacing:2,offset:0},theme:e.getTheme().name,...e.getOverrides&&Object.keys(e.getOverrides()).length>0?{overrides:e.getOverrides()}:{},indicators:e.getIndicators?.()??[],drawings:e.getDrawings(),orders:e.getOrders?.()??[],positions:e.getPositions?.()??[],alerts:e.getAlerts?.()??[]}}static serialize(e){return JSON.stringify(e)}static deserialize(e){return oE(JSON.parse(e))}static saveToStorage(e,t){localStorage.setItem(e,this.serialize(t))}static loadFromStorage(e){let t=localStorage.getItem(e);return t?this.deserialize(t):null}static downloadFile(e,t=`tc-chart-state.json`){let n=new Blob([this.serialize(e)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}static loadFromFile(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.type=`file`,n.accept=`.json`,n.onchange=async()=>{let r=n.files?.[0];if(!r){t(Error(`No file selected`));return}let i=await r.text();e(this.deserialize(i))},n.click()})}},lE=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;grouped=null;setOnChange(e){this.onChange=e}push(e){if(this.grouped){this.grouped.push(e);return}this.undoStack.push(e),this.undoStack.length>this.maxHistory&&this.undoStack.shift(),this.redoStack.length=0,this.onChange?.()}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(){let e=this.undoStack.pop();return e?(this.redoStack.push(e),this.onChange?.(),e):null}redo(){let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.onChange?.(),e):null}clear(){this.undoStack.length=0,this.redoStack.length=0,this.onChange?.()}group(e){if(this.grouped)return e();let t=[];this.grouped=t;try{return e()}finally{this.grouped=null,t.length===1?this.push(t[0]):t.length>1&&this.push({type:`drawingBatch`,before:null,after:null,actions:t})}}last(){return this.grouped?this.grouped[this.grouped.length-1]??null:this.undoStack[this.undoStack.length-1]??null}dropLast(){if(this.grouped){this.grouped.pop();return}this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.grouped){this.grouped.length>0?this.grouped[this.grouped.length-1]=e:this.grouped.push(e);return}if(this.undoStack.length===0){this.push(e);return}this.undoStack[this.undoStack.length-1]=e,this.redoStack.length=0,this.onChange?.()}getState(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoCount:this.undoStack.length,redoCount:this.redoStack.length}}},uE=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function dE(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function fE(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var pE=15,mE=0x38d7ea4c68000;function hE(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=mE?e:Number(e.toPrecision(pE))}var gE=e=>{let t=hE(e);return t===null?``:String(t)},_E=class{static toCSV(e,n=[]){let r=[...uE,...n.map(e=>fE(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[dE(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(gE),...n.map(e=>gE(e.values[t]))].join(`,`))].join(`
25
- `)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:dE(e.time,r),open:hE(e.open),high:hE(e.high),low:hE(e.low),close:hE(e.close),volume:hE(e.volume)};for(let e of n)i[e.name]=hE(e.values[t]);return i}),null,2)}static download(e,t,n){let r=new Blob([e],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}};function vE(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function yE(e,t,n=-1/0){return t===null?e:e.filter(e=>e.entryTime>=n&&e.entryTime<t).map(e=>{if(e.exitTime===void 0||e.exitTime<t)return e;let{exitTime:n,exitPrice:r,pnl:i,pnlPercent:a,...o}=e;return o})}var bE=1,xE=3,SE=class extends LS{markers=[];style={...t.DEFAULT_SIGNAL_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addMarker(e){let t=e.id??`tc_signal_${bE++}`,n={...e,id:t};return this.markers.push(n),this.emit(`added`,n),this.requestRender?.(),t}removeMarker(e){this.markers=this.markers.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getMarkers(){return[...this.markers]}clearMarkers(){this.markers=[],this.emit(`cleared`,void 0),this.requestRender?.()}setMarkers(e){this.markers=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownMarkers(){return[...vE(this.markers,this.revealUntil,this.revealFrom)]}markerAt(t,n){let r=this.dataGetter?.();if(!r||r.length===0)return null;let{chartRect:i}=n;if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return null;let a=this.style.arrowSize??12,o=vE(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.w(e.N(s.time,r),n),l=e.k(s.price,n),u=a*Math.max(.6,Math.min(1,s.confidence)),d=s.direction===`long`?l-u:(s.direction,l-u*.4),f=s.direction===`long`?l+u*.4:s.direction===`short`?l+u:l+u*.4;if(Math.abs(t.x-c)<=u*.6+xE&&t.y>=d-xE&&t.y<=f+xE)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=vE(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=yS(this.style,r),c=s.arrowSize??12;t.save(),t.beginPath(),t.rect(o.x,o.y,o.width,o.height),t.clip();for(let l of a){let a=e.w(e.N(l.time,i),n),u=e.k(l.price,n);if(a<o.x-c||a>o.x+o.width+c||u<o.y-c||u>o.y+o.height+c)continue;let d=this.resolveColor(l,s),f=c*Math.max(.6,Math.min(1,l.confidence));if(this.renderArrow(t,a,u,l.direction,f,d),s.showLabel&&l.label){t.font=`10px ${r.font.family}`,t.fillStyle=d,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+3:u-f-3;t.fillText(l.label,a,e)}if(s.showConfidence&&l.confidence<1){t.font=`9px ${r.font.family}`,t.fillStyle=d,t.globalAlpha=.7,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+(l.label?14:3):u-f-(l.label?14:3);t.fillText(`${Math.round(l.confidence*100)}%`,a,e),t.globalAlpha=1}}t.restore()}resolveColor(e,t){if(e.color)return e.color;if(t.sourceColors?.[e.source])return t.sourceColors[e.source];switch(e.direction){case`long`:return t.longColor??`#1fa874`;case`short`:return t.shortColor??`#e8505b`;default:return t.neutralColor??`#9E9E9E`}}renderArrow(e,t,n,r,i,a){e.fillStyle=a,e.beginPath(),r===`long`?(e.moveTo(t,n-i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n+i*.4),e.lineTo(t+i*.2,n+i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):r===`short`?(e.moveTo(t,n+i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n-i*.4),e.lineTo(t+i*.2,n-i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):e.arc(t,n,i*.4,0,Math.PI*2),e.closePath(),e.fill()}},CE=18,wE=4,TE=2,EE=6,DE=18+2*wE,OE=3,kE=300,AE=10,jE=8,ME=8,NE=1.35,PE=6,FE={news:`N`,earnings:`E`,dividend:`D`,split:`S`,event:`i`},IE={news:`#4c8dff`,earnings:`#f2a93b`,dividend:`#4fae8a`,split:`#a78bfa`},LE=1,RE=class{marks=[];requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;hoveredId=null;tooltip=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setMarks(e){this.marks=(0,t.readChartMarks)(e),this.requestRender?.()}addMark(e){let[n]=(0,t.readChartMarks)([{...e,id:e.id??`tc_mark_${LE++}`}]);if(!n)return null;let r=this.marks.filter(e=>e.id!==n.id);return r.length>=t.MAX_CHART_MARKS?null:(this.marks=[...r,n].sort((e,t)=>e.time-t.time),this.requestRender?.(),n.id)}removeMark(e){this.marks=this.marks.filter(t=>t.id!==e),this.requestRender?.()}clearMarks(){this.marks=[],this.requestRender?.()}getMarks(){return this.marks.map(e=>({...e}))}count(){return this.marks.length}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}setHovered(e){let t=e?.marks[0]?.id??null;return t===this.hoveredId?!1:(this.hoveredId=t,this.requestRender?.(),!0)}isHovering(){return this.hoveredId!==null}tooltipBox(){return this.tooltip?{...this.tooltip}:null}badges(t){let n=this.dataGetter?.();if(!n||n.length===0||this.marks.length===0)return[];let{chartRect:r}=t,i=r.y+r.height-18/2-wE,a=[];for(let o of this.marks){if(this.revealUntil!==null&&(o.time<this.revealFrom||o.time>=this.revealUntil))continue;let s=e.N(o.time,n);if(s<0||s>=n.length)continue;let c=e.w(Math.floor(s),t);if(c<r.x||c>r.x+r.width)continue;let l=a[a.length-1];l&&c-l.x<18+TE?l.marks.push(o):a.push({x:c,y:i,marks:[o]})}return a}badgeAt(e,t){let{chartRect:n}=t;if(e.x<n.x||e.x>n.x+n.width||e.y<n.y||e.y>n.y+n.height)return null;let r=18/2+EE,i=null,a=1/0;for(let n of this.badges(t)){let t=Math.abs(e.x-n.x),o=Math.abs(e.y-n.y);t>r||o>r||t>=a||(a=t,i=n)}return i}render(e,t,n){this.tooltip=null;let r=this.badges(t);if(r.length===0)return;let{chartRect:i}=t;e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip();let a=null;for(let t of r){let r=this.hoveredId!==null&&t.marks.some(e=>e.id===this.hoveredId);r&&(a=t),this.renderBadge(e,t,n,r)}a&&this.renderTooltip(e,a,t,n),e.restore()}colorOf(e,t){if(e.color)return e.color;let n=e.kind??`event`;return n===`event`?t.textSecondary:IE[n]}renderBadge(e,t,n,r){let i=t.marks[0],a=this.colorOf(i,n);e.fillStyle=n.background,e.beginPath(),e.arc(t.x,t.y,9+(r?3:1.5),0,Math.PI*2),e.fill(),r&&(e.fillStyle=a,e.globalAlpha=.35,e.beginPath(),e.arc(t.x,t.y,12,0,Math.PI*2),e.fill(),e.globalAlpha=1),e.fillStyle=a,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.fill();let o=t.marks.length>1?String(t.marks.length):i.label??FE[i.kind??`event`];e.fillStyle=ne(a),e.font=`600 ${o.length>1?10:11}px ${n.font.family}`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(o,t.x,t.y+.5)}renderTooltip(e,t,n,r){let{chartRect:i}=n,a=r.font.sizeMedium,o=r.font.sizeSmall,s=`600 ${a}px ${r.font.family}`,c=`${o}px ${r.font.family}`,l=Math.min(kE,i.width-2*wE),u=l-2*AE;if(u<=0)return;let d=[...t.marks].reverse().slice(0,OE),f=t.marks.length-d.length,p=[];d.forEach((t,n)=>{p.push({text:zE(e,t.title,s,u),font:s,color:r.text,height:a*NE,gap:n===0?0:ME}),t.text&&p.push({text:zE(e,t.text,c,u),font:c,color:r.textSecondary,height:o*NE,gap:0})}),f>0&&p.push({text:`+${f}`,font:c,color:r.textSecondary,height:o*NE,gap:ME});let m=p.reduce((e,t)=>e+t.gap+t.height,0)+2*AE,h=Math.max(i.x+wE,Math.min(i.x+i.width-wE-l,t.x-l/2)),g=Math.max(i.y+wE,t.y-18/2-jE-m);this.tooltip={x:h,y:g,width:l,height:m},e.fillStyle=r.axisLabelBackground,e.strokeStyle=r.axisLine,e.lineWidth=1,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(Math.round(h)+.5,Math.round(g)+.5,l,m,PE):e.rect(Math.round(h)+.5,Math.round(g)+.5,l,m),e.fill(),e.stroke(),e.textAlign=`left`,e.textBaseline=`top`;let _=g+AE;for(let t of p)_+=t.gap,e.font=t.font,e.fillStyle=t.color,e.fillText(t.text,h+AE,_),_+=t.height}};function zE(e,t,n,r){if(e.font=n,e.measureText(t).width<=r)return t;let i=[...t],a=0,o=i.length;for(;a<o;){let t=a+o+1>>>1;e.measureText(`${i.slice(0,t).join(``).trimEnd()}…`).width<=r?a=t:o=t-1}return`${i.slice(0,a).join(``).trimEnd()}…`}var BE=12,VE=2,HE=1,UE=class extends LS{zones=[];style={...t.DEFAULT_TRADE_ZONE_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;pricePrecision=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setPricePrecision(e){this.pricePrecision=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addZone(e){let t=e.id??`tc_zone_${HE++}`,n={...e,id:t};return this.zones.push(n),this.emit(`added`,n),this.requestRender?.(),t}updateZone(e,t){let n=this.zones.findIndex(t=>t.id===e);n!==-1&&(this.zones[n]={...this.zones[n],...t},this.requestRender?.())}removeZone(e){this.zones=this.zones.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getZones(){return[...this.zones]}clearZones(){this.zones=[],this.emit(`cleared`,void 0),this.requestRender?.()}setZones(e){this.zones=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownZones(){return[...yE(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=yE(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=bS(this.style,n);e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip();for(let a of i)this.renderZone(e,a,r,t,n,o);e.restore()}renderZone(n,r,i,a,o,s){let{chartRect:c}=a,l=e.N(r.entryTime,i),u=r.exitTime==null?i.length-1:e.N(r.exitTime,i),d=e.w(l,a),f=e.w(u,a),p=Math.max(c.x,Math.min(d,f)),m=Math.min(c.x+c.width,Math.max(d,f));if(m-p<1)return;let h=e.k(r.entryPrice,a),g=r.exitPrice==null?e.k(r.entryPrice,a):e.k(r.exitPrice,a),_=Math.min(h,g),v=Math.max(Math.max(h,g)-_,2),y=r.exitTime==null,b=r.pnl==null?r.direction===`long`?(r.exitPrice??r.entryPrice)>=r.entryPrice:(r.exitPrice??r.entryPrice)<=r.entryPrice:r.pnl>=0,x=y?s.activeColor??`#4c8dff`:b?s.profitColor??`#1fa874`:s.lossColor??`#e8505b`;n.fillStyle=x,n.globalAlpha=s.fillOpacity??.12,n.fillRect(p,_,m-p,v),n.globalAlpha=1;let S=s.borderWidth??1;if(n.strokeStyle=x,n.lineWidth=S,n.setLineDash([]),n.beginPath(),n.moveTo(p,Math.round(h)+.5),n.lineTo(m,Math.round(h)+.5),n.stroke(),!y&&r.exitPrice!=null&&(n.setLineDash([3,3]),n.beginPath(),n.moveTo(p,Math.round(g)+.5),n.lineTo(m,Math.round(g)+.5),n.stroke(),n.setLineDash([])),fx(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-BE,BE,x),n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText((0,t.priceTagText)(r.entryPrice,a,this.pricePrecision??void 0),p+4+BE+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,i=e=>(0,t.formatPrice)(e,VE,a.numberLocale??`en-US`),s=r.pnlPercent==null?`${e}${i(r.pnl)}`:`${e}${i(r.pnl)} (${e}${i(r.pnlPercent)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let c=n.measureText(s).width+8,l=m-c-2,u=_+2;n.globalAlpha=.85,n.fillStyle=o.background,A(n,l,u,c,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(s,m-4,u+1)}s.showLabel&&r.label&&(n.font=`9px ${o.font.family}`,n.fillStyle=x,n.globalAlpha=.8,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(r.label,p+4,h+3),n.globalAlpha=1)}},WE=2,GE=4,KE=t.MAX_PRICE_DECIMALS,qE=class{active=!1;startBar=0;startPrice=0;endBar=0;endPrice=0;startTime=null;endTime=null;isActive(){return this.active}begin(t,n,r){let i=Math.round(e.P(t.x,n)),a=e.I(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=JE(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.P(t.x,n));this.endBar=i,this.endPrice=e.I(t.y,n),this.endTime=JE(i,r)}end(){this.active=!1}render(n,r,i){if(!this.active)return;let a=e.w(this.startBar,r),o=e.w(this.endBar,r),s=e.k(this.startPrice,r),c=e.k(this.endPrice,r),l=Math.min(a,o),u=Math.max(a,o),d=Math.min(s,c),f=Math.max(s,c),p=u-l,m=f-d,h=this.endPrice>=this.startPrice?i.candleUp:i.candleDown,g=tD(h,.14);n.save();let{chartRect:_}=r;n.beginPath(),n.rect(_.x,_.y,_.width,_.height),n.clip(),n.fillStyle=g,n.fillRect(l,d,p,m),n.strokeStyle=h,n.lineWidth=1,n.setLineDash([4,3]),n.strokeRect(l+.5,d+.5,p,m),n.setLineDash([]),n.strokeStyle=h,n.lineWidth=1.5,n.beginPath(),n.moveTo(a,s),n.lineTo(o,c),n.stroke(),QE(n,a,s,h),QE(n,o,c,h),n.restore();let v=Math.abs(this.endBar-this.startBar),y=this.endPrice-this.startPrice,b=this.startPrice===0?0:y/this.startPrice*100,x=this.startTime!==null&&this.endTime!==null?ZE(Math.abs(this.endTime-this.startTime)):null,S=[],C=y>0?`+`:y<0?`−`:``,w=Math.abs(y),T=(0,t.formatPrice)(Math.abs(b),WE,r.numberLocale??`en-US`);S.push(`${C}${YE(w,r)} (${C}${T}%)`),S.push(`${v} bars${x?` · `+x:``}`),n.save(),$E(n,o,c,S,h,i),n.restore()}};function JE(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function YE(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??XE(e))}function XE(e){return e>=1e3?2:e>=1?4:e<=0?GE-1:Math.min(KE,GE-1-Math.floor(Math.log10(e)))}function ZE(e){let t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;let n=t/60;if(n<60)return`${n.toFixed(1)}m`;let r=n/60;if(r<24)return`${r.toFixed(1)}h`;let i=r/24;if(i<30)return`${i.toFixed(1)}d`;let a=i/30;return a<12?`${a.toFixed(1)}mo`:`${(i/365).toFixed(1)}y`}function QE(e,t,n,r){e.fillStyle=r,e.beginPath(),e.arc(t,n,3.5,0,Math.PI*2),e.fill(),e.fillStyle=`#fff`,e.beginPath(),e.arc(t,n,1.5,0,Math.PI*2),e.fill()}function $E(e,t,n,r,i,a){e.font=`600 11px ${a.font.family}`;let o=0;for(let t of r){let n=e.measureText(t).width;n>o&&(o=n)}let s=Math.ceil(o)+16,c=r.length*14+12,l=t+8,u=n+8,d=e.canvas.clientWidth||e.canvas.width;l+s>d-4&&(l=t-s-8),l<4&&(l=4),e.fillStyle=a.background,e.globalAlpha=.96,eD(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,eD(e,l+.5,u+.5,s-1,c-1,6),e.stroke(),e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<r.length;t++)e.fillStyle=t===0?i:a.textSecondary,e.fillText(r[t],l+8,u+6+t*14)}function eD(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function tD(e,t){if(e.startsWith(`#`)){let n=0,r=0,i=0;return e.length===4?(n=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16),i=parseInt(e[3]+e[3],16)):e.length>=7&&(n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16)),`rgba(${n},${r},${i},${t})`}if(e.startsWith(`rgb`)){let n=e.match(/[\d.]+/g);if(n&&n.length>=3)return`rgba(${n[0]},${n[1]},${n[2]},${t})`}return e}var nD=6,rD=class{start=null;current=null;isActive(){return this.start!==null}begin(e){this.start=e,this.current=e}update(e){this.start&&(this.current=e)}end(){let e=this.start,t=this.current;if(this.cancel(),!e||!t)return null;let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y);return{x0:n,y0:i,x1:r,y1:a,isClick:r-n<6&&a-i<6}}cancel(){this.start=null,this.current=null}render(e,t,n){if(!this.start||!this.current)return;let{chartRect:r}=t,i=e=>Math.max(r.x,Math.min(r.x+r.width,e)),a=e=>Math.max(r.y,Math.min(r.y+r.height,e)),o=i(Math.min(this.start.x,this.current.x)),s=i(Math.max(this.start.x,this.current.x)),c=a(Math.min(this.start.y,this.current.y)),l=a(Math.max(this.start.y,this.current.y));e.save(),e.fillStyle=n.crosshair,e.globalAlpha=.1,e.fillRect(o,c,s-o,l-c),e.globalAlpha=.8,e.strokeStyle=n.crosshair,e.lineWidth=1,e.setLineDash([4,3]),e.strokeRect(Math.round(o)+.5,Math.round(c)+.5,Math.round(s-o),Math.round(l-c)),e.restore()}},iD={linear:e=>e,easeOutCubic:e=>1-(1-e)**3,easeOutQuart:e=>1-(1-e)**4,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,easeOutExpo:e=>e===1?1:1-2**(-10*e),easeOutElastic:e=>e===0||e===1?e:2**(-10*e)*Math.sin((e*10-.75)*(2*Math.PI/3))+1,spring:e=>1-Math.E**(-6*e)*Math.cos(8*e)},aD=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??iD.easeOutCubic,onUpdate:t.onUpdate,onComplete:t.onComplete}),this.running||(this.running=!0,this.tick())}cancel(e){this.animations.delete(e),this.animations.size===0&&this.stop()}cancelAll(){this.animations.clear(),this.stop()}isAnimating(e){return e?this.animations.has(e):this.animations.size>0}tick(){this.frameId=requestAnimationFrame(e=>{let t=[];for(let[n,r]of this.animations){r.startTime<0&&(r.startTime=e);let i=e-r.startTime,a=Math.min(1,i/r.duration),o=r.easing(a);r.onUpdate(o),a>=1&&(r.onComplete?.(),t.push(n))}for(let e of t)this.animations.delete(e);this.animations.size>0?this.tick():this.running=!1})}stop(){this.frameId&&=(cancelAnimationFrame(this.frameId),0),this.running=!1}dispose(){this.cancelAll()}};function oD(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}function sD(e,t){let n=oD(e),r=Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!==void 0));return{...n,font:{...n.font,...r}}}var cD=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;sizer;themeGiven;fontGiven;constructor(e,t,n){this.container=e,this.themeGiven=t,this.fontGiven=n,this.theme=sD(t,n),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,s(this.canvas),this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.sizer=new o(e),this.updateSize(),this.sizer.onResize(()=>{this.updateSize(),this.renderNow()})}updateSize(){this.dpr=this.sizer.getDpr();let e=this.sizer.readContainerSize();if(this.width=e.width,this.height=e.height,this.width<=0||this.height<=0)return;let t=i(e,this.dpr,this.sizer.getDeviceSize());this.canvas.width!==t.width&&(this.canvas.width=t.width),this.canvas.height!==t.height&&(this.canvas.height=t.height)}requestRender(){this.frameId===null&&(this.frameId=requestAnimationFrame(()=>{this.frameId=null,(this.width===0||this.height===0)&&this.updateSize(),this.renderNow()}))}renderNow(){this.width===0||this.height===0||(this.ctx.save(),this.ctx.setTransform(this.canvas.width/this.width,0,0,this.canvas.height/this.height,0,0),this.ctx.clearRect(0,0,this.width,this.height),this.renderChart(this.ctx,this.width,this.height,this.theme),this.ctx.restore())}applyBaseOptions(e){`theme`in e&&(this.themeGiven=e.theme),`font`in e&&(this.fontGiven=e.font),(`theme`in e||`font`in e)&&(this.theme=sD(this.themeGiven,this.fontGiven)),e.ariaLabel!==void 0&&this.setLabel(e.ariaLabel)}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.themeGiven=e,this.theme=sD(e,this.fontGiven),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.sizer.destroy(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},lD=class{pos=null;canvas;onUpdate;handleMove;handleLeave;handleOutside;handleCancel;constructor(e,t){this.canvas=e,this.onUpdate=t,this.handleMove=t=>{let n=e.getBoundingClientRect();this.pos={x:t.clientX-n.left,y:t.clientY-n.top},this.onUpdate()},this.handleLeave=e=>{e.pointerType!==`touch`&&this.clear()},this.handleOutside=t=>{t.composedPath().includes(e)||this.clear()},this.handleCancel=()=>this.clear(),e.addEventListener(`pointermove`,this.handleMove),e.addEventListener(`pointerdown`,this.handleMove),e.addEventListener(`pointerleave`,this.handleLeave),e.addEventListener(`pointercancel`,this.handleCancel),e.ownerDocument.addEventListener(`pointerdown`,this.handleOutside,!0)}clear(){this.pos!==null&&(this.pos=null,this.onUpdate())}getPosition(){return this.pos}isActive(){return this.pos!==null}drawCrosshair(e,t,n,r){this.pos&&(e.save(),e.strokeStyle=r,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(this.pos.x,0),e.lineTo(this.pos.x,n),e.stroke(),e.beginPath(),e.moveTo(0,this.pos.y),e.lineTo(t,this.pos.y),e.stroke(),e.restore())}destroy(){this.canvas.removeEventListener(`pointermove`,this.handleMove),this.canvas.removeEventListener(`pointerdown`,this.handleMove),this.canvas.removeEventListener(`pointerleave`,this.handleLeave),this.canvas.removeEventListener(`pointercancel`,this.handleCancel),this.canvas.ownerDocument.removeEventListener(`pointerdown`,this.handleOutside,!0)}};function uD(e,n,r,i,a){let{data:o,mode:s=`area`,lineWidth:c=1.5,showLastPoint:l=!1,showMinMax:u=!1}=i;if(o.length<2||n<=0||r<=0)return;let d=i.color??a.lineColor,f=i.fillColor??d,p=n-4,m=r-4,h=1/0,g=-1/0,_=0,v=0;for(let e=0;e<o.length;e++)o[e]<h&&(h=o[e],_=e),o[e]>g&&(g=o[e],v=e);let y=g-h||1,b=e=>2+e/(o.length-1)*p,x=e=>2+m-(e-h)/y*m;if(s===`area`){let n=e.createLinearGradient(0,2,0,r-2);n.addColorStop(0,(0,t.withAlpha)(f,Hd)),n.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));e.lineTo(b(o.length-1),r-2),e.lineTo(b(0),r-2),e.closePath(),e.fillStyle=n,e.fill()}e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));if(e.strokeStyle=d,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),l){let t=i.lastPointColor??d,n=b(o.length-1),r=x(o[o.length-1]);e.beginPath(),e.arc(n,r,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(u){let t=i.minPointColor??a.candleDown,n=i.maxPointColor??a.candleUp;e.beginPath(),e.arc(b(_),x(h),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(b(v),x(g),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var dD=.2,fD=.01,pD=24,mD=16,hD=`Spread`;function gD(e,t){let n=e.filter(e=>Number.isFinite(e.price)&&Number.isFinite(e.volume)).sort((e,n)=>t===`bid`?n.price-e.price:e.price-n.price),r=0;return n.map(e=>({price:e.price,cumulativeVolume:r+=e.volume}))}function _D(e,t,n,r){let i=gD(e.data.bids,`bid`),a=gD(e.data.asks,`ask`),o=i[0]?.price,s=a[0]?.price,c=o!==void 0&&s!==void 0,l=c?(o+s)/2:o??s??0,u=i.length>0?i[i.length-1].price:l,d=a.length>0?a[a.length-1].price:l,f=(Math.max(l-u,d-l)||Math.abs(l)*fD||1)*(1+dD),p=$d(0,Math.max(0,...i.map(e=>e.cumulativeVolume),...a.map(e=>e.cumulativeVolume))||1,5),m=e.volumeFormat??q(p,e.locale),h=12+Math.max(0,...p.ticks.map(e=>r(m(e),11)))+8,g=12+(c&&e.midPriceLine!==!1&&e.spreadLabel!==!1?mD:0);return{plot:{x:h,y:g,width:Math.max(1,t-h-12),height:Math.max(1,n-g-12-20)},volume:p,priceMin:l-f,priceMax:l+f,bids:i,asks:a,mid:c?l:null,spread:c?s-o:0}}function vD(e,t){return e.length===1?[e[0],{price:t,cumulativeVolume:e[0].cumulativeVolume}]:e}function yD(e,t,n){let r=null;for(let i of e){if(n===`bid`?i.price<t:i.price>t)break;r=i}return r}function bD(e,n,r,i,a,o,s){if(n<=0||r<=0)return;e.fillStyle=a.background,e.fillRect(0,0,n,r);let{data:c}=i;if(c.bids.length===0&&c.asks.length===0)return;let l=s??((t,n=11)=>(e.font=J(a,n),e.measureText(t).width)),{plot:u,volume:d,priceMin:f,priceMax:p,bids:m,asks:h,mid:g,spread:_}=_D(i,n,r,l),v=u.y+u.height,y=e=>u.x+(e-f)/(p-f)*u.width,b=e=>G(d,e,u.y,u.height,!0),x=wf([...m,...h].map(e=>e.price)),S=i.priceFormat??sf(i.locale,x),C=i.volumeFormat??K(i.locale);Tf(e,u,d,`vertical`,a,i.volumeFormat??q(d,i.locale)),e.save(),e.font=J(a,11),e.fillStyle=a.axisLabel,e.strokeStyle=a.grid,e.textAlign=`center`,e.textBaseline=`top`;let w=l(S(p),11)+pD,T=$d(f,p,Math.max(2,Math.floor(u.width/w))),E=i.priceFormat??q(T,i.locale);e.font=J(a,11);for(let t of T.ticks)t<f||t>p||(gf(e,y(t),u.y,y(t),v),e.fillText(E(t),Math.round(y(t)),v+6));e.restore();let D=(t,n,r)=>{if(t.length===0)return;let i=()=>{for(let n=1;n<t.length;n++)e.lineTo(y(t[n].price),b(t[n-1].cumulativeVolume)),e.lineTo(y(t[n].price),b(t[n].cumulativeVolume))};e.fillStyle=r,e.beginPath(),e.moveTo(y(t[0].price),v),e.lineTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.lineTo(y(t[t.length-1].price),v),e.closePath(),e.fill(),e.strokeStyle=n,e.lineWidth=1.5,e.lineJoin=`miter`,e.beginPath(),e.moveTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.stroke()},O=i.bidColor??a.candleUp,k=i.askColor??a.candleDown;if(e.save(),e.beginPath(),e.rect(u.x,u.y,u.width,u.height),e.clip(),D(vD(m,f),O,i.bidFillColor??(0,t.withAlpha)(O,.25)),D(vD(h,p),k,i.askFillColor??(0,t.withAlpha)(k,.25)),e.restore(),g!==null&&i.midPriceLine!==!1&&(e.save(),e.strokeStyle=a.textSecondary,e.setLineDash([4,4]),gf(e,y(g),u.y,y(g),v),e.setLineDash([]),i.spreadLabel!==!1&&(e.font=J(a,11),e.fillStyle=a.textSecondary,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${typeof i.spreadLabel==`string`?i.spreadLabel:hD}: ${S(_)}`,Math.round(y(g)),12+mD/2-2)),e.restore()),!o||o.x<u.x||o.x>u.x+u.width)return;let A=f+(o.x-u.x)/u.width*(p-f);e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(e,o.x,u.y,o.x,v),e.restore();let j=yD(m,A,`bid`),ee=yD(h,A,`ask`),te=[{text:S((j??ee)?.price??A),bold:!0}];j&&te.push({text:C(j.cumulativeVolume),color:O}),ee&&te.push({text:C(ee.cumulativeVolume),color:k}),mf(e,te,o,{x:0,y:0,width:n,height:r},a)}var xD=.19,SD=864e5,CD=80,wD=3,TD=.05,ED=`Benchmark`;function DD(e,t){let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].time-t);a<r&&(r=a,n=i)}return n}function OD(e,t,n){return of(n,e<SD?{...t>SD?{month:`short`,day:`numeric`}:{},hour:`2-digit`,minute:`2-digit`}:e>=28*SD?{month:`short`,...t>=365*SD?{year:`numeric`}:{},timeZone:`UTC`}:{month:`short`,day:`numeric`,timeZone:`UTC`})}function kD(e,t){let n=e<7*SD;return of(t,{month:`short`,day:`numeric`,...e>=365*SD?{year:`numeric`}:{},...n?{hour:`2-digit`,minute:`2-digit`}:{timeZone:`UTC`}})}function AD(e){for(let t=1;t<e.length;t++)if(e[t].time<e[t-1].time)return[...e].sort((e,t)=>e.time-t.time);return e}function jD(e,t,n,r,i=``){let{data:a,benchmark:o}=e,s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of a)Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value)),Number.isFinite(e.time)&&(l=Math.min(l,e.time),u=Math.max(u,e.time));for(let e of o??[])Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value));let d=s===c?Math.abs(s)*TD||1:0,f=$d(s-d,c+d,5),p=e.valueFormat??q(f,e.locale),m=Math.max(0,...f.ticks.map(e=>r(p(e),11))),h=o&&o.length>=2?ff([{label:e.benchmarkLabel??ED,color:i}],t-24,r):null,g=12+m+8,_=12+(h?h.height+6:0);return{plot:{x:g,y:_,width:Math.max(1,t-g-12),height:Math.max(1,n-_-12-20)},scale:f,timeMin:l,timeMax:u,legend:h}}function MD(e,t,n,r,i,a){let{plot:o,timeMin:s,timeMax:c}=t,l=Cf(s,c,Math.max(1,Math.floor(o.width/CD))),u=i??OD(l.length>1?l[1]-l[0]:c-s,c-s,a);e.save(),e.font=J(r,11),e.fillStyle=r.axisLabel,e.strokeStyle=r.grid,e.textAlign=`center`,e.textBaseline=`top`;for(let t of l){let r=o.x+(t-s)/(c-s)*o.width;gf(e,r,o.y,r,o.y+o.height);let i=u(t),a=e.measureText(i).width/2;r-a>=0&&r+a<=n&&e.fillText(i,Math.round(r),o.y+o.height+6)}e.restore()}function ND(e,n,r,i,a,o,s){if(n<=0||r<=0||(e.fillStyle=a.background,e.fillRect(0,0,n,r),i.data.length<2))return;let c=AD(i.data),l=i.benchmark&&AD(i.benchmark),u=s??((t,n=11)=>(e.font=J(a,n),e.measureText(t).width)),d=i.lineColor??a.lineColor,f=i.benchmarkColor??a.textSecondary,p=jD(i,n,r,u,f),{plot:m,scale:h,timeMin:g,timeMax:_,legend:v}=p;if(!(_>=g))return;let y=_-g||1,b=e=>m.x+(e-g)/y*m.width,x=e=>G(h,e,m.y,m.height,!0),S=m.y+m.height,C=i.timeFormat??kD(y,i.locale);Tf(e,m,h,`vertical`,a,i.valueFormat??q(h,i.locale)),MD(e,p,n,a,i.timeFormat,i.locale),v&&pf(e,v,m.x,12,a);let w=(t,n=e=>t[e].value)=>{e.moveTo(b(t[0].time),x(n(0)));for(let r=1;r<t.length;r++)e.lineTo(b(t[r].time),x(n(r)))};if(e.save(),e.beginPath(),e.rect(m.x,m.y,m.width,m.height),e.clip(),i.drawdown===!0){let n=[],r=-1/0;for(let e of c)n.push(r=Number.isFinite(e.value)?Math.max(r,e.value):r);e.fillStyle=i.drawdownColor??(0,t.withAlpha)(a.candleDown,xD),e.beginPath(),w(c,e=>n[e]);for(let t=c.length-1;t>=0;t--)e.lineTo(b(c[t].time),x(c[t].value));e.closePath(),e.fill()}if(i.fillArea===!0){let n=e.createLinearGradient(0,m.y,0,S);n.addColorStop(0,(0,t.withAlpha)(d,Hd)),n.addColorStop(1,`transparent`),e.fillStyle=n,e.beginPath(),w(c),e.lineTo(b(c[c.length-1].time),S),e.lineTo(b(c[0].time),S),e.closePath(),e.fill()}if(e.lineJoin=`round`,l&&l.length>=2&&(e.strokeStyle=f,e.lineWidth=1,e.beginPath(),w(l),e.stroke()),e.strokeStyle=d,e.lineWidth=i.lineWidth??1.5,e.beginPath(),w(c),e.stroke(),e.restore(),!o||o.x<m.x||o.x>m.x+m.width)return;let T=c[DD(c,g+(o.x-m.x)/m.width*y)];if(!T)return;e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(e,b(T.time),m.y,b(T.time),S),e.restore(),e.fillStyle=d,e.beginPath(),e.arc(b(T.time),x(T.value),wD,0,Math.PI*2),e.fill();let E=i.valueFormat??K(i.locale),D=[{text:C(T.time),bold:!0},{text:E(T.value),color:d}],O=l?DD(l,T.time):-1;l&&O>=0&&D.push({text:`${i.benchmarkLabel??ED}: ${E(l[O].value)}`,color:f}),mf(e,D,o,{x:0,y:0,width:n,height:r},a)}function PD(e,t,n){if(e.length===0)return[];let r=e.length,i=Math.ceil(Math.sqrt(r)),a=Math.ceil(r/i),o=t.width/i,s=t.height/a,c=[];for(let a=0;a<r;a++){let r=a%i,l=Math.floor(a/i);c.push({id:e[a].id,rect:{x:t.x+r*o+n,y:t.y+l*s+n,width:Math.max(0,o-n*2),height:Math.max(0,s-n*2)}})}return c}function FD(e,t){let n=e.reduce((e,t)=>e+t,0);if(n===0||t===0)return 1/0;let r=0;for(let i of e){let e=n/t,a=i/e,o=e>a?e/a:a/e;o>r&&(r=o)}return r}function ID(e,t,n,r,i,a){let o=r?n.height:n.width,s=e.reduce((e,t)=>e+t,0),c=o>0?s/o:0,l=0;for(let o=0;o<e.length;o++){let s=c>0?e[o]/c:0,u;u=r?{x:n.x+i,y:n.y+l+i,width:Math.max(0,c-i*2),height:Math.max(0,s-i*2)}:{x:n.x+l+i,y:n.y+i,width:Math.max(0,s-i*2),height:Math.max(0,c-i*2)},a.push({id:t[o],rect:u}),l+=s}}function LD(e,t,n,r,i){if(e.length===0)return;let a=n.width>=n.height,o=a?n.height:n.width;if(e.length===1){ID(e,t,n,a,r,i);return}let s=[],c=[],l=0;for(;l<e.length;){let u=[...s,e[l]];if(s.length===0||FD(u,o)<=FD(s,o))s.push(e[l]),c.push(t[l]),l++;else{ID(s,c,n,a,r,i);let u=s.reduce((e,t)=>e+t,0),d=o>0?u/o:0;n=a?{x:n.x+d,y:n.y,width:n.width-d,height:n.height}:{x:n.x,y:n.y+d,width:n.width,height:n.height-d},LD(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&ID(s,c,n,a,r,i)}function RD(e,t,n){if(e.length===0)return[];let r=e=>e.weight>0&&Number.isFinite(e.weight)?e.weight:0,i=[...e].sort((e,t)=>r(t)-r(e)),a=i.reduce((e,t)=>e+r(t),0);if(a===0)return[];let o=t.width*t.height,s=i.map(e=>r(e)/a*o),c=i.map(e=>e.id),l=[];return LD(s,c,{...t},n,l),l}var zD=2,BD=18;function VD(e,t,n,r=18){let i=new Map;for(let t of e){if(!(t.weight>0))continue;let e=t.group??``,n=i.get(e);n?n.push(t):i.set(e,[t])}let a=[...i.keys()],o=RD(a.map((e,t)=>({id:String(t),weight:i.get(e).reduce((e,t)=>e+t.weight,0)})),t,0),s=[],c=[];for(let e of o){let t=a[Number(e.id)],o=i.get(t),l=o.reduce((e,t)=>e+t.weight,0),u=o.reduce((e,t)=>e+(Number.isFinite(t.value)?t.value*t.weight:0),0),d=e.rect,f=t!==``&&d.height>=r*2.5&&d.width>=40?r:0,p={x:d.x+zD/2,y:d.y+zD/2+f,width:Math.max(0,d.width-zD),height:Math.max(0,d.height-zD-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...RD(o,p,n))}return{groups:s,cells:c}}function HD(e){return Number.isFinite(e)?(e>=0?`+`:``)+e.toFixed(2)+`%`:``}function UD(e){return e.label}function WD(e,n){let r=n.min??-5,i=n.max??5;if(!Number.isFinite(e))return n.zero;if(e<=r)return n.negative;if(e>=i)return n.positive;if(e<0){let i=1-e/r;return(0,t.lerpColor)(n.negative,n.zero,i)}let a=e/i;return(0,t.lerpColor)(n.zero,n.positive,a)}var GD=`#FFFFFF`,KD=`#11151b`;function qD(e,n){let r=/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return Lf(r?(0,t.lerpColor)(n,`rgb(${r[1]},${r[2]},${r[3]})`,Number(r[4])):(0,t.lerpColor)(e,e,0))===KD?KD:GD}function JD(e,t,n,r,i,a){let o=Math.min(a,r/2,i/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.arcTo(t+r,n,t+r,n+o,o),e.lineTo(t+r,n+i-o),e.arcTo(t+r,n+i,t+r-o,n+i,o),e.lineTo(t+o,n+i),e.arcTo(t,n+i,t,n+i-o,o),e.lineTo(t,n+o),e.arcTo(t,n,t+o,n,o),e.closePath()}function YD(e,t,n,r,i,a,o,s,c,l,u,d){if(i<40||a<30)return;let f=n+i/2,p=r+a/2;e.save();let m=d===GD;if(e.shadowColor=m?`rgba(0,0,0,0.6)`:`transparent`,e.shadowBlur=m?2:0,e.fillStyle=d,e.textAlign=`center`,s){let n=l(t),r=Math.min(o.font.sizeMedium,i/n.length*1.5,a/4);e.font=`bold `+Math.max(8,r)+`px `+o.font.family,e.textBaseline=c?`bottom`:`middle`,e.fillText(n,f,c?p-1:p,i-8)}if(c){let n=u(t.value),r=Math.min(o.font.sizeSmall,i/n.length*1.5,a/4);e.font=Math.max(7,r)+`px `+o.font.family,e.textBaseline=s?`top`:`middle`,e.fillText(n,f,s?p+1:p,i-8)}e.restore()}function XD(e,t,n,r){let i=[{text:n(e),bold:!0}],a=r(e.value);a!==``&&i.push({text:a,color:t});for(let[t,n]of Object.entries(e.meta??{}))i.push({text:t+`: `+String(n)});return i}function ZD(e,t,n,r,i,a,o,s,c=[]){if(t<=0||n<=0||(e.fillStyle=o.background,e.fillRect(0,0,t,n),r.length===0||i.length===0))return null;let l=a.colorScale,u=Nf([],o,l),d={negative:u.negative,zero:u.zero,positive:u.positive,min:l?.min,max:l?.max},f=a.cellRadius??4,p=a.showLabels!==!1,m=a.showValues!==!1,h=a.valueFormat??HD,g=a.labelFormat??UD,_=new Map;for(let e of r)_.set(e.id,e);let v=null,y=null;if(s)for(let e of i){let{x:t,y:n,width:r,height:i}=e.rect;if(s.x>=t&&s.x<=t+r&&s.y>=n&&s.y<=n+i){v=e.id;let t=_.get(e.id);t&&(y={cell:t,rect:e});break}}for(let t of i){let n=_.get(t.id);if(!n)continue;let{x:r,y:i,width:a,height:s}=t.rect;if(a<=0||s<=0)continue;let c=WD(n.value,d);JD(e,r,i,a,s,f),e.fillStyle=c,e.fill(),YD(e,n,r,i,a,s,o,p,m,g,h,qD(c,o.background)),t.id===v&&(JD(e,r,i,a,s,f),e.strokeStyle=o.text,e.lineWidth=1.5,e.stroke())}let b=s&&!y?c.find(e=>e.header>0&&QD(e,s)):void 0;return $D(e,c,o,h,b),y&&s?mf(e,XD(y.cell,WD(y.cell.value,d),g,h),s,{x:0,y:0,width:t,height:n},o):b&&s&&mf(e,XD({id:``,label:b.name,value:b.value},void 0,e=>e.label,h),s,{x:0,y:0,width:t,height:n},o),y}function QD(e,t){let n=e.rect;return t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+e.header}function $D(e,t,n,r,i){if(t.length===0)return;e.save(),e.textBaseline=`middle`;let a=n.font.sizeSmall,o=t=>e.measureText(t).width;for(let s of t){if(s.header<=0)continue;let{x:t,y:c,width:l}=s.rect,u=c+s.header/2+1;e.font=a+`px `+n.font.family;let d=r(s.value),f=o(d),p=l>=f*2+24;p&&(e.textAlign=`right`,e.fillStyle=s.value<0?n.candleDown:s.value>0?n.candleUp:n.textSecondary,e.fillText(d,t+l-5,u)),e.font=`600 `+a+`px `+n.font.family,e.textAlign=`left`,e.fillStyle=s===i?n.text:n.textSecondary;let m=l-10-(p?f+8:0),h=Ef(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var eO=.7,tO=1,nO=.382,rO=Math.PI/4,iO=4;function aO(e){return e.type?e.type:e.value<0?`negative`:`positive`}function oO(e){let t=0;return e.map(e=>{let n=aO(e),r=Number.isFinite(e.value)?e.value:0,i=n===`total`||n===`subtotal`?0:t,a=i+r;return t=a,{type:n,value:r,start:i,end:a}})}function sO(e,t,n,r){let i=e.data??[],a=oO(i),o=0,s=0;for(let{start:e,end:t}of a)o=Math.min(o,e,t),s=Math.max(s,e,t);let c=(s-o||1)*.1,l=$d(o<0?o-c:0,s>0?s+c:0,5),u=e.valueFormat??q(l,e.locale),d=12+Math.max(0,...l.ticks.map(e=>r(u(e),11)))+8,f=Math.max(1,t-d-12),p=f/Math.max(1,i.length),m=e.labelFormat??(e=>e),h=Math.max(0,...i.map(e=>r(m(e.label),11))),g=h>p-4,_=g?Math.min(n*nO,Math.ceil((h+11)*Math.sin(rO))+6):20,v={x:d,y:12,width:f,height:Math.max(1,n-24-_)},y=p*Math.min(1,Math.max(.05,e.barWidth??eO)),b=e=>G(l,e,v.y,v.height,!0);return{plot:v,scale:l,bars:a.map((e,t)=>{let n=Math.min(b(e.start),b(e.end)),r=v.x+t*p;return{label:i[t].label,value:e.value,type:e.type,start:e.start,end:e.end,x:r+(p-y)/2,y:n,width:y,height:Math.max(tO,Math.abs(b(e.end)-b(e.start))),slotX:r,slotWidth:p}}),turned:g,labelRoom:_}}function cO(e,t){let{plot:n,bars:r}=e;return r.length===0||t<n.x||t>n.x+n.width?-1:Math.min(r.length-1,Math.floor((t-n.x)/r[0].slotWidth))}function lO(e,t,n,r){let{bars:i,scale:a,plot:o}=t;if(r!==`none`){e.save(),e.strokeStyle=n,e.setLineDash(r===`dashed`?[4,4]:[]);for(let t=0;t<i.length-1;t++){let n=i[t].x+i[t].width,r=i[t+1].x,s=G(a,i[t].end,o.y,o.height,!0);r>n&&gf(e,n,s,r,s)}e.restore()}}function uO(e,t,n,r,i){e.save(),e.font=J(n,10),e.fillStyle=n.textSecondary,e.textAlign=`center`;let a=[];for(let n of t.bars){let t=n.type===`positive`||n.type===`negative`?i?`${n.value>=0?`+`:``}${r(n.value)}`:r(n.end):r(n.value),o=e.measureText(t).width,s=n.end<n.start,c=n.x+n.width/2,l={x:c-o/2,y:s?n.y+n.height+iO:n.y-iO-11,width:o,height:11};a.some(e=>l.x<e.x+e.width+2&&e.x<l.x+l.width+2&&l.y<e.y+e.height&&e.y<l.y+l.height)||(a.push(l),e.textBaseline=s?`top`:`bottom`,e.fillText(t,Math.round(c),Math.round(s?l.y:n.y-iO)))}e.restore()}function dO(e,t,n,r,i){let{plot:a,bars:o,turned:s,labelRoom:c}=t;e.save(),e.font=J(n,11),e.fillStyle=n.axisLabel;let l=a.y+a.height+6;if(!s){e.textAlign=`center`,e.textBaseline=`top`;for(let t of o)e.fillText(r(t.label),Math.round(t.slotX+t.slotWidth/2),l);e.restore();return}e.textAlign=`right`,e.textBaseline=`middle`;for(let t of o){let n=t.slotX+t.slotWidth/2,a=Math.min((c-6)/Math.sin(rO)-11,(n-2)/Math.cos(rO)),o=Ef(r(t.label),a,i);o&&(e.save(),e.translate(n,l+2),e.rotate(-rO),e.fillText(o,0,0),e.restore())}e.restore()}function fO(e,t,n,r,i,a,o){if(t<=0||n<=0)return{hitBar:null};e.fillStyle=i.background,e.fillRect(0,0,t,n);let s=r.data;if(!s||s.length===0)return{hitBar:null};let c=o??((t,n=11)=>(e.font=J(i,n),e.measureText(t).width)),l=sO(r,t,n,c),{plot:u,scale:d,bars:f}=l,p=r.valueFormat??q(d,r.locale),m=r.valueFormat??K(r.locale),h={positive:r.positiveColor??i.candleUp,negative:r.negativeColor??i.candleDown,total:r.totalColor??i.lineColor,subtotal:r.subtotalColor??i.textSecondary};Tf(e,u,d,`vertical`,i,p),lO(e,l,r.connectorColor??i.textSecondary,r.connectorStyle??`dashed`);let g=hf(e);for(let t of f){let n=g.x(t.x)-g.width/2,r=g.x(t.x+t.width)-g.width/2;e.fillStyle=h[t.type],e.fillRect(n,t.y,Math.max(g.width,r-n),t.height)}e.strokeStyle=i.axisLine;let _=G(d,0,u.y,u.height,!0);gf(e,u.x,_,u.x+u.width,_),r.showValues!==!1&&uO(e,l,i,m,r.showDelta!==!1),dO(e,l,i,r.labelFormat??(e=>e),c);let v=a?cO(l,a.x):-1;if(a&&v>=0){let r=f[v],o=r.slotX+r.slotWidth/2;e.save(),e.strokeStyle=i.crosshair,e.setLineDash([4,4]),gf(e,o,u.y,o,u.y+u.height),e.restore();let s=r.type===`positive`||r.type===`negative`,c=[{text:r.label,bold:!0}];s&&c.push({text:`${r.value>=0?`+`:``}${m(r.value)}`,color:h[r.type]}),c.push({text:s?`= ${m(r.end)}`:m(r.end),color:s?void 0:h[r.type]}),mf(e,c,a,{x:0,y:0,width:t,height:n},i)}return{hitBar:v>=0?v:null}}var pO=Math.PI/180,mO=150,hO=240,gO=90,_O=.14,vO=1.6*pO,yO=.22,bO=8,xO=18,SO=16,CO=6.5,wO=20,TO=5,EO=28;function DO(e,t,n){return e<t?t:e>n?n:e}function OO(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function kO(e){let t=Number.isFinite(e.startAngle)?e.startAngle:mO,n=(Number.isFinite(e.endAngle)?e.endAngle:t+hO)-t;return n<=0&&(n=(n%360+360)%360||360),n=DO(n,gO,360),{start:(t%360+360)%360*pO,sweep:n*pO}}function AO(e,t){let n=Math.min(Math.cos(e),Math.cos(t)),r=Math.max(Math.cos(e),Math.cos(t)),i=Math.min(Math.sin(e),Math.sin(t)),a=Math.max(Math.sin(e),Math.sin(t));for(let o=Math.ceil(e/(Math.PI/2));Math.PI/2*o<=t;o++){let e=Math.PI/2*o;n=Math.min(n,Math.cos(e)),r=Math.max(r,Math.cos(e)),i=Math.min(i,Math.sin(e)),a=Math.max(a,Math.sin(e))}return{minX:n,maxX:r,minY:i,maxY:a}}function jO(e){if(e.showZoneLabels!==!0||!e.zones)return 0;let t=e.zones.reduce((e,t)=>Math.max(e,t.label?.length??0),0);return t>0?t*CO+12:0}function MO(e,t,n){let r=Number.isFinite(n.min)?n.min:0,i=Number.isFinite(n.max)?n.max:100;i-r>Math.abs(r)*1e-9||(i=r+Math.max(1,Math.abs(r)*1e-6));let{start:a,sweep:o}=kO(n),s=a,c=a+o,l=DO(n.thickness??_O,.04,.5),u=AO(s,c),d=Math.max(u.maxY,.18),f=jO(n),p=f>0?SO:0,m=Math.max(1,e-2*bO-2*f),h=Math.max(1,t-2*bO-xO-p),g=1+l/2,_=Math.max(8,Math.min(m/((u.maxX-u.minX)*g),h/((d-u.minY)*g))),v=_*l,y=(d-u.minY)*_*g+xO+p,b=e/2-(u.maxX+u.minX)/2*_,x=(t-y)/2+p-u.minY*_*g,S=_-v/2,C=Math.max(11,Math.round(S*.46)),w=u.maxY>.3?x-C*.12:x-C*.55,T=Math.max(Math.sin(s),Math.sin(c)),E=T>.2?x+T*_+v/2+2:1/0,D=Math.min(t-bO,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function NO(e,t){let n=Number.isFinite(e)?DO((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function PO(e,t){if(!t||!Number.isFinite(e))return;let n;for(let r of t)e>=r.from&&e<=r.to&&(n=r);return n}function FO(e,t,n){let r=(t??[]).map(t=>({a0:NO(t.from,e),a1:NO(t.to,e),color:t.color,track:!1})).filter(e=>e.a1>e.a0).sort((e,t)=>e.a0-t.a0),i=[],a=e.startAngle;for(let e of r)e.a1<=a||(e.a0>a+1e-9&&i.push({a0:a,a1:e.a0,color:n,track:!0}),i.push({...e,a0:Math.max(e.a0,a)}),a=e.a1);return a<e.endAngle-1e-9&&i.push({a0:a,a1:e.endAngle,color:n,track:!0}),i}function IO(e,t,n,r,i){r<=n||(e.beginPath(),e.arc(t.cx,t.cy,t.radius,n,r,!1),e.lineWidth=t.thickness,e.lineCap=`butt`,e.strokeStyle=i,e.stroke())}function LO(e,t,n,r,i,a){let o=t.cx+Math.cos(n)*t.radius,s=t.cy+Math.sin(n)*t.radius,c=a===`start`?n-Math.PI:n;e.globalAlpha=i,e.beginPath(),e.arc(o,s,t.thickness/2,c,c+(i>=1?Math.PI*2:Math.PI),!1),e.closePath(),e.fillStyle=r,e.fill(),e.globalAlpha=1}function RO(e,t,n,r,i,a){let o=FO(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?vO/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?vO/2:0,c=n.a0+a,l=n.a1-s;if(n.track){IO(e,t,c,l,n.color);return}e.globalAlpha=yO,IO(e,t,c,l,n.color),e.globalAlpha=1,IO(e,t,c,Math.min(l,r),n.color)}),s||IO(e,t,t.startAngle,r,a);let c=r>t.startAngle+1e-9,l=r>=t.endAngle-1e-9,u=(e,t)=>e.track?[!s&&t?a:i,1]:[e.color,t?1:yO],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);LO(e,t,t.startAngle,d,f,`start`),LO(e,t,t.endAngle,p,m,`end`)}function zO(e,t,n){let r=t.radius-t.thickness/2;if(r<EO)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=wO;n++){let a=n%TO===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/wO,s=r-i,c=s-(a?Math.max(6,t.thickness*.55):Math.max(3,t.thickness*.3));e.globalAlpha=a?.55:.3,e.lineWidth=a?1.5:1,e.beginPath(),e.moveTo(t.cx+Math.cos(o)*s,t.cy+Math.sin(o)*s),e.lineTo(t.cx+Math.cos(o)*c,t.cy+Math.sin(o)*c),e.stroke()}e.globalAlpha=1}function BO(e,t,n,r,i){let a=t.cx+Math.cos(n)*t.radius,o=t.cy+Math.sin(n)*t.radius;e.beginPath(),e.arc(a,o,t.thickness*.78,0,Math.PI*2),e.fillStyle=r,e.fill(),e.lineWidth=Math.max(2,t.thickness*.32),e.strokeStyle=i,e.stroke()}function VO(e,t,n,r,i){let a=Math.cos(n),o=Math.sin(n),s=t.radius-t.thickness*.9,c=Math.max(6,t.thickness*.6),l=Math.max(1.5,t.thickness*.14);e.beginPath(),e.moveTo(t.cx+a*s,t.cy+o*s),e.lineTo(t.cx-o*l-a*c,t.cy+a*l-o*c),e.lineTo(t.cx+o*l-a*c,t.cy-a*l-o*c),e.closePath(),e.fillStyle=r,e.fill(),e.beginPath(),e.arc(t.cx,t.cy,Math.max(4,t.thickness*.42),0,Math.PI*2),e.fill(),e.lineWidth=2,e.strokeStyle=i,e.stroke()}function HO(e,t,n,r,i,a,o){e.font=`${n} ${r}px ${i}`;let s=e.measureText(t).width;if(s<=a)return r;let c=Math.floor(r*a/s);return c<o?0:(e.font=`${n} ${c}px ${i}`,c)}function UO(e,t,n,r,i,a,o){let s=a.font.family,c=(t.radius-t.thickness/2)*1.3,l=a.font.sizeSmall;e.textAlign=`center`,e.textBaseline=`middle`;let u=HO(e,n,`600`,t.valueSize,s,c,l);if(u===0)return;let d=o?Math.min(t.cy+u*.8,t.textBottom-u/2):t.valueY;e.fillStyle=a.text,e.fillText(n,t.cx,d);let f=Math.max(l,Math.round(u*.26));if(i?.label&&!o){let n=i.label.toUpperCase();HO(e,n,`600`,f,s,c*.9,l)>0&&(e.fillStyle=i.color,e.fillText(n,t.cx,d-u*.78))}if(r){let n=d+u*.72;n+f/2<=t.textBottom&&HO(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function WO(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall+1}px ${r.font.family}`;let i=t.thickness/2+6;for(let[r,a]of[[t.startAngle,t.min],[t.endAngle,t.max]]){let o=Math.cos(r),s=Math.sin(r),c=t.cx+o*t.radius,l=t.cy+s*t.radius;s>.2?(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(n(a),c,l+i)):(e.textAlign=o<-.2?`right`:o>.2?`left`:`center`,e.textBaseline=s<-.2?`bottom`:`middle`,e.fillText(n(a),c+o*i,l+s*i))}}function GO(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textBaseline=`middle`;let i=t.radius+t.thickness/2+8;for(let r of n){if(!r.label)continue;let n=NO((DO(r.from,t.min,t.max)+DO(r.to,t.min,t.max))/2,t),a=Math.cos(n);e.textAlign=a<-.2?`right`:a>.2?`left`:`center`,e.fillText(r.label,t.cx+a*i,t.cy+Math.sin(n)*i)}}function KO(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=MO(t,n,r),s=Number.isFinite(a),c=s?DO(a,o.min,o.max):o.min,l=NO(c,o),u=s?PO(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??OO,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),RO(e,o,r.zones,l,r.trackColor??i.grid,p),zO(e,o,i.textSecondary),s&&(d?VO(e,o,l,r.needleColor??i.text,i.background):BO(e,o,l,p,i.background)),r.showValue!==!1&&UO(e,o,s?f(c):`—`,r.label,u,i,d),WO(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&GO(e,o,r.zones,i),e.restore()}var qO=12,JO=.72,YO=20,XO=.35;function ZO(e){let t=0,n=0,r=e.mode===`stacked`;return e.categories.forEach((i,a)=>{let o=0,s=0;for(let i of e.series){let e=i.values[a];Number.isFinite(e)&&(r?e>=0?o+=e:s+=e:(n=Math.max(n,e),t=Math.min(t,e)))}n=Math.max(n,o),t=Math.min(t,s)}),[t,n]}function QO(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function $O(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),t-qO*2,i):null,s=qO+(o?o.height+6:0),[c,l]=ZO(e),u=$d(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??q(u,e.locale),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=qO+Math.min(t*XO,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-qO-f/2),height:Math.max(1,n-s-qO-YO)}}else{let e=qO+f+8;p={x:e,y:s,width:Math.max(1,t-e-qO),height:Math.max(1,n-s-qO-YO)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*JO,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?G(u,e,p.x,p.width):G(u,e,p.y,p.height,!0),x=b(0),S=QO(e,r),C=Array(m).fill(0),w=Array(m).fill(0),T=[];return e.series.forEach((t,n)=>{e.categories.forEach((e,r)=>{let i=t.values[r];if(!Number.isFinite(i))return;let o=0;v&&(o=i>=0?C[r]:w[r],i>=0?C[r]+=i:w[r]+=i);let s=b(o),c=b(o+i),l=h+r*g+(g-_)/2+(v?0:n*y),u=S?i>=0?S.positive:S.negative:uf(n,t.color),d=Math.min(s,c),f=Math.abs(c-s);T.push(a?{x:d,y:l,width:f,height:y,category:e,series:t.name,value:i,index:r,color:u}:{x:l,y:d,width:y,height:f,category:e,series:t.name,value:i,index:r,color:u})})}),{plot:p,scale:u,orientation:a?`horizontal`:`vertical`,zero:x,bars:T,bandStart:h,band:g,legend:o,legendY:qO}}function ek(e,t,n){for(let r of e.bars)if(t>=r.x-2&&t<=r.x+r.width+2&&n>=r.y-2&&n<=r.y+r.height+2)return r;return null}function tk(e,t,n,r){let{plot:i}=e;if(t<i.x||t>i.x+i.width||n<i.y||n>i.y+i.height)return-1;let a=e.orientation===`horizontal`?n:t,o=Math.floor((a-e.bandStart)/e.band);return o>=0&&o<r?o:-1}function nk(e,n,r,i,a,o,s=$O(i,n,r,a,df(e,a))){let c=df(e,a),l=i.valueFormat??K(i.locale),{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&pf(e,s.legend,qO,s.legendY,a),Tf(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??q(s.scale,i.locale));let p=o&&i.crosshair!==!1?tk(s,o.x,o.y,i.categories.length):-1;if(p>=0){e.fillStyle=(0,t.withAlpha)(a.crosshair,.08);let n=s.bandStart+p*s.band;f?e.fillRect(u.x,n,u.width,s.band):e.fillRect(n,u.y,s.band,u.height)}for(let t of s.bars)e.fillStyle=t.color,e.fillRect(t.x,t.y,Math.max(t.width,+!!f),Math.max(t.height,+!f));e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath();let m=Math.round(s.zero)+.5;if(f?(e.moveTo(m,u.y),e.lineTo(m,u.y+u.height)):(e.moveTo(u.x,m),e.lineTo(u.x+u.width,m)),e.stroke(),rk(e,i.categories,s,a,c),i.showValues&&ik(e,s,a,l,i.mode===`stacked`),p>=0&&o){let t=[{text:i.categories[p],bold:!0}];for(let e of s.bars)e.index===p&&t.push({text:`${e.series}: ${l(e.value)}`,color:e.color});mf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function rk(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=J(r,11),e.fillStyle=r.axisLabel;let o=Math.max(0,...t.map(e=>i(e,11))),s=n.orientation===`vertical`?Math.max(1,Math.ceil((o+8)/Math.max(1,n.band))):1;t.forEach((t,r)=>{if(r%s!==0)return;let o=n.bandStart+(r+.5)*n.band;n.orientation===`horizontal`?(e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(Ef(t,a.x-qO-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(Ef(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function ik(e,t,n,r,i){e.save(),e.font=J(n,10),e.fillStyle=n.textSecondary;for(let n of t.bars){let a=r(n.value);if(t.orientation===`horizontal`){e.textBaseline=`middle`;let t=n.y+n.height/2;i?(e.textAlign=`center`,e.measureText(a).width<n.width-4&&e.fillText(a,n.x+n.width/2,t)):n.value>=0?(e.textAlign=`left`,e.fillText(a,n.x+n.width+4,t)):(e.textAlign=`right`,e.fillText(a,n.x-4,t))}else{e.textAlign=`center`;let t=n.x+n.width/2;i?(e.textBaseline=`middle`,n.height>13&&e.measureText(a).width<n.width&&e.fillText(a,t,n.y+n.height/2)):n.value>=0?(e.textBaseline=`bottom`,e.fillText(a,t,n.y-3)):(e.textBaseline=`top`,e.fillText(a,t,n.y+n.height+3))}}e.restore()}var ak=12,ok=-Math.PI/2,sk=Math.PI*2,ck=5,lk=1.4,uk=18;function dk(e,t,n,r,i){let a=e.data.filter(e=>Number.isFinite(e.value)&&e.value>0),o=a.reduce((e,t)=>e+t.value,0),s=a.map((t,n)=>({label:`${t.label} ${af(e.locale)(t.value/o)}`,color:uf(n,t.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*lk&&a.length*uk<=n-ak*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-ak*2,d=c?ff(s,u,i,l):null,f=l?t-u-ak*3:t-ak*2,p=l?n-ak*2:n-ak*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-ck),h=ak+f/2,g=ak+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=ok,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*sk,{label:e.label,value:e.value,share:n,start:r,end:y,color:uf(t,e.color),slice:e}});return{cx:h,cy:g,radius:m,inner:m*v,total:o,slices:b,legend:d,legendX:l?t-u-ak:ak,legendY:l?Math.max(ak,g-(d?.height??0)/2):ak*2+p}}function fk(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+ck)return null;let o=Math.atan2(i,r);for(;o<ok;)o+=sk;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function pk(e,t,n,r,i,a,o=dk(r,t,n,i,df(e,i))){let s=df(e,i),c=r.valueFormat??K(r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?fk(o,a.x,a.y):null,{cx:u,cy:d,radius:f,inner:p}=o;for(let t of o.slices){let n=(t.start+t.end)/2,r=t===l?ck:0,a=u+Math.cos(n)*r,s=d+Math.sin(n)*r;e.beginPath(),e.arc(a,s,f,t.start,t.end),p>0?e.arc(a,s,p,t.end,t.start,!0):e.lineTo(a,s),e.closePath(),e.fillStyle=t.color,e.fill(),o.slices.length>1&&(e.strokeStyle=i.background,e.lineWidth=1.5,e.stroke())}return r.showLabels!==!1&&mk(e,o,i,r.locale),hk(e,o,r,i,s),o.legend&&pf(e,o.legend,o.legendX,o.legendY,i),l&&a&&mf(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${af(r.locale)(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function mk(e,t,n,r){let{cx:i,cy:a,radius:o,inner:s}=t,c=s>0?(o+s)/2:o*.62;e.save(),e.font=J(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=af(r)(n.share);if((n.end-n.start)*c<e.measureText(t).width+8||s>0&&o-s<15)continue;let l=(n.start+n.end)/2;e.fillText(t,i+Math.cos(l)*c,a+Math.sin(l)*c)}e.restore()}function hk(e,t,n,r,i){if(t.inner<=0||!n.centerLabel&&!n.centerValue)return;let a=t.inner*1.6;if(e.save(),e.textAlign=`center`,e.textBaseline=`middle`,n.centerValue){let o=Math.max(12,Math.min(28,t.inner*.42));e.font=J(r,o,`600`),e.fillStyle=r.text,e.fillText(Ef(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=J(r,11),e.fillStyle=r.textSecondary,e.fillText(Ef(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var gk=12,_k=5,vk=3,yk=18,bk=20,xk=6;function Sk(e,n,r,i,a){let o=1/0,s=-1/0,c=1/0,l=-1/0,u=0;for(let t of e.series)for(let e of t.points)!Number.isFinite(e.x)||!Number.isFinite(e.y)||(e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<c&&(c=e.y),e.y>l&&(l=e.y),e.size!==void 0&&Number.isFinite(e.size)&&e.size>u&&(u=e.size));let d=e.maxRadius??24,f=d+xk,p=(e,t,n)=>{if(e>t)return[0,1];let r=(t-e)*f/Math.max(1,n-f*2);return[e>=0?Math.max(0,e-r):e-r,t<=0?Math.min(0,t+r):t+r]},m=$d(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=$d(...p(c,l,r*.7),5),g=e.xFormat??q(m,e.locale),_=e.yFormat??q(h,e.locale),v=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),n-gk*2,a):null,y=gk+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=gk+(e.yLabel?yk:0)+b+8,S=gk+bk+(e.xLabel?yk:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-gk-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=uf(n,e.color),i=(0,t.withAlpha)(r,.55),a=(0,t.withAlpha)(r,.85);for(let t of e.points){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))continue;let n=t.size!==void 0&&Number.isFinite(t.size)&&t.size>0&&u>0?Math.max(vk,d*Math.sqrt(t.size/u)):_k;T.push({px:G(m,t.x,w.x,w.width),py:G(h,t.y,w.y,w.height,!0),r:n,color:r,fill:i,hoverFill:a,series:e.name,label:t.label,point:t})}}),{plot:w,xScale:m,yScale:h,points:T,drawOrder:T.map((e,t)=>t).sort((e,t)=>T[t].r-T[e].r),legend:v}}function Ck(e,t,n){let r=null,i=1/0;for(let a of e.points){let e=Math.hypot(a.px-t,a.py-n);e<=a.r+xk&&e<i&&(r=a,i=e)}return r}function wk(e,t,n,r,i,a,o=Sk(r,t,n,i,df(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??q(c,r.locale),d=r.yFormat??q(l,r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&pf(e,o.legend,gk,gk,i),Tf(e,s,l,`vertical`,i,d),Tf(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&Tk(e,o,i),Ek(e,o,r,i);let f=a&&r.crosshair!==!1?Ck(o,a.x,a.y):null;e.save(),e.beginPath(),e.rect(s.x,s.y,s.width,s.height),e.clip();for(let t of o.drawOrder){let n=o.points[t];e.beginPath(),e.arc(n.px,n.py,n===f?n.r+2:n.r,0,Math.PI*2),e.fillStyle=n===f?n.hoverFill:n.fill,e.fill(),e.strokeStyle=n.color,e.lineWidth=1,e.stroke()}if(e.restore(),r.showLabels){e.save(),e.font=J(i,10),e.fillStyle=i.textSecondary,e.textAlign=`left`,e.textBaseline=`middle`;for(let t of o.points)t.label&&e.fillText(t.label,t.px+t.r+4,t.py);e.restore()}if(f&&a){let o=[{text:f.label??f.series,bold:!0,color:f.color}];f.label&&r.series.length>1&&o.push({text:f.series}),o.push({text:`${r.xLabel??`x`}: ${(r.xFormat??K(r.locale))(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??K(r.locale))(f.point.y)}`}),f.point.size!==void 0&&o.push({text:K(r.locale)(f.point.size)}),mf(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function Tk(e,t,n){let{plot:r,xScale:i,yScale:a}=t;if(e.save(),e.strokeStyle=n.axisLine,e.lineWidth=1,e.beginPath(),i.min<0&&i.max>0){let t=Math.round(G(i,0,r.x,r.width))+.5;e.moveTo(t,r.y),e.lineTo(t,r.y+r.height)}if(a.min<0&&a.max>0){let t=Math.round(G(a,0,r.y,r.height,!0))+.5;e.moveTo(r.x,t),e.lineTo(r.x+r.width,t)}e.stroke(),e.restore()}function Ek(e,t,n,r){let{plot:i}=t;e.save(),e.font=J(r,11,`600`),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,i.x+i.width/2,i.y+i.height+bk+yk)),n.yLabel&&(e.translate(gk+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var Dk=1e-9,Ok=1e3,kk=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function Ak(e,t={}){let n=e.filter(e=>Number.isFinite(e));if(n.length===0)return[];let r=1/0,i=-1/0;for(let e of n)e<r&&(r=e),e>i&&(i=e);if(r===i)return[{from:r,to:i,count:n.length}];let a=t.binWidth;if(a!==void 0&&a>0&&Number.isFinite(a)){let e=Math.floor(r/a+Dk),t=Math.max(e,Math.ceil(i/a-Dk)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:kk((e+n)*a),to:kk((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+Dk)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(Ok,Math.floor(o)):Math.min(Ok,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:kk(r+t*c),to:kk(t===s-1?i:r+(t+1)*c),count:0}));for(let e of n)l[Math.min(s-1,Math.floor((e-r)/c+Dk))].count++;return l}var jk=12,Mk=20,Nk=16;function Pk(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function Fk(e,t,n,r,i){let a=Ak(e.values,{bins:e.bins,binWidth:e.binWidth}),o=a.length>0?a[0].from:0,s=a.length>0?a[a.length-1].to:1,c=(e.markers??[]).map(e=>e.value).filter(e=>Number.isFinite(e)),l=$d(Math.min(o,...c),Math.max(s,...c),Math.max(2,Math.floor(t/110))),u=0;for(let e of a)e.count>u&&(u=e.count);let d=$d(0,Math.max(4,u),4),f=e.valueFormat??q(l,e.locale),p=Math.max(0,...d.ticks.map(t=>i(q(d,e.locale)(t),11))),m=jk+(c.length>0?Nk:0),h=jk+p+8,g=jk+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-jk-Mk)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=G(l,t.from,_.x,_.width),i=t.to>t.from?G(l,t.to,_.x,_.width):n+_.width/10,a=G(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:Pk(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function Ik(e,t,n){let{plot:r}=e;return n<r.y||n>r.y+r.height?null:e.bars.find(e=>t>=e.x&&t<e.x+e.width)??null}function Lk(e,n,r,i,a,o,s=Fk(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale),{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,l,s.yScale,`vertical`,a,q(s.yScale,i.locale)),Tf(e,l,s.xScale,`horizontal`,a,i.valueFormat??q(s.xScale,i.locale));let u=o&&i.crosshair!==!1?Ik(s,o.x,o.y):null;for(let n of s.bars)e.fillStyle=n===u?n.color:(0,t.withAlpha)(n.color,.75),e.fillRect(n.x+(n.width>3?.5:0),n.y,Math.max(1,n.width-+(n.width>3)),n.height);if(Rk(e,s,i,a,c),u&&o){let{bin:t}=u;mf(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${K(i.locale)(t.count)} · ${af(i.locale)(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function Rk(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=J(r,10),e.textAlign=`center`,e.textBaseline=`bottom`;let o=[];for(let s of n.markers??[]){if(!Number.isFinite(s.value))continue;let n=Math.round(G(t.xScale,s.value,a.x,a.width))+.5,c=s.color??r.text;e.strokeStyle=c,e.setLineDash([4,3]),e.lineWidth=1,e.beginPath(),e.moveTo(n,a.y),e.lineTo(n,a.y+a.height),e.stroke(),e.setLineDash([]),e.fillStyle=c;let l=s.label?`${s.label} ${i(s.value)}`:i(s.value),u=e.measureText(l).width/2+4,d=0;for(;o.some(e=>e.row===d&&n-u<e.to&&n+u>e.from);)d++;o.push({from:n-u,to:n+u,row:d}),e.fillText(l,n,a.y-3+d*14)}e.restore()}var zk=864e5,Bk=3,Vk=12,Hk=16,Uk=10,Wk=28,Gk=6;function Kk(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=Date.UTC(n,r-1,i),o=new Date(a);return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?null:Math.round(a/zk)}function qk(e){return new Date(e*zk).toISOString().slice(0,10)}var Jk=e=>((e+4)%7+7)%7;function Yk(e,t){let n=e.from===void 0?null:Kk(e.from),r=e.to===void 0?null:Kk(e.to);if(n===null||r===null){let e=1/0,i=-1/0;for(let n of t.keys())n<e&&(e=n),n>i&&(i=n);n??=Number.isFinite(e)?e:null,r??=Number.isFinite(i)?i:null}if(n===null||r===null||n>r)return null;let i=new Date(r*zk).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/zk)),r]}function Xk(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*zk).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/zk)),o=i-n(i);r.push({year:e,first:i,last:a,origin:o,weeks:Math.floor((a-o)/7)+1}),i=a+1}return r}var Zk=new Map;function Qk(e){let t=e??``,n=Zk.get(t);if(!n){try{n={month:new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`}),weekday:new Intl.DateTimeFormat(e,{weekday:`short`,timeZone:`UTC`}),long:new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`})}}catch{n=Qk(void 0)}Zk.set(t,n)}return n}function $k(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=Kk(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=Qk(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||Jk(e)>=1&&Jk(e)<=5,u=Yk(e,a),d=t-Vk*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(Jk(e)-m+7)%7,g=u?Xk(u[0],u[1],h):[],_=e=>n-Vk*2-f-e*Hk-(e-1)*Uk;for(;g.length>1&&_(g.length)/(g.length*p)<Bk;)g=g.slice(1);let v=[];for(let[e,t]of a)g.length>0&&e>=g[0].first&&e<=g[g.length-1].last&&l(e)&&v.push(t.value);let y=Nf(v,r,e.colorScale),b={cells:[],months:[],weekdays:[],years:[],scale:y,bar:null,pitch:0,formatDate:s};if(g.length===0||d<=0||_(g.length)<=0)return b;let x=g.length>1,S=g.map(e=>String(e.year)),C=Array.from({length:p},(e,t)=>o.weekday.format(new Date((3+m+t)*zk))),w=Vk+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+Gk,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(Wk,(t-w-Vk)/T,_(g.length)/(g.length*p));if(!(E>0))return b;let D=E-(E>=6?Math.max(1,Math.round(E*.12)):0),O=T*E,k=w+Math.max(0,(t-w-Vk-O)/2),A={...b,pitch:E},j=Vk;for(let[e,n]of g.entries()){let r=j+Hk;x&&A.years.push({label:S[e],x:k-Gk,y:j});let s=-1,c=-1/0;for(let e=n.first;e<=n.last;e++){if(!l(e))continue;let u=k+Math.floor((e-n.origin)/7)*E,d=r+h(e)*E,f=a.get(e);A.cells.push({x:u,y:d,size:D,date:qk(e),day:f,color:f&&Number.isFinite(f.value)?Pf(f.value,y):null});let p=new Date(e*zk).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*zk)),r=u+i(n,10);u>=c&&r<=t&&(A.months.push({label:n,x:u,y:j}),c=r+4)}}if(E>=8){let e=E>=13?1:2;for(let t=0;t<p;t+=e)A.weekdays.push({label:C[t],x:k-Gk,y:r+t*E+D/2})}j=r+p*E+Uk}return f>0&&(A.bar={x:k,y:j-Uk+8,width:Math.min(O,t-k-Vk),height:f-8}),A}function eA(e,t,n){for(let r of e.cells)if(t>=r.x&&t<r.x+e.pitch&&n>=r.y&&n<r.y+e.pitch)return r;return null}function tA(e,n,r,i,a,o,s=$k(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?eA(s,o.x,o.y):null,u=(0,t.withAlpha)(a.textSecondary,.12),d=s.pitch>=10?2:0;e.save();for(let t of s.cells)e.fillStyle=t.color??u,e.beginPath(),d>0&&typeof e.roundRect==`function`?e.roundRect(t.x,t.y,t.size,t.size,d):e.rect(t.x,t.y,t.size,t.size),e.fill();l&&(e.strokeStyle=a.text,e.lineWidth=1.5,e.strokeRect(l.x-.75,l.y-.75,l.size+1.5,l.size+1.5)),e.fillStyle=a.textSecondary,e.font=J(a,10),e.textAlign=`left`,e.textBaseline=`top`;for(let t of s.months)e.fillText(t.label,t.x,t.y);e.textAlign=`right`,e.textBaseline=`middle`;for(let t of s.weekdays)e.fillText(t.label,t.x,t.y);e.font=J(a,11,`600`),e.fillStyle=a.text,e.textBaseline=`top`;for(let t of s.years)e.fillText(t.label,t.x,t.y);if(e.restore(),s.bar&&Rf(e,s.bar,s.scale,c,a),l&&o){let t=[{text:s.formatDate(l.date),bold:!0,color:l.color??void 0}];if(l.day){t.push({text:c(l.day.value)});for(let[e,n]of Object.entries(l.day.meta??{}))t.push({text:`${e}: ${String(n)}`})}else t.push({text:`–`});mf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var nA=12,rA=6,iA=72,aA=Math.PI/4,oA=Math.sin(aA);function sA(e){let t=e.length,n=Array.from({length:t},()=>Array(t).fill(NaN));for(let r=0;r<t;r++)for(let i=r;i<t;i++){let t=cA(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function cA(e,t,n){let r=Math.min(e.length,t.length),i=0,a=0,o=0;for(let n=0;n<r;n++)Number.isFinite(e[n])&&Number.isFinite(t[n])&&(i++,a+=e[n],o+=t[n]);if(i<3)return NaN;let s=a/i,c=o/i,l=0,u=0,d=0;for(let n=0;n<r;n++){if(!Number.isFinite(e[n])||!Number.isFinite(t[n]))continue;let r=e[n]-s,i=t[n]-c;l+=r*i,u+=r*r,d+=i*i}return u===0||d===0?NaN:n?1:Math.max(-1,Math.min(1,l/Math.sqrt(u*d)))}var lA=e=>e.toFixed(2);function uA(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function dA(e,t,n,r,i){let a=e.rows.slice(0,200),o=(e.columns??e.rows).slice(0,200),s=e.columns===void 0||e.columns.length===e.rows.length&&e.columns.every((t,n)=>t===e.rows[n]),c=[];for(let t=0;t<a.length;t++)for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];Number.isFinite(r)&&uA(e.triangle,s,t,n)&&c.push(r)}let l=Nf(c,r,e.colorScale),u={cells:[],rowLabels:[],columnLabels:[],grid:{x:0,y:0,width:0,height:0},pitch:0,scale:l,bar:null,at:[]};if(a.length===0||o.length===0||t<=0||n<=0)return u;let d=Math.min(t*.3,Math.max(...a.map(e=>i(e,11)))),f=Math.max(...o.map(e=>i(e,11))),p=e.legend===!1?0:28,m=nA+d+rA,h=t-m-nA,g=e=>Math.min(iA,h/o.length,(n-e-nA-p)/a.length),_=nA+11+rA,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/oA),_=nA+b*oA+11,v=g(_)),!(v>0))return u;let x=v-+(v>=8),S=m+Math.max(0,(h-o.length*v)/2);y&&(b=Math.max(0,Math.min(b,(S+x/2-2-11*oA/2)/oA))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??lA,w=e.showValues!==!1,T=Math.max(8,Math.min(11,v/3));for(let t=0;t<a.length;t++){u.at.push([]);for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];if(!Number.isFinite(r)||!uA(e.triangle,s,t,n))continue;let c=Pf(r,l),d=w?C(r):``,f=w&&v>=18&&i(d,T)<=v-4,p={x:S+n*v,y:_+t*v,size:x,cell:{row:a[t],column:o[n],value:r,rowIndex:t,columnIndex:n},color:c,text:f?d:null,textColor:Lf(c)};u.cells.push(p),u.at[t][n]=p}}let E=Math.max(1,Math.ceil(11/v)),D=Math.max(1,Math.ceil(11/(y?v*oA:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:Ef(a[e],d,i),index:e,x:S-rA,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:Ef(o[e],b,i),index:e,x:S+e*v+x/2,y:_-rA,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-nA),height:p-8}),u}function fA(e,t,n){let{grid:r,pitch:i}=e;return i<=0||t<r.x||n<r.y||t>=r.x+r.width||n>=r.y+r.height?null:e.at[Math.floor((n-r.y)/i)]?.[Math.floor((t-r.x)/i)]??null}function pA(e,t,n,r,i,a,o=dA(r,t,n,i,df(e,i))){let s=r.valueFormat??lA;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?fA(o,a.x,a.y):null;e.save();let l=Math.max(8,Math.min(11,o.pitch/3));e.textAlign=`center`,e.textBaseline=`middle`,e.font=J(i,l);for(let t of o.cells)e.fillStyle=t.color,e.fillRect(t.x,t.y,t.size,t.size),t.text&&(e.fillStyle=t.textColor,e.fillText(t.text,t.x+t.size/2,t.y+t.size/2));c&&(e.strokeStyle=i.text,e.lineWidth=1.5,e.strokeRect(c.x+.75,c.y+.75,c.size-1.5,c.size-1.5)),e.font=J(i,11),e.fillStyle=i.textSecondary,e.textAlign=`right`;for(let t of o.rowLabels)e.fillStyle=c&&c.cell.rowIndex===t.index?i.text:i.textSecondary,e.fillText(t.text,t.x,t.y);for(let t of o.columnLabels)e.fillStyle=c&&c.cell.columnIndex===t.index?i.text:i.textSecondary,t.rotated?(e.save(),e.translate(t.x,t.y),e.rotate(aA),e.textAlign=`right`,e.fillText(t.text,0,0),e.restore()):(e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t.text,t.x,t.y),e.textBaseline=`middle`);if(e.restore(),o.bar&&Rf(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;mf(e,[{text:`${r.row} × ${r.column}`,bold:!0,color:c.color},{text:s(r.value)}],a,{x:0,y:0,width:t,height:n},i)}return o}var mA=12,hA=18,gA=20,_A=10,vA=.2,yA=2e3,bA=1e-9;function xA(e,t,n=1/0){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):25,i=[],a=Math.max(r-1,e.length-(Number.isFinite(n)?Math.max(1,Math.floor(n)):e.length));for(let t=a;t<e.length;t++){let n=0,a=0;for(let i=t-r+1;i<=t;i++)n+=e[i].volume,a+=e[i].close;i.push({time:e[t].time,volume:n/r,price:a/r})}return i}var SA=(e,t)=>t-e>bA*Math.max(Math.abs(e),Math.abs(t));function CA(e){if(e.length<2)return null;let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e)t=Math.min(t,a.volume),n=Math.max(n,a.volume),r=Math.min(r,a.price),i=Math.max(i,a.price);let a=e[e.length-2],o=e[e.length-1],s=SA(t,n)?(o.volume-a.volume)/(n-t):0,c=SA(r,i)?(o.price-a.price)/(i-r):0;if(Math.abs(s)<1e-6&&Math.abs(c)<1e-6)return null;let l=(Math.atan2(c,s)+2*Math.PI)%(2*Math.PI);return Math.round(l/(Math.PI/4))%8+1}function wA(e,n,r,i,a){let o=xA(e.data,e.period??25,TA(e)),s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of o)s=Math.min(s,e.volume),c=Math.max(c,e.volume),l=Math.min(l,e.price),u=Math.max(u,e.price);o.length>0&&!SA(s,c)&&(c=s),o.length>0&&!SA(l,u)&&(u=l);let d=$d(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=$d(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??q(f,e.locale),m=e.volumeFormat??q(d,e.locale),h=mA+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?hA:0),g=mA+a(m(d.max),11)/2,_=mA,v=mA+gA+(e.xLabel?hA:0),y={x:h,y:_,width:Math.max(1,n-h-g),height:Math.max(1,r-_-v)},b=Math.max(1,o.length-1);return{plot:y,xScale:d,yScale:f,points:o.map((e,t)=>({px:G(d,e.volume,y.x,y.width),py:G(f,e.price,y.y,y.height,!0),alpha:vA+(1-vA)*t/b,point:e})),phase:CA(o),color:e.color??t.TC_SERIES_COLORS[0]}}function TA(e){let t=e.points??60;return Number.isFinite(t)?Math.min(yA,Math.max(2,Math.floor(t))):60}function EA(e,t,n){let r=null,i=_A*_A;for(let a=e.points.length-1;a>=0;a--){let o=e.points[a],s=(o.px-t)**2+(o.py-n)**2;s<i&&(r=o,i=s)}return r}function DA(e,n,r,i,a,o,s=wA(i,n,r,a,df(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??of(i.locale,{year:`numeric`,month:`short`,day:`numeric`}),f=i.priceFormat??K(i.locale),p=i.volumeFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,c,s.yScale,`vertical`,a,i.priceFormat??q(s.yScale,i.locale)),Tf(e,c,s.xScale,`horizontal`,a,i.volumeFormat??q(s.xScale,i.locale)),OA(e,c,i,a),e.save(),e.lineWidth=1.5,e.lineJoin=`round`;for(let n=1;n<l.length;n++)e.strokeStyle=(0,t.withAlpha)(u,l[n].alpha),e.beginPath(),e.moveTo(l[n-1].px,l[n-1].py),e.lineTo(l[n].px,l[n].py),e.stroke();for(let n of l)e.fillStyle=(0,t.withAlpha)(u,n.alpha),e.beginPath(),e.arc(n.px,n.py,2,0,Math.PI*2),e.fill();let m=l[l.length-1];m&&(e.fillStyle=u,e.strokeStyle=a.background,e.lineWidth=2,e.beginPath(),e.arc(m.px,m.py,5,0,Math.PI*2),e.fill(),e.stroke()),e.restore();let h=o&&i.crosshair!==!1?EA(s,o.x,o.y):null;return h&&o&&(e.save(),e.strokeStyle=a.text,e.lineWidth=1.5,e.beginPath(),e.arc(h.px,h.py,5,0,Math.PI*2),e.stroke(),e.restore(),mf(e,[{text:d(h.point.time),bold:!0,color:u},{text:`${i.yLabel??`Price`}: ${f(h.point.price)}`},{text:`${i.xLabel??`Volume`}: ${p(h.point.volume)}`}],o,{x:0,y:0,width:n,height:r},a)),s}function OA(e,t,n,r){e.save(),e.font=J(r,11),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,t.x+t.width/2,t.y+t.height+gA+hA)),n.yLabel&&(e.translate(mA+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Xv,exports.ADXIndicator=Es,exports.ALMAIndicator=Oc,exports.ATRIndicator=Ts,exports.AXIS_LABEL_HEIGHT=ee,exports.AcceleratorOscillatorIndicator=mc,exports.AccumulationDistributionIndicator=wc,exports.AccumulativeSwingIndexIndicator=yu,exports.AdvanceDeclineIndicator=xu,exports.AlertDragHandler=zd,exports.AlertManager=AT,exports.AlligatorIndicator=ds,exports.AnchoredNoteTool=Vy,exports.AnchoredTextTool=By,exports.AnchoredVWAPIndicator=ns,exports.AnchoredVWAPTool=ov,exports.Animator=aD,exports.ArcTool=db,exports.AreaRenderer=$e,exports.AroonIndicator=js,exports.ArrowMarkTool=Ty,exports.ArrowTool=X_,exports.AverageDayRangeIndicator=el,exports.AveragePriceIndicator=cl,exports.AwesomeOscillatorIndicator=bs,exports.AxisDragHandler=Rd,exports.BalanceOfPowerIndicator=$s,exports.BalloonTool=zy,exports.BarCountdown=fe,exports.BarRenderer=et,exports.BarsPatternTool=Kb,exports.BaseFinanceChart=cD,exports.BaselineRenderer=rt,exports.BinanceAdapter=rw,exports.BollingerBandWidthIndicator=Vc,exports.BollingerBandsIndicator=zo,exports.BollingerPercentBIndicator=Bc,exports.BracketTool=eS,exports.BrushTool=ib,exports.BybitAdapter=_w,exports.CANDLE_PATTERNS=Yl,exports.CCIIndicator=ks,exports.CMFIndicator=Ps,exports.COUNTDOWN_HEIGHT=de,exports.CROSSHAIR_CURSORS=Qf,exports.CalloutTool=gy,exports.CandlestickRenderer=le,exports.CanvasLayer=c,exports.ChaikinOscillatorIndicator=xs,exports.ChaikinVolatilityIndicator=sc,exports.ChandeKrollStopIndicator=Lc,exports.ChandeMomentumIndicator=tc,exports.ChandelierExitIndicator=us,exports.ChartLegend=Kw,exports.ChartMarkManager=RE,exports.ChartStateManager=cE,exports.ChopZoneIndicator=Tu,exports.ChoppinessIndexIndicator=Ls,exports.CircleTool=ey,exports.CoinbaseAdapter=dw,exports.CompareRenderer=Wr,exports.CompareSymbolIndicator=no,exports.CompareSymbolPaneIndicator=ro,exports.ConnorsRSIIndicator=Vs,exports.CoppockIndicator=Us,exports.CorrelationCoefficientIndicator=co,exports.CorrelationLogIndicator=lo,exports.CrossLineTool=Mv,exports.CrosshairHandler=Hf,exports.CrosshairTooltip=gp,exports.CurrentPriceLine=US,exports.CurveTool=ub,exports.CyclicLinesTool=cy,exports.CypherPatternTool=$v,exports.DEFAULT_LEGEND_CONFIG=Gw,exports.DEFAULT_MAX_PIXEL_RATIO=n,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=pT,exports.DEMAIndicator=Ec,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=md,exports.DOUBLE_TAP_PX=hd,exports.DPRManager=o,exports.DataExporter=_E,exports.DateAndPriceRangeTool=iy,exports.DateRangeTool=z_,exports.DepthHeatmapBuffer=Qt,exports.DepthHeatmapRenderer=$t,exports.DepthOverlay=jS,exports.DepthOverlayLayer=MS,exports.DetrendedPriceOscillatorIndicator=Qs,exports.DisjointChannelTool=Og,exports.DisparityIndexIndicator=_c,exports.DonchianChannelIndicator=Qo,exports.DrawingBase=Y,exports.DrawingManager=Xm,exports.DrawingRenderer=ih,exports.EMAIndicator=Ro,exports.EaseOfMovementIndicator=ic,exports.Easing=iD,exports.ElderRayIndicator=qs,exports.ElliottCorrectionTool=A_,exports.ElliottDoubleComboTool=M_,exports.ElliottImpulseTool=k_,exports.ElliottTriangleTool=j_,exports.ElliottTripleComboTool=N_,exports.ElliottWaveTool=O_,exports.EllipseTool=Yg,exports.Emitter=LS,exports.EnvelopeIndicator=hs,exports.EquivolumeRenderer=ut,exports.EventBus=Op,exports.ExtendedLineTool=vg,exports.FibArcsTool=kb,exports.FibChannelTool=Bv,exports.FibCirclesTool=Ob,exports.FibExtensionTool=Kg,exports.FibRetracementTool=Wg,exports.FibSpeedResistanceFanTool=qv,exports.FibSpiralTool=Mb,exports.FibTimeZonesTool=yv,exports.FibWedgeTool=Ab,exports.FinanceCrosshair=lD,exports.FisherTransformIndicator=Zs,exports.FlagTool=Sy,exports.FlatTopBottomTool=kg,exports.ForceIndexIndicator=Bs,exports.ForecastTool=Wb,exports.GROUP_HEADER=BD,exports.GannBoxTool=iv,exports.GannFanTool=$_,exports.GannSquareTool=Nb,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=al,exports.HLCAreaRenderer=ft,exports.HammingMAIndicator=fu,exports.HeadAndShouldersTool=Zv,exports.HiLoRenderer=_t,exports.HighlighterTool=ab,exports.HistoricalVolatilityIndicator=Uc,exports.HollowCandleRenderer=tt,exports.HorizontalLineTool=pg,exports.HorizontalRayTool=mg,exports.HullMAIndicator=as,exports.ICON_GLYPHS=Ey,exports.INDICATOR_CATEGORIES=Fu,exports.INDICATOR_WORKER_MIN_BARS=Do,exports.INTERVAL_LIMITS=Da,exports.INTERVAL_UNITS=Ea,exports.IchimokuIndicator=Jo,exports.IconTool=Oy,exports.IndicatorBase=I,exports.IndicatorEngine=Io,exports.IndicatorValueMap=L,exports.IndicatorWorkerClient=qu,exports.IndicatorWorkerHost=Wu,exports.IndicatorWorkerPool=Yu,exports.InfoLineTool=Pv,exports.InteractionManager=Td,exports.KAMAIndicator=kc,exports.KEPT_BUCKETS=JS,exports.KSTIndicator=Ws,exports.KagiRenderer=at,exports.KeltnerChannelIndicator=Zo,exports.KeyboardHandler=ap,exports.KlingerIndicator=Xs,exports.KrakenAdapter=ww,exports.LSMAIndicator=Ac,exports.LayerManager=l,exports.LineRenderer=Qe,exports.LineWithMarkersRenderer=mt,exports.LinearRegressionChannelIndicator=is,exports.LinearRegressionSlopeIndicator=Qc,exports.MACDIndicator=Cs,exports.MAChannelIndicator=cu,exports.MACrossIndicator=Pc,exports.MADoubleIndicator=gu,exports.MARK_BADGE_SIZE=CE,exports.MARK_ROW_HEIGHT=DE,exports.MARibbonIndicator=ol,exports.MATripleIndicator=_u,exports.MAX_ALERT_BARS=xT,exports.MAX_BASE_RATIO=KS,exports.MAX_BASE_REQUESTS=GS,exports.MFIIndicator=As,exports.MIN_ALERT_BARS=ST,exports.MIN_BAR_UNIT=Fe,exports.MIN_BAR_UNIT_LIMIT=Ie,exports.MTFMovingAverageIndicator=cs,exports.MajorityRuleIndicator=Su,exports.ManualFeed=Uw,exports.MarketProfileRenderer=Lt,exports.MassIndexIndicator=ec,exports.McGinleyDynamicIndicator=jc,exports.MeasureOverlay=qE,exports.MeasureTool=B_,exports.MedianPriceIndicator=ll,exports.MockAdapter=iw,exports.ModifiedSchiffPitchforkTool=n_,exports.MomentumIndicator=Hc,exports.NetVolumeIndicator=tl,exports.NoteTool=hy,exports.OBVIndicator=Ds,exports.OrderDraftTool=oS,exports.OrderRenderer=Nx,exports.PRICE_AXIS_ADD_STRIP=Od,exports.PRICE_SCALE_MARGIN=ze,exports.PanHandler=Id,exports.PaneResizeHandler=Bd,exports.PaperExecutionAdapter=PS,exports.ParabolicSARIndicator=Yo,exports.ParallelChannelTool=xg,exports.PathTool=ob,exports.PercentagePriceOscillatorIndicator=fc,exports.PeriodLevelsRenderer=Ht,exports.PinnedTooltip=wp,exports.PitchfanTool=jb,exports.PitchforkTool=e_,exports.PivotMarkersRenderer=Jt,exports.PivotPointsIndicator=es,exports.PointAndFigureRenderer=ct,exports.PollingAdapter=sw,exports.PolylineTool=sb,exports.PositionRenderer=Gx,exports.PrettyGoodOscillatorIndicator=yc,exports.PriceAxis=D,exports.PriceAxisAddButton=kd,exports.PriceLabelTool=Xy,exports.PriceLines=_T,exports.PriceOscillatorIndicator=Ou,exports.PriceRangeTool=I_,exports.PriceVolumeTrendIndicator=ac,exports.ProjectionTool=Gb,exports.QstickIndicator=vc,exports.RANGE_PRESETS=Ue,exports.ROCIndicator=Ms,exports.RSIIndicator=Ss,exports.RayTool=_g,exports.ReconnectManager=VS,exports.RectangleTool=Jg,exports.RegressionChannelTool=Eg,exports.RelativeMomentumIndexIndicator=gc,exports.RelativeVigorIndicator=cc,exports.RelativeVolatilityIndexIndicator=Xc,exports.RenderEngine=je,exports.RenderLoop=u,exports.RenkoRenderer=it,exports.ReplayController=RC,exports.ReplayManager=zT,exports.ResamplingAdapter=aC,exports.ReshapeMemo=Zr,exports.RiskRewardTool=jv,exports.RotatedRectangleTool=Ag,exports.SELECTION_BOX_MIN_SIZE=nD,exports.SMAIndicator=Lo,exports.SMIErgodicIndicator=Du,exports.SMMAIndicator=Dc,exports.SNAPSHOT_VERSION=VT,exports.SYMBOL_INDICATOR_IDS=eo,exports.SYMBOL_ZONE_WAIT_MS=qS,exports.SchaffTrendCycleIndicator=Js,exports.SchiffPitchforkTool=t_,exports.Screenshot=tT,exports.SelectionBoxOverlay=rD,exports.SessionBreaks=oT,exports.SessionShading=mT,exports.SessionVWAPIndicator=ls,exports.SignalMarkerManager=SE,exports.SignpostTool=Ry,exports.SineLineTool=Rb,exports.SpreadIndicator=io,exports.StandardErrorBandsIndicator=nl,exports.StandardErrorIndicator=$c,exports.StdDevIndicator=bc,exports.StepLineRenderer=pt,exports.StochasticIndicator=ws,exports.StochasticMomentumIndexIndicator=Yc,exports.StochasticRSIIndicator=lc,exports.StreamManager=LC,exports.SupertrendIndicator=Xo,exports.SymbolSeriesStore=tn,exports.TEMAIndicator=ys,exports.TOUCH_REACH=pd,exports.TRIXIndicator=nc,exports.TSIIndicator=Ns,exports.TapTracker=gd,exports.TextAnnotationTool=J_,exports.ThreeDrivesTool=Qv,exports.TickAggregator=BS,exports.TickBarAdapter=uC,exports.TickBarBuilder=lC,exports.TimeAxis=ld,exports.TimeCyclesTool=Lb,exports.TradeZoneManager=UE,exports.TradingContextMenu=Jx,exports.TradingDragHandler=qx,exports.TradingManager=SS,exports.TradingRenderer=CS,exports.TrendAngleTool=$h,exports.TrendLineTool=fg,exports.TrendStrengthIndexIndicator=Zc,exports.TriangleTool=Xg,exports.TypicalPriceIndicator=ul,exports.UPBIT_MAX_CANDLES=kw,exports.UlcerIndexIndicator=Kc,exports.UltimateOscillatorIndicator=Rs,exports.UndoRedoManager=lE,exports.UpbitAdapter=Pw,exports.VOLUME_HEIGHT_RATIO=vt,exports.VROCIndicator=Tc,exports.VWAPIndicator=Go,exports.VWMAIndicator=ps,exports.VerticalLineTool=gg,exports.Viewport=Ve,exports.VolatilityIndexIndicator=vu,exports.VolatilityOHLCIndicator=ju,exports.VolatilityZeroTrendIndicator=Mu,exports.VolumeCandleRenderer=lt,exports.VolumeDeltaIndicator=Fs,exports.VolumeOscillatorIndicator=Wc,exports.VolumeProfileIndicator=Cc,exports.VolumeProfileRangeTool=hv,exports.VolumeProfileRenderer=St,exports.VolumeRenderer=yt,exports.VortexIndicator=Is,exports.WMAIndicator=ms,exports.Watermark=nT,exports.WebSocketAdapter=ow,exports.WilliamsADIndicator=oc,exports.WilliamsFractalsIndicator=Ic,exports.WilliamsRIndicator=Os,exports.XABCDPatternTool=Yv,exports.ZigZagIndicator=rs,exports.ZoomHandler=Ld,exports.adapterFromFeed=CC,exports.alignAxisTags=pe,exports.alignOutput=wa,exports.arcPoints=lb,exports.assignSessionLetters=Ft,exports.axisFormat=q,exports.axisTimes=si,exports.barIndexToTime=e.C,exports.barIndexToX=e.w,exports.barTimeStep=e.T,exports.barTimeStepMs=e.E,exports.barsToColumns=uo,exports.bracketRiskReward=Xx,exports.canvasMeasure=df,exports.cappedPixelRatio=r,exports.claimGpuContext=e.n,exports.classifyPivots=Wt,exports.cleanIntervals=ja,exports.columnsToBars=fo,exports.columnsToOutput=So,exports.computeBarLayout=$O,exports.computeBracketDefaults=Yx,exports.computeCalendarLayout=$k,exports.computeCounterClockLayout=wA,exports.computeDepthLayout=_D,exports.computeDonutLayout=dk,exports.computeEquityLayout=jD,exports.computeHistogramLayout=Fk,exports.computeMarketProfile=Nt,exports.computeMatrixLayout=dA,exports.computePeriodLevels=Vt,exports.computeScatterLayout=Sk,exports.computeSessionProfiles=It,exports.computeWaterfallLayout=sO,exports.correlationMatrix=sA,exports.counterClockPhase=CA,exports.counterClockPoints=xA,exports.createIndicatorWorker=Gu,exports.curvePoints=cb,exports.dayToIso=qk,exports.defaultFormat=cf,exports.depthBars=kS,exports.describeInputs=Hu,exports.detectCandlePatterns=$l,exports.drawAxisValueLabels=ae,exports.drawIcon=fx,exports.drawingAxisSpan=Bm,exports.drawnKeys=Wi,exports.feedFromAdapter=TC,exports.fillTag=A,exports.financeTheme=sD,exports.findDominantSwing=ah,exports.findPivots=Gt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=Ub,exports.formatTooltipTime=pp,exports.getIntParam=H,exports.getNumberParam=V,exports.getVisibleData=He,exports.gpuContextsLeft=e.r,exports.hasHistogram=$i,exports.hasTrades=pC,exports.histogramBins=Ak,exports.hitBar=ek,exports.hitCategory=tk,exports.hitDay=eA,exports.hitHistogramBar=Ik,exports.hitMatrixCell=fA,exports.hitSlice=fk,exports.hitWaterfallBar=cO,exports.idleCssCursor=ip,exports.indicatorCategory=Lu,exports.indicatorValuePrecision=j,exports.indicatorWorkerPool=Xu,exports.inferOrderType=rS,exports.inputSource=xa,exports.isCrosshairCursor=$f,exports.isDataFeed=yC,exports.isDense=e.f,exports.isInWindow=dT,exports.isPriceLevelAlert=wT,exports.isRegularSession=fT,exports.isSeriesPalette=Na,exports.isUpTone=Gi,exports.isWorkerResponse=Uu,exports.labelTextColor=ne,exports.layoutAxisValueLabels=ie,exports.layoutGroupedTreemap=VD,exports.layoutLegend=ff,exports.layoutSquarifiedTreemap=RD,exports.layoutUniformGrid=PD,exports.lineSourceBars=Ca,exports.lineSpace=Xp,exports.loadWebGL=Ne,exports.loadWebGLRenderer=Pe,exports.lttbDownsample=Ye,exports.lttbVisibleIndices=Ze,exports.mergeSessionHours=lT,exports.minuteOfDay=uT,exports.nearestCounterClockPoint=EA,exports.nearestPoint=Ck,exports.niceScale=$d,exports.numberFormat=K,exports.outputToColumns=_o,exports.paneLogRange=Zi,exports.paneValueRange=Xi,exports.parseDay=Kk,exports.pastTimeStep=e.D,exports.percentFormat=af,exports.plotColor=Yi,exports.plotLook=Ji,exports.plotShown=Ki,exports.pointAndFigureColumns=vi,exports.priceBucketRow=e.O,exports.priceScaleText=d,exports.priceSourceBars=Sa,exports.priceToY=e.k,exports.priceToYMapper=e.A,exports.rangePresetStart=Je,exports.readAlertOptions=MT,exports.readableText=Lf,exports.registerBuiltInDrawingTools=qb,exports.registerBuiltInIndicators=Pu,exports.renderAxisValueLabels=oe,exports.renderBarChart=nk,exports.renderCalendar=tA,exports.renderCounterClock=DA,exports.renderDenseBars=e.p,exports.renderDepthChart=bD,exports.renderDonut=pk,exports.renderEquityCurve=ND,exports.renderGauge=KO,exports.renderHeatmap=ZD,exports.renderHistogram=Lk,exports.renderMatrix=pA,exports.renderPlots=ea,exports.renderScatter=wk,exports.renderSparkline=uD,exports.renderWaterfall=fO,exports.resolveBarIndex=e.j,exports.resolveColorScale=Nf,exports.scaleColor=Pf,exports.servesTimeframe=tC,exports.setMaxWebGLCharts=e.i,exports.shownCount=TA,exports.shownOnInterval=Aa,exports.sourceParam=ba,exports.spreadLabels=te,exports.streamAdapterOf=bC,exports.timeToX=e.M,exports.timestampToBarIndex=e.N,exports.toHeikinAshi=Gr,exports.toKagi=mi,exports.toLineBreak=pi,exports.toPointAndFigure=_i,exports.toRangeBars=Li,exports.toRenko=ci,exports.tpoLetter=Pt,exports.waveLabel=w_,exports.whenGpuContextFree=e.a,exports.withResampling=$S,exports.withTickBars=fC,exports.xToBarIndex=e.P,exports.xToTime=e.F,exports.yToPrice=e.I;
24
+ `,t.addEventListener(`mouseenter`,()=>{t.style.background=`#1f2630`}),t.addEventListener(`mouseleave`,()=>{t.style.background=`transparent`}),t.addEventListener(`click`,()=>{this.onItemSelect?.(e.intent),this.hide()}),s.appendChild(t)}n.appendChild(s),this.menuElement=s;let l=e=>{(e instanceof KeyboardEvent&&e.key===`Escape`||e instanceof MouseEvent&&!s.contains(e.target))&&this.hide()};document.addEventListener(`mousedown`,l),document.addEventListener(`keydown`,l),this.removeHandler=()=>{document.removeEventListener(`mousedown`,l),document.removeEventListener(`keydown`,l)}}hide(){this.menuElement?.remove(),this.menuElement=null,this.removeHandler?.(),this.removeHandler=null}destroy(){this.hide(),this.onItemSelect=null}};function Yx(e,t,n={}){let r=Math.max(Math.abs(t)*(n.riskFraction??.01),1e-8),i=r*(n.riskReward??2);return e===`buy`?{side:e,entry:t,stopLoss:t-r,takeProfit:t+i}:{side:e,entry:t,stopLoss:t+r,takeProfit:t-i}}function Xx(e){let t=Math.abs(e.entry-e.stopLoss);return t===0?0:Math.abs(e.takeProfit-e.entry)/t}var Zx=6,Qx=.12,$x=[6,3],eS=class{draft=null;dragStart=null;dragging=null;defaults;constructor(e={}){this.defaults=e}start(e,t){this.draft=Yx(e,t,this.defaults),this.dragging=null}cancel(){this.draft=null,this.dragging=null}isActive(){return this.draft!==null}getDraft(){return this.draft?{...this.draft}:null}hitTest(t,n,r=Zx){if(!this.draft)return null;let i=[`entry`,`sl`,`tp`],a=null,o=r;for(let r of i){let i=e.k(this.priceOf(r),n),s=Math.abs(i-t.y);s<=o&&(o=s,a=r)}return a}beginDrag(e,t,n){let r=this.hitTest(e,t,n);return r!==null&&this.beginDragOn(r)}beginDragOn(e){return this.draft?(this.dragging=e,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=null,this.dragStart=null}drag(t,n){if(!this.draft||!this.dragging)return!1;let r=e.I(t.y,n);return this.draft=nS(this.draft,this.dragging,r),!0}endDrag(){this.dragging=null,this.dragStart=null}isDragging(){return this.dragging!==null}priceOf(e){let t=this.draft;return e===`entry`?t.entry:e===`sl`?t.stopLoss:t.takeProfit}render(e,t,n,r){this.renderLines(e,t,n),xx(e,this.tags(t,n),t,n,[])}renderLines(t,n,r){let i=this.draft;if(!i)return;let{chartRect:a}=n,o=e.k(i.entry,n),s=e.k(i.stopLoss,n),c=e.k(i.takeProfit,n),{profit:l,loss:u}=tS(r);t.save(),t.globalAlpha=Qx,t.fillStyle=l,t.fillRect(a.x,Math.min(o,c),a.width,Math.abs(c-o)),t.fillStyle=u,t.fillRect(a.x,Math.min(o,s),a.width,Math.abs(s-o)),t.globalAlpha=1,Yb(t,n,o,r.text,$x),Yb(t,n,c,l,[]),Yb(t,n,s,u,[]),t.restore()}tags(t,n){let r=this.draft;if(!r)return[];let{profit:i,loss:a}=tS(n),o=r.side===`buy`?1:-1,s=e=>{let t=r.entry===0?0:(e-r.entry)/r.entry*100*o;return`${t>=0?`+`:``}${t.toFixed(2)}%`};return[{y:e.k(r.entry,t),color:n.text,grab:{kind:`bracket`,handle:`entry`},cells:[{kind:`stamp`,text:r.side===`buy`?`Long`:`Short`},{kind:`text`,text:`${Xx(r).toFixed(2)}R`}]},{y:e.k(r.takeProfit,t),color:i,grab:{kind:`bracket`,handle:`tp`},cells:[{kind:`stamp`,text:`TP`},{kind:`text`,text:s(r.takeProfit),color:i}]},{y:e.k(r.stopLoss,t),color:a,grab:{kind:`bracket`,handle:`sl`},cells:[{kind:`stamp`,text:`SL`},{kind:`text`,text:s(r.stopLoss),color:a}]}].filter(e=>Z(e.y,t))}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))wx(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let{profit:o,loss:s}=tS(r),c=[];for(let[l,u]of[[a.takeProfit,o],[a.stopLoss,s],[a.entry,r.text]]){let r=e.k(l,n);Z(r,n)&&c.push({y:r,text:(0,t.priceTagText)(l,n,i),color:u})}return c}};function tS(e){return{profit:e.style?.trading.profit??e.candleUp,loss:e.style?.trading.loss??e.candleDown}}function nS(e,t,n){let r=e.side===`buy`;if(t===`entry`){let t=n-e.entry;return{side:e.side,entry:n,stopLoss:e.stopLoss+t,takeProfit:e.takeProfit+t}}if(t===`sl`){let t=r?Math.min(n,e.entry):Math.max(n,e.entry);return{...e,stopLoss:t}}let i=r?Math.max(n,e.entry):Math.min(n,e.entry);return{...e,takeProfit:i}}function rS(e,t,n){return n==null?`limit`:e===`buy`?t<=n?`limit`:`stop`:t>=n?`limit`:`stop`}var iS=6,aS=[6,3],oS=class{draft=null;dragStart=null;dragging=!1;start(e,t,n=1){this.draft={side:e,price:t,quantity:n},this.dragging=!1}cancel(){this.draft=null,this.dragging=!1}isActive(){return this.draft!==null}isDragging(){return this.dragging}getDraft(){return this.draft?{...this.draft}:null}setPrice(e){return this.draft?(this.draft={...this.draft,price:e},!0):!1}toIntent(e){return this.draft?{side:this.draft.side,type:rS(this.draft.side,this.draft.price,e),price:this.draft.price,quantity:this.draft.quantity}:null}hitTest(t,n,r=iS){return this.draft?Math.abs(e.k(this.draft.price,n)-t.y)<=r:!1}beginDrag(e,t,n){return this.hitTest(e,t,n)&&this.beginDragOn()}beginDragOn(){return this.draft?(this.dragging=!0,this.dragStart=this.draft,!0):!1}cancelDrag(){this.dragging&&this.dragStart&&(this.draft=this.dragStart),this.dragging=!1,this.dragStart=null}drag(t,n){return!this.draft||!this.dragging?!1:this.setPrice(e.I(t.y,n))}endDrag(){this.dragging=!1,this.dragStart=null}render(e,t,n,r,i){this.renderLines(e,t,n),xx(e,this.tags(t,n,r),t,n,[])}renderLines(t,n,r){let i=this.draft;i&&(t.save(),Yb(t,n,e.k(i.price,n),sS(i.side,r),aS),t.restore())}tags(t,n,r){let i=this.draft;if(!i)return[];let a=e.k(i.price,t);if(!Z(a,t))return[];let o=rS(i.side,i.price,r);return[{y:a,color:sS(i.side,n),grab:{kind:`draft`},cells:[{kind:`stamp`,text:String(i.quantity)},{kind:`text`,text:kx({side:i.side,type:o})}]}]}renderAxisBadges(e,t,n,r){for(let i of this.axisBadges(t,n,r))wx(e,i.y,i.text,i.color,t,n)}axisBadges(n,r,i){let a=this.draft;if(!a)return[];let o=e.k(a.price,n);return Z(o,n)?[{y:o,text:(0,t.priceTagText)(a.price,n,i),color:sS(a.side,r)}]:[]}};function sS(e,t){return e===`buy`?t.style?.trading.buy??t.candleUp:t.style?.trading.sell??t.candleDown}var cS=2;function lS(e,t){return e.type===t.type?e.type===`cancelOrder`?e.orderId===t.orderId:e.type===`removeStop`?e.positionId===t.positionId&&e.which===t.which:e.positionId===t.positionId:!1}function uS(e,t,n=cS){let r=(e,n)=>t.x>=e.x-n&&t.x<=e.x+e.size+n&&t.y>=e.y-n&&t.y<=e.y+e.size+n;for(let t=e.length-1;t>=0;t--)if(r(e[t],0))return e[t];let i=null,a=1/0;for(let o of e){if(!r(o,n))continue;let e=Math.hypot(t.x-(o.x+o.size/2),t.y-(o.y+o.size/2));e<a&&(a=e,i=o)}return i}var dS=5,fS=7,pS=2;function mS(e,n){let r=n.data;return r&&r.length>0?e/(0,t.barTimeUnit)(r):e}function hS(t,n,r,i){if(n.length===0)return;let{chartRect:a}=r,o=i.orderColors?.buy??`#1fa874`,s=i.orderColors?.sell??`#e8505b`;t.lineWidth=1.5;for(let i of n){let n=e.M(mS(i.time,r),r),c=e.k(i.price,r);if(n<a.x||n>a.x+a.width||c<a.y||c>a.y+a.height)continue;let l=i.side===`buy`,u=l?c+pS:c-pS,d=l?u+fS:u-fS;t.beginPath(),t.moveTo(n,u),t.lineTo(n-dS,d),t.lineTo(n+dS,d),t.closePath();let f=l?o:s;!i.reason||i.reason===`order`?(t.fillStyle=f,t.fill()):(t.strokeStyle=f,t.stroke())}}function gS(e){for(let t in e)if(e[t]!==null)return!0;return!1}function _S(e,t){let n={};for(let r of Object.keys(e)){let i=e[r];i!==null&&(n[t[r]]=i)}return n}function vS(e,t){let n=t.style?.trading;return!n||!gS(n)?e:{...e,orderColors:{...e.orderColors,..._S({buy:n.buy,sell:n.sell},{buy:`buy`,sell:`sell`})},positionColors:{...e.positionColors,..._S({profit:n.profit,loss:n.loss,entry:n.entry},{profit:`profit`,loss:`loss`,entry:`entry`})}}}function yS(e,t){let n=t.style?.markers;return!n||!gS(n)?e:{...e,..._S(n,{long:`longColor`,short:`shortColor`,neutral:`neutralColor`})}}function bS(e,t){let n=t.style?.tradeZones;return!n||!gS(n)?e:{...e,..._S(n,{profit:`profitColor`,loss:`lossColor`,active:`activeColor`})}}var xS=1e3,SS=class{orders=[];positions=[];currentPrice=null;config;orderRenderer=new Nx;positionRenderer=new Gx;dragHandler;contextMenu=new Jx;bracket=new eS;orderDraft=new oS;buttons=[];tagBoxes=[];tagInset=0;drawnTags=[];grabOffset=0;fills=[];realisedPnl=0;requestRender=null;eventCallback=null;container=null;constructor(e){this.config={...t.DEFAULT_TRADING_CONFIG,...e},this.dragHandler=new qx(this.config.dragThreshold),this.contextMenu.onItemSelect=e=>{this.eventCallback?.(`orderPlace`,e)}}setContainer(e){this.container=e}setRequestRender(e){this.requestRender=e}setEventCallback(e){this.eventCallback=e}setOrders(e){this.orders=e,this.requestRender?.()}setPositions(e){this.positions=e,this.requestRender?.()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}getCurrentPrice(){return this.currentPrice}setCurrentPrice(e){this.currentPrice=e,this.requestRender?.()}setConfig(e){Object.assign(this.config,e),this.requestRender?.()}addFill(e){this.fills=[...this.fills.slice(-(xS-1)),e],this.realisedPnl+=e.pnl??0,this.requestRender?.()}setFills(e){this.fills=e.slice(-xS),this.realisedPnl=e.reduce((e,t)=>e+(t.pnl??0),0),this.requestRender?.()}getRealisedPnl(){return this.realisedPnl}getFills(){return[...this.fills]}armed=null;isOverButton(e){return this.config.enabled&&uS(this.buttons,e)!==null}runButton(e){switch(e.type){case`cancelOrder`:this.eventCallback?.(`orderCancel`,{orderId:e.orderId});break;case`closePosition`:this.eventCallback?.(`positionClose`,{positionId:e.positionId});break;case`reversePosition`:this.eventCallback?.(`positionReverse`,{positionId:e.positionId});break;case`removeStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,[e.which]:null});break;case`trailStop`:this.eventCallback?.(`positionModify`,{positionId:e.positionId,trailingStop:e.distance});break}}startBracket(e,t){this.bracket.start(e,t),this.requestRender?.()}cancelBracket(){this.bracket.isActive()&&(this.bracket.cancel(),this.requestRender?.())}confirmBracket(){let e=this.bracket.getDraft();return e?(this.eventCallback?.(`bracketPlace`,{side:e.side,entry:e.entry,stopLoss:e.stopLoss,takeProfit:e.takeProfit,riskReward:Xx(e)}),this.bracket.cancel(),this.requestRender?.(),!0):!1}isBracketActive(){return this.bracket.isActive()}startOrderDraft(e,t){this.orderDraft.start(e,t),this.requestRender?.()}cancelOrderDraft(){this.orderDraft.isActive()&&(this.orderDraft.cancel(),this.requestRender?.())}confirmOrderDraft(){let e=this.orderDraft.toIntent(this.currentPrice);return e?(this.eventCallback?.(`orderPlace`,e),this.orderDraft.cancel(),this.requestRender?.(),!0):!1}isOrderDraftActive(){return this.orderDraft.isActive()}isOverDraggableLine(t,n,r=8){if(!this.config.enabled)return!1;if(gx(this.tagBoxes,t.x,t.y)&&!uS(this.buttons,t))return!0;let i=i=>{if(i===void 0)return!1;let a=e.k(i,n);return Z(a,n)&&Math.abs(t.y-a)<=r};for(let e of this.orders)if(e.draggable!==!1&&i(e.price))return!0;for(let e of this.positions)if(i(e.stopLoss)||i(e.takeProfit))return!0;return!1}onPointerDown(e,t,n){if(!this.config.enabled)return!1;let r=uS(this.buttons,e,n?.button),i=r?null:gx(this.tagBoxes,e.x,e.y);return i&&this.grabTag(i,e)||(this.grabOffset=0,this.bracket.isActive()&&this.bracket.beginDrag(e,t,n?.handle))||this.orderDraft.isActive()&&this.orderDraft.beginDrag(e,t,n?.handle)?(this.requestRender?.(),!0):r?(this.armed=r.action,!0):this.dragHandler.onPointerDown(e,this.orders,this.positions,t,n?.order??8)}grabTag(e,t){this.grabOffset=e.lineY-t.y;let n=e.grab;switch(n.kind){case`bracket`:return this.bracket.beginDragOn(n.handle);case`draft`:return this.orderDraft.beginDragOn();case`order`:{let t=this.orders.find(e=>e.id===n.orderId);return t!==void 0&&this.dragHandler.beginOrder(t,e.lineY)}case`stop`:{let t=this.positions.find(e=>e.id===n.positionId);return t!==void 0&&this.dragHandler.beginStop(t,n.which,e.lineY)}}}onPointerMove(e,t){if(this.armed)return!0;let n=this.grabOffset===0?e:{x:e.x,y:Jb(e.y+this.grabOffset,t)};if(this.bracket.isDragging()){let e=this.bracket.drag(n,t);return e&&this.requestRender?.(),e}if(this.orderDraft.isDragging()){let e=this.orderDraft.drag(n,t);return e&&this.requestRender?.(),e}if(!this.dragHandler.isActive())return!1;let r=this.dragHandler.onPointerMove(n,t);return r&&this.requestRender?.(),r}onPointerUp(e){if(this.grabOffset=0,this.armed){let t=this.armed;this.armed=null;let n=e?uS(this.buttons,e):null;return n&&lS(n.action,t)&&this.runButton(t),!0}if(this.bracket.isDragging())return this.bracket.endDrag(),this.requestRender?.(),!0;if(this.orderDraft.isDragging())return this.orderDraft.endDrag(),this.requestRender?.(),!0;let t=this.dragHandler.onPointerUp();return t?(t.sourceType===`order`?this.eventCallback?.(`orderModify`,{orderId:t.id,newPrice:t.newPrice,previousPrice:t.previousPrice}):this.eventCallback?.(`positionModify`,{positionId:t.id,[t.sourceType]:t.newPrice}),this.requestRender?.(),!0):!1}cancelPointer(){this.grabOffset=0;let e=!1;return this.armed&&(this.armed=null,e=!0),this.bracket.isDragging()&&(this.bracket.cancelDrag(),e=!0),this.orderDraft.isDragging()&&(this.orderDraft.cancelDrag(),e=!0),this.dragHandler.cancel()&&(e=!0),e&&this.requestRender?.(),e}onContextMenu(n,r){if(!this.config.enabled||!this.config.contextMenu?.enabled||!this.container)return!1;let i=e.I(n.y,r);return this.contextMenu.show(n,i,this.container,this.config,e=>(0,t.priceTagText)(e,r,this.config.pricePrecision)),!0}tagRects(){return this.drawnTags}setTagInset(e){this.tagInset=Math.max(0,e)}render(e,t,n){if(this.buttons=[],this.tagBoxes=[],this.drawnTags=[],!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.renderInPlot(e,t,n)}finally{e.restore()}}renderInPlot(e,t,n){let r=vS(this.config,n);r.fillMarks!==!1&&hS(e,this.fills,t,r);let i=this.dragHandler.getDragState();this.positionRenderer.renderLines(e,this.positions,this.currentPrice,t,r,i),this.orderRenderer.renderLines(e,this.orders,t,r,i),this.bracket.renderLines(e,t,n),this.orderDraft.renderLines(e,t,n),xx(e,[...this.bracket.tags(t,n),...this.orderDraft.tags(t,n,this.currentPrice),...this.positionRenderer.tags(this.positions,this.currentPrice,t,r,i),...this.orderRenderer.tags(this.orders,t,r,i)],t,n,this.buttons,this.tagBoxes,this.tagInset,this.drawnTags)}renderAxisBadges(e,t,n,r){if(this.config.enabled){if(r){let{chartRect:i}=t;this.sortedAxisBadges(t,n).forEach((a,o)=>{let s=r[o]??a.y;!Number.isFinite(s)||s-16/2<i.y-.5||s+16/2>i.y+i.height+.5||wx(e,s,a.text,a.color,t,n)});return}for(let r of Cx(this.axisBadges(t,n),t))wx(e,r.at,r.text,r.color,t,n)}}axisBadgeLines(e,n=t.DARK_THEME){return this.config.enabled?this.sortedAxisBadges(e,n).map(e=>e.y):[]}sortedAxisBadges(e,t){return this.axisBadges(e,t).sort((e,t)=>e.y-t.y)}axisBadges(e,t){let n=vS(this.config,t);return[...this.positionRenderer.axisBadges(this.positions,e,n,this.dragHandler.getDragState()),...this.orderRenderer.axisBadges(this.orders,e,n,this.dragHandler.getDragState()),...this.bracket.axisBadges(e,t,this.config.pricePrecision),...this.orderDraft.axisBadges(e,t,this.config.pricePrecision)]}axisTagYs(e,n=t.DARK_THEME){return this.config.enabled?Cx(this.axisBadges(e,n),e).map(e=>e.at):[]}destroy(){this.contextMenu.destroy()}},CS=class{constructor(e){this.manager=e}render(e,t,n){this.manager.render(e,t,n)}renderAxisBadges(e,t,n,r){this.manager.renderAxisBadges(e,t,n,r)}axisBadgeLines(e,t){return this.manager.axisBadgeLines(e,t)}tagRects(){return this.manager.tagRects()}axisTagYs(e,t){return this.manager.axisTagYs(e,t)}},wS=`rgba(31, 168, 116,0.15)`,TS=`rgba(232, 80, 91,0.15)`,ES=`#1fa874`,DS=`#e8505b`,OS=100;function kS(e){return typeof e==`number`&&Number.isFinite(e)&&e>0?e:null}function AS(e,t,n){let r=new Map;for(let i of e){let e=Number((i.price/t).toPrecision(12)),a=n?Math.ceil(e-.5):Math.floor(e+.5);r.set(a,(r.get(a)??0)+i.volume)}return[...r].map(([e,n])=>({price:e*t,volume:n}))}function jS(e,t=`cumulative`,n){let r=kS(n),i=(e,n)=>{let i=e.filter(e=>Number.isFinite(e.price)&&Number.isFinite(e.volume)&&e.volume>0),a=r===null?i:AS(i,r,n);a.sort((e,t)=>n?t.price-e.price:e.price-t.price);let o=0;return a.map(e=>(o+=e.volume,{price:e.price,value:t===`cumulative`?o:e.volume}))},a=i(e.bids,!0),o=i(e.asks,!1),s=0;for(let e of a)s=Math.max(s,e.value);for(let e of o)s=Math.max(s,e.value);return{bids:a,asks:o,max:s}}function MS(t,n){if(t.length<2)return 1/0;let r=Math.abs(e.k(t[0].price,n)-e.k(t[1].price,n));return r>0?r:1/0}var NS=class{cache=null;invalidate(){this.cache=null}render(t,n,r,i){if(!i.enabled)return;let a=i.mode===`level`?`level`:`cumulative`,o=kS(i.rowSize);(!this.cache||this.cache.depth!==n||this.cache.mode!==a||this.cache.rowSize!==o)&&(this.cache={depth:n,mode:a,rowSize:o,bars:jS(n,a,o??void 0)});let{bids:s,asks:c,max:l}=this.cache.bars;if(l===0)return;let{chartRect:u}=r,d=Math.min(Math.max(i.maxWidth??OS,0),u.width),f=u.x+u.width,p=Math.min(MS(s,r),MS(c,r)),m=Number.isFinite(p)?p:4,h=Math.max(1,a===`level`?m-1:m),g=u.y,_=u.y+u.height,v=t=>{if(o===null){let n=e.k(t,r);return n<g||n>_?null:{y:n-h/2,h}}let n=e.k(t+o/2,r),i=e.k(t-o/2,r),s=Math.min(n,i),c=Math.abs(i-n);return!Number.isFinite(s)||!Number.isFinite(c)||s+c<g||s>_?null:{y:s,h:Math.max(1,a===`level`&&c>2?c-1:c)}},y=(e,n)=>{t.fillStyle=n;for(let{price:n,value:r}of e){let e=v(n);if(!e)continue;let i=r/l*d;t.fillRect(f-i,e.y,i,e.h)}};if(y(s,i.bidColor??wS),y(c,i.askColor??TS),i.markBest){let n=(n,i)=>{if(!n)return;let a=e.k(n.price,r);a<u.y||a>u.y+u.height||(t.fillStyle=i,t.fillRect(f-d,a-.5,d,1))};n(s[0],i.bestBidColor??ES),n(c[0],i.bestAskColor??DS)}}},PS=class{data=null;config={};overlay=new NS;setData(e){this.data=e,this.overlay.invalidate()}setConfig(e){this.config={...this.config,...e}}getConfig(){return{...this.config}}isActive(){return!!this.config.enabled&&this.data!==null}render(e,t,n){if(!this.data||!this.config.enabled)return;let{chartRect:r}=t;e.save();try{e.beginPath(),e.rect(r.x,r.y,r.width,r.height),e.clip(),this.overlay.render(e,this.data,t,this.config)}finally{e.restore()}}};function FS(e,t){let n=e.trailingStop;if(n===void 0||!(n>0)||!Number.isFinite(t)||!(t>0))return e;let r=e.side===`buy`,i=r?t-n:t+n,a=e.stopLoss;return a!==void 0&&(r?i<=a:i>=a)?e:{...e,stopLoss:i}}var IS=class{name=`paper`;state=`disconnected`;listeners=new Map;orders=[];positions=[];markPrice;markTime;seq=0;constructor(e={}){this.markPrice=e.markPrice??0}connect(e){this.state=`connected`,this.emit(`connectionChange`,this.state),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}disconnect(){this.state=`disconnected`,this.emit(`connectionChange`,this.state)}getConnectionState(){return this.state}setMarkPrice(e,t){this.markPrice=e,this.markTime=t!==void 0&&Number.isFinite(t)?t:void 0,this.checkPendingOrders(),this.checkStops()}fillTime(){return this.markTime??Date.now()}getOrders(){return[...this.orders]}getPositions(){return[...this.positions]}async placeOrder(e){let t={id:this.nextId(`ord`),side:e.side,type:e.type,price:e.price,stopPrice:e.stopPrice,quantity:e.quantity??1,label:e.type===`market`?void 0:RS(e.type),draggable:!0,stopLoss:e.stopLoss,takeProfit:e.takeProfit,timeInForce:e.timeInForce};return e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(t.trailingStop=e.trailingStop),e.type===`market`?this.fill(t,this.markPrice||e.price):(this.orders=[...this.orders,t],this.emit(`orders`,this.orders)),t}async modifyOrder(e){this.orders=this.orders.map(t=>t.id===e.orderId?{...t,price:e.newPrice}:t),this.emit(`orders`,this.orders)}async cancelOrder(e){this.orders=this.orders.filter(t=>t.id!==e.orderId),this.emit(`orders`,this.orders)}async modifyPosition(e){let t=(e,t)=>e===void 0?t:e??void 0;this.positions=this.positions.map(n=>{if(n.id!==e.positionId)return n;let r={...n,stopLoss:t(e.stopLoss,n.stopLoss),takeProfit:t(e.takeProfit,n.takeProfit)};return e.trailingStop===null?delete r.trailingStop:e.trailingStop!==void 0&&Number.isFinite(e.trailingStop)&&e.trailingStop>0&&(r.trailingStop=e.trailingStop),e.stopLoss===null&&delete r.trailingStop,typeof e.stopLoss==`number`?r:FS(r,this.markPrice)}),this.emit(`positions`,this.positions)}async closePosition(e){let t=this.positions.find(t=>t.id===e.positionId);t&&(this.close(t,this.markPrice||t.entryPrice,`close`),this.emit(`positions`,this.positions))}async reversePosition(e){let t=this.positions.find(t=>t.id===e.positionId);if(!t)return;let n=this.markPrice||t.entryPrice;this.close(t,n,`reverse`);let r=t.quantity-(t.closedQuantity??0),i={id:this.nextId(`ord`),side:LS(t.side),type:`market`,price:n,quantity:r};this.fill(i,n)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear(),this.orders=[],this.positions=[]}fill(e,t){this.orders=this.orders.filter(t=>t.id!==e.id);let n={id:this.nextId(`pos`),side:e.side,entryPrice:t,quantity:e.quantity,stopLoss:e.stopLoss,takeProfit:e.takeProfit};e.trailingStop!==void 0&&(n.trailingStop=e.trailingStop),this.positions=[...this.positions,n];let r={orderId:e.id,side:e.side,price:t,quantity:e.quantity,time:this.fillTime(),positionId:n.id,reason:`order`};this.emit(`fill`,r),this.emit(`orders`,this.orders),this.emit(`positions`,this.positions)}close(e,t,n){this.positions=this.positions.filter(t=>t.id!==e.id);let r=e.quantity-(e.closedQuantity??0),i=e.side===`buy`?1:-1;this.emit(`fill`,{orderId:this.nextId(`ord`),side:LS(e.side),price:t,quantity:r,time:this.fillTime(),positionId:e.id,reason:n,pnl:(t-e.entryPrice)*r*i})}checkPendingOrders(){let e=this.orders.filter(e=>this.isTriggered(e));for(let t of e)this.fill(t,t.type===`limit`?t.price:t.stopPrice??t.price)}isTriggered(e){if(e.type===`limit`)return e.side===`buy`?this.markPrice<=e.price:this.markPrice>=e.price;if(e.type===`stop`||e.type===`stopLimit`){let t=e.stopPrice??e.price;return e.side===`buy`?this.markPrice>=t:this.markPrice<=t}return!1}trailStops(){let e=!1;return this.positions=this.positions.map(t=>{let n=FS(t,this.markPrice);return n!==t&&(e=!0),n}),e}checkStops(){let e=!1;for(let t of[...this.positions]){let n=t.stopLoss!==void 0&&(t.side===`buy`?this.markPrice<=t.stopLoss:this.markPrice>=t.stopLoss),r=t.takeProfit!==void 0&&(t.side===`buy`?this.markPrice>=t.takeProfit:this.markPrice<=t.takeProfit);!n&&!r||(this.close(t,n?t.stopLoss:t.takeProfit,n?`stopLoss`:`takeProfit`),e=!0)}this.trailStops()&&(e=!0),e&&this.emit(`positions`,this.positions)}nextId(e){return`${e}-${++this.seq}`}emit(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function LS(e){return e===`buy`?`sell`:`buy`}function RS(e){switch(e){case`stop`:return`STOP`;case`stopLimit`:return`STOP LIMIT`;default:return`LIMIT`}}var zS=class{listeners=new Map;on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),()=>n.delete(t)}once(e,t){let n=this.on(e,e=>{n(),t(e)});return n}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(n)for(let e of n)e(t)}removeAllListeners(){this.listeners.clear()}},BS=6e4,VS=e=>[e.open,e.high,e.low,e.close].every(Number.isFinite),HS=class extends zS{currentBar=null;newest=-1/0;builtFromTrades=!1;lastTradeAt=null;timeframe;timeframeMs;dateFrame;bucket={};dateStamps=!1;tickRing;ringHead=0;ringCount=0;ringCapacity;constructor(e,n=1e3){super(),this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.ringCapacity=n,this.tickRing=Array(n)}setTimeframe(e){this.timeframe=e,this.timeframeMs=(0,t.timeframeToMs)(e),this.dateFrame=(0,t.timeframeSpansDays)(e),this.reset()}seed(e){this.builtOffTheBuckets()&&(this.currentBar=null,this.newest=-1/0,this.lastTradeAt=null),Number.isFinite(e)&&(this.newest=Math.max(this.newest,(0,t.normalizeBarTime)(e)))}resume(e){if(!VS(e))return;let n=(0,t.normalizeBarTime)(e.time);n<this.newest||(this.newest=n,this.currentBar={time:n,open:e.open,high:e.high,low:e.low,close:e.close,volume:e.volume??0,closed:!1,tickCount:0},this.builtFromTrades=!0,this.lastTradeAt=null)}setTimeZone(e,t=!1){this.bucket={timeZone:e??void 0},this.dateStamps=t}processTick(e){let n=(this.ringHead+this.ringCount)%this.ringCapacity;this.tickRing[n]=e,this.ringCount<this.ringCapacity?this.ringCount++:this.ringHead=(this.ringHead+1)%this.ringCapacity;let r=this.barFor(e.time);r!==null&&(this.newest=(0,t.normalizeBarTime)(r),this.lastTradeAt=e.time,!this.currentBar||this.currentBar.time!==r?(this.currentBar&&(this.currentBar.closed=!0,this.emit(`barClose`,this.currentBar)),this.currentBar={time:r,open:e.price,high:e.price,low:e.price,close:e.price,volume:e.volume,closed:!1,tickCount:1},this.builtFromTrades=!0):(this.currentBar.high=Math.max(this.currentBar.high,e.price),this.currentBar.low=Math.min(this.currentBar.low,e.price),this.currentBar.close=e.price,this.currentBar.volume+=e.volume,this.currentBar.tickCount++),this.emit(`bar`,this.currentBar))}processBar(e,n){let r=(0,t.normalizeBarTime)(e.time);if(r<this.newest){n&&this.emit(`correction`,{...e});return}if(this.newest=r,this.builtFromTrades=!1,n&&this.currentBar&&(0,t.normalizeBarTime)(this.currentBar.time)===r)this.currentBar={...e,closed:!0,tickCount:this.currentBar.tickCount+1},this.emit(`barClose`,this.currentBar),this.currentBar=null;else if(!n)this.currentBar={...e,closed:!1,tickCount:(this.currentBar?.tickCount??0)+1},this.emit(`bar`,this.currentBar);else{let t={...e,closed:!0,tickCount:1};this.emit(`barClose`,t),this.currentBar=null}}getCurrentBar(){return this.currentBar?{...this.currentBar}:null}getTickBuffer(){let e=Array(this.ringCount);for(let t=0;t<this.ringCount;t++)e[t]=this.tickRing[(this.ringHead+t)%this.ringCapacity];return e}reset(){this.currentBar=null,this.newest=-1/0,this.builtFromTrades=!1,this.lastTradeAt=null,this.ringHead=0,this.ringCount=0}barFor(e){let n=this.alignToTimeframe(e);if((0,t.normalizeBarTime)(n)>=this.newest)return n;if((0,t.normalizeBarTime)(e)<this.instantOf(this.newest))return null;let r=this.currentBar;return r!==null&&(0,t.normalizeBarTime)(r.time)===this.newest?r.time:this.newest}instantOf(e){return!this.dateStamps||!this.dateFrame?e:e-(0,t.offsetAt)(this.bucket.timeZone??0,e)*BS}builtOffTheBuckets(){let e=this.currentBar;return e===null||!this.builtFromTrades?!1:this.lastTradeAt===null?!this.startsABucket((0,t.normalizeBarTime)(e.time)):this.alignToTimeframe(this.lastTradeAt)!==e.time}startsABucket(e){return this.timeframeMs>0?this.dateStamps&&this.dateFrame?(0,t.timeframeBucketStart)(e,this.timeframe)===e:this.alignToTimeframe(e)===e:!0}alignToTimeframe(e){if(!(this.timeframeMs>0))return e;let n=(0,t.timeframeBucketStart)(e,this.timeframe,this.bucket);return!this.dateStamps||!this.dateFrame?n:n+(0,t.offsetAt)(this.bucket.timeZone??0,n)*BS}},US=class extends zS{config;attempt=0;timer=null;active=!1;constructor(e){super(),this.config={...t.DEFAULT_RECONNECT,...e}}schedule(e){if(!this.config.enabled||!this.active)return;if(this.cancel(),this.attempt++,this.attempt>this.config.maxRetries){this.emit(`giveUp`,{attempts:this.attempt-1}),this.active=!1;return}let t=this.computeDelay();this.emit(`attempt`,{attempt:this.attempt,delay:t}),this.timer=setTimeout(()=>{this.timer=null,this.active&&e()},t)}onConnected(){this.attempt=0,this.cancel(),this.emit(`success`,void 0)}start(){this.active=!0}stop(){this.active=!1,this.cancel(),this.attempt=0}cancel(){this.timer&&=(clearTimeout(this.timer),null)}getAttempt(){return this.attempt}isActive(){return this.active}computeDelay(){let e=this.config.baseDelay,t=this.config.backoffMultiplier**(this.attempt-1),n=Math.min(e*t,this.config.maxDelay),r=n*.25*(Math.random()*2-1);return Math.max(0,Math.round(n+r))}},WS=20,GS=class{price=null;previousClose=null;visible=!0;flashUntil=0;pricePrecision=null;locale=`en-US`;tag=null;setLocale(e){this.locale=e}setPrice(e,t){this.price!==null&&e!==this.price&&(this.flashUntil=Date.now()+300),t===void 0?e!==this.price&&(this.previousClose=this.price??e):this.previousClose=t,this.price=e}setVisible(e){this.visible=e}isVisible(){return this.visible}setPricePrecision(e){this.pricePrecision=e}getPrice(){return this.price}getTag(){return this.tag}render(e,t,n){this.renderLine(e,t,n),this.renderTag(e,t,n)}placed(t,n){let r=n.style?.lastPrice;if(!this.visible||this.price===null||r?.visible===!1)return null;let i=e.k(this.price,t),{chartRect:a}=t;return i<a.y||i>a.y+a.height?null:{y:i,color:this.previousClose===null||this.price>=this.previousClose?r?.up??n.candleUp??`#1fa874`:r?.down??n.candleDown??`#e8505b`}}renderLine(n,r,i){let a=this.placed(r,i);if(!a)return;let{y:o,color:s}=a,{chartRect:c}=r,l=i.style?.lastPrice,u=Date.now()<this.flashUntil,d=l?.width??1;n.setLineDash((0,t.lineDash)(l?.style??`dotted`,[4,3],d)),n.strokeStyle=s,n.lineWidth=d,n.globalAlpha=u?1:.7,n.beginPath(),e.y(n,c.x,c.x+c.width,Math.round(o)+.5,d),n.stroke(),n.setLineDash([]),n.globalAlpha=1}renderTag(e,n,r){this.tag=null;let i=this.placed(n,r);if(!i||this.price===null)return;let{y:a,color:o}=i,{chartRect:s}=n,c=s.x+s.width+1,l=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),u=n.formatPrice?n.formatPrice(this.price):(0,t.formatPrice)(this.price,l,this.locale);e.font=`bold 11px ${r.font.family}`;let d=(n.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2;e.fillStyle=o,A(e,c,a-WS/2,d,WS,r),this.tag={x:c,y:a-WS/2,width:d,height:WS,color:o},e.fillStyle=ne(o),e.textBaseline=`middle`,e.textAlign=`left`,e.fillText(u,c+7,a)}},KS=1e3,qS=10,JS=1440,YS=5e3,XS=2,ZS=864e5,QS=6e4,$S=[`tick`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],eC=new WeakMap;function tC(e){if(e instanceof sC||!e.supportedTimeframes?.length)return e;let t=eC.get(e);return t||(t=new sC(e,e.supportedTimeframes),eC.set(e,t)),t}function nC(e,n,r){if(n.includes(e))return e;let i=(0,t.pickBaseTimeframe)(e,n,{timeZone:r});return i&&Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(i))<=1440?i:null}function rC(e,n){if((0,t.tickBarCount)(n)!==null)return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`;let r=e.supportedTimeframes;return!r?.length||nC(n,r)!==null}function iC(e,n,r){let i=(0,t.parseTimeframe)(n),a=r!==void 0&&(0,t.timeframeSpansDays)(n)&&e%ZS!==0,o=a?e+(0,t.offsetAt)(r,e)*QS:e,s;if(i?.unit===`M`){let e=new Date(o);s=Date.UTC(e.getUTCFullYear(),e.getUTCMonth()+i.count,1)}else s=o+(0,t.timeframeToMs)(n);return a?(0,t.wallToUtc)(s,r):s}function aC(e,t){let n=t[0],r={time:e,open:n.open,high:n.high,low:n.low,close:n.close,volume:n.volume};for(let e=1;e<t.length;e++){let n=t[e];n.high>r.high&&(r.high=n.high),n.low<r.low&&(r.low=n.low),r.close=n.close,r.volume+=n.volume}return r}function oC(e,t){return aC(e,[...t.values()].sort((e,t)=>e.time-t.time))}var sC=class{name;fetchHistoryBefore;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;unsubscribe=[];live=null;bucket=null;parts=new Map;closedBuckets=new Map;tail=null;generation=0;zones=new Map;resolving=new Map;unanswered=new Map;constructor(e,t){this.inner=e,this.baseTimeframes=t,this.name=e.name,e.fetchHistoryBefore&&(this.fetchHistoryBefore=(e,t,n,r)=>this.historyBefore(e,t,n,r)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e=>this.resolveShared(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),e.fetchTrades&&(this.fetchTrades=e.fetchTrades.bind(e)),e.subscribeTrades&&(this.subscribeTrades=e.subscribeTrades.bind(e)),this.listen(`bar`,e=>this.onBar(e));for(let e of $S)this.listen(e,t=>this.emit(e,t.data))}baseFor(e){let t=nC(e,this.baseTimeframes);if(!t)throw RangeError(`${this.name} cannot serve the ${e} timeframe`);return t}connect(e){let t=this.baseFor(e.timeframe);this.generation++,this.resetBucket(),this.closedBuckets.clear(),this.live=t===e.timeframe?null:{symbol:e.symbol,target:e.timeframe,...this.planFor(e.timeframe,this.keptZone(e.symbol))},this.live&&this.resumeFromHistory(this.live),this.inner.connect({...e,timeframe:this.live?.base??t})}disconnect(){this.generation++,this.inner.disconnect(),this.resetBucket(),this.closedBuckets.clear(),this.live=null}getConnectionState(){return this.inner.getConnectionState()}async fetchHistory(e,t,n=500){if(this.baseFor(t)===t)return this.inner.fetchHistory(e,t,n);let r=this.generation,{plan:i,bars:a}=await this.baseBarsWithZone(e,t,async i=>{let a=this.baseBarsFor(t,i,n),o=await this.inner.fetchHistory(e,i,Math.min(a,KS));return this.extendBack(e,i,o,a,r)});return this.rememberTail(e,t,a,i),this.toTarget(a,t,n,i)}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.generation++;for(let e of this.unsubscribe)e();this.unsubscribe.length=0,this.listeners.clear(),this.inner.dispose()}bucketFor(e,t){let n=nC(t,this.baseTimeframes);return n===null||n===t?null:{...this.planFor(t,this.keptZone(e)).bucket}}waitsForZone(e){return typeof this.inner.resolveSymbol==`function`&&(0,t.timeframeFollowsDays)(e)}keptZone(e){return this.zones.get(e)??void 0}renewZone(e){let t=this.unanswered.get(e);if(!t)return;let n=t.zone,r=t.asked!==void 0&&this.resolving.get(e)===t.asked;n===void 0&&r||(this.unanswered.delete(e),n===void 0?this.zones.delete(e):this.zones.set(e,n))}async zoneFor(e){if(this.zones.has(e))return this.keptZone(e);let t,n=new Promise(e=>{t=setTimeout(()=>e(),YS)});try{await Promise.race([this.resolveShared(e),n])}catch{}finally{clearTimeout(t)}return this.zones.has(e)||(this.zones.set(e,null),this.unanswered.set(e,{asked:this.resolving.get(e)})),this.keptZone(e)}resolveShared(e){let t=this.resolving.get(e);if(t)return t;let n=this.inner.resolveSymbol.bind(this.inner),r=Promise.resolve().then(()=>n(e));this.resolving.set(e,r);let i=()=>{this.resolving.get(e)===r&&this.resolving.delete(e)};return r.then(t=>{this.keepZone(e,t),i()},i),r}keepZone(e,n){let r=(0,t.symbolTimeZone)(n),i=r&&(0,t.isValidTimeZone)(r)&&!(0,t.isUtcTimeZone)(r)?r:null,a=this.unanswered.get(e);a?this.unanswered.set(e,{...a,zone:i}):this.zones.has(e)||this.zones.set(e,i)}planFor(e,n){let r=this.baseFor(e),i=n!==void 0&&r!==e&&(0,t.timeframeFollowsDays)(e)?nC(e,this.baseTimeframes,n):null,a=i??r,o=i?n:void 0;return{base:a,zone:o,bucket:{timeZone:o,dates:(0,t.timeframeSpansDays)(a)}}}async historyBefore(e,t,n,r){let i=this.inner.fetchHistoryBefore.bind(this.inner);if(this.baseFor(t)===t)return i(e,t,n,r);let a=this.generation,{plan:o,bars:s}=await this.baseBarsWithZone(e,t,async o=>{let s=this.baseBarsFor(t,o,r),c=await i(e,o,n,Math.min(s,KS));return this.extendBack(e,o,c.filter(e=>e.time<n),s,a,1)});return this.toTarget(s,t,r,o)}async baseBarsWithZone(e,t,n){if(!this.waitsForZone(t)||this.zones.has(e)){let r=this.planFor(t,this.keptZone(e));return{plan:r,bars:await n(r.base)}}let r=this.planFor(t,void 0).base,i=n(r);i.catch(()=>{});let a=this.planFor(t,await this.zoneFor(e));return{plan:a,bars:await(a.base===r?i:n(a.base))}}baseBarsFor(e,n,r){return(r+1)*Math.ceil((0,t.timeframeToMs)(e)/(0,t.timeframeToMs)(n))}async extendBack(e,t,n,r,i,a=1){let o=this.inner.fetchHistoryBefore?.bind(this.inner),s=n,c=a;for(;o&&s.length>0&&s.length<r&&c<10&&i===this.generation;){let n=s[0].time,i=await o(e,t,n,Math.min(r-s.length,KS));c++;let a=i.filter(e=>e.time<n);if(a.length===0)break;s=a.concat(s)}return s}toTarget(e,n,r,i){if(e.length===0)return[];let a=(0,t.resampleBars)(e,n,i.bucket);return a.length>1&&a[0].time!==e[0].time&&a.shift(),a.length>r?a.slice(a.length-r):a}rememberTail(e,n,r,i){if(r.length===0)return;let a=(0,t.timeframeBucketStart)(r[r.length-1].time,n,i.bucket),o=r.length;for(;o>0&&(0,t.timeframeBucketStart)(r[o-1].time,n,i.bucket)===a;)o--;this.tail={symbol:e,target:n,zone:i.zone,bucket:a,bars:r.slice(o)}}resumeFromHistory(e){let t=this.tail;if(!(!t||t.symbol!==e.symbol||t.target!==e.target||t.zone!==e.zone)){this.bucket=t.bucket;for(let e of t.bars)this.parts.set(e.time,e)}}onBar(e){let n=this.live;if(!n){this.emit(`bar`,e.data);return}let{bar:r,closed:i}=e.data,a=(0,t.timeframeBucketStart)(r.time,n.target,n.bucket);if(this.bucket!==null&&a<this.bucket){i&&this.correctClosed(a,r);return}if(this.bucket!==null&&a>this.bucket){let e=this.composed();e&&this.emit(`bar`,{bar:e,closed:!0}),this.keepClosed(),this.resetBucket()}this.bucket=a,this.parts.set(r.time,r);let o=this.composed();if(!o)return;let s=(0,t.timeframeBucketStart)(iC(r.time,n.base,n.zone),n.target,n.bucket),c=i&&s!==a;this.emit(`bar`,{bar:o,closed:c}),c&&(this.keepClosed(),this.resetBucket(),this.bucket=s)}composed(){return this.bucket===null||this.parts.size===0?null:oC(this.bucket,this.parts)}correctClosed(e,t){let n=this.closedBuckets.get(e);n&&(n.set(t.time,t),this.emit(`bar`,{bar:oC(e,n),closed:!0}))}keepClosed(){if(!(this.bucket===null||this.parts.size===0)){this.closedBuckets.set(this.bucket,this.parts);for(let e of this.closedBuckets.keys()){if(this.closedBuckets.size<=2)break;this.closedBuckets.delete(e)}}}resetBucket(){this.bucket=null,this.parts=new Map}listen(e,t){let n=e=>t(e);this.inner.on(e,n),this.unsubscribe.push(()=>this.inner.off(e,n))}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},cC=1e3,lC=15e3,uC=[`tick`,`bar`,`barClose`,`snapshot`,`connectionChange`,`error`,`symbolInfo`],dC=class{bar=null;count=0;lastTime=-1/0;constructor(e){this.tradesPerBar=e}push(e){let t=[],n=!1;for(let r of e){if(this.bar)this.bar={...this.bar,high:Math.max(this.bar.high,r.price),low:Math.min(this.bar.low,r.price),close:r.price,volume:this.bar.volume+r.volume};else{let e=Math.max(r.time,this.lastTime+1);this.lastTime=e,this.bar={time:e,open:r.price,high:r.price,low:r.price,close:r.price,volume:r.volume},this.count=0}this.count++,n=!0,this.count>=this.tradesPerBar&&(t.push({bar:this.bar,closed:!0}),this.bar=null,n=!1)}return n&&this.bar&&t.push({bar:this.bar,closed:!1}),t}build(e){return this.bar=null,this.count=0,this.lastTime=-1/0,this.push(e).map(e=>e.bar)}},fC=class{name;supportedTimeframes;searchSymbols;resolveSymbol;subscribeQuotes;fetchNews;fetchTrades;subscribeTrades;listeners=new Map;tick=null;stopTrades=null;keepAlive=null;tickMode=!1;state=`disconnected`;constructor(e){this.inner=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes,e.searchSymbols&&(this.searchSymbols=e.searchSymbols.bind(e)),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol.bind(e)),e.subscribeQuotes&&(this.subscribeQuotes=e.subscribeQuotes.bind(e)),e.fetchNews&&(this.fetchNews=e.fetchNews.bind(e)),this.fetchTrades=e.fetchTrades.bind(e),this.subscribeTrades=e.subscribeTrades.bind(e);for(let t of uC)e.on(t,e=>{this.tickMode||this.emit(t,e.data)})}async fetchHistory(e,n,r){let i=(0,t.tickBarCount)(n);if(i===null)return this.inner.fetchHistory(e,n,r);let a=(await this.inner.fetchTrades(e,cC)).filter(gC).sort((e,t)=>e.time-t.time),o=new dC(i),s=o.build(a);return this.tick={symbol:e,builder:o,after:a.length?a[a.length-1].time:-1/0},r!==void 0&&r>0?s.slice(-r):s}fetchHistoryBefore(e,n,r,i){return(0,t.tickBarCount)(n)!==null||!this.inner.fetchHistoryBefore?Promise.resolve([]):this.inner.fetchHistoryBefore(e,n,r,i)}connect(e){this.disconnect();let n=(0,t.tickBarCount)(e.timeframe);if(n===null){this.tickMode=!1,this.inner.connect(e);return}this.tickMode=!0;let r=this.tick?.symbol===e.symbol?this.tick:{symbol:e.symbol,builder:new dC(n),after:-1/0};this.tick=r,this.stopTrades=this.inner.subscribeTrades(e.symbol,e=>{let t=e.filter(e=>gC(e)&&e.time>=r.after);for(let{bar:e,closed:n}of r.builder.push(t))this.emit(`bar`,{bar:e,closed:n}),this.emit(`tick`,{time:e.time,price:e.close,volume:e.volume})}),this.state=`connected`,this.emit(`connectionChange`,`connected`),this.keepAlive=setInterval(()=>this.emit(`connectionChange`,`connected`),lC)}disconnect(){this.tickMode?(this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.state=`disconnected`):this.inner.disconnect()}getConnectionState(){return this.tickMode?this.state:this.inner.getConnectionState()}dispose(){this.stopTrades?.(),this.stopTrades=null,this.keepAlive&&clearInterval(this.keepAlive),this.keepAlive=null,this.listeners.clear(),this.inner.dispose()}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}emit(e,t){let n=this.listeners.get(e);if(!n)return;let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}},pC=new WeakMap;function mC(e){if(e instanceof fC||!hC(e))return e;let t=pC.get(e);return t||(t=new fC(e),pC.set(e,t)),t}function hC(e){return typeof e.fetchTrades==`function`&&typeof e.subscribeTrades==`function`}function gC(e){return Number.isFinite(e?.time)&&Number.isFinite(e?.price)&&Number.isFinite(e?.volume)}var _C=Symbol(`tradecanvas.sourceAdapter`),vC=new WeakSet;function yC(e){return vC.has(e)}var bC=(e,t)=>`${e}\u0000${t}`;function xC(e){return typeof e.getBars==`function`&&typeof e.subscribeBars==`function`}function SC(e){if(e.adapter&&e.feed)throw TypeError(`A stream takes an adapter or a feed, not both`);if(e.adapter)return e.adapter;if(e.feed)return TC(e.feed);throw TypeError(`A stream needs an adapter or a feed`)}function CC(e,t,n){for(let r of n){let n=t[r];typeof n==`function`&&(e[r]=n.bind(t))}}var wC=[`resolveSymbol`,`searchSymbols`,`subscribeQuotes`,`fetchNews`,`fetchTrades`,`subscribeTrades`];function TC(e){let t=e[_C];if(t)return t;let n=new EC(e);return vC.add(n),n}var EC=class{name;supportedTimeframes;fetchHistoryBefore;state=`disconnected`;listeners=new Map;unsubscribe=null;requests=new Map;streamed=null;constructor(e){this.feed=e,this.name=e.name,e.supportedTimeframes&&(this.supportedTimeframes=e.supportedTimeframes),e.pagesBack!==!1&&(this.fetchHistoryBefore=(e,t,n,r)=>this.feed.getBars({symbol:e,timeframe:t,countBack:r,before:n,signal:this.signalFor(e,t)})),CC(this,e,wC)}fetchHistory(e,t,n=500){return this.feed.getBars({symbol:e,timeframe:t,countBack:n,signal:this.signalFor(e,t)})}fetchStreamHistory(e,t){return this.streamed=bC(e.symbol,e.timeframe),this.fetchHistory(e.symbol,e.timeframe,t)}connect(e){this.subscribe({symbol:e.symbol,timeframe:e.timeframe})}subscribe(e,t){this.stopSubscription(),this.streamed=bC(e.symbol,e.timeframe);let n=!0,r=!1,i=null;this.unsubscribe=()=>{n=!1,i?.()};let a=e=>{this.setState(e),t?.connection(e)},o=this.feed.subscribeBars(e,{bar:(e,r)=>{n&&(this.emit(`bar`,{bar:e,closed:r}),t?.bar(e,r))},tick:e=>{n&&(this.emit(`tick`,e),t?.tick(e))},connection:e=>{n&&(r=!0,a(e))},symbolInfo:e=>{n&&(this.emit(`symbolInfo`,e),t?.symbolInfo(e))},error:e=>{n&&(this.emit(`error`,{message:e}),t?.error(e))}});if(!n){o();return}i=o,r||a(`connected`)}disconnect(){this.stopSubscription(),this.streamed!==null&&(this.requests.get(this.streamed)?.abort(),this.requests.delete(this.streamed),this.streamed=null),this.state=`disconnected`}getConnectionState(){return this.state}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}signalFor(e,t){let n=bC(e,t),r=this.requests.get(n);return r||(r=new AbortController,this.requests.set(n,r)),r.signal}stopSubscription(){let e=this.unsubscribe;this.unsubscribe=null,e?.()}setState(e){this.state=e,this.emit(`connectionChange`,e)}emit(e,t){let n={type:e,data:t,timestamp:Date.now()};for(let t of[...this.listeners.get(e)??[]])t(n)}};function DC(e){let t={name:e.name,...e.supportedTimeframes?{supportedTimeframes:e.supportedTimeframes}:{},pagesBack:typeof e.fetchHistoryBefore==`function`,getBars:async({symbol:t,timeframe:n,countBack:r,before:i})=>i===void 0?e.fetchHistory(t,n,r):e.fetchHistoryBefore?e.fetchHistoryBefore(t,n,i,r):[],subscribeBars:(t,n)=>OC(e,t,n),[_C]:e};return CC(t,e,wC),t}function OC(e,t,n){let r=[[`bar`,e=>{let{bar:t,closed:r}=e.data;n.bar(t,r)}],[`tick`,e=>n.tick(e.data)],[`connectionChange`,e=>n.connection(e.data)],[`symbolInfo`,e=>n.symbolInfo(e.data)],[`error`,e=>n.error(e.data?.message??`Adapter error`)]];for(let[t,n]of r)e.on(t,n);return e.connect({symbol:t.symbol,timeframe:t.timeframe}),()=>{for(let[t,n]of r)e.off(t,n);e.disconnect()}}function kC(e){let t=SC(e),n=!yC(t),r=tC(t),i=r instanceof sC?r:null,a=mC(r);return a instanceof EC?new AC(a,i,n):new jC(a,i,n)}var AC=class{subscriber=null;constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.subscriber=e}getBars(e,t){return this.adapter.fetchStreamHistory(e,t)}subscribeBars(e){this.adapter.subscribe(e,this.subscriber??void 0)}unsubscribe(){this.adapter.disconnect()}release(){this.subscriber=null}},jC=class{unlisten=[];constructor(e,t,n){this.adapter=e,this.resampler=t,this.watchSilence=n}listen(e){this.hear(`connectionChange`,t=>e.connection(t.data)),this.hear(`tick`,t=>e.tick(t.data)),this.hear(`bar`,t=>{let{bar:n,closed:r}=t.data;e.bar(n,r)}),this.hear(`error`,t=>e.error(t.data?.message??`Adapter error`));try{this.hear(`symbolInfo`,t=>e.symbolInfo(t?.data))}catch{}}getBars(e,t){return this.adapter.fetchHistory(e.symbol,e.timeframe,t)}subscribeBars(e){this.adapter.connect({symbol:e.symbol,timeframe:e.timeframe})}unsubscribe(){this.adapter.disconnect()}release(){for(let e of this.unlisten)e();this.unlisten=[]}hear(e,t){this.adapter.on(e,t),this.unlisten.push(()=>this.adapter.off(e,t))}},MC=2e4,NC=6e4,PC=3e4,FC=500,IC=864e5;function LC(e,n){if(!n)return e;let{time:r,open:i,high:a,low:o,close:s,volume:c}=n;return[...e,{time:(0,t.normalizeBarTime)(r)/(0,t.barTimeUnit)(e),open:i,high:a,low:o,close:s,volume:c}]}function RC(e,n,r){return(0,t.timeframeBucketStart)(e,n,{timeZone:r})===e&&(0,t.timeframeBucketStart)(e,n)!==e}var zC=class extends zS{config=null;source=null;aggregator=null;reconnector;priceLine=new GS;state=`disconnected`;lastPrice=null;previousClose=null;sentPreviousClose=null;previousCloseTime=null;heartbeatTimer=null;lastMessageTime=0;connectSeq=0;timeZone=null;historyEnd=null;constructor(){super(),this.reconnector=new US,this.wireReconnector()}async connect(e){this.disconnect();let n=kC(e);n.resampler?.renewZone(e.symbol),this.config={...t.DEFAULT_STREAM_CONFIG,...e},this.source=n,this.aggregator=new HS(e.timeframe),this.historyEnd=null,this.applyTickZone(),this.reconnector.removeAllListeners(),this.reconnector.stop(),this.reconnector=new US(e.reconnect??t.DEFAULT_RECONNECT),this.wireReconnector(),this.aggregator.on(`bar`,e=>{this.emit(`barUpdate`,e),this.updatePrice(e.close)}),this.aggregator.on(`barClose`,e=>{this.setPreviousClose(e),this.emit(`barClose`,e)}),this.aggregator.on(`correction`,e=>{(0,t.normalizeBarTime)(e.time)===this.previousCloseTime&&(this.previousClose=e.close),this.emit(`barCorrection`,e)}),n.listen(this.subscriber()),this.reconnector.start(),await this.doConnect()}disconnect(){this.connectSeq++,this.reconnector.stop(),this.stopHeartbeat(),this.source&&=(this.source.release(),this.source.unsubscribe(),null),this.aggregator?.reset(),this.aggregator?.removeAllListeners(),this.aggregator=null,this.config=null,this.historyEnd=null,this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,this.setState(`disconnected`)}async switchTo(e,t){!this.config||!this.source||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.aggregator?.reset(),this.aggregator?.setTimeframe(t),this.lastPrice=null,this.previousClose=null,this.previousCloseTime=null,this.sentPreviousClose=null,(e!==this.config.symbol||t!==this.config.timeframe)&&this.source.resampler?.renewZone(e),this.config.symbol=e,this.config.timeframe=t,await this.doConnect())}getConnectionState(){return this.state}setTimeZone(e){if(e!==null&&!(0,t.isValidTimeZone)(e))throw RangeError(`Unknown time zone: ${e}`);this.timeZone=e,this.applyTickZone()}getConnectionInfo(){return{state:this.state,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}}getLastPrice(){return this.lastPrice}applyTickZone(){let e=this.config;if(!this.aggregator||!e)return;let t=this.historyEnd,n=t!==null&&t%IC===0,r=this.source?.resampler?.bucketFor(e.symbol,e.timeframe);if(r){let e=r.dates===!0&&n;this.aggregator.setTimeZone(r.timeZone??(e?this.timeZone:null),e);return}this.aggregator.setTimeZone(this.tickZone(e.timeframe,t),n)}tickZone(e,n){let r=this.timeZone;return r===null||(0,t.timeframeSpansDays)(e)||n!==null&&RC(n,e,r)?r:null}async doConnect(){if(!this.config||!this.source)return;let e=++this.connectSeq,n={symbol:this.config.symbol,timeframe:this.config.timeframe};this.setState(`connecting`);try{let r=await this.source.getBars(n,this.config.historyLimit??FC);if(e!==this.connectSeq||!this.source)return;let i=r.length>0?r[r.length-1]:null;this.historyEnd=i?(0,t.normalizeBarTime)(i.time):null,this.applyTickZone(),this.seedAggregator(i);let a=this.formingAfter(i);i&&!a&&(this.setPreviousClose(i),this.updatePrice(i.close)),this.emit(`snapshot`,LC(r,a)),this.source.subscribeBars(n),this.startHeartbeat()}catch(t){if(e!==this.connectSeq)return;let n=t instanceof Error?t.message:String(t);this.emit(`error`,{message:n,code:`CONNECT_FAILED`}),this.setState(`error`),this.reconnector.schedule(()=>this.doConnect())}}wireReconnector(){this.reconnector.on(`attempt`,({attempt:e,delay:t})=>{this.state=`reconnecting`,this.emit(`connectionChange`,{state:`reconnecting`,reconnectAttempt:e,lastMessageTime:this.lastMessageTime})}),this.reconnector.on(`giveUp`,({attempts:e})=>{this.setState(`error`),this.emit(`error`,{message:`Reconnection failed after ${e} attempts`,code:`RECONNECT_EXHAUSTED`})})}subscriber(){return{connection:e=>this.onConnection(e),tick:e=>this.onTick(e),bar:(e,t)=>this.onBar(e,t),error:e=>this.emit(`error`,{message:e??`Adapter error`}),symbolInfo:e=>{e&&typeof e==`object`&&this.emit(`symbolInfo`,e)}}}onConnection(e){this.lastMessageTime=Date.now(),e===`connected`?(this.reconnector.onConnected(),this.setState(`connected`)):(e===`disconnected`||e===`error`)&&this.reconnector.schedule(()=>this.doConnect())}onTick(e){this.lastMessageTime=Date.now(),this.emit(`tick`,e),(e.bid!==void 0||e.ask!==void 0)&&this.emit(`quote`,{bid:e.bid,ask:e.ask}),this.config?.aggregateTicks&&this.aggregator?this.aggregator.processTick(e):this.updatePrice(e.price)}onBar(e,t){this.lastMessageTime=Date.now(),this.aggregator?.processBar(e,t)}setPreviousClose(e){this.previousClose=e.close,this.previousCloseTime=(0,t.normalizeBarTime)(e.time)}seedAggregator(e){this.aggregator&&(this.aggregator.seed(e?e.time:-1/0),e&&this.config?.aggregateTicks&&this.aggregator.resume(e))}formingAfter(e){let n=this.aggregator?.getCurrentBar()??null;return!n||e&&(0,t.normalizeBarTime)(n.time)<=(0,t.normalizeBarTime)(e.time)?null:n}updatePrice(e){e===this.lastPrice&&this.previousClose===this.sentPreviousClose||(this.lastPrice=e,this.sentPreviousClose=this.previousClose,this.priceLine.setPrice(e,this.previousClose??void 0),this.emit(`priceChange`,{price:e,previousClose:this.previousClose}))}setState(e){this.state!==e&&(this.state=e,this.emit(`connectionChange`,{state:e,reconnectAttempt:this.reconnector.getAttempt(),lastMessageTime:this.lastMessageTime}))}wake(e){!this.source||!this.config||this.state===`connecting`||this.state===`disconnected`||this.state===`connected`&&e===`visible`&&(!this.source.watchSilence||Date.now()-this.lastMessageTime<=MC)||(this.reconnector.stop(),this.source.unsubscribe(),this.reconnector.start(),this.doConnect())}startHeartbeat(){this.stopHeartbeat(),this.heartbeatTimer=setInterval(()=>{this.source?.watchSilence===!0&&Date.now()-this.lastMessageTime>NC&&this.state===`connected`&&(this.emit(`error`,{message:`Heartbeat timeout`,code:`HEARTBEAT_TIMEOUT`}),this.source?.unsubscribe(),this.reconnector.schedule(()=>this.doConnect()))},PC)}stopHeartbeat(){this.heartbeatTimer&&=(clearInterval(this.heartbeatTimer),null)}dispose(){this.disconnect(),this.removeAllListeners()}},BC=class extends zS{data;speed;index;status=`idle`;timer=null;constructor(e){if(super(),e.data.length===0)throw Error(`ReplayController requires non-empty data`);this.data=e.data,this.speed=Math.max(.01,e.speed??1),this.index=Math.max(0,Math.min(e.startIndex??0,e.data.length)),e.autoStart&&this.start()}getStatus(){return this.status}getIndex(){return this.index}getTotal(){return this.data.length}getPrefix(){return this.data.slice(0,this.index)}start(){if(this.status!==`playing`){if(this.index>=this.data.length){this.transition(`finished`);return}this.transition(`playing`),this.scheduleNext()}}pause(){this.status===`playing`&&(this.clearTimer(),this.transition(`paused`))}resume(){this.status===`paused`&&this.start()}stop(){this.clearTimer(),this.index=0,this.transition(`idle`)}step(e=1){if(!(e<=0)){this.clearTimer();for(let t=0;t<e;t++)if(!this.emitNext())return;this.status!==`finished`&&this.transition(`paused`)}}seek(e){let t=Math.max(0,Math.min(e,this.data.length));this.clearTimer(),this.index=t;let n=t>=this.data.length?`finished`:`paused`;this.transition(n)}setSpeed(e){this.speed=Math.max(.01,e),this.status===`playing`&&(this.clearTimer(),this.scheduleNext())}destroy(){this.clearTimer(),this.removeAllListeners()}scheduleNext(){let e=1e3/this.speed;this.timer=setTimeout(()=>{this.timer=null,this.status===`playing`&&this.emitNext()&&this.scheduleNext()},e)}emitNext(){if(this.index>=this.data.length)return this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1;let e=this.data[this.index],t=this.index;return this.index++,this.emit(`bar`,{bar:e,index:t,total:this.data.length}),this.index>=this.data.length?(this.transition(`finished`),this.emit(`finished`,{total:this.data.length}),!1):!0}clearTimer(){this.timer!==null&&(clearTimeout(this.timer),this.timer=null)}transition(e){this.status!==e&&(this.status=e,this.emit(`stateChange`,{status:e,index:this.index,total:this.data.length}))}};function VC(e){if(!Array.isArray(e)||e.length<6)return null;let t=e[0];if(typeof t!=`number`||!Number.isFinite(t))return null;let n=UC(e[1]),r=UC(e[2]),i=UC(e[3]),a=UC(e[4]),o=UC(e[5]);return n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}function HC(e){if(!WC(e))return null;let t=e.t;if(typeof t!=`number`||!Number.isFinite(t))return null;let n=UC(e.o),r=UC(e.h),i=UC(e.l),a=UC(e.c),o=UC(e.v);if(n===null||r===null||i===null||a===null||o===null)return null;let s=typeof e.x==`boolean`?e.x:!1;return{bar:{time:t,open:n,high:r,low:i,close:a,volume:o},closed:s}}function UC(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function WC(e){return typeof e==`object`&&!!e}function Q(e){let t=typeof e==`string`?Number(e):e;return typeof t==`number`&&Number.isFinite(t)?t:void 0}function GC(e){let n=e&&typeof e==`object`&&`data`in e?e.data:e;if(!n||typeof n!=`object`)return null;let r=n;return r.e===`24hrMiniTicker`?(0,t.readQuote)({symbol:r.s,last:Q(r.c),open:Q(r.o),high:Q(r.h),low:Q(r.l),volume:Q(r.v),time:Q(r.E)}):null}function KC(e){if(!e||typeof e!=`object`)return null;let n=e;return(0,t.readQuote)({symbol:n.symbol,last:Q(n.lastPrice),change:Q(n.priceChange),changePercent:Q(n.priceChangePercent),open:Q(n.openPrice),high:Q(n.highPrice),low:Q(n.lowPrice),prevClose:Q(n.prevClosePrice),volume:Q(n.volume),bid:Q(n.bidPrice),ask:Q(n.askPrice),time:Q(n.closeTime)})}function qC(e){if(!e||typeof e!=`object`)return null;let t=e,n=Q(t.T),r=Q(t.p),i=Q(t.q);return n!==void 0&&r!==void 0&&i!==void 0?{time:n,price:r,volume:i}:null}var JC=64,YC=(e,t)=>`${e}|${t}`,XC=class{last=new Map;serve(e,t,n){if(!Array.isArray(n)||n.length===0)return;let r=n[n.length-1],i=Number(r?.time);if(!Number.isFinite(i))return;let a=YC(e,t);this.last.delete(a),this.last.set(a,{time:i,close:Number(r?.close??NaN)}),this.last.size>JC&&this.last.delete(this.last.keys().next().value)}lastBar(e,t){return this.last.get(YC(e,t))}},ZC=class{newest=-1/0;servedClose=null;served=new XC;serve(e,t,n){this.served.serve(e,t,n)}reset(e,n){let r=this.served.lastBar(e,n);this.newest=r===void 0?-1/0:(0,t.normalizeBarTime)(r.time),this.servedClose=r?.close??null}admit(e,n=!1){let r=(0,t.normalizeBarTime)(e.time);return Number.isFinite(r)?r<this.newest||r===this.newest&&n&&e.close===this.servedClose?!1:(this.servedClose=null,this.newest=r,!0):!0}},QC={"1s":`1s`,"1m":`1m`,"3m":`3m`,"5m":`5m`,"15m":`15m`,"30m":`30m`,"1h":`1h`,"2h":`2h`,"4h":`4h`,"6h":`6h`,"8h":`8h`,"12h":`12h`,"1d":`1d`,"3d":`3d`,"1w":`1w`,"1M":`1M`},$C=1e3,ew=200,tw=[`USDT`,`USDC`,`FDUSD`,`BTC`,`ETH`,`BNB`,`EUR`,`TRY`,`BRL`,`JPY`];function nw(e){let t=e.currency?tw.indexOf(e.currency):-1;return t<0?0:40-t*3}function rw(e){if(typeof e.symbol!=`string`||e.status!==`TRADING`)return null;let n=typeof e.baseAsset==`string`?e.baseAsset:``,r=typeof e.quoteAsset==`string`?e.quoteAsset:``,i=Array.isArray(e.filters)?e.filters.find(e=>typeof e==`object`&&!!e&&e.filterType===`PRICE_FILTER`&&typeof e.tickSize==`string`):void 0,a={symbol:e.symbol,description:n&&r?`${n} / ${r}`:e.symbol,exchange:`Binance`,type:`crypto`};return i&&(a.pricePrecision=(0,t.stepDecimals)(i.tickSize),a.minTick=Number(i.tickSize)),a.timeZone=`UTC`,r&&(a.currency=r),a}function iw(e){let t=e?.symbols;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=rw(e);t&&n.push(t)}return n}var aw=class{name=`binance`;supportedTimeframes=Object.keys(QC);ws=null;state=`disconnected`;listeners=new Map;config=null;restBase;wsBase;symbolList=null;newestBar=new ZC;constructor(e){this.restBase=e?.restBase??`https://api.binance.com/api/v3`,this.wsBase=e?.wsBase??`wss://stream.binance.com:9443/ws`}connect(e){this.config=e,this.newestBar.reset(e.symbol,e.timeframe),this.connectWs()}disconnect(){if(this.ws){let e=this.ws;e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,e.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n=500){let r=await this.fetchKlines(e,t,n,``);return this.newestBar.serve(e,t,r),r}async searchSymbols(e,n){return(0,t.rankSymbols)(await this.loadSymbols(),e,n?.limit??50,nw)}async resolveSymbol(e){if(this.symbolList){let t=(await this.symbolList.catch(()=>null))?.find(t=>t.symbol===e);if(t)return t}let t=await fetch(`${this.restBase}/exchangeInfo?symbol=${encodeURIComponent(e)}`);return t.ok?iw(await t.json())[0]??null:null}loadSymbols(){return this.symbolList||(this.symbolList=(async()=>{let e=await fetch(`${this.restBase}/exchangeInfo`);if(!e.ok)throw Error(`Binance REST error: ${e.status}`);return iw(await e.json())})(),this.symbolList.catch(()=>{this.symbolList=null})),this.symbolList}subscribeQuotes(e,t){let n=[...new Set(e.map(e=>e.trim().toUpperCase()))].filter(e=>/^[A-Z0-9]{2,30}$/.test(e)).slice(0,ew);if(n.length===0)return()=>{};let r=!1,i=null,a=null,o=0,s=new Set,c=new AbortController;(async()=>{let e=await fetch(`${this.restBase}/ticker/24hr?symbols=${encodeURIComponent(JSON.stringify(n))}`,{signal:c.signal});if(e.ok)return e.json();let t=await fetch(`${this.restBase}/ticker/24hr`,{signal:c.signal});if(!t.ok)return[];let r=await t.json(),i=new Set(n);return Array.isArray(r)?r.filter(e=>i.has(e?.symbol)):[]})().then(e=>{if(r||!Array.isArray(e))return;let n=e.map(KC).filter(e=>e!==null&&!s.has(e.symbol));n.length>0&&t(n)}).catch(()=>{});let l=this.wsBase.replace(/\/ws\/?$/,``),u=()=>{if(!r){try{i=new WebSocket(`${l}/stream?streams=${n.map(e=>`${e.toLowerCase()}@miniTicker`).join(`/`)}`)}catch{d();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=GC(n);!i||r||(s.add(i.symbol),t([i]))},i.onclose=()=>{i=null,d()}}},d=()=>{r||(a=setTimeout(u,Math.min(3e4,1e3*2**o++)))};return u(),()=>{r=!0,c.abort(),a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=await fetch(`${this.restBase}/aggTrades?symbol=${encodeURIComponent(e.toUpperCase())}&limit=${n}`);if(!r.ok)throw Error(`Binance aggTrades ${r.status}`);let i=await r.json();return Array.isArray(i)?i.map(qC).filter(e=>e!==null):[]}subscribeTrades(e,t){let n=`${e.trim().toLowerCase()}@aggTrade`;if(!/^[a-z0-9]{2,30}@aggTrade$/.test(n))return()=>{};let r=!1,i=null,a=null,o=0,s=()=>{if(!r){try{i=new WebSocket(`${this.wsBase}/${n}`)}catch{c();return}i.onopen=()=>{o=0},i.onmessage=e=>{let n;try{n=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}let i=qC(n);i&&!r&&t([i])},i.onclose=()=>{i=null,c()}}},c=()=>{r||(a=setTimeout(s,Math.min(3e4,1e3*2**o++)))};return s(),()=>{r=!0,a&&clearTimeout(a),i&&=(i.onopen=null,i.onmessage=null,i.onclose=null,i.close(),null)}}fetchHistoryBefore(e,t,n,r=500){return this.fetchKlines(e,t,Math.min(r,$C),`&endTime=${Math.floor(n)-1}`)}async fetchKlines(e,t,n,r){let i=QC[t]??`15m`,a=`${this.restBase}/klines?symbol=${e}&interval=${i}&limit=${n}${r}`,o=await fetch(a);if(!o.ok)throw Error(`Binance REST error: ${o.status}`);let s=await o.json();if(!Array.isArray(s))return[];let c=[];for(let e of s){let t=VC(e);t&&c.push(t)}return c}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}connectWs(){if(!this.config)return;let e=`${this.config.symbol.toLowerCase()}@kline_${QC[this.config.timeframe]??`15m`}`,t=`${this.wsBase}/${e}`;this.setState(`connecting`);try{this.ws=new WebSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws.onopen=()=>{this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`)},this.ws.onmessage=e=>{let t;try{t=JSON.parse(typeof e.data==`string`?e.data:``)}catch{return}typeof t==`object`&&t&&t.e===`kline`&&this.handleKline(t.k)},this.ws.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},this.ws.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}handleKline(e){let t=HC(e);if(!t)return;let{bar:n,closed:r}=t,i=this.newestBar.admit(n,r);this.emitEvent(`bar`,{bar:n,closed:r}),i&&this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume})}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},ow=class{name=`mock`;state=`disconnected`;listeners=new Map;config=null;options;tickTimer=null;currentPrice;oldestOpen=new Map;forming=null;formingTimeframe=null;constructor(e){this.options={basePrice:100,volatility:1.5,tickInterval:2e3,historySize:500,...e},this.currentPrice=this.options.basePrice}connect(e){this.config=e,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startTicking()}disconnect(){this.stopTicking(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}subscribeQuotes(e,t){let n=[...new Set(e)].map(e=>{let t=this.options.basePrice*(.5+sw(e)%1e3/1e3);return{symbol:e,open:t,last:t,high:t,low:t,volume:0}});if(n.length===0)return()=>{};let r=this.options.volatility/100,i=()=>t(n.map(e=>({symbol:e.symbol,last:e.last,open:e.open,high:e.high,low:e.low,volume:e.volume,change:e.last-e.open,changePercent:(e.last-e.open)/e.open*100,time:Date.now()})));i();let a=setInterval(()=>{for(let e of n)e.last=Math.max(e.open*.01,e.last*(1+(Math.random()-.5)*r)),e.high=Math.max(e.high,e.last),e.low=Math.min(e.low,e.last),e.volume+=Math.random()*100;i()},this.options.tickInterval);return()=>clearInterval(a)}async fetchTrades(e,t=1e3){let n=Math.max(1,Math.min(1e3,Math.floor(t))),r=Date.now(),i=this.options.volatility/1e3,a=this.options.basePrice*(.5+sw(e)%1e3/1e3),o=[];for(let e=n-1;e>=0;e--)a=Math.max(a*.5,a*(1+(Math.random()-.5)*i)),o.push({time:r-e*1e3,price:a,volume:Math.random()*5});return o}subscribeTrades(e,t){let n=this.options.volatility/1e3,r=this.options.basePrice*(.5+sw(e)%1e3/1e3),i=setInterval(()=>{let e=[];for(let t=0;t<3;t++)r=Math.max(r*.5,r*(1+(Math.random()-.5)*n)),e.push({time:Date.now(),price:r,volume:Math.random()*5});t(e)},this.options.tickInterval);return()=>clearInterval(i)}async fetchHistory(e,t,n){let r=this.options.historyGenerator?this.options.historyGenerator(e,t,n??this.options.historySize):this.generateHistory(t,n??this.options.historySize);return r.length>0&&this.oldestOpen.set(e,r[0].open),this.forming=r.length>0?{...r[r.length-1]}:null,this.formingTimeframe=t,r}async fetchHistoryBefore(e,n,r,i){let a=(0,t.timeframeToMs)(n),o=this.options.volatility/100,s=Array(Math.max(0,i)),c=this.oldestOpen.get(e)??this.options.basePrice;for(let e=0;e<i;e++){let t=c/(1+(Math.random()-.52)*o),n=Math.max(t,c)+Math.random()*c*o*.3,l=Math.max(0,Math.min(t,c)-Math.random()*c*o*.3),u=Math.floor(1e4+Math.random()*1e5);s[i-1-e]={time:r-(e+1)*a,open:t,high:n,low:l,close:c,volume:u},c=t}return this.oldestOpen.set(e,c),s}async searchSymbols(e,n){return(0,t.rankSymbols)(this.options.symbols??[],e,n?.limit??50)}async resolveSymbol(e){return this.options.symbols?.find(t=>t.symbol===e)??null}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}generateHistory(e,n){let r=[],i=(0,t.timeframeToMs)(e),a=Math.floor(Date.now()/i)*i,o=this.options.basePrice,s=this.options.volatility/100;for(let e=n-1;e>=0;e--){let t=a-e*i,n=(Math.random()-.48)*o*s,c=o;o+=n;let l=Math.max(c,o)+Math.random()*o*s*.3,u=Math.min(c,o)-Math.random()*o*s*.3,d=Math.floor(1e4+Math.random()*1e5);r.push({time:t,open:c,high:l,low:u,close:o,volume:d})}return this.currentPrice=o,r}startTicking(){this.stopTicking();let e=this.options.tickInterval??2e3;this.tickTimer=setInterval(()=>{if(this.state!==`connected`||!this.config)return;let e=this.options.volatility/100,t=(Math.random()-.48)*this.currentPrice*e*.3;this.currentPrice+=t;let n=Date.now(),r=this.tickBar(n,t,Math.floor(100+Math.random()*5e3));this.emitEvent(`bar`,{bar:r,closed:!1}),this.emitEvent(`tick`,{time:n,price:this.currentPrice,volume:r.volume})},e)}tickBar(e,n,r){let i=this.config.timeframe,a=(0,t.timeframeToMs)(i),o=Math.floor(e/a)*a,s=this.currentPrice,c=this.formingTimeframe===i?this.forming:null,l=Math.abs(n)*.2,u;if(c&&c.time===o)u={time:o,open:c.open,high:Math.max(c.high,s+l),low:Math.min(c.low,s-l),close:s,volume:c.volume+r};else{let e=c?.close??s-n;u={time:o,open:e,high:Math.max(e,s)+l,low:Math.min(e,s)-l,close:s,volume:r}}return this.forming=u,this.formingTimeframe=i,{...u}}stopTicking(){this.tickTimer&&=(clearInterval(this.tickTimer),null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function sw(e){let t=0;for(let n=0;n<e.length;n++)t=t*31+e.charCodeAt(n)>>>0;return t}var cw=class{name;supportedTimeframes;ws=null;state=`disconnected`;config=null;listeners=new Map;opts;newestBar=new ZC;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.newestBar.reset(e.symbol,e.timeframe),this.openSocket()}disconnect(){let e=this.config;if(this.ws){if(this.opts.unsubscribeMessage&&e)try{this.sendMessage(this.opts.unsubscribeMessage(e))}catch{}let t=this.ws;t.onopen=null,t.onmessage=null,t.onerror=null,t.onclose=null,t.close(),this.ws=null}this.setState(`disconnected`)}getConnectionState(){return this.state}fetchHistory(e,t,n){let r=this.opts.fetchHistory(e,t,n??this.opts.defaultHistoryLimit??500);return Promise.resolve(r).then(n=>(this.newestBar.serve(e,t,n),n))}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}openSocket(){let e=this.config;if(!e)return;let t=this.opts.wsUrl(e);this.setState(`connecting`);let n;try{n=this.createSocket(t)}catch{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket creation failed`}),this.emitEvent(`connectionChange`,`error`);return}this.ws=n,n.onopen=()=>{if(this.setState(`connected`),this.emitEvent(`connectionChange`,`connected`),this.opts.subscribeMessage)try{this.sendMessage(this.opts.subscribeMessage(e))}catch{}},n.onmessage=t=>{let n=this.decode(t.data);if(n===void 0)return;let r;try{r=this.opts.parseMessage(n,e)}catch{return}if(!r)return;let i=r.bar?this.newestBar.admit(r.bar,r.closed??!1):!1;r.bar&&this.emitEvent(`bar`,{bar:r.bar,closed:r.closed??!1}),r.tick?this.emitEvent(`tick`,r.tick):r.bar&&i&&this.emitEvent(`tick`,{time:Date.now(),price:r.bar.close,volume:r.bar.volume})},n.onerror=()=>{this.setState(`error`),this.emitEvent(`error`,{message:`WebSocket error`})},n.onclose=()=>{this.setState(`disconnected`),this.emitEvent(`connectionChange`,`disconnected`)}}sendMessage(e){e===void 0||!this.ws||this.ws.send(typeof e==`string`?e:JSON.stringify(e))}decode(e){if(this.opts.decode)try{return this.opts.decode(e)}catch{return}if(typeof e==`string`)try{return JSON.parse(e)}catch{return}return e}createSocket(e){if(this.opts.socketFactory)return this.opts.socketFactory(e);let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);return new t(e)}setState(e){this.state=e}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}},lw=class{name;supportedTimeframes;state=`disconnected`;listeners=new Map;config=null;timer=null;lastBarTime=0;served=new XC;opts;fetchHistoryBefore;searchSymbols;resolveSymbol;constructor(e){this.opts=e,this.name=e.name,this.supportedTimeframes=e.supportedTimeframes;let t=e.fetchHistoryBefore;t&&(this.fetchHistoryBefore=(e,n,r,i)=>t(e,n,r,i)),e.searchSymbols&&(this.searchSymbols=e.searchSymbols),e.resolveSymbol&&(this.resolveSymbol=e.resolveSymbol)}connect(e){this.config=e,this.lastBarTime=this.served.lastBar(e.symbol,e.timeframe)?.time??0,this.state=`connected`,this.emitEvent(`connectionChange`,`connected`),this.startPolling()}disconnect(){this.stopPolling(),this.state=`disconnected`,this.emitEvent(`connectionChange`,`disconnected`)}getConnectionState(){return this.state}async fetchHistory(e,t,n){let r=await this.opts.fetchBars(e,t,n??this.opts.defaultHistoryLimit??500);return this.served.serve(e,t,r),r}on(e,t){let n=this.listeners.get(e);n||(n=new Set,this.listeners.set(e,n)),n.add(t)}off(e,t){this.listeners.get(e)?.delete(t)}dispose(){this.disconnect(),this.listeners.clear()}async poll(){let e=this.config;if(!e||this.state!==`connected`)return;let t;try{t=await this.opts.fetchBars(e.symbol,e.timeframe,this.opts.pollLimit??2)}catch(e){this.emitEvent(`error`,{message:`Poll failed`,cause:e});return}if(t.length===0)return;let n=t[t.length-1];if(!(n.time<this.lastBarTime)){if(this.lastBarTime>0&&n.time>this.lastBarTime){let e=t.find(e=>e.time===this.lastBarTime);e&&this.emitEvent(`bar`,{bar:e,closed:!0})}this.emitEvent(`bar`,{bar:n,closed:!1}),this.emitEvent(`tick`,{time:Date.now(),price:n.close,volume:n.volume}),this.lastBarTime=n.time}}startPolling(){this.stopPolling(),this.poll();let e=this.opts.setInterval??((e,t)=>setInterval(e,t));this.timer=e(()=>{this.poll()},this.opts.intervalMs??5e3)}stopPolling(){this.timer!==null&&((this.opts.clearInterval??(e=>clearInterval(e)))(this.timer),this.timer=null)}emitEvent(e,t){let n=this.listeners.get(e);if(n){let r={type:e,data:t,timestamp:Date.now()};for(let e of n)e(r)}}};function $(e){if(typeof e==`number`)return Number.isFinite(e)?e:null;if(typeof e==`string`){let t=parseFloat(e);return Number.isFinite(t)?t:null}return null}function uw(e){return typeof e==`object`&&!!e}var dw={"1m":60,"5m":300,"15m":900,"1h":3600,"6h":21600,"1d":86400};function fw(e){return dw[e]??3600}var pw=class extends lw{constructor(e={}){let t=e.restBase??`https://api.exchange.coinbase.com`;super({name:`coinbase`,supportedTimeframes:Object.keys(dw),intervalMs:e.intervalMs??5e3,pollLimit:2,fetchBars:(e,n)=>mw(t,e,n)})}};async function mw(e,t,n){let r=`${e}/products/${t}/candles?granularity=${fw(n)}`,i=await fetch(r);if(!i.ok)throw Error(`Coinbase REST error: ${i.status}`);return hw(await i.json())}function hw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=gw(n);e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function gw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:i,high:r,low:n,close:a,volume:o}}var _w={"1m":`1`,"3m":`3`,"5m":`5`,"15m":`15`,"30m":`30`,"1h":`60`,"2h":`120`,"4h":`240`,"6h":`360`,"12h":`720`,"1d":`D`,"1w":`W`,"1M":`M`};function vw(e){return _w[e]??`1`}var yw=class extends cw{constructor(e={}){let t=e.restBase??`https://api.bybit.com`,n=e.wsBase??`wss://stream.bybit.com/v5/public/spot`,r=e.category??`spot`;super({name:`bybit`,wsUrl:()=>n,subscribeMessage:e=>({op:`subscribe`,args:[`kline.${vw(e.timeframe)}.${e.symbol}`]}),unsubscribeMessage:e=>({op:`unsubscribe`,args:[`kline.${vw(e.timeframe)}.${e.symbol}`]}),supportedTimeframes:Object.keys(_w),parseMessage:bw,fetchHistory:(e,n,i)=>xw(t,r,e,n,i),fetchHistoryBefore:(e,n,i,a)=>xw(t,r,e,n,a,Math.floor(i)-1)})}};function bw(e){if(!uw(e)||typeof e.topic!=`string`||!e.topic.startsWith(`kline.`))return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!uw(n))return null;let r=$(n.start),i=$(n.open),a=$(n.high),o=$(n.low),s=$(n.close),c=$(n.volume);if(r===null||i===null||a===null||o===null||s===null||c===null)return null;let l=typeof n.confirm==`boolean`?n.confirm:!1;return{bar:{time:r,open:i,high:a,low:o,close:s,volume:c},closed:l}}async function xw(e,t,n,r,i,a){let o=`${e}/v5/market/kline?category=${t}&symbol=${n}&interval=${vw(r)}&limit=${Math.min(Math.max(i,1),1e3)}${a===void 0?``:`&end=${a}`}`,s=await fetch(o);if(!s.ok)throw Error(`Bybit REST error: ${s.status}`);return Sw(await s.json())}function Sw(e){if(!uw(e)||!uw(e.result))return[];let t=e.result.list;if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Cw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function Cw(e){if(!Array.isArray(e)||e.length<6)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[5]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t,open:n,high:r,low:i,close:a,volume:o}}var ww={"1m":1,"5m":5,"15m":15,"30m":30,"1h":60,"4h":240,"1d":1440,"1w":10080};function Tw(e){return ww[e]??1}var Ew=class extends cw{constructor(e={}){let t=e.restBase??`https://api.kraken.com`,n=e.wsBase??`wss://ws.kraken.com/v2`;super({name:`kraken`,wsUrl:()=>n,subscribeMessage:e=>({method:`subscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Tw(e.timeframe)}}),unsubscribeMessage:e=>({method:`unsubscribe`,params:{channel:`ohlc`,symbol:[e.symbol],interval:Tw(e.timeframe)}}),supportedTimeframes:Object.keys(ww),parseMessage:Dw,fetchHistory:(e,n)=>Ow(t,e,n)})}};function Dw(e){if(!uw(e)||e.channel!==`ohlc`)return null;let t=e.data;if(!Array.isArray(t)||t.length===0)return null;let n=t[t.length-1];if(!uw(n))return null;let r=$(n.open),i=$(n.high),a=$(n.low),o=$(n.close),s=$(n.volume),c=typeof n.interval_begin==`string`?Date.parse(n.interval_begin):NaN;return r===null||i===null||a===null||o===null||s===null||!Number.isFinite(c)?null:{bar:{time:c,open:r,high:i,low:a,close:o,volume:s},closed:!1}}async function Ow(e,t,n){let r=Tw(n),i=t.replace(`/`,``),a=`${e}/0/public/OHLC?pair=${encodeURIComponent(i)}&interval=${r}`,o=await fetch(a);if(!o.ok)throw Error(`Kraken REST error: ${o.status}`);return kw(await o.json())}function kw(e){if(!uw(e)||!uw(e.result))return[];let t=null;for(let[n,r]of Object.entries(e.result))if(n!==`last`&&Array.isArray(r)){t=r;break}if(!Array.isArray(t))return[];let n=[];for(let e of t){let t=Aw(e);t&&n.push(t)}return n.sort((e,t)=>e.time-t.time),n}function Aw(e){if(!Array.isArray(e)||e.length<7)return null;let t=$(e[0]),n=$(e[1]),r=$(e[2]),i=$(e[3]),a=$(e[4]),o=$(e[6]);return t===null||n===null||r===null||i===null||a===null||o===null?null:{time:t*1e3,open:n,high:r,low:i,close:a,volume:o}}var jw=200,Mw={"1m":`minutes/1`,"3m":`minutes/3`,"5m":`minutes/5`,"15m":`minutes/15`,"30m":`minutes/30`,"1h":`minutes/60`,"4h":`minutes/240`,"1d":`days`,"1w":`weeks`,"1M":`months`},Nw={"1m":`candle.1m`,"3m":`candle.3m`,"5m":`candle.5m`,"15m":`candle.15m`,"30m":`candle.30m`,"1h":`candle.60m`,"4h":`candle.240m`,"1d":`ticker`};function Pw(e){return Mw[e]??null}function Fw(e){return Nw[e]??null}var Iw=class extends cw{constructor(e={}){let t=e.restBase??`https://api.upbit.com`,n=e.wsUrl??`wss://api.upbit.com/websocket/v1`;super({name:`upbit`,wsUrl:()=>n,socketFactory:e.socketFactory??Lw,decode:zw,subscribeMessage:e=>[{ticket:`tradecanvas`},{type:Fw(e.timeframe)??`candle.1m`,codes:[e.symbol]},{format:`DEFAULT`}],supportedTimeframes:Object.keys(Nw),parseMessage:Bw,fetchHistory:(e,n,r)=>Uw(t,e,n,r),fetchHistoryBefore:(e,n,r,i)=>Uw(t,e,n,i,r)})}};function Lw(e){let t=globalThis.WebSocket;if(!t)throw Error(`No WebSocket implementation available`);let n=new t(e);return n.binaryType=`arraybuffer`,n}var Rw=null;function zw(e){if(typeof e==`string`)return JSON.parse(e);if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return JSON.parse((Rw??=new TextDecoder).decode(e))}function Bw(e){if(!uw(e)||typeof e.type!=`string`)return null;if(e.type.startsWith(`candle.`)){let t=Hw(e,e.candle_date_time_utc,e.candle_acc_trade_volume);return t?{bar:t,closed:!1}:null}if(e.type===`ticker`&&typeof e.trade_date==`string`&&/^\d{8}$/.test(e.trade_date)){let t=e.trade_date,n=Hw(e,`${t.slice(0,4)}-${t.slice(4,6)}-${t.slice(6,8)}T00:00:00`,e.acc_trade_volume);return n?{bar:n,closed:!1}:null}return null}function Vw(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){let e=uw(n)?Hw(n,n.candle_date_time_utc,n.candle_acc_trade_volume):null;e&&t.push(e)}return t.sort((e,t)=>e.time-t.time),t}function Hw(e,t,n){let r=typeof t==`string`?Date.parse(`${t}Z`):NaN,i=$(e.opening_price),a=$(e.high_price),o=$(e.low_price),s=$(e.trade_price),c=$(n);return!Number.isFinite(r)||i===null||a===null||o===null||s===null||c===null?null:{time:r,open:i,high:a,low:o,close:s,volume:c}}async function Uw(e,t,n,r,i){let a=Pw(n);if(!a)throw Error(`Upbit has no ${n} candles`);let o=new URLSearchParams({market:t,count:String(Math.min(Math.max(Math.floor(r),1),200))});i!==void 0&&o.set(`to`,new Date(i).toISOString().replace(/\.\d{3}Z$/,`Z`));let s=await fetch(`${e}/v1/candles/${a}?${o}`);if(!s.ok)throw Error(`Upbit REST error: ${s.status}`);return Vw(await s.json())}var Ww=(e,t)=>`${e}\u0000${t}`,Gw=class{name;series=new Map;subscribers=new Map;constructor(e={}){this.name=e.name??`manual`}setBars(e,t,n){let r=n.map(e=>({...e})).sort((e,t)=>e.time-t.time);this.series.set(Ww(e,t),r)}pushBar(e,t,n,r=!1){let i=Ww(e,t),a=this.series.get(i)??[],o=a[a.length-1],s={...n},c=r;if(!o||s.time>o.time)this.series.set(i,[...a,s]);else{let n=a.findIndex(e=>e.time===s.time);if(n<0)throw RangeError(`ManualFeed: no ${e} ${t} bar at ${s.time} to replace`);n<a.length-1&&(c=!0),this.series.set(i,a.map((e,t)=>t===n?s:e))}for(let e of[...this.subscribers.get(i)??[]])e.bar({...s},c)}async getBars(e){let t=this.series.get(Ww(e.symbol,e.timeframe))??[],{before:n}=e,r=n===void 0?t.length:Kw(t,n);return t.slice(Math.max(0,r-e.countBack),r).map(e=>({...e}))}subscribeBars(e,t){let n=Ww(e.symbol,e.timeframe),r=this.subscribers.get(n);return r||(r=new Set,this.subscribers.set(n,r)),r.add(t),()=>{r.delete(t),r.size===0&&this.subscribers.delete(n)}}};function Kw(e,t){let n=0,r=e.length;for(;n<r;){let i=n+r>>1;e[i].time<t?n=i+1:r=i}return n}var qw={visible:!0,showSymbol:!0,showOHLC:!0,showChange:!0,showVolume:!0,position:`top-left`,fontSize:12,fontFamily:null,ground:!0},Jw=class{config={...qw};symbol=``;timeframe=``;hoverBar=null;hoverPrev=null;indicators=[];statusText=null;exchange=``;drawnHeight=null;drawnWidth=0;locale=`en-US`;inset=Xw;top=Yw;lineGap=Zw;pricePrecision=null;reportedHeight=null;resizeListener=null;setResizeListener(e){this.resizeListener=e}forgetHeight(){this.drawnHeight=null,this.reportedHeight=null}reportResize(){let e=this.getHeight();e!==this.reportedHeight&&(this.reportedHeight=e,this.resizeListener?.())}setConfig(e){Object.assign(this.config,e),this.forgetHeight()}getConfig(){return{...this.config}}setPricePrecision(e){this.pricePrecision=e}setLocale(e){this.locale=e}setSymbol(e){e!==this.symbol&&(this.symbol=e,this.forgetHeight())}setTimeframe(e){e!==this.timeframe&&(this.timeframe=e,this.forgetHeight())}setChartType(e){}setHoverBar(e,t=null){this.hoverBar=e,this.hoverPrev=e?t:null}setIndicatorValues(e){this.indicators=e}setStatusText(e){e!==this.statusText&&(this.statusText=e,this.forgetHeight())}setExchange(e){e!==this.exchange&&(this.exchange=e,this.forgetHeight())}title(){return this.config.showSymbol?[(0,t.tickerOf)(this.symbol),this.timeframe,this.exchange].filter(Boolean).join(` · `):``}titleCells(e,t,n,r,i){let a=[],o=this.title();if(o){let i=`600 ${t}px ${n}`;e.font=i,a.push({label:``,labelWidth:0,value:o,width:e.measureText(o).width,color:r,font:i})}if(this.statusText){let r=`${t}px ${n}`;e.font=r,a.push({label:``,labelWidth:0,value:this.statusText,width:e.measureText(this.statusText).width,color:i,font:r})}return a}priceCells(e,n,r,i,a,o,s,c){let l=`${o}px ${s}`;e.font=l;let u=i.close>=i.open,d=this.pricePrecision??(0,t.autoPricePrecision)(n.priceRange.min,n.priceRange.max),f=e=>n.formatPrice?.(e)??(0,t.formatPrice)(e,d,this.locale),p=[{label:`O`,value:f(i.open),color:c},{label:`H`,value:f(i.high),color:c},{label:`L`,value:f(i.low),color:c},{label:`C`,value:f(i.close),color:u?r.candleUp:r.candleDown}];if(this.config.showChange){let e=i.close-a.close,n=a.close===0?0:e/a.close*100,o=e>=0?`+`:``,s=(0,t.formatPrice)(n,2,this.locale);p.push({label:``,value:`${o}${f(e)} (${o}${s}%)`,color:e>=0?r.candleUp:r.candleDown})}return p.map(t=>({...t,labelWidth:t.label?e.measureText(t.label+` `).width:0,width:nT(e,t.value),font:l}))}setSpacing(e){e.inset===this.inset&&e.top===this.top&&e.lineGap===this.lineGap||(this.inset=e.inset,this.top=e.top,this.lineGap=e.lineGap,this.drawnHeight=null)}getInset(){return this.inset}getHeight(){if(!this.config.visible||this.config.position!==`top-left`)return 0;if(this.drawnHeight!==null)return this.drawnHeight;let e=this.config.fontSize,t=this.top;return(this.config.showOHLC||this.title()||this.statusText)&&(t+=e+this.lineGap),this.config.showVolume&&(t+=e+2),t}getWidth(){return!this.config.visible||this.config.position!==`top-left`?0:this.drawnWidth}render(e,n,r,i){if(!this.config.visible)return this.reportResize();if(i.length===0)return;let a=this.hoverBar??i[i.length-1],o=this.hoverBar?this.hoverPrev??a:i.length>1?i[i.length-2]:a,{chartRect:s}=n,c=this.config.fontSize,l=this.config.fontFamily??r.font.family,u=r.style?.legend.text??r.text,d=r.style?.legend.label??r.textSecondary,f=this.config.position===`top-left`,p=f?s.x+this.inset:s.x+s.width-this.inset,m=s.y+this.top;e.textAlign=f?`left`:`right`,e.textBaseline=`top`;let h=0,g=this.titleCells(e,c,l,u,d);if(this.config.showOHLC&&g.push(...this.priceCells(e,n,r,a,o,c,l,u)),g.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width;for(let n of tT(g,t,s.width-2*this.inset)){let i=n.reduce((e,n)=>e+n.labelWidth+n.width+t,-t);h=Math.max(h,i);let a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let r of n)e.font=r.font,r.label&&(e.fillStyle=d,e.fillText(r.label,a,m),a+=r.labelWidth),e.fillStyle=r.color,e.fillText(r.value,a,m),a+=r.width+t;m+=c+this.lineGap}e.textAlign=f?`left`:`right`}if(this.config.showVolume){e.font=`${c}px ${l}`,e.fillStyle=d;let n=(0,t.formatVolumeLoc)(a.volume,this.locale),i=e.measureText(`Vol ${n}`).width;this.drawGround(e,r,f?p:p-i,m,i,c),e.fillStyle=d,e.fillText(`Vol ${n}`,p,m),h=Math.max(h,i),m+=c+2}if(this.drawnHeight=f?m-s.y:null,this.drawnWidth=f?this.inset+h:0,this.reportResize(),this.indicators.length>0){e.font=`${c}px ${l}`;let t=e.measureText(` `).width,n=this.indicators.map(t=>{let n=`${t.name} ${t.value}`;return{entry:n,color:t.color,width:nT(e,n)}}),i=n.reduce((e,n)=>e+n.width+t,-t),a=f?p:p-i;this.drawGround(e,r,a,m,i,c),e.textAlign=`left`;for(let{entry:r,color:i,width:o}of n)e.fillStyle=i,e.fillText(r,a,m),a+=o+t}}drawGround(e,t,n,r,i,a){!this.config.ground||i<=0||(e.save(),e.globalAlpha=Qw,e.fillStyle=t.background,e.fillRect(n-$w,r-eT,i+2*$w,a+this.lineGap),e.restore())}},{legendTop:Yw,legendInset:Xw,legendLineGap:Zw}=t.CHART_SPACING[t.DEFAULT_CHART_DENSITY],Qw=.72,$w=3,eT=1;function tT(e,t,n){let r=[],i=[],a=0;for(let o of e){let e=o.labelWidth+o.width;i.length>0&&a+t+e>n&&(r.push(i),i=[],a=0),a+=(i.length>0?t:0)+e,i.push(o)}return i.length>0&&r.push(i),r}function nT(e,t){let n=t.replace(/\d/g,`0`);return Math.max(e.measureText(t).width,e.measureText(n.replace(/[-−]/g,`+`)).width,e.measureText(n.replace(/\+/g,`-`)).width)}var rT=class{static toDataURL(e,t){return this.compose(e,t)?.toDataURL(`image/png`)??``}static async toBlob(e,t){let n=this.compose(e,t);return n?new Promise(e=>n.toBlob(e,`image/png`)):null}static download(e,t=`chart.png`,n){let r=this.toDataURL(e,n);if(!r)return;let i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i)}static compose(e,t){let n=e.querySelectorAll(`canvas`);if(n.length===0)return null;let r=n[0],i=r.width,a=r.height,o=document.createElement(`canvas`);o.width=i,o.height=a;let s=o.getContext(`2d`);t&&(s.fillStyle=t,s.fillRect(0,0,i,a));let c=Array.from(n).sort((e,t)=>(parseInt(e.style.zIndex)||0)-(parseInt(t.style.zIndex)||0));for(let e of c)s.drawImage(e,0,0);return o}},iT=class{config=null;setConfig(e){this.config=e}isVisible(){return!!this.config?.text}render(e,t,n){if(!this.config?.text)return;let{chartRect:r}=t,i=this.config.fontSize??48,a=n.style?.watermark.color??this.config.color??n.textSecondary;e.save(),e.globalAlpha=.07,e.font=`bold ${i}px ${n.font.family}`,e.fillStyle=a,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(this.config.text,r.x+r.width/2,r.y+r.height/2),e.restore()}},aT={solid:null,dashed:[6,4],dotted:[2,3]},oT=6;function sT(e,t){let n=[...e].sort((e,t)=>t.rank-e.rank||e.px-t.px),r=[],i=[];for(let e of n){let n=0,a=r.length;for(;n<a;){let t=n+a>>1;r[t]<e.px?n=t+1:a=t}n>0&&e.px-r[n-1]<t||n<r.length&&r[n]-e.px<t||(r.splice(n,0,e.px),i.push(e))}return i.sort((e,t)=>e.px-t.px)}var cT=class{config={visible:!1};cachedBreaksTyped=[];cachedMedianStep=0;cacheValid=!1;lastDataLength=0;firstTime=NaN;lastTime=NaN;tz=null;setConfig(e){Object.assign(this.config,e)}setTimezone(e){e!==this.tz&&(this.tz=e,this.invalidateCache())}isVisible(){return this.config.visible}setVisible(e){this.config.visible=e}computeBreaksTyped(e){if(e.length<2)return[];let n=this.lastDataLength,r=this.cacheValid&&e.length>=n&&e[0].time===this.firstTime&&e[n-1].time===this.lastTime;if(r&&e.length===n)return this.cachedBreaksTyped;let i=r?this.cachedBreaksTyped.slice():[],a=(0,t.barTimeUnit)(e),o=r?n:1,s=(0,t.timeParts)(e[o-1].time*a,this.tz);for(let n=o;n<e.length;n++){let r=(0,t.timeParts)(e[n].time*a,this.tz);if(r.year!==s.year)i.push({idx:n,kind:`year`});else if(r.month!==s.month)i.push({idx:n,kind:`month`});else if(r.day!==s.day){let e=new Date(Date.UTC(r.year,r.month-1,r.day)).getUTCDay()===1;i.push({idx:n,kind:e?`week`:`day`})}s=r}return this.lastDataLength=e.length,this.firstTime=e[0].time,this.lastTime=e[e.length-1].time,this.cachedBreaksTyped=i,r||(this.cachedMedianStep=lT(e)),this.cacheValid=!0,i}render(e,t,n,r){this.renderLines(e,t,n,r)}renderLines(e,t,n,r){let i=this.lineMarks(t,r,n);if(i.length===0)return;let{chartRect:a}=t,o=this.look(n),s=aT[o.style];e.save(),s&&e.setLineDash(s),e.strokeStyle=o.color;for(let t of i)e.globalAlpha=t.alpha,e.lineWidth=t.width,e.beginPath(),e.moveTo(t.px,a.y),e.lineTo(t.px,a.y+a.height),e.stroke();e.restore()}lineRects(e,t,n){let r=this.lineMarks(e,n,t);if(r.length===0)return[];let{color:i,style:a}=this.look(t),o=aT[a]??void 0,{y:s,height:c}=e.chartRect;return r.map(e=>({x:e.px-e.width/2,y:s,width:e.width,height:c,color:i,alpha:e.alpha,...o?{dash:o}:{}}))}look(e){let t=e.style?.sessionBreaks;return{color:t?.color??this.config.color??e.axisLine,style:t?.style??this.config.lineStyle??`dashed`,width:t?.width??this.config.lineWidth??1}}lineMarks(e,t,n){return sT(this.marks(e,t,n),oT)}marks(t,n,r){if(!this.config.visible||n.length<2)return[];let i=this.computeBreaksTyped(n);if(i.length===0||this.cachedMedianStep>=1380*60*1e3)return[];let{chartRect:a}=t,o=this.look(r).width,s=[];for(let n of i){let r=e.w(n.idx,t)-(t.barWidth+t.barSpacing)/2;if(r<a.x-1||r>a.x+a.width+1)continue;let i=Math.round(r)+.5,c=.25,l=o,u=3;n.kind===`day`?(c=.22,u=0):n.kind===`week`?(c=.34,u=1):n.kind===`month`?(c=.5,u=2,l=o+.5):(c=.7,l=o+1),s.push({px:i,width:l,alpha:c,rank:u})}return s}invalidateCache(){this.lastDataLength=0,this.cachedBreaksTyped=[],this.cachedMedianStep=0,this.cacheValid=!1}};function lT(e){if(e.length<2)return 0;let n=Math.min(50,e.length-1),r=(0,t.barTimeUnit)(e),i=[];for(let t=1;t<=n;t++)i.push((e[t].time-e[t-1].time)*r);return i.sort((e,t)=>e-t),i[Math.floor(i.length/2)]}var uT=864e5;function dT(e,t){let n={...e,...t};return t.tzOffsetMinutes!==void 0&&t.timeZone===void 0&&delete n.timeZone,n.windows?n.windows=n.windows.map(e=>({...e})):delete n.windows,n}function fT(e,t){let n=((e+t*6e4)%uT+uT)%uT;return Math.floor(n/6e4)}function pT(e,t,n){return t===n?!0:t<n?e>=t&&e<n:e>=t||e<n}function mT(e,n){let r=fT(e,n.timeZone?(0,t.zoneOffsetMinutes)(n.timeZone,e):n.tzOffsetMinutes??0);return n.windows&&n.windows.length>0?n.windows.some(e=>pT(r,e.startMinute,e.endMinute)):pT(r,n.startMinute,n.endMinute)}var hT={startMinute:570,endMinute:960,tzOffsetMinutes:-300,timeZone:`America/New_York`},gT=class{visible=!1;config={...hT};setVisible(e){this.visible=e}isVisible(){return this.visible}setConfig(e){this.config=dT(this.config,e)}replaceConfig(e){this.config=dT(e,{})}getConfig(){return{...this.config,windows:this.config.windows?.map(e=>({...e}))}}render(e,t,n,r){let i=this.rects(t,n,r);if(i.length!==0){e.save(),e.fillStyle=i[0].color;for(let t of i)e.fillRect(t.x,t.y,t.width,t.height);e.restore()}}rects(t,n,r){if(!this.visible||t.length===0)return[];let{chartRect:i}=n,{from:a,to:o}=n.visibleRange,s=Math.max(0,a),c=Math.min(o,t.length-1);if(c<s)return[];let l=n.barWidth+n.barSpacing,u=r.name===`light`?`rgba(0,0,0,0.045)`:`rgba(0,0,0,0.28)`,d=[],f=-1,p=(t,r)=>{let a=e.w(t,n)-l/2,o=e.w(r,n)+l/2;d.push({x:a,y:i.y,width:o-a,height:i.height,color:u,alpha:1})};for(let e=s;e<=c;e++){let n=!mT(t[e].time,this.config);n&&f===-1?f=e:!n&&f!==-1&&(p(f,e-1),f=-1)}return f!==-1&&p(f,c),d}},_T=[2,3],vT=16,yT=class{highLow=!1;quote=null;quoteShown=!0;priceText=null;setPriceText(e){this.priceText=e}setQuoteShown(e){this.quoteShown=e}setHighLow(e){this.highLow=e}isHighLowVisible(){return this.highLow}setBidAsk(e){this.quote=e?{...e}:null}getBidAsk(){return this.quote?{...this.quote}:null}levels(e,t){let n=[];if(this.highLow){let r=Math.max(0,t.visibleRange.from),i=Math.min(e.length-1,t.visibleRange.to),a=-1/0,o=1/0;for(let t=r;t<=i;t++)e[t].high>a&&(a=e[t].high),e[t].low<o&&(o=e[t].low);Number.isFinite(a)&&n.push({kind:`high`,price:a}),Number.isFinite(o)&&n.push({kind:`low`,price:o})}let{bid:r,ask:i}=(this.quoteShown?this.quote:null)??{};return r!==void 0&&Number.isFinite(r)&&n.push({kind:`bid`,price:r}),i!==void 0&&Number.isFinite(i)&&n.push({kind:`ask`,price:i}),n}render(t,n,r,i){let{chartRect:a}=n;t.save(),t.setLineDash(_T),t.lineWidth=1;for(let o of this.levels(i,n)){let i=Math.round(e.k(o.price,n))+.5;i<a.y||i>a.y+a.height||(t.strokeStyle=bT(o.kind,r),t.beginPath(),e.y(t,a.x,a.x+a.width,i),t.stroke())}t.restore()}renderAxisTags(n,r,i,a,o){let{chartRect:s}=r,c=s.x+s.width+1,l=(r.priceAxisWidth??t.PRICE_AXIS_WIDTH)-2,u=(0,t.autoPricePrecision)(r.priceRange.min,r.priceRange.max);n.save(),n.font=`${i.font.sizeSmall}px ${i.font.family}`,n.textBaseline=`middle`,n.textAlign=`left`;for(let d of this.levels(a,r)){let a=e.k(d.price,r);if(a<s.y||a>s.y+s.height)continue;let f=o?.get(d.kind)??a;if(Number.isNaN(f))continue;n.fillStyle=bT(d.kind,i),A(n,c,f-vT/2,l,vT,i),n.fillStyle=i.background;let p=r.formatPrice?.(d.price)??this.priceText?.(d.price)??(0,t.formatPrice)(d.price,u);n.fillText(p,c+7,f)}n.restore()}};function bT(e,t){switch(e){case`bid`:return t.candleUp;case`ask`:return t.candleDown;default:return t.style?.highLow.color??t.textSecondary}}var xT=12,ST=3,CT=500,wT=2,TT=[`movesUp`,`movesDown`];function ET(e){return e.channel===`price`&&!e.drawingId&&!e.target&&!TT.includes(e.condition)}function DT(e,t,n,r){switch(r){case`crossingUp`:return e!==void 0&&e<n&&t>=n;case`crossingDown`:return e!==void 0&&e>n&&t<=n;case`crossing`:return e!==void 0&&(e<n&&t>=n||e>n&&t<=n);case`greaterThan`:return t>n;case`lessThan`:return t<n;default:return!1}}var OT=[`crossing`,`crossingUp`,`crossingDown`];function kT(e,t,n){let r=e<0&&t>=0,i=e>0&&t<=0;return n===`crossingUp`?r:n===`crossingDown`?i:r||i}var AT=1,jT=2**31-1,MT=class extends zS{alerts=[];lastValues=new Map;drawingSides=new Map;drawingLevels=null;requestRender=null;pricePrecision=null;barTime=null;expiryTimer=null;history=new Map;lastDiffs=new Map;setBarTime(e){this.barTime=e}setRequestRender(e){this.requestRender=e}setPricePrecision(e){this.pricePrecision=e}addAlert(e,t=`crossing`,n,r=!1,i=`price`,a,o={}){let s=NT(t,i,o),c=`tc_alert_${AT++}`,l={id:c,price:e,condition:t,message:n,triggered:!1,repeating:r,channel:i,label:a,...s};return this.alerts.push(l),s.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`added`,l),this.requestRender?.(),c}setDrawingLevels(e){this.drawingLevels=e}addDrawingAlert(e,t=`crossing`,n,r=!1,i){if(!OT.includes(t))throw RangeError(`An alert on a drawing takes a crossing condition, not "${t}"`);let a=`tc_alert_${AT++}`,o={id:a,price:this.drawingLevels?.(e)?.[0]??NaN,condition:t,message:n,triggered:!1,repeating:r,channel:`price`,label:i,drawingId:e};return this.alerts.push(o),this.emit(`added`,o),a}removeDrawingAlerts(e){for(let t of this.alerts.filter(t=>t.drawingId===e))this.removeAlert(t.id)}takeDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId===e);for(let e of t)this.removeAlert(e.id);return t.map(e=>({...e}))}restoreAlerts(e){for(let t of e){if(this.alerts.some(e=>e.id===t.id))continue;let e={...t};this.alerts.push(e),this.emit(`added`,e)}this.scheduleExpiry(),this.requestRender?.()}pruneDrawingAlerts(e){let t=this.alerts.filter(t=>t.drawingId!==void 0&&!e.has(t.drawingId));for(let e of t)this.removeAlert(e.id);return t.length}removeAlert(e){this.drawingSides.delete(e),this.lastDiffs.delete(e);let t=this.alerts.some(t=>t.id===e&&t.expiresAt!==void 0);this.alerts=this.alerts.filter(t=>t.id!==e),t&&this.scheduleExpiry(),this.emit(`removed`,e),this.requestRender?.()}getAlerts(){return[...this.alerts]}getAlertAtPoint(t,n,r=6){let{chartRect:i}=n;if(t.y<i.y||t.y>i.y+i.height)return null;let a=null,o=r;for(let r of this.alerts){if(!ET(r))continue;let i=Math.abs(e.k(r.price,n)-t.y);i<=o&&(o=i,a=r)}return a}updateAlertPrice(e,t){let n=this.alerts.find(t=>t.id===e);!n||!Number.isFinite(t)||(n.price=t,n.triggered=!1,n.expiresAt!==void 0&&this.scheduleExpiry(),this.emit(`updated`,{...n}),this.requestRender?.())}clearAlerts(){this.alerts=[],this.lastDiffs.clear(),this.drawingSides.clear(),this.scheduleExpiry(),this.requestRender?.()}checkPrice(e){this.checkChannel(`price`,e),this.checkDrawingAlerts(e)}checkDrawings(e){this.checkDrawingAlerts(e)}expire(){let e=Date.now(),t=this.alerts.filter(t=>!t.expired&&t.expiresAt!==void 0&&e>=t.expiresAt&&!(t.triggered&&!t.repeating));if(t.length!==0){for(let e of t)e.expired=!0;try{for(let e of t)this.emit(`expired`,{...e}),this.emit(`updated`,{...e})}finally{this.requestRender?.(),this.scheduleExpiry()}}}scheduleExpiry(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null;let e=Math.min(...this.alerts.filter(e=>!e.expired&&e.expiresAt!==void 0&&!(e.triggered&&!e.repeating)).map(e=>e.expiresAt));if(!Number.isFinite(e))return;let t=Math.min(Math.max(0,e-Date.now()),jT);this.expiryTimer=setTimeout(()=>{this.expiryTimer=null,this.expire(),this.expiryTimer||this.scheduleExpiry()},t)}dispose(){this.expiryTimer&&clearTimeout(this.expiryTimer),this.expiryTimer=null}checkDrawingAlerts(e){if(!(!this.drawingLevels||!Number.isFinite(e)))for(let t of this.alerts){if(!t.drawingId||t.expired)continue;let n=this.drawingLevels(t.drawingId);if(!n||n.length===0){this.drawingSides.delete(t.id);continue}t.price=n[0];let r=n.map(t=>Math.sign(e-t)),i=this.drawingSides.get(t.id);this.drawingSides.set(t.id,r),!(!i||i.length!==r.length)&&(r.some((e,n)=>kT(i[n],e,t.condition))?t.triggered||(t.triggered=!0,this.emit(`triggered`,{...t})):t.repeating&&(t.triggered=!1))}}checkChannel(e,t){this.checkChannels(new Map([[e,t]]))}checkChannels(e,t={}){let n=(e instanceof Map?[...e.entries()]:Object.entries(e)).filter(([,e])=>Number.isFinite(e));if(n.length===0)return;this.expire();let r=new Map,i=new Map;for(let[e,t]of n){r.set(e,this.lastValues.get(e));let n=this.recordBar(e,t);n&&i.set(e,n),this.lastValues.set(e,t)}for(let e of this.alerts){if(e.drawingId||e.expired)continue;let n=r.has(e.channel),a=e.target!==void 0&&r.has(e.target);if(!n&&!a||e.target!==void 0&&t.together&&!(n&&a))continue;let o;if(e.onBarClose){let t=i.get(e.channel)??(e.target?i.get(e.target):void 0);if(!t)continue;o=this.closedBarMet(e,t)}else if(e.target)o=this.targetMet(e);else if(TT.includes(e.condition)){if(!n)continue;o=this.moveMet(e,this.history.get(e.channel)??[])}else{let t=r.get(e.channel);if(!n||t===void 0)continue;o=DT(t,this.lastValues.get(e.channel),e.price,e.condition)}this.settle(e,o)}}settle(e,t){t?e.triggered||(e.triggered=!0,this.emit(`triggered`,{...e})):e.repeating&&(e.triggered=!1)}targetMet(e){let t=this.lastValues.get(e.channel),n=e.target?this.lastValues.get(e.target):void 0;if(t===void 0||n===void 0)return!1;let r=t-n,i=this.lastDiffs.get(e.id);return this.lastDiffs.set(e.id,r),e.price=n,DT(i,r,0,e.condition)}moveMet(e,t,n=t.length){let r=e.bars??1,i=t.slice(Math.max(0,n-r),n);if(i.length<2||e.percent===void 0)return!1;let a=i[i.length-1].value,o=i.map(e=>e.value);if(e.condition===`movesUp`){let t=Math.min(...o);return t!==0&&(a-t)/Math.abs(t)*100>=e.percent}let s=Math.max(...o);return s!==0&&(s-a)/Math.abs(s)*100>=e.percent}closedBarMet(e,t){let n=this.history.get(e.channel)??[],r=n.findIndex(e=>e.time===t.time);if(r<0)return!1;if(TT.includes(e.condition))return this.moveMet(e,n,r+1);let i=(e,t)=>{let r=this.history.get(e)??[],i=n[t]?.time;return i===void 0?void 0:r.find(e=>e.time===i)?.value},a=n[r].value,o=r>0?n[r-1].value:void 0,s=e.price;if(e.target){let t=i(e.target,r),n=r>0?i(e.target,r-1):void 0;if(t===void 0)return!1;a-=t,o=o!==void 0&&n!==void 0?o-n:void 0,s=0,e.price=t}return DT(o,a,s,e.condition)}recordBar(e,t){let n=this.barTime;if(n===null)return null;let r=this.history.get(e)??[],i=r[r.length-1];if(i&&n<i.time)return r=r.filter(e=>e.time<n),r.push({time:n,value:t}),this.history.set(e,r),null;if(i&&i.time===n)return r[r.length-1]={time:n,value:t},null;i=r[r.length-1],r.push({time:n,value:t});let a=Math.min(502,Math.max(3,...this.alerts.map(e=>(e.bars??1)+2)));return r.length>a&&r.splice(0,r.length-a),this.history.set(e,r),i?{channel:e,time:i.time}:null}seedLastValue(e,t){Number.isFinite(t)&&this.lastValues.set(e,t)}clearLastValues(){this.lastValues.clear(),this.drawingSides.clear(),this.history.clear(),this.lastDiffs.clear()}saveToStorage(e){try{let t=this.alerts.map(e=>({id:e.id,price:e.price,condition:e.condition,message:e.message,triggered:e.triggered,repeating:e.repeating,channel:e.channel,label:e.label,drawingId:e.drawingId,target:e.target,percent:e.percent,bars:e.bars,onBarClose:e.onBarClose,expiresAt:e.expiresAt,expired:e.expired}));localStorage.setItem(e,JSON.stringify(t))}catch{}}loadFromStorage(e){try{let t=localStorage.getItem(e);if(!t)return;let n=JSON.parse(t);if(!Array.isArray(n))return;for(let e of n){if(typeof e.drawingId==`string`&&e.condition&&!e.triggered){OT.includes(e.condition)&&this.addDrawingAlert(e.drawingId,e.condition,e.message,e.repeating??!1,e.label);continue}if(!e.condition||e.triggered||e.expired)continue;let t=PT(e),n=!t.target&&!TT.includes(e.condition),r=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:NaN;if(!(n&&Number.isNaN(r)))try{this.addAlert(r,e.condition,e.message,e.repeating??!1,e.channel??`price`,e.label,t)}catch{}}}catch{}}render(n,r,i){let{chartRect:a}=r;for(let o of this.alerts){if(!ET(o))continue;let s=e.k(o.price,r);if(s<a.y||s>a.y+a.height)continue;let c=o.expired?`#8a93a3`:o.triggered?`#f2a93b`:`#4c8dff`;n.setLineDash([2,6]),n.strokeStyle=c,n.lineWidth=1,n.beginPath(),e.y(n,a.x,a.x+a.width,Math.round(s)+.5),n.stroke(),n.setLineDash([]),n.font=`10px ${i.font.family}`,n.fillStyle=c,n.textBaseline=`bottom`,n.textAlign=`right`;let l=`${(0,t.priceTagText)(o.price,r,this.pricePrecision??void 0)}${o.message?` - ${o.message}`:``}`,u=a.x+a.width-4;n.fillText(l,u,s-2);let d=u-n.measureText(l).width-ST-xT;d>=a.x&&fx(n,t.UI_ICONS.bell,d,s-2-xT,xT,c)}}};function NT(e,t,n){let r={},i=TT.includes(e);if(n.target!==void 0){if(i)throw RangeError(`An alert on a move takes no other line`);if(n.target===t)throw RangeError(`An alert can’t compare a line with itself`);r.target=n.target}if(i){let{percent:e,bars:t}=n;if(e===void 0||!Number.isFinite(e)||e<=0)throw RangeError(`An alert on a move needs a percent above 0`);if(t===void 0||!Number.isInteger(t)||t<2||t>500)throw RangeError(`An alert on a move needs 2 to 500 bars`);r.percent=e,r.bars=t}return n.onBarClose&&(r.onBarClose=!0),n.expiresAt!==void 0&&Number.isFinite(n.expiresAt)&&(r.expiresAt=n.expiresAt),r}function PT(e){let t={};return typeof e.target==`string`&&e.target&&(t.target=e.target),typeof e.percent==`number`&&Number.isFinite(e.percent)&&(t.percent=e.percent),typeof e.bars==`number`&&Number.isInteger(e.bars)&&(t.bars=e.bars),e.onBarClose===!0&&(t.onBarClose=!0),typeof e.expiresAt==`number`&&Number.isFinite(e.expiresAt)&&(t.expiresAt=e.expiresAt),t}var FT=16,IT=3*FT,LT=1e3/30,RT=1e-9,zT=()=>typeof requestAnimationFrame==`function`&&!(typeof document<`u`&&document.hidden),BT={now:()=>typeof performance<`u`?performance.now():Date.now(),frame:e=>zT()?{raf:requestAnimationFrame(e)}:{timeout:setTimeout(e,FT)},cancel:e=>{let t=e;t.raf!==void 0&&cancelAnimationFrame(t.raf),t.timeout!==void 0&&clearTimeout(t.timeout)}},VT=class extends zS{data=[];cursor=-1;timer=null;frameHandle=null;run=0;state=`stopped`;config={speed:1,interval:500};paceMs=null;owedMs=0;constructor(e=BT){super(),this.clock=e}load(e){this.stop(),this.data=e,this.cursor=-1,this.owedMs=0}play(e){if(this.data.length===0)return;if(e){let{startIndex:t,paused:n,duration:r,...i}=e;this.config={...this.config,...i};let a=t===void 0?null:this.clamp(t);if(n){this.clearTimer(),this.seekTo(a??Math.max(0,this.cursor)),this.setPace(r),this.setState(`paused`);return}a!==null&&(this.cursor=a-1,this.owedMs=0),this.setPace(r)}if(this.isAtEnd()){this.clearTimer(),this.setState(`paused`);return}this.clearTimer();let t=this.stepMs();if(!(t>0)||!Number.isFinite(t)){this.setState(`paused`);return}this.setState(`playing`),this.config.animate?this.runForming(t):t<FT||this.paceMs!==null?this.runFrames(t):this.timer=setInterval(()=>this.advance(1),t)}pause(){this.clearTimer(),this.setState(`paused`)}resume(){this.state===`paused`&&this.play()}stop(){this.clearTimer(),this.cursor=-1,this.owedMs=0,this.setState(`stopped`)}seekTo(e){this.data.length!==0&&(this.cursor=this.clamp(e),this.owedMs=0,this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}))}setSpeed(e){let t=this.getFraction();this.config={...this.config,speed:e},this.paceMs=null;let n=this.stepMs();this.owedMs=n>0&&Number.isFinite(n)?t*n:0,this.state===`playing`&&this.play()}getState(){return this.state}isAtEnd(){return this.data.length>0&&this.cursor>=this.data.length-1}getProgress(){let e=this.data.length;return{current:Math.max(0,this.cursor),total:e,percent:e>0?(this.cursor+1)/e*100:0}}remainingMs(){return this.paceMs===null?null:this.paceMs*Math.max(0,this.data.length-1-this.cursor)}getStepMs(){return this.stepMs()}getFraction(){let e=this.stepMs();return e>0&&Number.isFinite(e)?Math.min(1,this.owedMs/e):0}dispose(){this.stop(),this.removeAllListeners(),this.data=[]}setPace(e){this.paceMs=e!==void 0&&e>0&&Number.isFinite(e)?e/Math.max(1,this.data.length-1-this.cursor):null}runFrames(e){let t=this.run,n=this.clock.now(),r=0,i=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let a=this.clock.now();r+=Math.min(50,Math.max(0,a-n)),n=a;let o=Math.floor(r/e);try{o>0&&(r-=o*e,this.advance(o))}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(i))}};this.frameHandle=this.clock.frame(i)}stepMs(){return this.paceMs??this.config.interval/this.config.speed}runForming(e){let t=this.run,n=e>=IT,r=this.clock.now(),i=-1/0,a=r=>{!n||this.isAtEnd()||t!==this.run||this.state!==`playing`||(i=r,this.emit(`phase`,{index:this.cursor+1,fraction:Math.min(1,this.owedMs/e)}))},o=()=>{if(t!==this.run||this.state!==`playing`)return;this.frameHandle=null;let n=this.clock.now();this.owedMs+=Math.min(50,Math.max(0,n-r)),r=n;let s=Math.floor((this.owedMs+RT)/e);try{s>0?(this.owedMs=Math.max(0,this.owedMs-s*e),this.advance(s),a(n)):n-i+FT/2>=LT&&a(n)}finally{t===this.run&&this.state===`playing`&&this.frameHandle===null&&(this.frameHandle=this.clock.frame(o))}};a(r),this.frameHandle=this.clock.frame(o)}advance(e){if(this.isAtEnd()){this.finish();return}this.cursor=Math.min(this.data.length-1,this.cursor+e),this.emit(`bar`,{bar:this.data[this.cursor],index:this.cursor,total:this.data.length}),this.isAtEnd()&&this.finish()}finish(){this.clearTimer(),this.setState(`paused`),this.emit(`complete`,void 0)}clamp(e){return Number.isFinite(e)?Math.max(0,Math.min(Math.floor(e),this.data.length-1)):0}clearTimer(){this.run++,this.timer&&=(clearInterval(this.timer),null),this.frameHandle!==null&&(this.clock.cancel(this.frameHandle),this.frameHandle=null)}setState(e){this.state!==e&&(this.state=e,this.emit(`stateChange`,e))}},HT=64,UT=3,WT=3;function GT(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function KT(e){return Array.isArray(e)?e:[]}function qT(e,t){return typeof e==`string`?e:t}function JT(e,t){return typeof e==`number`&&Number.isFinite(e)?e:t}function YT(e){if(!GT(e)||typeof e.id!=`string`||typeof e.type!=`string`||!Array.isArray(e.anchors)||e.anchors.length===0||e.anchors.length>XT||!GT(e.style))return null;let n=[];for(let t of e.anchors){if(!GT(t)||typeof t.time!=`number`||typeof t.price!=`number`||!Number.isFinite(t.time)||!Number.isFinite(t.price))return null;n.push({time:t.time,price:t.price})}let r=(0,t.sanitizeDrawingStyle)(e.style);return r.color===void 0||r.lineWidth===void 0?null:{id:e.id,type:e.type,anchors:n,style:{lineStyle:`solid`,...r,color:r.color,lineWidth:r.lineWidth},visible:typeof e.visible==`boolean`?e.visible:!0,locked:typeof e.locked==`boolean`?e.locked:!1,options:GT(e.options)?e.options:void 0,intervals:ja(e.intervals)??void 0,group:eE(e.group),...tm(e.name)===void 0?{}:{name:tm(e.name)},...typeof e.paneId==`string`&&e.paneId.length>0&&e.paneId.length<=ZT?{paneId:e.paneId}:{},meta:GT(e.meta)?e.meta:void 0}}var XT=5e3,ZT=200,QT=64,$T=80;function eE(e){if(!(!GT(e)||typeof e.id!=`string`||typeof e.name!=`string`)&&!(e.id===``||e.id.length>QT))return{id:e.id,name:e.name.slice(0,$T)}}function tE(e){return!GT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.type!=`string`||typeof e.price!=`number`||typeof e.quantity!=`number`?null:e}function nE(e){if(!GT(e))return;let n={},r=KT(e.colors).filter(e=>typeof e==`string`);r.length>0&&(n.colors=r);let i=KT(e.lineWidths).filter(e=>typeof e==`number`&&Number.isFinite(e)&&e>0);i.length>0&&(n.lineWidths=i),typeof e.opacity==`number`&&Number.isFinite(e.opacity)&&(n.opacity=Math.min(1,Math.max(0,e.opacity)));let a=(0,t.readIndicatorPlotStyles)(e.plots);return a&&(n.plots=a),Object.keys(n).length>0?n:void 0}var rE=[`crossingUp`,`crossingDown`,`crossing`,`greaterThan`,`lessThan`,`movesUp`,`movesDown`];function iE(e){if(!GT(e)||typeof e.id!=`string`)return null;let t=typeof e.drawingId==`string`?e.drawingId:void 0,n=typeof e.price==`number`&&Number.isFinite(e.price)?e.price:null,r=rE.find(t=>t===e.condition)??`crossing`,i=PT(e),a=i.target!==void 0||r===`movesUp`||r===`movesDown`;return n===null&&!t&&!a?null:{id:e.id,price:n??NaN,drawingId:t,condition:r,message:typeof e.message==`string`?e.message:void 0,triggered:e.triggered===!0,repeating:e.repeating===!0,channel:qT(e.channel,`price`),label:typeof e.label==`string`?e.label:void 0,...i,...e.expired===!0?{expired:!0}:{}}}function aE(e){return!GT(e)||typeof e.id!=`string`||typeof e.side!=`string`||typeof e.entryPrice!=`number`||typeof e.quantity!=`number`?null:e}var oE=4e3;function sE(e){if(!GT(e))return;let n={},r=[];for(let[i,a]of Object.entries(e)){let e=(0,t.readChartStyleOverrides)(a);r.push(...e.rejected);let o=Object.fromEntries(Object.entries(e.overrides).filter(([,e])=>e!==null));Object.keys(o).length>0&&(n[i.slice(0,HT)]=o)}return r.length>0&&console.warn(`Saved style overrides left out: ${[...new Set(r)].join(`, `)}`),n}function cE(e){if(!GT(e))return lE();typeof e.version==`number`&&e.version>WT&&console.warn(`Chart state from a newer version (${e.version}); loading what this version understands.`);let n=GT(e.viewport)?e.viewport:{},r=[];for(let n of KT(e.indicators))GT(n)&&(typeof n.id!=`string`||typeof n.instanceId!=`string`||GT(n.params)&&r.push({id:n.id,instanceId:n.instanceId,params:n.params,position:typeof n.position==`string`?n.position:void 0,style:nE(n.style),visible:typeof n.visible==`boolean`?n.visible:void 0,levels:Array.isArray(n.levels)?n.levels.filter(e=>typeof e==`number`&&Number.isFinite(e)):void 0,pane:typeof n.pane==`string`?n.pane:void 0,scale:n.scale===`left`?`left`:void 0,intervals:ja(n.intervals)??void 0,paneStyle:(0,t.readPaneStyle)(n.paneStyle)??void 0,paneSize:typeof n.paneSize==`number`&&Number.isFinite(n.paneSize)&&n.paneSize>0?Math.min(n.paneSize,oE):void 0,paneOrder:typeof n.paneOrder==`number`&&Number.isInteger(n.paneOrder)&&n.paneOrder>=0?n.paneOrder:void 0,paneCollapsed:n.paneCollapsed===!0?!0:void 0,paneMaximized:n.paneMaximized===!0?!0:void 0,paneLog:n.paneLog===!0?!0:void 0,paneInvert:n.paneInvert===!0?!0:void 0,panePercent:n.panePercent===!0?!0:void 0}));let i=[];for(let t of KT(e.drawings)){let e=YT(t);e&&i.push(e)}let a=[];for(let t of KT(e.orders)){let e=tE(t);e&&a.push(e)}let o=[];for(let t of KT(e.positions)){let e=aE(t);e&&o.push(e)}let s=[];for(let t of KT(e.alerts)){let e=iE(t);e&&s.push(e)}let c=sE(e.overrides);return{version:typeof e.version==`number`&&Array.isArray(e.indicators)?e.version:1,timestamp:JT(e.timestamp,Date.now()),symbol:typeof e.symbol==`string`?e.symbol:void 0,timeframe:typeof e.timeframe==`string`?e.timeframe:void 0,chartType:qT(e.chartType,`candlestick`),...e.chartTypeOptions===void 0?{}:{chartTypeOptions:(0,t.readChartTypeOptions)(e.chartTypeOptions)},viewport:{barWidth:JT(n.barWidth,8),barSpacing:JT(n.barSpacing,2),offset:JT(n.offset,0)},theme:typeof e.theme==`string`?e.theme:void 0,...c?{overrides:c}:{},locale:typeof e.locale==`string`?e.locale:void 0,indicators:r,drawings:i,orders:a,positions:o,alerts:s}}function lE(){return{version:1,timestamp:Date.now(),chartType:`candlestick`,viewport:{barWidth:8,barSpacing:2,offset:0},indicators:[],drawings:[],orders:[],positions:[],alerts:[]}}var uE=class{static capture(e,t){return{version:e.getIndicators?WT:1,timestamp:Date.now(),chartType:t?.chartType??`candlestick`,...t?.chartTypeOptions&&Object.keys(t.chartTypeOptions).length>0?{chartTypeOptions:t.chartTypeOptions}:{},symbol:t?.symbol,timeframe:t?.timeframe,viewport:{barWidth:8,barSpacing:2,offset:0},theme:e.getTheme().name,...e.getOverrides&&Object.keys(e.getOverrides()).length>0?{overrides:e.getOverrides()}:{},indicators:e.getIndicators?.()??[],drawings:e.getDrawings(),orders:e.getOrders?.()??[],positions:e.getPositions?.()??[],alerts:e.getAlerts?.()??[]}}static serialize(e){return JSON.stringify(e)}static deserialize(e){return cE(JSON.parse(e))}static saveToStorage(e,t){localStorage.setItem(e,this.serialize(t))}static loadFromStorage(e){let t=localStorage.getItem(e);return t?this.deserialize(t):null}static downloadFile(e,t=`tc-chart-state.json`){let n=new Blob([this.serialize(e)],{type:`application/json`}),r=URL.createObjectURL(n),i=document.createElement(`a`);i.href=r,i.download=t,document.body.appendChild(i),i.click(),document.body.removeChild(i),URL.revokeObjectURL(r)}static loadFromFile(){return new Promise((e,t)=>{let n=document.createElement(`input`);n.type=`file`,n.accept=`.json`,n.onchange=async()=>{let r=n.files?.[0];if(!r){t(Error(`No file selected`));return}let i=await r.text();e(this.deserialize(i))},n.click()})}},dE=class{undoStack=[];redoStack=[];maxHistory=50;onChange=null;grouped=null;setOnChange(e){this.onChange=e}push(e){if(this.grouped){this.grouped.push(e);return}this.undoStack.push(e),this.undoStack.length>this.maxHistory&&this.undoStack.shift(),this.redoStack.length=0,this.onChange?.()}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}undo(){let e=this.undoStack.pop();return e?(this.redoStack.push(e),this.onChange?.(),e):null}redo(){let e=this.redoStack.pop();return e?(this.undoStack.push(e),this.onChange?.(),e):null}clear(){this.undoStack.length=0,this.redoStack.length=0,this.onChange?.()}group(e){if(this.grouped)return e();let t=[];this.grouped=t;try{return e()}finally{this.grouped=null,t.length===1?this.push(t[0]):t.length>1&&this.push({type:`drawingBatch`,before:null,after:null,actions:t})}}last(){return this.grouped?this.grouped[this.grouped.length-1]??null:this.undoStack[this.undoStack.length-1]??null}dropLast(){if(this.grouped){this.grouped.pop();return}this.undoStack.pop()&&(this.redoStack.length=0,this.onChange?.())}replaceLast(e){if(this.grouped){this.grouped.length>0?this.grouped[this.grouped.length-1]=e:this.grouped.push(e);return}if(this.undoStack.length===0){this.push(e);return}this.undoStack[this.undoStack.length-1]=e,this.redoStack.length=0,this.onChange?.()}getState(){return{canUndo:this.undoStack.length>0,canRedo:this.redoStack.length>0,undoCount:this.undoStack.length,redoCount:this.redoStack.length}}},fE=[`Time`,`Open`,`High`,`Low`,`Close`,`Volume`];function pE(e,n){return new Date((0,t.normalizeBarTime)(e,n)).toISOString()}function mE(e){let t=/^[=+\-@\t\r]/.test(e)&&!/^-?\d/.test(e)?`'${e}`:e;return/[",\r\n]/.test(t)?`"${t.replace(/"/g,`""`)}"`:t}var hE=15,gE=0x38d7ea4c68000;function _E(e){return e==null||!Number.isFinite(e)?null:Number.isInteger(e)||Math.abs(e)>=gE?e:Number(e.toPrecision(hE))}var vE=e=>{let t=_E(e);return t===null?``:String(t)},yE=class{static toCSV(e,n=[]){let r=[...fE,...n.map(e=>mE(e.name))].join(`,`),i=(0,t.barTimeUnit)(e);return[r,...e.map((e,t)=>[pE(e.time,i),...[e.open,e.high,e.low,e.close,e.volume].map(vE),...n.map(e=>vE(e.values[t]))].join(`,`))].join(`
25
+ `)}static toJSON(e,n=[]){let r=(0,t.barTimeUnit)(e);return JSON.stringify(e.map((e,t)=>{let i={time:pE(e.time,r),open:_E(e.open),high:_E(e.high),low:_E(e.low),close:_E(e.close),volume:_E(e.volume)};for(let e of n)i[e.name]=_E(e.values[t]);return i}),null,2)}static download(e,t,n){let r=new Blob([e],{type:n}),i=URL.createObjectURL(r),a=document.createElement(`a`);a.href=i,a.download=t,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(i)}};function bE(e,t,n=-1/0){return t===null?e:e.filter(e=>e.time>=n&&e.time<t)}function xE(e,t,n=-1/0){return t===null?e:e.filter(e=>e.entryTime>=n&&e.entryTime<t).map(e=>{if(e.exitTime===void 0||e.exitTime<t)return e;let{exitTime:n,exitPrice:r,pnl:i,pnlPercent:a,...o}=e;return o})}var SE=1,CE=3,wE=class extends zS{markers=[];style={...t.DEFAULT_SIGNAL_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addMarker(e){let t=e.id??`tc_signal_${SE++}`,n={...e,id:t};return this.markers.push(n),this.emit(`added`,n),this.requestRender?.(),t}removeMarker(e){this.markers=this.markers.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getMarkers(){return[...this.markers]}clearMarkers(){this.markers=[],this.emit(`cleared`,void 0),this.requestRender?.()}setMarkers(e){this.markers=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownMarkers(){return[...bE(this.markers,this.revealUntil,this.revealFrom)]}markerAt(t,n){let r=this.dataGetter?.();if(!r||r.length===0)return null;let{chartRect:i}=n;if(t.x<i.x||t.x>i.x+i.width||t.y<i.y||t.y>i.y+i.height)return null;let a=this.style.arrowSize??12,o=bE(this.markers,this.revealUntil,this.revealFrom);for(let i=o.length-1;i>=0;i--){let s=o[i],c=e.w(e.N(s.time,r),n),l=e.k(s.price,n),u=a*Math.max(.6,Math.min(1,s.confidence)),d=s.direction===`long`?l-u:(s.direction,l-u*.4),f=s.direction===`long`?l+u*.4:s.direction===`short`?l+u:l+u*.4;if(Math.abs(t.x-c)<=u*.6+CE&&t.y>=d-CE&&t.y<=f+CE)return s}return null}render(t,n,r){let i=this.dataGetter?.(),a=bE(this.markers,this.revealUntil,this.revealFrom);if(!i||i.length===0||a.length===0)return;let{chartRect:o}=n,s=yS(this.style,r),c=s.arrowSize??12;t.save(),t.beginPath(),t.rect(o.x,o.y,o.width,o.height),t.clip();for(let l of a){let a=e.w(e.N(l.time,i),n),u=e.k(l.price,n);if(a<o.x-c||a>o.x+o.width+c||u<o.y-c||u>o.y+o.height+c)continue;let d=this.resolveColor(l,s),f=c*Math.max(.6,Math.min(1,l.confidence));if(this.renderArrow(t,a,u,l.direction,f,d),s.showLabel&&l.label){t.font=`10px ${r.font.family}`,t.fillStyle=d,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+3:u-f-3;t.fillText(l.label,a,e)}if(s.showConfidence&&l.confidence<1){t.font=`9px ${r.font.family}`,t.fillStyle=d,t.globalAlpha=.7,t.textAlign=`center`,t.textBaseline=l.direction===`long`?`top`:`bottom`;let e=l.direction===`long`?u+f+(l.label?14:3):u-f-(l.label?14:3);t.fillText(`${Math.round(l.confidence*100)}%`,a,e),t.globalAlpha=1}}t.restore()}resolveColor(e,t){if(e.color)return e.color;if(t.sourceColors?.[e.source])return t.sourceColors[e.source];switch(e.direction){case`long`:return t.longColor??`#1fa874`;case`short`:return t.shortColor??`#e8505b`;default:return t.neutralColor??`#9E9E9E`}}renderArrow(e,t,n,r,i,a){e.fillStyle=a,e.beginPath(),r===`long`?(e.moveTo(t,n-i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n+i*.4),e.lineTo(t+i*.2,n+i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):r===`short`?(e.moveTo(t,n+i),e.lineTo(t-i*.6,n),e.lineTo(t-i*.2,n),e.lineTo(t-i*.2,n-i*.4),e.lineTo(t+i*.2,n-i*.4),e.lineTo(t+i*.2,n),e.lineTo(t+i*.6,n)):e.arc(t,n,i*.4,0,Math.PI*2),e.closePath(),e.fill()}},TE=18,EE=4,DE=2,OE=6,kE=18+2*EE,AE=3,jE=300,ME=10,NE=8,PE=8,FE=1.35,IE=6,LE={news:`N`,earnings:`E`,dividend:`D`,split:`S`,event:`i`},RE={news:`#4c8dff`,earnings:`#f2a93b`,dividend:`#4fae8a`,split:`#a78bfa`},zE=1,BE=class{marks=[];requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;hoveredId=null;tooltip=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setMarks(e){this.marks=(0,t.readChartMarks)(e),this.requestRender?.()}addMark(e){let[n]=(0,t.readChartMarks)([{...e,id:e.id??`tc_mark_${zE++}`}]);if(!n)return null;let r=this.marks.filter(e=>e.id!==n.id);return r.length>=t.MAX_CHART_MARKS?null:(this.marks=[...r,n].sort((e,t)=>e.time-t.time),this.requestRender?.(),n.id)}removeMark(e){this.marks=this.marks.filter(t=>t.id!==e),this.requestRender?.()}clearMarks(){this.marks=[],this.requestRender?.()}getMarks(){return this.marks.map(e=>({...e}))}count(){return this.marks.length}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}setHovered(e){let t=e?.marks[0]?.id??null;return t===this.hoveredId?!1:(this.hoveredId=t,this.requestRender?.(),!0)}isHovering(){return this.hoveredId!==null}tooltipBox(){return this.tooltip?{...this.tooltip}:null}badges(t){let n=this.dataGetter?.();if(!n||n.length===0||this.marks.length===0)return[];let{chartRect:r}=t,i=r.y+r.height-18/2-EE,a=[];for(let o of this.marks){if(this.revealUntil!==null&&(o.time<this.revealFrom||o.time>=this.revealUntil))continue;let s=e.N(o.time,n);if(s<0||s>=n.length)continue;let c=e.w(Math.floor(s),t);if(c<r.x||c>r.x+r.width)continue;let l=a[a.length-1];l&&c-l.x<18+DE?l.marks.push(o):a.push({x:c,y:i,marks:[o]})}return a}badgeAt(e,t){let{chartRect:n}=t;if(e.x<n.x||e.x>n.x+n.width||e.y<n.y||e.y>n.y+n.height)return null;let r=18/2+OE,i=null,a=1/0;for(let n of this.badges(t)){let t=Math.abs(e.x-n.x),o=Math.abs(e.y-n.y);t>r||o>r||t>=a||(a=t,i=n)}return i}render(e,t,n){this.tooltip=null;let r=this.badges(t);if(r.length===0)return;let{chartRect:i}=t;e.save(),e.beginPath(),e.rect(i.x,i.y,i.width,i.height),e.clip();let a=null;for(let t of r){let r=this.hoveredId!==null&&t.marks.some(e=>e.id===this.hoveredId);r&&(a=t),this.renderBadge(e,t,n,r)}a&&this.renderTooltip(e,a,t,n),e.restore()}colorOf(e,t){if(e.color)return e.color;let n=e.kind??`event`;return n===`event`?t.textSecondary:RE[n]}renderBadge(e,t,n,r){let i=t.marks[0],a=this.colorOf(i,n);e.fillStyle=n.background,e.beginPath(),e.arc(t.x,t.y,9+(r?3:1.5),0,Math.PI*2),e.fill(),r&&(e.fillStyle=a,e.globalAlpha=.35,e.beginPath(),e.arc(t.x,t.y,12,0,Math.PI*2),e.fill(),e.globalAlpha=1),e.fillStyle=a,e.beginPath(),e.arc(t.x,t.y,9,0,Math.PI*2),e.fill();let o=t.marks.length>1?String(t.marks.length):i.label??LE[i.kind??`event`];e.fillStyle=ne(a),e.font=`600 ${o.length>1?10:11}px ${n.font.family}`,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(o,t.x,t.y+.5)}renderTooltip(e,t,n,r){let{chartRect:i}=n,a=r.font.sizeMedium,o=r.font.sizeSmall,s=`600 ${a}px ${r.font.family}`,c=`${o}px ${r.font.family}`,l=Math.min(jE,i.width-2*EE),u=l-2*ME;if(u<=0)return;let d=[...t.marks].reverse().slice(0,AE),f=t.marks.length-d.length,p=[];d.forEach((t,n)=>{p.push({text:VE(e,t.title,s,u),font:s,color:r.text,height:a*FE,gap:n===0?0:PE}),t.text&&p.push({text:VE(e,t.text,c,u),font:c,color:r.textSecondary,height:o*FE,gap:0})}),f>0&&p.push({text:`+${f}`,font:c,color:r.textSecondary,height:o*FE,gap:PE});let m=p.reduce((e,t)=>e+t.gap+t.height,0)+2*ME,h=Math.max(i.x+EE,Math.min(i.x+i.width-EE-l,t.x-l/2)),g=Math.max(i.y+EE,t.y-18/2-NE-m);this.tooltip={x:h,y:g,width:l,height:m},e.fillStyle=r.axisLabelBackground,e.strokeStyle=r.axisLine,e.lineWidth=1,e.beginPath(),typeof e.roundRect==`function`?e.roundRect(Math.round(h)+.5,Math.round(g)+.5,l,m,IE):e.rect(Math.round(h)+.5,Math.round(g)+.5,l,m),e.fill(),e.stroke(),e.textAlign=`left`,e.textBaseline=`top`;let _=g+ME;for(let t of p)_+=t.gap,e.font=t.font,e.fillStyle=t.color,e.fillText(t.text,h+ME,_),_+=t.height}};function VE(e,t,n,r){if(e.font=n,e.measureText(t).width<=r)return t;let i=[...t],a=0,o=i.length;for(;a<o;){let t=a+o+1>>>1;e.measureText(`${i.slice(0,t).join(``).trimEnd()}…`).width<=r?a=t:o=t-1}return`${i.slice(0,a).join(``).trimEnd()}…`}var HE=12,UE=2,WE=1,GE=class extends zS{zones=[];style={...t.DEFAULT_TRADE_ZONE_STYLE};requestRender=null;dataGetter=null;revealUntil=null;revealFrom=-1/0;pricePrecision=null;setRequestRender(e){this.requestRender=e}setDataGetter(e){this.dataGetter=e}setPricePrecision(e){this.pricePrecision=e}setStyle(e){this.style={...this.style,...e},this.requestRender?.()}getStyle(){return{...this.style}}addZone(e){let t=e.id??`tc_zone_${WE++}`,n={...e,id:t};return this.zones.push(n),this.emit(`added`,n),this.requestRender?.(),t}updateZone(e,t){let n=this.zones.findIndex(t=>t.id===e);n!==-1&&(this.zones[n]={...this.zones[n],...t},this.requestRender?.())}removeZone(e){this.zones=this.zones.filter(t=>t.id!==e),this.emit(`removed`,e),this.requestRender?.()}getZones(){return[...this.zones]}clearZones(){this.zones=[],this.emit(`cleared`,void 0),this.requestRender?.()}setZones(e){this.zones=[...e],this.requestRender?.()}setRevealUntil(e,t=-1/0){e===this.revealUntil&&t===this.revealFrom||(this.revealUntil=e,this.revealFrom=t,this.requestRender?.())}shownZones(){return[...xE(this.zones,this.revealUntil,this.revealFrom)]}render(e,t,n){let r=this.dataGetter?.(),i=xE(this.zones,this.revealUntil,this.revealFrom);if(!r||r.length===0||i.length===0)return;let{chartRect:a}=t,o=bS(this.style,n);e.save(),e.beginPath(),e.rect(a.x,a.y,a.width,a.height),e.clip();for(let a of i)this.renderZone(e,a,r,t,n,o);e.restore()}renderZone(n,r,i,a,o,s){let{chartRect:c}=a,l=e.N(r.entryTime,i),u=r.exitTime==null?i.length-1:e.N(r.exitTime,i),d=e.w(l,a),f=e.w(u,a),p=Math.max(c.x,Math.min(d,f)),m=Math.min(c.x+c.width,Math.max(d,f));if(m-p<1)return;let h=e.k(r.entryPrice,a),g=r.exitPrice==null?e.k(r.entryPrice,a):e.k(r.exitPrice,a),_=Math.min(h,g),v=Math.max(Math.max(h,g)-_,2),y=r.exitTime==null,b=r.pnl==null?r.direction===`long`?(r.exitPrice??r.entryPrice)>=r.entryPrice:(r.exitPrice??r.entryPrice)<=r.entryPrice:r.pnl>=0,x=y?s.activeColor??`#4c8dff`:b?s.profitColor??`#1fa874`:s.lossColor??`#e8505b`;n.fillStyle=x,n.globalAlpha=s.fillOpacity??.12,n.fillRect(p,_,m-p,v),n.globalAlpha=1;let S=s.borderWidth??1;if(n.strokeStyle=x,n.lineWidth=S,n.setLineDash([]),n.beginPath(),n.moveTo(p,Math.round(h)+.5),n.lineTo(m,Math.round(h)+.5),n.stroke(),!y&&r.exitPrice!=null&&(n.setLineDash([3,3]),n.beginPath(),n.moveTo(p,Math.round(g)+.5),n.lineTo(m,Math.round(g)+.5),n.stroke(),n.setLineDash([])),fx(n,r.direction===`long`?t.UI_ICONS.trendingUp:t.UI_ICONS.trendingDown,p+4,h-3-HE,HE,x),n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`bottom`,n.textAlign=`left`,n.fillText((0,t.priceTagText)(r.entryPrice,a,this.pricePrecision??void 0),p+4+HE+3,h-3),s.showPnl&&!y&&r.pnl!=null){let e=r.pnl>=0?`+`:``,i=e=>(0,t.formatPrice)(e,UE,a.numberLocale??`en-US`),s=r.pnlPercent==null?`${e}${i(r.pnl)}`:`${e}${i(r.pnl)} (${e}${i(r.pnlPercent)}%)`;n.font=`bold 10px ${o.font.family}`,n.fillStyle=x,n.textBaseline=`top`,n.textAlign=`right`;let c=n.measureText(s).width+8,l=m-c-2,u=_+2;n.globalAlpha=.85,n.fillStyle=o.background,A(n,l,u,c,14,o),n.globalAlpha=1,n.fillStyle=x,n.fillText(s,m-4,u+1)}s.showLabel&&r.label&&(n.font=`9px ${o.font.family}`,n.fillStyle=x,n.globalAlpha=.8,n.textBaseline=`top`,n.textAlign=`left`,n.fillText(r.label,p+4,h+3),n.globalAlpha=1)}},KE=2,qE=4,JE=t.MAX_PRICE_DECIMALS,YE=class{active=!1;startBar=0;startPrice=0;endBar=0;endPrice=0;startTime=null;endTime=null;isActive(){return this.active}begin(t,n,r){let i=Math.round(e.P(t.x,n)),a=e.I(t.y,n);this.startBar=i,this.startPrice=a,this.endBar=i,this.endPrice=a,this.startTime=XE(i,r),this.endTime=this.startTime,this.active=!0}update(t,n,r){if(!this.active)return;let i=Math.round(e.P(t.x,n));this.endBar=i,this.endPrice=e.I(t.y,n),this.endTime=XE(i,r)}end(){this.active=!1}render(n,r,i){if(!this.active)return;let a=e.w(this.startBar,r),o=e.w(this.endBar,r),s=e.k(this.startPrice,r),c=e.k(this.endPrice,r),l=Math.min(a,o),u=Math.max(a,o),d=Math.min(s,c),f=Math.max(s,c),p=u-l,m=f-d,h=this.endPrice>=this.startPrice?i.candleUp:i.candleDown,g=rD(h,.14);n.save();let{chartRect:_}=r;n.beginPath(),n.rect(_.x,_.y,_.width,_.height),n.clip(),n.fillStyle=g,n.fillRect(l,d,p,m),n.strokeStyle=h,n.lineWidth=1,n.setLineDash([4,3]),n.strokeRect(l+.5,d+.5,p,m),n.setLineDash([]),n.strokeStyle=h,n.lineWidth=1.5,n.beginPath(),n.moveTo(a,s),n.lineTo(o,c),n.stroke(),eD(n,a,s,h),eD(n,o,c,h),n.restore();let v=Math.abs(this.endBar-this.startBar),y=this.endPrice-this.startPrice,b=this.startPrice===0?0:y/this.startPrice*100,x=this.startTime!==null&&this.endTime!==null?$E(Math.abs(this.endTime-this.startTime)):null,S=[],C=y>0?`+`:y<0?`−`:``,w=Math.abs(y),T=(0,t.formatPrice)(Math.abs(b),KE,r.numberLocale??`en-US`);S.push(`${C}${ZE(w,r)} (${C}${T}%)`),S.push(`${v} bars${x?` · `+x:``}`),n.save(),tD(n,o,c,S,h,i),n.restore()}};function XE(e,n){return e<0||e>=n.length?null:n[e].time*(0,t.barTimeUnit)(n)}function ZE(e,n){return(0,t.priceTagText)(e,n,n.pricePrecision??QE(e))}function QE(e){return e>=1e3?2:e>=1?4:e<=0?qE-1:Math.min(JE,qE-1-Math.floor(Math.log10(e)))}function $E(e){let t=e/1e3;if(t<60)return`${t.toFixed(0)}s`;let n=t/60;if(n<60)return`${n.toFixed(1)}m`;let r=n/60;if(r<24)return`${r.toFixed(1)}h`;let i=r/24;if(i<30)return`${i.toFixed(1)}d`;let a=i/30;return a<12?`${a.toFixed(1)}mo`:`${(i/365).toFixed(1)}y`}function eD(e,t,n,r){e.fillStyle=r,e.beginPath(),e.arc(t,n,3.5,0,Math.PI*2),e.fill(),e.fillStyle=`#fff`,e.beginPath(),e.arc(t,n,1.5,0,Math.PI*2),e.fill()}function tD(e,t,n,r,i,a){e.font=`600 11px ${a.font.family}`;let o=0;for(let t of r){let n=e.measureText(t).width;n>o&&(o=n)}let s=Math.ceil(o)+16,c=r.length*14+12,l=t+8,u=n+8,d=e.canvas.clientWidth||e.canvas.width;l+s>d-4&&(l=t-s-8),l<4&&(l=4),e.fillStyle=a.background,e.globalAlpha=.96,nD(e,l,u,s,c,6),e.fill(),e.globalAlpha=1,e.strokeStyle=i,e.lineWidth=1,nD(e,l+.5,u+.5,s-1,c-1,6),e.stroke(),e.fillStyle=a.text,e.textBaseline=`top`,e.textAlign=`left`;for(let t=0;t<r.length;t++)e.fillStyle=t===0?i:a.textSecondary,e.fillText(r[t],l+8,u+6+t*14)}function nD(e,t,n,r,i,a){e.beginPath(),e.moveTo(t+a,n),e.arcTo(t+r,n,t+r,n+i,a),e.arcTo(t+r,n+i,t,n+i,a),e.arcTo(t,n+i,t,n,a),e.arcTo(t,n,t+r,n,a),e.closePath()}function rD(e,t){if(e.startsWith(`#`)){let n=0,r=0,i=0;return e.length===4?(n=parseInt(e[1]+e[1],16),r=parseInt(e[2]+e[2],16),i=parseInt(e[3]+e[3],16)):e.length>=7&&(n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),i=parseInt(e.slice(5,7),16)),`rgba(${n},${r},${i},${t})`}if(e.startsWith(`rgb`)){let n=e.match(/[\d.]+/g);if(n&&n.length>=3)return`rgba(${n[0]},${n[1]},${n[2]},${t})`}return e}var iD=6,aD=class{start=null;current=null;isActive(){return this.start!==null}begin(e){this.start=e,this.current=e}update(e){this.start&&(this.current=e)}end(){let e=this.start,t=this.current;if(this.cancel(),!e||!t)return null;let n=Math.min(e.x,t.x),r=Math.max(e.x,t.x),i=Math.min(e.y,t.y),a=Math.max(e.y,t.y);return{x0:n,y0:i,x1:r,y1:a,isClick:r-n<6&&a-i<6}}cancel(){this.start=null,this.current=null}render(e,t,n){if(!this.start||!this.current)return;let{chartRect:r}=t,i=e=>Math.max(r.x,Math.min(r.x+r.width,e)),a=e=>Math.max(r.y,Math.min(r.y+r.height,e)),o=i(Math.min(this.start.x,this.current.x)),s=i(Math.max(this.start.x,this.current.x)),c=a(Math.min(this.start.y,this.current.y)),l=a(Math.max(this.start.y,this.current.y));e.save(),e.fillStyle=n.crosshair,e.globalAlpha=.1,e.fillRect(o,c,s-o,l-c),e.globalAlpha=.8,e.strokeStyle=n.crosshair,e.lineWidth=1,e.setLineDash([4,3]),e.strokeRect(Math.round(o)+.5,Math.round(c)+.5,Math.round(s-o),Math.round(l-c)),e.restore()}},oD={linear:e=>e,easeOutCubic:e=>1-(1-e)**3,easeOutQuart:e=>1-(1-e)**4,easeInOutCubic:e=>e<.5?4*e*e*e:1-(-2*e+2)**3/2,easeOutExpo:e=>e===1?1:1-2**(-10*e),easeOutElastic:e=>e===0||e===1?e:2**(-10*e)*Math.sin((e*10-.75)*(2*Math.PI/3))+1,spring:e=>1-Math.E**(-6*e)*Math.cos(8*e)},sD=class{animations=new Map;frameId=0;running=!1;animate(e,t){this.animations.set(e,{startTime:-1,duration:t.duration,easing:t.easing??oD.easeOutCubic,onUpdate:t.onUpdate,onComplete:t.onComplete}),this.running||(this.running=!0,this.tick())}cancel(e){this.animations.delete(e),this.animations.size===0&&this.stop()}cancelAll(){this.animations.clear(),this.stop()}isAnimating(e){return e?this.animations.has(e):this.animations.size>0}tick(){this.frameId=requestAnimationFrame(e=>{let t=[];for(let[n,r]of this.animations){r.startTime<0&&(r.startTime=e);let i=e-r.startTime,a=Math.min(1,i/r.duration),o=r.easing(a);r.onUpdate(o),a>=1&&(r.onComplete?.(),t.push(n))}for(let e of t)this.animations.delete(e);this.animations.size>0?this.tick():this.running=!1})}stop(){this.frameId&&=(cancelAnimationFrame(this.frameId),0),this.running=!1}dispose(){this.cancelAll()}};function cD(e){return!e||e===`dark`?t.DARK_THEME:e===`light`?t.LIGHT_THEME:e}function lD(e,t){let n=cD(e),r=Object.fromEntries(Object.entries(t??{}).filter(([,e])=>e!==void 0));return{...n,font:{...n.font,...r}}}var uD=class{canvas;ctx;container;theme;width=0;height=0;dpr=1;frameId=null;sizer;themeGiven;fontGiven;constructor(e,t,n){this.container=e,this.themeGiven=t,this.fontGiven=n,this.theme=lD(t,n),this.canvas=document.createElement(`canvas`),this.canvas.style.width=`100%`,this.canvas.style.height=`100%`,this.canvas.style.display=`block`,s(this.canvas),this.canvas.setAttribute(`role`,`img`),e.appendChild(this.canvas),this.ctx=this.canvas.getContext(`2d`),this.sizer=new o(e),this.updateSize(),this.sizer.onResize(()=>{this.updateSize(),this.renderNow()})}updateSize(){this.dpr=this.sizer.getDpr();let e=this.sizer.readContainerSize();if(this.width=e.width,this.height=e.height,this.width<=0||this.height<=0)return;let t=i(e,this.dpr,this.sizer.getDeviceSize());this.canvas.width!==t.width&&(this.canvas.width=t.width),this.canvas.height!==t.height&&(this.canvas.height=t.height)}requestRender(){this.frameId===null&&(this.frameId=requestAnimationFrame(()=>{this.frameId=null,(this.width===0||this.height===0)&&this.updateSize(),this.renderNow()}))}renderNow(){this.width===0||this.height===0||(this.ctx.save(),this.ctx.setTransform(this.canvas.width/this.width,0,0,this.canvas.height/this.height,0,0),this.ctx.clearRect(0,0,this.width,this.height),this.renderChart(this.ctx,this.width,this.height,this.theme),this.ctx.restore())}applyBaseOptions(e){`theme`in e&&(this.themeGiven=e.theme),`font`in e&&(this.fontGiven=e.font),(`theme`in e||`font`in e)&&(this.theme=lD(this.themeGiven,this.fontGiven)),e.ariaLabel!==void 0&&this.setLabel(e.ariaLabel)}setLabel(e){this.canvas.setAttribute(`aria-label`,e)}setTheme(e){this.themeGiven=e,this.theme=lD(e,this.fontGiven),this.requestRender()}destroy(){this.frameId!==null&&cancelAnimationFrame(this.frameId),this.sizer.destroy(),this.canvas.width=0,this.canvas.height=0,this.canvas.remove()}},dD=class{pos=null;canvas;onUpdate;handleMove;handleLeave;handleOutside;handleCancel;constructor(e,t){this.canvas=e,this.onUpdate=t,this.handleMove=t=>{let n=e.getBoundingClientRect();this.pos={x:t.clientX-n.left,y:t.clientY-n.top},this.onUpdate()},this.handleLeave=e=>{e.pointerType!==`touch`&&this.clear()},this.handleOutside=t=>{t.composedPath().includes(e)||this.clear()},this.handleCancel=()=>this.clear(),e.addEventListener(`pointermove`,this.handleMove),e.addEventListener(`pointerdown`,this.handleMove),e.addEventListener(`pointerleave`,this.handleLeave),e.addEventListener(`pointercancel`,this.handleCancel),e.ownerDocument.addEventListener(`pointerdown`,this.handleOutside,!0)}clear(){this.pos!==null&&(this.pos=null,this.onUpdate())}getPosition(){return this.pos}isActive(){return this.pos!==null}drawCrosshair(e,t,n,r){this.pos&&(e.save(),e.strokeStyle=r,e.lineWidth=.5,e.setLineDash([4,4]),e.beginPath(),e.moveTo(this.pos.x,0),e.lineTo(this.pos.x,n),e.stroke(),e.beginPath(),e.moveTo(0,this.pos.y),e.lineTo(t,this.pos.y),e.stroke(),e.restore())}destroy(){this.canvas.removeEventListener(`pointermove`,this.handleMove),this.canvas.removeEventListener(`pointerdown`,this.handleMove),this.canvas.removeEventListener(`pointerleave`,this.handleLeave),this.canvas.removeEventListener(`pointercancel`,this.handleCancel),this.canvas.ownerDocument.removeEventListener(`pointerdown`,this.handleOutside,!0)}};function fD(e,n,r,i,a){let{data:o,mode:s=`area`,lineWidth:c=1.5,showLastPoint:l=!1,showMinMax:u=!1}=i;if(o.length<2||n<=0||r<=0)return;let d=i.color??a.lineColor,f=i.fillColor??d,p=n-4,m=r-4,h=1/0,g=-1/0,_=0,v=0;for(let e=0;e<o.length;e++)o[e]<h&&(h=o[e],_=e),o[e]>g&&(g=o[e],v=e);let y=g-h||1,b=e=>2+e/(o.length-1)*p,x=e=>2+m-(e-h)/y*m;if(s===`area`){let n=e.createLinearGradient(0,2,0,r-2);n.addColorStop(0,(0,t.withAlpha)(f,Hd)),n.addColorStop(1,`transparent`),e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));e.lineTo(b(o.length-1),r-2),e.lineTo(b(0),r-2),e.closePath(),e.fillStyle=n,e.fill()}e.beginPath(),e.moveTo(b(0),x(o[0]));for(let t=1;t<o.length;t++)e.lineTo(b(t),x(o[t]));if(e.strokeStyle=d,e.lineWidth=c,e.lineJoin=`round`,e.stroke(),l){let t=i.lastPointColor??d,n=b(o.length-1),r=x(o[o.length-1]);e.beginPath(),e.arc(n,r,3,0,Math.PI*2),e.fillStyle=t,e.fill()}if(u){let t=i.minPointColor??a.candleDown,n=i.maxPointColor??a.candleUp;e.beginPath(),e.arc(b(_),x(h),2.5,0,Math.PI*2),e.fillStyle=t,e.fill(),e.beginPath(),e.arc(b(v),x(g),2.5,0,Math.PI*2),e.fillStyle=n,e.fill()}}var pD=.2,mD=.01,hD=24,gD=16,_D=`Spread`;function vD(e,t){let n=e.filter(e=>Number.isFinite(e.price)&&Number.isFinite(e.volume)).sort((e,n)=>t===`bid`?n.price-e.price:e.price-n.price),r=0;return n.map(e=>({price:e.price,cumulativeVolume:r+=e.volume}))}function yD(e,t,n,r){let i=vD(e.data.bids,`bid`),a=vD(e.data.asks,`ask`),o=i[0]?.price,s=a[0]?.price,c=o!==void 0&&s!==void 0,l=c?(o+s)/2:o??s??0,u=i.length>0?i[i.length-1].price:l,d=a.length>0?a[a.length-1].price:l,f=(Math.max(l-u,d-l)||Math.abs(l)*mD||1)*(1+pD),p=$d(0,Math.max(0,...i.map(e=>e.cumulativeVolume),...a.map(e=>e.cumulativeVolume))||1,5),m=e.volumeFormat??q(p,e.locale),h=12+Math.max(0,...p.ticks.map(e=>r(m(e),11)))+8,g=12+(c&&e.midPriceLine!==!1&&e.spreadLabel!==!1?gD:0);return{plot:{x:h,y:g,width:Math.max(1,t-h-12),height:Math.max(1,n-g-12-20)},volume:p,priceMin:l-f,priceMax:l+f,bids:i,asks:a,mid:c?l:null,spread:c?s-o:0}}function bD(e,t){return e.length===1?[e[0],{price:t,cumulativeVolume:e[0].cumulativeVolume}]:e}function xD(e,t,n){let r=null;for(let i of e){if(n===`bid`?i.price<t:i.price>t)break;r=i}return r}function SD(e,n,r,i,a,o,s){if(n<=0||r<=0)return;e.fillStyle=a.background,e.fillRect(0,0,n,r);let{data:c}=i;if(c.bids.length===0&&c.asks.length===0)return;let l=s??((t,n=11)=>(e.font=J(a,n),e.measureText(t).width)),{plot:u,volume:d,priceMin:f,priceMax:p,bids:m,asks:h,mid:g,spread:_}=yD(i,n,r,l),v=u.y+u.height,y=e=>u.x+(e-f)/(p-f)*u.width,b=e=>G(d,e,u.y,u.height,!0),x=wf([...m,...h].map(e=>e.price)),S=i.priceFormat??sf(i.locale,x),C=i.volumeFormat??K(i.locale);Tf(e,u,d,`vertical`,a,i.volumeFormat??q(d,i.locale)),e.save(),e.font=J(a,11),e.fillStyle=a.axisLabel,e.strokeStyle=a.grid,e.textAlign=`center`,e.textBaseline=`top`;let w=l(S(p),11)+hD,T=$d(f,p,Math.max(2,Math.floor(u.width/w))),E=i.priceFormat??q(T,i.locale);e.font=J(a,11);for(let t of T.ticks)t<f||t>p||(gf(e,y(t),u.y,y(t),v),e.fillText(E(t),Math.round(y(t)),v+6));e.restore();let D=(t,n,r)=>{if(t.length===0)return;let i=()=>{for(let n=1;n<t.length;n++)e.lineTo(y(t[n].price),b(t[n-1].cumulativeVolume)),e.lineTo(y(t[n].price),b(t[n].cumulativeVolume))};e.fillStyle=r,e.beginPath(),e.moveTo(y(t[0].price),v),e.lineTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.lineTo(y(t[t.length-1].price),v),e.closePath(),e.fill(),e.strokeStyle=n,e.lineWidth=1.5,e.lineJoin=`miter`,e.beginPath(),e.moveTo(y(t[0].price),b(t[0].cumulativeVolume)),i(),e.stroke()},O=i.bidColor??a.candleUp,k=i.askColor??a.candleDown;if(e.save(),e.beginPath(),e.rect(u.x,u.y,u.width,u.height),e.clip(),D(bD(m,f),O,i.bidFillColor??(0,t.withAlpha)(O,.25)),D(bD(h,p),k,i.askFillColor??(0,t.withAlpha)(k,.25)),e.restore(),g!==null&&i.midPriceLine!==!1&&(e.save(),e.strokeStyle=a.textSecondary,e.setLineDash([4,4]),gf(e,y(g),u.y,y(g),v),e.setLineDash([]),i.spreadLabel!==!1&&(e.font=J(a,11),e.fillStyle=a.textSecondary,e.textAlign=`center`,e.textBaseline=`middle`,e.fillText(`${typeof i.spreadLabel==`string`?i.spreadLabel:_D}: ${S(_)}`,Math.round(y(g)),12+gD/2-2)),e.restore()),!o||o.x<u.x||o.x>u.x+u.width)return;let A=f+(o.x-u.x)/u.width*(p-f);e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(e,o.x,u.y,o.x,v),e.restore();let j=xD(m,A,`bid`),ee=xD(h,A,`ask`),te=[{text:S((j??ee)?.price??A),bold:!0}];j&&te.push({text:C(j.cumulativeVolume),color:O}),ee&&te.push({text:C(ee.cumulativeVolume),color:k}),mf(e,te,o,{x:0,y:0,width:n,height:r},a)}var CD=.19,wD=864e5,TD=80,ED=3,DD=.05,OD=`Benchmark`;function kD(e,t){let n=-1,r=1/0;for(let i=0;i<e.length;i++){let a=Math.abs(e[i].time-t);a<r&&(r=a,n=i)}return n}function AD(e,t,n){return of(n,e<wD?{...t>wD?{month:`short`,day:`numeric`}:{},hour:`2-digit`,minute:`2-digit`}:e>=28*wD?{month:`short`,...t>=365*wD?{year:`numeric`}:{},timeZone:`UTC`}:{month:`short`,day:`numeric`,timeZone:`UTC`})}function jD(e,t){let n=e<7*wD;return of(t,{month:`short`,day:`numeric`,...e>=365*wD?{year:`numeric`}:{},...n?{hour:`2-digit`,minute:`2-digit`}:{timeZone:`UTC`}})}function MD(e){for(let t=1;t<e.length;t++)if(e[t].time<e[t-1].time)return[...e].sort((e,t)=>e.time-t.time);return e}function ND(e,t,n,r,i=``){let{data:a,benchmark:o}=e,s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of a)Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value)),Number.isFinite(e.time)&&(l=Math.min(l,e.time),u=Math.max(u,e.time));for(let e of o??[])Number.isFinite(e.value)&&(s=Math.min(s,e.value),c=Math.max(c,e.value));let d=s===c?Math.abs(s)*DD||1:0,f=$d(s-d,c+d,5),p=e.valueFormat??q(f,e.locale),m=Math.max(0,...f.ticks.map(e=>r(p(e),11))),h=o&&o.length>=2?ff([{label:e.benchmarkLabel??OD,color:i}],t-24,r):null,g=12+m+8,_=12+(h?h.height+6:0);return{plot:{x:g,y:_,width:Math.max(1,t-g-12),height:Math.max(1,n-_-12-20)},scale:f,timeMin:l,timeMax:u,legend:h}}function PD(e,t,n,r,i,a){let{plot:o,timeMin:s,timeMax:c}=t,l=Cf(s,c,Math.max(1,Math.floor(o.width/TD))),u=i??AD(l.length>1?l[1]-l[0]:c-s,c-s,a);e.save(),e.font=J(r,11),e.fillStyle=r.axisLabel,e.strokeStyle=r.grid,e.textAlign=`center`,e.textBaseline=`top`;for(let t of l){let r=o.x+(t-s)/(c-s)*o.width;gf(e,r,o.y,r,o.y+o.height);let i=u(t),a=e.measureText(i).width/2;r-a>=0&&r+a<=n&&e.fillText(i,Math.round(r),o.y+o.height+6)}e.restore()}function FD(e,n,r,i,a,o,s){if(n<=0||r<=0||(e.fillStyle=a.background,e.fillRect(0,0,n,r),i.data.length<2))return;let c=MD(i.data),l=i.benchmark&&MD(i.benchmark),u=s??((t,n=11)=>(e.font=J(a,n),e.measureText(t).width)),d=i.lineColor??a.lineColor,f=i.benchmarkColor??a.textSecondary,p=ND(i,n,r,u,f),{plot:m,scale:h,timeMin:g,timeMax:_,legend:v}=p;if(!(_>=g))return;let y=_-g||1,b=e=>m.x+(e-g)/y*m.width,x=e=>G(h,e,m.y,m.height,!0),S=m.y+m.height,C=i.timeFormat??jD(y,i.locale);Tf(e,m,h,`vertical`,a,i.valueFormat??q(h,i.locale)),PD(e,p,n,a,i.timeFormat,i.locale),v&&pf(e,v,m.x,12,a);let w=(t,n=e=>t[e].value)=>{e.moveTo(b(t[0].time),x(n(0)));for(let r=1;r<t.length;r++)e.lineTo(b(t[r].time),x(n(r)))};if(e.save(),e.beginPath(),e.rect(m.x,m.y,m.width,m.height),e.clip(),i.drawdown===!0){let n=[],r=-1/0;for(let e of c)n.push(r=Number.isFinite(e.value)?Math.max(r,e.value):r);e.fillStyle=i.drawdownColor??(0,t.withAlpha)(a.candleDown,CD),e.beginPath(),w(c,e=>n[e]);for(let t=c.length-1;t>=0;t--)e.lineTo(b(c[t].time),x(c[t].value));e.closePath(),e.fill()}if(i.fillArea===!0){let n=e.createLinearGradient(0,m.y,0,S);n.addColorStop(0,(0,t.withAlpha)(d,Hd)),n.addColorStop(1,`transparent`),e.fillStyle=n,e.beginPath(),w(c),e.lineTo(b(c[c.length-1].time),S),e.lineTo(b(c[0].time),S),e.closePath(),e.fill()}if(e.lineJoin=`round`,l&&l.length>=2&&(e.strokeStyle=f,e.lineWidth=1,e.beginPath(),w(l),e.stroke()),e.strokeStyle=d,e.lineWidth=i.lineWidth??1.5,e.beginPath(),w(c),e.stroke(),e.restore(),!o||o.x<m.x||o.x>m.x+m.width)return;let T=c[kD(c,g+(o.x-m.x)/m.width*y)];if(!T)return;e.save(),e.strokeStyle=a.crosshair,e.setLineDash([4,4]),gf(e,b(T.time),m.y,b(T.time),S),e.restore(),e.fillStyle=d,e.beginPath(),e.arc(b(T.time),x(T.value),ED,0,Math.PI*2),e.fill();let E=i.valueFormat??K(i.locale),D=[{text:C(T.time),bold:!0},{text:E(T.value),color:d}],O=l?kD(l,T.time):-1;l&&O>=0&&D.push({text:`${i.benchmarkLabel??OD}: ${E(l[O].value)}`,color:f}),mf(e,D,o,{x:0,y:0,width:n,height:r},a)}function ID(e,t,n){if(e.length===0)return[];let r=e.length,i=Math.ceil(Math.sqrt(r)),a=Math.ceil(r/i),o=t.width/i,s=t.height/a,c=[];for(let a=0;a<r;a++){let r=a%i,l=Math.floor(a/i);c.push({id:e[a].id,rect:{x:t.x+r*o+n,y:t.y+l*s+n,width:Math.max(0,o-n*2),height:Math.max(0,s-n*2)}})}return c}function LD(e,t){let n=e.reduce((e,t)=>e+t,0);if(n===0||t===0)return 1/0;let r=0;for(let i of e){let e=n/t,a=i/e,o=e>a?e/a:a/e;o>r&&(r=o)}return r}function RD(e,t,n,r,i,a){let o=r?n.height:n.width,s=e.reduce((e,t)=>e+t,0),c=o>0?s/o:0,l=0;for(let o=0;o<e.length;o++){let s=c>0?e[o]/c:0,u;u=r?{x:n.x+i,y:n.y+l+i,width:Math.max(0,c-i*2),height:Math.max(0,s-i*2)}:{x:n.x+l+i,y:n.y+i,width:Math.max(0,s-i*2),height:Math.max(0,c-i*2)},a.push({id:t[o],rect:u}),l+=s}}function zD(e,t,n,r,i){if(e.length===0)return;let a=n.width>=n.height,o=a?n.height:n.width;if(e.length===1){RD(e,t,n,a,r,i);return}let s=[],c=[],l=0;for(;l<e.length;){let u=[...s,e[l]];if(s.length===0||LD(u,o)<=LD(s,o))s.push(e[l]),c.push(t[l]),l++;else{RD(s,c,n,a,r,i);let u=s.reduce((e,t)=>e+t,0),d=o>0?u/o:0;n=a?{x:n.x+d,y:n.y,width:n.width-d,height:n.height}:{x:n.x,y:n.y+d,width:n.width,height:n.height-d},zD(e.slice(l),t.slice(l),n,r,i);return}}s.length>0&&RD(s,c,n,a,r,i)}function BD(e,t,n){if(e.length===0)return[];let r=e=>e.weight>0&&Number.isFinite(e.weight)?e.weight:0,i=[...e].sort((e,t)=>r(t)-r(e)),a=i.reduce((e,t)=>e+r(t),0);if(a===0)return[];let o=t.width*t.height,s=i.map(e=>r(e)/a*o),c=i.map(e=>e.id),l=[];return zD(s,c,{...t},n,l),l}var VD=2,HD=18;function UD(e,t,n,r=18){let i=new Map;for(let t of e){if(!(t.weight>0))continue;let e=t.group??``,n=i.get(e);n?n.push(t):i.set(e,[t])}let a=[...i.keys()],o=BD(a.map((e,t)=>({id:String(t),weight:i.get(e).reduce((e,t)=>e+t.weight,0)})),t,0),s=[],c=[];for(let e of o){let t=a[Number(e.id)],o=i.get(t),l=o.reduce((e,t)=>e+t.weight,0),u=o.reduce((e,t)=>e+(Number.isFinite(t.value)?t.value*t.weight:0),0),d=e.rect,f=t!==``&&d.height>=r*2.5&&d.width>=40?r:0,p={x:d.x+VD/2,y:d.y+VD/2+f,width:Math.max(0,d.width-VD),height:Math.max(0,d.height-VD-f)};s.push({name:t,rect:{...d},header:f,value:l>0?u/l:0,count:o.length}),c.push(...BD(o,p,n))}return{groups:s,cells:c}}function WD(e){return Number.isFinite(e)?(e>=0?`+`:``)+e.toFixed(2)+`%`:``}function GD(e){return e.label}function KD(e,n){let r=n.min??-5,i=n.max??5;if(!Number.isFinite(e))return n.zero;if(e<=r)return n.negative;if(e>=i)return n.positive;if(e<0){let i=1-e/r;return(0,t.lerpColor)(n.negative,n.zero,i)}let a=e/i;return(0,t.lerpColor)(n.zero,n.positive,a)}var qD=`#FFFFFF`,JD=`#11151b`;function YD(e,n){let r=/^rgba\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)$/i.exec(e.trim());return Lf(r?(0,t.lerpColor)(n,`rgb(${r[1]},${r[2]},${r[3]})`,Number(r[4])):(0,t.lerpColor)(e,e,0))===JD?JD:qD}function XD(e,t,n,r,i,a){let o=Math.min(a,r/2,i/2);e.beginPath(),e.moveTo(t+o,n),e.lineTo(t+r-o,n),e.arcTo(t+r,n,t+r,n+o,o),e.lineTo(t+r,n+i-o),e.arcTo(t+r,n+i,t+r-o,n+i,o),e.lineTo(t+o,n+i),e.arcTo(t,n+i,t,n+i-o,o),e.lineTo(t,n+o),e.arcTo(t,n,t+o,n,o),e.closePath()}function ZD(e,t,n,r,i,a,o,s,c,l,u,d){if(i<40||a<30)return;let f=n+i/2,p=r+a/2;e.save();let m=d===qD;if(e.shadowColor=m?`rgba(0,0,0,0.6)`:`transparent`,e.shadowBlur=m?2:0,e.fillStyle=d,e.textAlign=`center`,s){let n=l(t),r=Math.min(o.font.sizeMedium,i/n.length*1.5,a/4);e.font=`bold `+Math.max(8,r)+`px `+o.font.family,e.textBaseline=c?`bottom`:`middle`,e.fillText(n,f,c?p-1:p,i-8)}if(c){let n=u(t.value),r=Math.min(o.font.sizeSmall,i/n.length*1.5,a/4);e.font=Math.max(7,r)+`px `+o.font.family,e.textBaseline=s?`top`:`middle`,e.fillText(n,f,s?p+1:p,i-8)}e.restore()}function QD(e,t,n,r){let i=[{text:n(e),bold:!0}],a=r(e.value);a!==``&&i.push({text:a,color:t});for(let[t,n]of Object.entries(e.meta??{}))i.push({text:t+`: `+String(n)});return i}function $D(e,t,n,r,i,a,o,s,c=[]){if(t<=0||n<=0||(e.fillStyle=o.background,e.fillRect(0,0,t,n),r.length===0||i.length===0))return null;let l=a.colorScale,u=Nf([],o,l),d={negative:u.negative,zero:u.zero,positive:u.positive,min:l?.min,max:l?.max},f=a.cellRadius??4,p=a.showLabels!==!1,m=a.showValues!==!1,h=a.valueFormat??WD,g=a.labelFormat??GD,_=new Map;for(let e of r)_.set(e.id,e);let v=null,y=null;if(s)for(let e of i){let{x:t,y:n,width:r,height:i}=e.rect;if(s.x>=t&&s.x<=t+r&&s.y>=n&&s.y<=n+i){v=e.id;let t=_.get(e.id);t&&(y={cell:t,rect:e});break}}for(let t of i){let n=_.get(t.id);if(!n)continue;let{x:r,y:i,width:a,height:s}=t.rect;if(a<=0||s<=0)continue;let c=KD(n.value,d);XD(e,r,i,a,s,f),e.fillStyle=c,e.fill(),ZD(e,n,r,i,a,s,o,p,m,g,h,YD(c,o.background)),t.id===v&&(XD(e,r,i,a,s,f),e.strokeStyle=o.text,e.lineWidth=1.5,e.stroke())}let b=s&&!y?c.find(e=>e.header>0&&eO(e,s)):void 0;return tO(e,c,o,h,b),y&&s?mf(e,QD(y.cell,KD(y.cell.value,d),g,h),s,{x:0,y:0,width:t,height:n},o):b&&s&&mf(e,QD({id:``,label:b.name,value:b.value},void 0,e=>e.label,h),s,{x:0,y:0,width:t,height:n},o),y}function eO(e,t){let n=e.rect;return t.x>=n.x&&t.x<=n.x+n.width&&t.y>=n.y&&t.y<=n.y+e.header}function tO(e,t,n,r,i){if(t.length===0)return;e.save(),e.textBaseline=`middle`;let a=n.font.sizeSmall,o=t=>e.measureText(t).width;for(let s of t){if(s.header<=0)continue;let{x:t,y:c,width:l}=s.rect,u=c+s.header/2+1;e.font=a+`px `+n.font.family;let d=r(s.value),f=o(d),p=l>=f*2+24;p&&(e.textAlign=`right`,e.fillStyle=s.value<0?n.candleDown:s.value>0?n.candleUp:n.textSecondary,e.fillText(d,t+l-5,u)),e.font=`600 `+a+`px `+n.font.family,e.textAlign=`left`,e.fillStyle=s===i?n.text:n.textSecondary;let m=l-10-(p?f+8:0),h=Ef(s.name,m,e=>o(e),a);h&&e.fillText(h,t+5,u)}e.restore()}var nO=.7,rO=1,iO=.382,aO=Math.PI/4,oO=4;function sO(e){return e.type?e.type:e.value<0?`negative`:`positive`}function cO(e){let t=0;return e.map(e=>{let n=sO(e),r=Number.isFinite(e.value)?e.value:0,i=n===`total`||n===`subtotal`?0:t,a=i+r;return t=a,{type:n,value:r,start:i,end:a}})}function lO(e,t,n,r){let i=e.data??[],a=cO(i),o=0,s=0;for(let{start:e,end:t}of a)o=Math.min(o,e,t),s=Math.max(s,e,t);let c=(s-o||1)*.1,l=$d(o<0?o-c:0,s>0?s+c:0,5),u=e.valueFormat??q(l,e.locale),d=12+Math.max(0,...l.ticks.map(e=>r(u(e),11)))+8,f=Math.max(1,t-d-12),p=f/Math.max(1,i.length),m=e.labelFormat??(e=>e),h=Math.max(0,...i.map(e=>r(m(e.label),11))),g=h>p-4,_=g?Math.min(n*iO,Math.ceil((h+11)*Math.sin(aO))+6):20,v={x:d,y:12,width:f,height:Math.max(1,n-24-_)},y=p*Math.min(1,Math.max(.05,e.barWidth??nO)),b=e=>G(l,e,v.y,v.height,!0);return{plot:v,scale:l,bars:a.map((e,t)=>{let n=Math.min(b(e.start),b(e.end)),r=v.x+t*p;return{label:i[t].label,value:e.value,type:e.type,start:e.start,end:e.end,x:r+(p-y)/2,y:n,width:y,height:Math.max(rO,Math.abs(b(e.end)-b(e.start))),slotX:r,slotWidth:p}}),turned:g,labelRoom:_}}function uO(e,t){let{plot:n,bars:r}=e;return r.length===0||t<n.x||t>n.x+n.width?-1:Math.min(r.length-1,Math.floor((t-n.x)/r[0].slotWidth))}function dO(e,t,n,r){let{bars:i,scale:a,plot:o}=t;if(r!==`none`){e.save(),e.strokeStyle=n,e.setLineDash(r===`dashed`?[4,4]:[]);for(let t=0;t<i.length-1;t++){let n=i[t].x+i[t].width,r=i[t+1].x,s=G(a,i[t].end,o.y,o.height,!0);r>n&&gf(e,n,s,r,s)}e.restore()}}function fO(e,t,n,r,i){e.save(),e.font=J(n,10),e.fillStyle=n.textSecondary,e.textAlign=`center`;let a=[];for(let n of t.bars){let t=n.type===`positive`||n.type===`negative`?i?`${n.value>=0?`+`:``}${r(n.value)}`:r(n.end):r(n.value),o=e.measureText(t).width,s=n.end<n.start,c=n.x+n.width/2,l={x:c-o/2,y:s?n.y+n.height+oO:n.y-oO-11,width:o,height:11};a.some(e=>l.x<e.x+e.width+2&&e.x<l.x+l.width+2&&l.y<e.y+e.height&&e.y<l.y+l.height)||(a.push(l),e.textBaseline=s?`top`:`bottom`,e.fillText(t,Math.round(c),Math.round(s?l.y:n.y-oO)))}e.restore()}function pO(e,t,n,r,i){let{plot:a,bars:o,turned:s,labelRoom:c}=t;e.save(),e.font=J(n,11),e.fillStyle=n.axisLabel;let l=a.y+a.height+6;if(!s){e.textAlign=`center`,e.textBaseline=`top`;for(let t of o)e.fillText(r(t.label),Math.round(t.slotX+t.slotWidth/2),l);e.restore();return}e.textAlign=`right`,e.textBaseline=`middle`;for(let t of o){let n=t.slotX+t.slotWidth/2,a=Math.min((c-6)/Math.sin(aO)-11,(n-2)/Math.cos(aO)),o=Ef(r(t.label),a,i);o&&(e.save(),e.translate(n,l+2),e.rotate(-aO),e.fillText(o,0,0),e.restore())}e.restore()}function mO(e,t,n,r,i,a,o){if(t<=0||n<=0)return{hitBar:null};e.fillStyle=i.background,e.fillRect(0,0,t,n);let s=r.data;if(!s||s.length===0)return{hitBar:null};let c=o??((t,n=11)=>(e.font=J(i,n),e.measureText(t).width)),l=lO(r,t,n,c),{plot:u,scale:d,bars:f}=l,p=r.valueFormat??q(d,r.locale),m=r.valueFormat??K(r.locale),h={positive:r.positiveColor??i.candleUp,negative:r.negativeColor??i.candleDown,total:r.totalColor??i.lineColor,subtotal:r.subtotalColor??i.textSecondary};Tf(e,u,d,`vertical`,i,p),dO(e,l,r.connectorColor??i.textSecondary,r.connectorStyle??`dashed`);let g=hf(e);for(let t of f){let n=g.x(t.x)-g.width/2,r=g.x(t.x+t.width)-g.width/2;e.fillStyle=h[t.type],e.fillRect(n,t.y,Math.max(g.width,r-n),t.height)}e.strokeStyle=i.axisLine;let _=G(d,0,u.y,u.height,!0);gf(e,u.x,_,u.x+u.width,_),r.showValues!==!1&&fO(e,l,i,m,r.showDelta!==!1),pO(e,l,i,r.labelFormat??(e=>e),c);let v=a?uO(l,a.x):-1;if(a&&v>=0){let r=f[v],o=r.slotX+r.slotWidth/2;e.save(),e.strokeStyle=i.crosshair,e.setLineDash([4,4]),gf(e,o,u.y,o,u.y+u.height),e.restore();let s=r.type===`positive`||r.type===`negative`,c=[{text:r.label,bold:!0}];s&&c.push({text:`${r.value>=0?`+`:``}${m(r.value)}`,color:h[r.type]}),c.push({text:s?`= ${m(r.end)}`:m(r.end),color:s?void 0:h[r.type]}),mf(e,c,a,{x:0,y:0,width:t,height:n},i)}return{hitBar:v>=0?v:null}}var hO=Math.PI/180,gO=150,_O=240,vO=90,yO=.14,bO=1.6*hO,xO=.22,SO=8,CO=18,wO=16,TO=6.5,EO=20,DO=5,OO=28;function kO(e,t,n){return e<t?t:e>n?n:e}function AO(e){let t=Math.abs(e);return t>=1e6?(e/1e6).toFixed(2)+`M`:t>=1e3?(e/1e3).toFixed(1)+`K`:Number.isInteger(e)?e.toFixed(0):e.toFixed(1)}function jO(e){let t=Number.isFinite(e.startAngle)?e.startAngle:gO,n=(Number.isFinite(e.endAngle)?e.endAngle:t+_O)-t;return n<=0&&(n=(n%360+360)%360||360),n=kO(n,vO,360),{start:(t%360+360)%360*hO,sweep:n*hO}}function MO(e,t){let n=Math.min(Math.cos(e),Math.cos(t)),r=Math.max(Math.cos(e),Math.cos(t)),i=Math.min(Math.sin(e),Math.sin(t)),a=Math.max(Math.sin(e),Math.sin(t));for(let o=Math.ceil(e/(Math.PI/2));Math.PI/2*o<=t;o++){let e=Math.PI/2*o;n=Math.min(n,Math.cos(e)),r=Math.max(r,Math.cos(e)),i=Math.min(i,Math.sin(e)),a=Math.max(a,Math.sin(e))}return{minX:n,maxX:r,minY:i,maxY:a}}function NO(e){if(e.showZoneLabels!==!0||!e.zones)return 0;let t=e.zones.reduce((e,t)=>Math.max(e,t.label?.length??0),0);return t>0?t*TO+12:0}function PO(e,t,n){let r=Number.isFinite(n.min)?n.min:0,i=Number.isFinite(n.max)?n.max:100;i-r>Math.abs(r)*1e-9||(i=r+Math.max(1,Math.abs(r)*1e-6));let{start:a,sweep:o}=jO(n),s=a,c=a+o,l=kO(n.thickness??yO,.04,.5),u=MO(s,c),d=Math.max(u.maxY,.18),f=NO(n),p=f>0?wO:0,m=Math.max(1,e-2*SO-2*f),h=Math.max(1,t-2*SO-CO-p),g=1+l/2,_=Math.max(8,Math.min(m/((u.maxX-u.minX)*g),h/((d-u.minY)*g))),v=_*l,y=(d-u.minY)*_*g+CO+p,b=e/2-(u.maxX+u.minX)/2*_,x=(t-y)/2+p-u.minY*_*g,S=_-v/2,C=Math.max(11,Math.round(S*.46)),w=u.maxY>.3?x-C*.12:x-C*.55,T=Math.max(Math.sin(s),Math.sin(c)),E=T>.2?x+T*_+v/2+2:1/0,D=Math.min(t-SO,E);return{cx:b,cy:x,radius:_,thickness:v,startAngle:s,endAngle:c,min:r,max:i,valueY:w,valueSize:C,textBottom:D}}function FO(e,t){let n=Number.isFinite(e)?kO((e-t.min)/(t.max-t.min),0,1):0;return t.startAngle+(t.endAngle-t.startAngle)*n}function IO(e,t){if(!t||!Number.isFinite(e))return;let n;for(let r of t)e>=r.from&&e<=r.to&&(n=r);return n}function LO(e,t,n){let r=(t??[]).map(t=>({a0:FO(t.from,e),a1:FO(t.to,e),color:t.color,track:!1})).filter(e=>e.a1>e.a0).sort((e,t)=>e.a0-t.a0),i=[],a=e.startAngle;for(let e of r)e.a1<=a||(e.a0>a+1e-9&&i.push({a0:a,a1:e.a0,color:n,track:!0}),i.push({...e,a0:Math.max(e.a0,a)}),a=e.a1);return a<e.endAngle-1e-9&&i.push({a0:a,a1:e.endAngle,color:n,track:!0}),i}function RO(e,t,n,r,i){r<=n||(e.beginPath(),e.arc(t.cx,t.cy,t.radius,n,r,!1),e.lineWidth=t.thickness,e.lineCap=`butt`,e.strokeStyle=i,e.stroke())}function zO(e,t,n,r,i,a){let o=t.cx+Math.cos(n)*t.radius,s=t.cy+Math.sin(n)*t.radius,c=a===`start`?n-Math.PI:n;e.globalAlpha=i,e.beginPath(),e.arc(o,s,t.thickness/2,c,c+(i>=1?Math.PI*2:Math.PI),!1),e.closePath(),e.fillStyle=r,e.fill(),e.globalAlpha=1}function BO(e,t,n,r,i,a){let o=LO(t,n,i),s=o.some(e=>!e.track);o.forEach((n,i)=>{let a=i>0&&!n.track&&!o[i-1].track?bO/2:0,s=i<o.length-1&&!n.track&&!o[i+1].track?bO/2:0,c=n.a0+a,l=n.a1-s;if(n.track){RO(e,t,c,l,n.color);return}e.globalAlpha=xO,RO(e,t,c,l,n.color),e.globalAlpha=1,RO(e,t,c,Math.min(l,r),n.color)}),s||RO(e,t,t.startAngle,r,a);let c=r>t.startAngle+1e-9,l=r>=t.endAngle-1e-9,u=(e,t)=>e.track?[!s&&t?a:i,1]:[e.color,t?1:xO],[d,f]=u(o[0],c),[p,m]=u(o[o.length-1],l);zO(e,t,t.startAngle,d,f,`start`),zO(e,t,t.endAngle,p,m,`end`)}function VO(e,t,n){let r=t.radius-t.thickness/2;if(r<OO)return;let i=Math.max(4,t.thickness*.45);e.strokeStyle=n,e.lineCap=`butt`;for(let n=0;n<=EO;n++){let a=n%DO===0,o=t.startAngle+(t.endAngle-t.startAngle)*n/EO,s=r-i,c=s-(a?Math.max(6,t.thickness*.55):Math.max(3,t.thickness*.3));e.globalAlpha=a?.55:.3,e.lineWidth=a?1.5:1,e.beginPath(),e.moveTo(t.cx+Math.cos(o)*s,t.cy+Math.sin(o)*s),e.lineTo(t.cx+Math.cos(o)*c,t.cy+Math.sin(o)*c),e.stroke()}e.globalAlpha=1}function HO(e,t,n,r,i){let a=t.cx+Math.cos(n)*t.radius,o=t.cy+Math.sin(n)*t.radius;e.beginPath(),e.arc(a,o,t.thickness*.78,0,Math.PI*2),e.fillStyle=r,e.fill(),e.lineWidth=Math.max(2,t.thickness*.32),e.strokeStyle=i,e.stroke()}function UO(e,t,n,r,i){let a=Math.cos(n),o=Math.sin(n),s=t.radius-t.thickness*.9,c=Math.max(6,t.thickness*.6),l=Math.max(1.5,t.thickness*.14);e.beginPath(),e.moveTo(t.cx+a*s,t.cy+o*s),e.lineTo(t.cx-o*l-a*c,t.cy+a*l-o*c),e.lineTo(t.cx+o*l-a*c,t.cy-a*l-o*c),e.closePath(),e.fillStyle=r,e.fill(),e.beginPath(),e.arc(t.cx,t.cy,Math.max(4,t.thickness*.42),0,Math.PI*2),e.fill(),e.lineWidth=2,e.strokeStyle=i,e.stroke()}function WO(e,t,n,r,i,a,o){e.font=`${n} ${r}px ${i}`;let s=e.measureText(t).width;if(s<=a)return r;let c=Math.floor(r*a/s);return c<o?0:(e.font=`${n} ${c}px ${i}`,c)}function GO(e,t,n,r,i,a,o){let s=a.font.family,c=(t.radius-t.thickness/2)*1.3,l=a.font.sizeSmall;e.textAlign=`center`,e.textBaseline=`middle`;let u=WO(e,n,`600`,t.valueSize,s,c,l);if(u===0)return;let d=o?Math.min(t.cy+u*.8,t.textBottom-u/2):t.valueY;e.fillStyle=a.text,e.fillText(n,t.cx,d);let f=Math.max(l,Math.round(u*.26));if(i?.label&&!o){let n=i.label.toUpperCase();WO(e,n,`600`,f,s,c*.9,l)>0&&(e.fillStyle=i.color,e.fillText(n,t.cx,d-u*.78))}if(r){let n=d+u*.72;n+f/2<=t.textBottom&&WO(e,r,`400`,f,s,c,l)>0&&(e.fillStyle=a.textSecondary,e.fillText(r,t.cx,n))}}function KO(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall+1}px ${r.font.family}`;let i=t.thickness/2+6;for(let[r,a]of[[t.startAngle,t.min],[t.endAngle,t.max]]){let o=Math.cos(r),s=Math.sin(r),c=t.cx+o*t.radius,l=t.cy+s*t.radius;s>.2?(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(n(a),c,l+i)):(e.textAlign=o<-.2?`right`:o>.2?`left`:`center`,e.textBaseline=s<-.2?`bottom`:`middle`,e.fillText(n(a),c+o*i,l+s*i))}}function qO(e,t,n,r){e.fillStyle=r.textSecondary,e.font=`${r.font.sizeSmall}px ${r.font.family}`,e.textBaseline=`middle`;let i=t.radius+t.thickness/2+8;for(let r of n){if(!r.label)continue;let n=FO((kO(r.from,t.min,t.max)+kO(r.to,t.min,t.max))/2,t),a=Math.cos(n);e.textAlign=a<-.2?`right`:a>.2?`left`:`center`,e.fillText(r.label,t.cx+a*i,t.cy+Math.sin(n)*i)}}function JO(e,t,n,r,i,a){if(t<=0||n<=0)return;let o=PO(t,n,r),s=Number.isFinite(a),c=s?kO(a,o.min,o.max):o.min,l=FO(c,o),u=s?IO(c,r.zones):void 0,d=r.pointer===`needle`,f=r.valueFormat??AO,p=u?.color??r.needleColor??i.lineColor;e.save(),e.fillStyle=i.background,e.fillRect(0,0,t,n),BO(e,o,r.zones,l,r.trackColor??i.grid,p),VO(e,o,i.textSecondary),s&&(d?UO(e,o,l,r.needleColor??i.text,i.background):HO(e,o,l,p,i.background)),r.showValue!==!1&&GO(e,o,s?f(c):`—`,r.label,u,i,d),KO(e,o,f,i),r.showZoneLabels===!0&&r.zones?.length&&qO(e,o,r.zones,i),e.restore()}var YO=12,XO=.72,ZO=20,QO=.35;function $O(e){let t=0,n=0,r=e.mode===`stacked`;return e.categories.forEach((i,a)=>{let o=0,s=0;for(let i of e.series){let e=i.values[a];Number.isFinite(e)&&(r?e>=0?o+=e:s+=e:(n=Math.max(n,e),t=Math.min(t,e)))}n=Math.max(n,o),t=Math.min(t,s)}),[t,n]}function ek(e,t){let n=e.colorBySign;return n?n===!0?{positive:t.candleUp,negative:t.candleDown}:n:null}function tk(e,t,n,r,i){let a=e.orientation===`horizontal`,o=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),t-YO*2,i):null,s=YO+(o?o.height+6:0),[c,l]=$O(e),u=$d(c,l,a?Math.max(2,Math.floor(t/110)):5),d=e.valueFormat??q(u,e.locale),f=Math.max(0,...u.ticks.map(e=>i(d(e),11))),p;if(a){let r=YO+Math.min(t*QO,Math.max(0,...e.categories.map(e=>i(e,11))))+8;p={x:r,y:s,width:Math.max(1,t-r-YO-f/2),height:Math.max(1,n-s-YO-ZO)}}else{let e=YO+f+8;p={x:e,y:s,width:Math.max(1,t-e-YO),height:Math.max(1,n-s-YO-ZO)}}let m=Math.max(1,e.categories.length),h=a?p.y:p.x,g=(a?p.height:p.width)/m,_=g*XO,v=e.mode===`stacked`,y=v?_:_/Math.max(1,e.series.length),b=e=>a?G(u,e,p.x,p.width):G(u,e,p.y,p.height,!0),x=b(0),S=ek(e,r),C=Array(m).fill(0),w=Array(m).fill(0),T=[];return e.series.forEach((t,n)=>{e.categories.forEach((e,r)=>{let i=t.values[r];if(!Number.isFinite(i))return;let o=0;v&&(o=i>=0?C[r]:w[r],i>=0?C[r]+=i:w[r]+=i);let s=b(o),c=b(o+i),l=h+r*g+(g-_)/2+(v?0:n*y),u=S?i>=0?S.positive:S.negative:uf(n,t.color),d=Math.min(s,c),f=Math.abs(c-s);T.push(a?{x:d,y:l,width:f,height:y,category:e,series:t.name,value:i,index:r,color:u}:{x:l,y:d,width:y,height:f,category:e,series:t.name,value:i,index:r,color:u})})}),{plot:p,scale:u,orientation:a?`horizontal`:`vertical`,zero:x,bars:T,bandStart:h,band:g,legend:o,legendY:YO}}function nk(e,t,n){for(let r of e.bars)if(t>=r.x-2&&t<=r.x+r.width+2&&n>=r.y-2&&n<=r.y+r.height+2)return r;return null}function rk(e,t,n,r){let{plot:i}=e;if(t<i.x||t>i.x+i.width||n<i.y||n>i.y+i.height)return-1;let a=e.orientation===`horizontal`?n:t,o=Math.floor((a-e.bandStart)/e.band);return o>=0&&o<r?o:-1}function ik(e,n,r,i,a,o,s=tk(i,n,r,a,df(e,a))){let c=df(e,a),l=i.valueFormat??K(i.locale),{plot:u,orientation:d}=s,f=d===`horizontal`;e.fillStyle=a.background,e.fillRect(0,0,n,r),s.legend&&pf(e,s.legend,YO,s.legendY,a),Tf(e,u,s.scale,f?`horizontal`:`vertical`,a,i.valueFormat??q(s.scale,i.locale));let p=o&&i.crosshair!==!1?rk(s,o.x,o.y,i.categories.length):-1;if(p>=0){e.fillStyle=(0,t.withAlpha)(a.crosshair,.08);let n=s.bandStart+p*s.band;f?e.fillRect(u.x,n,u.width,s.band):e.fillRect(n,u.y,s.band,u.height)}for(let t of s.bars)e.fillStyle=t.color,e.fillRect(t.x,t.y,Math.max(t.width,+!!f),Math.max(t.height,+!f));e.strokeStyle=a.axisLine,e.lineWidth=1,e.beginPath();let m=Math.round(s.zero)+.5;if(f?(e.moveTo(m,u.y),e.lineTo(m,u.y+u.height)):(e.moveTo(u.x,m),e.lineTo(u.x+u.width,m)),e.stroke(),ak(e,i.categories,s,a,c),i.showValues&&ok(e,s,a,l,i.mode===`stacked`),p>=0&&o){let t=[{text:i.categories[p],bold:!0}];for(let e of s.bars)e.index===p&&t.push({text:`${e.series}: ${l(e.value)}`,color:e.color});mf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}function ak(e,t,n,r,i){let{plot:a}=n;e.save(),e.font=J(r,11),e.fillStyle=r.axisLabel;let o=Math.max(0,...t.map(e=>i(e,11))),s=n.orientation===`vertical`?Math.max(1,Math.ceil((o+8)/Math.max(1,n.band))):1;t.forEach((t,r)=>{if(r%s!==0)return;let o=n.bandStart+(r+.5)*n.band;n.orientation===`horizontal`?(e.textAlign=`right`,e.textBaseline=`middle`,e.fillText(Ef(t,a.x-YO-8,i),a.x-8,o)):(e.textAlign=`center`,e.textBaseline=`top`,e.fillText(Ef(t,n.band*s-4,i),o,a.y+a.height+6))}),e.restore()}function ok(e,t,n,r,i){e.save(),e.font=J(n,10),e.fillStyle=n.textSecondary;for(let n of t.bars){let a=r(n.value);if(t.orientation===`horizontal`){e.textBaseline=`middle`;let t=n.y+n.height/2;i?(e.textAlign=`center`,e.measureText(a).width<n.width-4&&e.fillText(a,n.x+n.width/2,t)):n.value>=0?(e.textAlign=`left`,e.fillText(a,n.x+n.width+4,t)):(e.textAlign=`right`,e.fillText(a,n.x-4,t))}else{e.textAlign=`center`;let t=n.x+n.width/2;i?(e.textBaseline=`middle`,n.height>13&&e.measureText(a).width<n.width&&e.fillText(a,t,n.y+n.height/2)):n.value>=0?(e.textBaseline=`bottom`,e.fillText(a,t,n.y-3)):(e.textBaseline=`top`,e.fillText(a,t,n.y+n.height+3))}}e.restore()}var sk=12,ck=-Math.PI/2,lk=Math.PI*2,uk=5,dk=1.4,fk=18;function pk(e,t,n,r,i){let a=e.data.filter(e=>Number.isFinite(e.value)&&e.value>0),o=a.reduce((e,t)=>e+t.value,0),s=a.map((t,n)=>({label:`${t.label} ${af(e.locale)(t.value/o)}`,color:uf(n,t.color)})),c=e.legend!==!1&&a.length>0,l=c&&t>=n*dk&&a.length*fk<=n-sk*2,u=l?Math.min(t*.4,Math.max(...s.map(e=>i(e.label,11)))+16):t-sk*2,d=c?ff(s,u,i,l):null,f=l?t-u-sk*3:t-sk*2,p=l?n-sk*2:n-sk*3-(d?.height??0),m=Math.max(0,Math.min(f,p)/2-uk),h=sk+f/2,g=sk+p/2,_=e.innerRadius,v=Math.min(.95,Math.max(0,_!==void 0&&Number.isFinite(_)?_:.6)),y=ck,b=a.map((e,t)=>{let n=e.value/o,r=y;return y+=n*lk,{label:e.label,value:e.value,share:n,start:r,end:y,color:uf(t,e.color),slice:e}});return{cx:h,cy:g,radius:m,inner:m*v,total:o,slices:b,legend:d,legendX:l?t-u-sk:sk,legendY:l?Math.max(sk,g-(d?.height??0)/2):sk*2+p}}function mk(e,t,n){let r=t-e.cx,i=n-e.cy,a=Math.hypot(r,i);if(a<e.inner||a>e.radius+uk)return null;let o=Math.atan2(i,r);for(;o<ck;)o+=lk;return e.slices.find(e=>o>=e.start&&o<e.end)??null}function hk(e,t,n,r,i,a,o=pk(r,t,n,i,df(e,i))){let s=df(e,i),c=r.valueFormat??K(r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n);let l=a&&r.crosshair!==!1?mk(o,a.x,a.y):null,{cx:u,cy:d,radius:f,inner:p}=o;for(let t of o.slices){let n=(t.start+t.end)/2,r=t===l?uk:0,a=u+Math.cos(n)*r,s=d+Math.sin(n)*r;e.beginPath(),e.arc(a,s,f,t.start,t.end),p>0?e.arc(a,s,p,t.end,t.start,!0):e.lineTo(a,s),e.closePath(),e.fillStyle=t.color,e.fill(),o.slices.length>1&&(e.strokeStyle=i.background,e.lineWidth=1.5,e.stroke())}return r.showLabels!==!1&&gk(e,o,i,r.locale),_k(e,o,r,i,s),o.legend&&pf(e,o.legend,o.legendX,o.legendY,i),l&&a&&mf(e,[{text:l.label,bold:!0,color:l.color},{text:`${c(l.value)} · ${af(r.locale)(l.share)}`}],a,{x:0,y:0,width:t,height:n},i),o}function gk(e,t,n,r){let{cx:i,cy:a,radius:o,inner:s}=t,c=s>0?(o+s)/2:o*.62;e.save(),e.font=J(n,11,`600`),e.textAlign=`center`,e.textBaseline=`middle`,e.fillStyle=`#fff`;for(let n of t.slices){let t=af(r)(n.share);if((n.end-n.start)*c<e.measureText(t).width+8||s>0&&o-s<15)continue;let l=(n.start+n.end)/2;e.fillText(t,i+Math.cos(l)*c,a+Math.sin(l)*c)}e.restore()}function _k(e,t,n,r,i){if(t.inner<=0||!n.centerLabel&&!n.centerValue)return;let a=t.inner*1.6;if(e.save(),e.textAlign=`center`,e.textBaseline=`middle`,n.centerValue){let o=Math.max(12,Math.min(28,t.inner*.42));e.font=J(r,o,`600`),e.fillStyle=r.text,e.fillText(Ef(n.centerValue,a,i,o),t.cx,t.cy+(n.centerLabel?o*.35:0))}n.centerLabel&&(e.font=J(r,11),e.fillStyle=r.textSecondary,e.fillText(Ef(n.centerLabel,a,i),t.cx,t.cy-(n.centerValue?11*1.1:0))),e.restore()}var vk=12,yk=5,bk=3,xk=18,Sk=20,Ck=6;function wk(e,n,r,i,a){let o=1/0,s=-1/0,c=1/0,l=-1/0,u=0;for(let t of e.series)for(let e of t.points)!Number.isFinite(e.x)||!Number.isFinite(e.y)||(e.x<o&&(o=e.x),e.x>s&&(s=e.x),e.y<c&&(c=e.y),e.y>l&&(l=e.y),e.size!==void 0&&Number.isFinite(e.size)&&e.size>u&&(u=e.size));let d=e.maxRadius??24,f=d+Ck,p=(e,t,n)=>{if(e>t)return[0,1];let r=(t-e)*f/Math.max(1,n-f*2);return[e>=0?Math.max(0,e-r):e-r,t<=0?Math.min(0,t+r):t+r]},m=$d(...p(o,s,n*.8),Math.max(2,Math.floor(n/110))),h=$d(...p(c,l,r*.7),5),g=e.xFormat??q(m,e.locale),_=e.yFormat??q(h,e.locale),v=e.legend??e.series.length>1?ff(e.series.map((e,t)=>({label:e.name,color:uf(t,e.color)})),n-vk*2,a):null,y=vk+(v?v.height+6:0),b=Math.max(0,...h.ticks.map(e=>a(_(e),11))),x=vk+(e.yLabel?xk:0)+b+8,S=vk+Sk+(e.xLabel?xk:0),C=a(g(m.max),11)/2,w={x,y,width:Math.max(1,n-x-vk-C),height:Math.max(1,r-y-S)},T=[];return e.series.forEach((e,n)=>{let r=uf(n,e.color),i=(0,t.withAlpha)(r,.55),a=(0,t.withAlpha)(r,.85);for(let t of e.points){if(!Number.isFinite(t.x)||!Number.isFinite(t.y))continue;let n=t.size!==void 0&&Number.isFinite(t.size)&&t.size>0&&u>0?Math.max(bk,d*Math.sqrt(t.size/u)):yk;T.push({px:G(m,t.x,w.x,w.width),py:G(h,t.y,w.y,w.height,!0),r:n,color:r,fill:i,hoverFill:a,series:e.name,label:t.label,point:t})}}),{plot:w,xScale:m,yScale:h,points:T,drawOrder:T.map((e,t)=>t).sort((e,t)=>T[t].r-T[e].r),legend:v}}function Tk(e,t,n){let r=null,i=1/0;for(let a of e.points){let e=Math.hypot(a.px-t,a.py-n);e<=a.r+Ck&&e<i&&(r=a,i=e)}return r}function Ek(e,t,n,r,i,a,o=wk(r,t,n,i,df(e,i))){let{plot:s,xScale:c,yScale:l}=o,u=r.xFormat??q(c,r.locale),d=r.yFormat??q(l,r.locale);e.fillStyle=i.background,e.fillRect(0,0,t,n),o.legend&&pf(e,o.legend,vk,vk,i),Tf(e,s,l,`vertical`,i,d),Tf(e,s,c,`horizontal`,i,u),r.zeroLines!==!1&&Dk(e,o,i),Ok(e,o,r,i);let f=a&&r.crosshair!==!1?Tk(o,a.x,a.y):null;e.save(),e.beginPath(),e.rect(s.x,s.y,s.width,s.height),e.clip();for(let t of o.drawOrder){let n=o.points[t];e.beginPath(),e.arc(n.px,n.py,n===f?n.r+2:n.r,0,Math.PI*2),e.fillStyle=n===f?n.hoverFill:n.fill,e.fill(),e.strokeStyle=n.color,e.lineWidth=1,e.stroke()}if(e.restore(),r.showLabels){e.save(),e.font=J(i,10),e.fillStyle=i.textSecondary,e.textAlign=`left`,e.textBaseline=`middle`;for(let t of o.points)t.label&&e.fillText(t.label,t.px+t.r+4,t.py);e.restore()}if(f&&a){let o=[{text:f.label??f.series,bold:!0,color:f.color}];f.label&&r.series.length>1&&o.push({text:f.series}),o.push({text:`${r.xLabel??`x`}: ${(r.xFormat??K(r.locale))(f.point.x)}`}),o.push({text:`${r.yLabel??`y`}: ${(r.yFormat??K(r.locale))(f.point.y)}`}),f.point.size!==void 0&&o.push({text:K(r.locale)(f.point.size)}),mf(e,o,a,{x:0,y:0,width:t,height:n},i)}return o}function Dk(e,t,n){let{plot:r,xScale:i,yScale:a}=t;if(e.save(),e.strokeStyle=n.axisLine,e.lineWidth=1,e.beginPath(),i.min<0&&i.max>0){let t=Math.round(G(i,0,r.x,r.width))+.5;e.moveTo(t,r.y),e.lineTo(t,r.y+r.height)}if(a.min<0&&a.max>0){let t=Math.round(G(a,0,r.y,r.height,!0))+.5;e.moveTo(r.x,t),e.lineTo(r.x+r.width,t)}e.stroke(),e.restore()}function Ok(e,t,n,r){let{plot:i}=t;e.save(),e.font=J(r,11,`600`),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,i.x+i.width/2,i.y+i.height+Sk+xk)),n.yLabel&&(e.translate(vk+11/2,i.y+i.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}var kk=1e-9,Ak=1e3,jk=e=>{let t=Number(e.toPrecision(12));return t===0?0:t};function Mk(e,t={}){let n=e.filter(e=>Number.isFinite(e));if(n.length===0)return[];let r=1/0,i=-1/0;for(let e of n)e<r&&(r=e),e>i&&(i=e);if(r===i)return[{from:r,to:i,count:n.length}];let a=t.binWidth;if(a!==void 0&&a>0&&Number.isFinite(a)){let e=Math.floor(r/a+kk),t=Math.max(e,Math.ceil(i/a-kk)-1)-e+1;if(t<=1e3){let r=Array.from({length:t},(t,n)=>({from:jk((e+n)*a),to:jk((e+n+1)*a),count:0}));for(let i of n)r[Math.min(t-1,Math.floor(i/a+kk)-e)].count++;return r}}let o=t.bins,s=typeof o==`number`&&Number.isFinite(o)&&o>=1?Math.min(Ak,Math.floor(o)):Math.min(Ak,Math.ceil(Math.log2(n.length))+1),c=(i-r)/s,l=Array.from({length:s},(e,t)=>({from:jk(r+t*c),to:jk(t===s-1?i:r+(t+1)*c),count:0}));for(let e of n)l[Math.min(s-1,Math.floor((e-r)/c+kk))].count++;return l}var Nk=12,Pk=20,Fk=16;function Ik(e,n,r){return n.colorBySign?(e.from+e.to)/2<0?r.candleDown:r.candleUp:n.color??t.TC_SERIES_COLORS[0]}function Lk(e,t,n,r,i){let a=Mk(e.values,{bins:e.bins,binWidth:e.binWidth}),o=a.length>0?a[0].from:0,s=a.length>0?a[a.length-1].to:1,c=(e.markers??[]).map(e=>e.value).filter(e=>Number.isFinite(e)),l=$d(Math.min(o,...c),Math.max(s,...c),Math.max(2,Math.floor(t/110))),u=0;for(let e of a)e.count>u&&(u=e.count);let d=$d(0,Math.max(4,u),4),f=e.valueFormat??q(l,e.locale),p=Math.max(0,...d.ticks.map(t=>i(q(d,e.locale)(t),11))),m=Nk+(c.length>0?Fk:0),h=Nk+p+8,g=Nk+i(f(l.max),11)/2,_={x:h,y:m,width:Math.max(1,t-h-g),height:Math.max(1,n-m-Nk-Pk)};return{plot:_,xScale:l,yScale:d,bars:a.map(t=>{let n=G(l,t.from,_.x,_.width),i=t.to>t.from?G(l,t.to,_.x,_.width):n+_.width/10,a=G(d,t.count,_.y,_.height,!0);return{x:n,y:a,width:Math.max(1,i-n),height:_.y+_.height-a,bin:t,color:Ik(t,e,r)}}),total:a.reduce((e,t)=>e+t.count,0)}}function Rk(e,t,n){let{plot:r}=e;return n<r.y||n>r.y+r.height?null:e.bars.find(e=>t>=e.x&&t<e.x+e.width)??null}function zk(e,n,r,i,a,o,s=Lk(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale),{plot:l}=s;e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,l,s.yScale,`vertical`,a,q(s.yScale,i.locale)),Tf(e,l,s.xScale,`horizontal`,a,i.valueFormat??q(s.xScale,i.locale));let u=o&&i.crosshair!==!1?Rk(s,o.x,o.y):null;for(let n of s.bars)e.fillStyle=n===u?n.color:(0,t.withAlpha)(n.color,.75),e.fillRect(n.x+(n.width>3?.5:0),n.y,Math.max(1,n.width-+(n.width>3)),n.height);if(Bk(e,s,i,a,c),u&&o){let{bin:t}=u;mf(e,[{text:t.to>t.from?`${c(t.from)} – ${c(t.to)}`:c(t.from),bold:!0,color:u.color},{text:`${K(i.locale)(t.count)} · ${af(i.locale)(s.total>0?t.count/s.total:0)}`}],o,{x:0,y:0,width:n,height:r},a)}return s}function Bk(e,t,n,r,i){let{plot:a}=t;e.save(),e.font=J(r,10),e.textAlign=`center`,e.textBaseline=`bottom`;let o=[];for(let s of n.markers??[]){if(!Number.isFinite(s.value))continue;let n=Math.round(G(t.xScale,s.value,a.x,a.width))+.5,c=s.color??r.text;e.strokeStyle=c,e.setLineDash([4,3]),e.lineWidth=1,e.beginPath(),e.moveTo(n,a.y),e.lineTo(n,a.y+a.height),e.stroke(),e.setLineDash([]),e.fillStyle=c;let l=s.label?`${s.label} ${i(s.value)}`:i(s.value),u=e.measureText(l).width/2+4,d=0;for(;o.some(e=>e.row===d&&n-u<e.to&&n+u>e.from);)d++;o.push({from:n-u,to:n+u,row:d}),e.fillText(l,n,a.y-3+d*14)}e.restore()}var Vk=864e5,Hk=3,Uk=12,Wk=16,Gk=10,Kk=28,qk=6;function Jk(e){let t=/^(\d{4})-(\d{2})-(\d{2})$/.exec(e);if(!t)return null;let[n,r,i]=[Number(t[1]),Number(t[2]),Number(t[3])],a=Date.UTC(n,r-1,i),o=new Date(a);return o.getUTCFullYear()!==n||o.getUTCMonth()!==r-1||o.getUTCDate()!==i?null:Math.round(a/Vk)}function Yk(e){return new Date(e*Vk).toISOString().slice(0,10)}var Xk=e=>((e+4)%7+7)%7;function Zk(e,t){let n=e.from===void 0?null:Jk(e.from),r=e.to===void 0?null:Jk(e.to);if(n===null||r===null){let e=1/0,i=-1/0;for(let n of t.keys())n<e&&(e=n),n>i&&(i=n);n??=Number.isFinite(e)?e:null,r??=Number.isFinite(i)?i:null}if(n===null||r===null||n>r)return null;let i=new Date(r*Vk).getUTCFullYear()-10+1;return[Math.max(n,Math.round(Date.UTC(i,0,1)/Vk)),r]}function Qk(e,t,n){let r=[],i=e;for(;i<=t;){let e=new Date(i*Vk).getUTCFullYear(),a=Math.min(t,Math.round(Date.UTC(e,11,31)/Vk)),o=i-n(i);r.push({year:e,first:i,last:a,origin:o,weeks:Math.floor((a-o)/7)+1}),i=a+1}return r}var $k=new Map;function eA(e){let t=e??``,n=$k.get(t);if(!n){try{n={month:new Intl.DateTimeFormat(e,{month:`short`,timeZone:`UTC`}),weekday:new Intl.DateTimeFormat(e,{weekday:`short`,timeZone:`UTC`}),long:new Intl.DateTimeFormat(e,{dateStyle:`full`,timeZone:`UTC`})}}catch{n=eA(void 0)}$k.set(t,n)}return n}function tA(e,t,n,r,i){let a=new Map;for(let t of e.data){let e=Jk(t.date);e!==null&&Number.isFinite(t.value)&&a.set(e,t)}let o=eA(e.locale),s=e.dateFormat??(e=>o.long.format(new Date(`${e}T00:00:00Z`))),c=e.weekdays===5,l=e=>!c||Xk(e)>=1&&Xk(e)<=5,u=Zk(e,a),d=t-Uk*2,f=e.legend===!1?0:28,p=c?5:7,m=c?1:e.weekStart??1,h=e=>(Xk(e)-m+7)%7,g=u?Qk(u[0],u[1],h):[],_=e=>n-Uk*2-f-e*Wk-(e-1)*Gk;for(;g.length>1&&_(g.length)/(g.length*p)<Hk;)g=g.slice(1);let v=[];for(let[e,t]of a)g.length>0&&e>=g[0].first&&e<=g[g.length-1].last&&l(e)&&v.push(t.value);let y=Nf(v,r,e.colorScale),b={cells:[],months:[],weekdays:[],years:[],scale:y,bar:null,pitch:0,formatDate:s};if(g.length===0||d<=0||_(g.length)<=0)return b;let x=g.length>1,S=g.map(e=>String(e.year)),C=Array.from({length:p},(e,t)=>o.weekday.format(new Date((3+m+t)*Vk))),w=Uk+Math.max(...C.map(e=>i(e,10)),...x?S.map(e=>i(e,11)):[0])+qk,T=Math.max(...g.map(e=>e.weeks)),E=Math.min(Kk,(t-w-Uk)/T,_(g.length)/(g.length*p));if(!(E>0))return b;let D=E-(E>=6?Math.max(1,Math.round(E*.12)):0),O=T*E,k=w+Math.max(0,(t-w-Uk-O)/2),A={...b,pitch:E},j=Uk;for(let[e,n]of g.entries()){let r=j+Wk;x&&A.years.push({label:S[e],x:k-qk,y:j});let s=-1,c=-1/0;for(let e=n.first;e<=n.last;e++){if(!l(e))continue;let u=k+Math.floor((e-n.origin)/7)*E,d=r+h(e)*E,f=a.get(e);A.cells.push({x:u,y:d,size:D,date:Yk(e),day:f,color:f&&Number.isFinite(f.value)?Pf(f.value,y):null});let p=new Date(e*Vk).getUTCMonth();if(p!==s){s=p;let n=o.month.format(new Date(e*Vk)),r=u+i(n,10);u>=c&&r<=t&&(A.months.push({label:n,x:u,y:j}),c=r+4)}}if(E>=8){let e=E>=13?1:2;for(let t=0;t<p;t+=e)A.weekdays.push({label:C[t],x:k-qk,y:r+t*E+D/2})}j=r+p*E+Gk}return f>0&&(A.bar={x:k,y:j-Gk+8,width:Math.min(O,t-k-Uk),height:f-8}),A}function nA(e,t,n){for(let r of e.cells)if(t>=r.x&&t<r.x+e.pitch&&n>=r.y&&n<r.y+e.pitch)return r;return null}function rA(e,n,r,i,a,o,s=tA(i,n,r,a,df(e,a))){let c=i.valueFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r);let l=o&&i.crosshair!==!1?nA(s,o.x,o.y):null,u=(0,t.withAlpha)(a.textSecondary,.12),d=s.pitch>=10?2:0;e.save();for(let t of s.cells)e.fillStyle=t.color??u,e.beginPath(),d>0&&typeof e.roundRect==`function`?e.roundRect(t.x,t.y,t.size,t.size,d):e.rect(t.x,t.y,t.size,t.size),e.fill();l&&(e.strokeStyle=a.text,e.lineWidth=1.5,e.strokeRect(l.x-.75,l.y-.75,l.size+1.5,l.size+1.5)),e.fillStyle=a.textSecondary,e.font=J(a,10),e.textAlign=`left`,e.textBaseline=`top`;for(let t of s.months)e.fillText(t.label,t.x,t.y);e.textAlign=`right`,e.textBaseline=`middle`;for(let t of s.weekdays)e.fillText(t.label,t.x,t.y);e.font=J(a,11,`600`),e.fillStyle=a.text,e.textBaseline=`top`;for(let t of s.years)e.fillText(t.label,t.x,t.y);if(e.restore(),s.bar&&Rf(e,s.bar,s.scale,c,a),l&&o){let t=[{text:s.formatDate(l.date),bold:!0,color:l.color??void 0}];if(l.day){t.push({text:c(l.day.value)});for(let[e,n]of Object.entries(l.day.meta??{}))t.push({text:`${e}: ${String(n)}`})}else t.push({text:`–`});mf(e,t,o,{x:0,y:0,width:n,height:r},a)}return s}var iA=12,aA=6,oA=72,sA=Math.PI/4,cA=Math.sin(sA);function lA(e){let t=e.length,n=Array.from({length:t},()=>Array(t).fill(NaN));for(let r=0;r<t;r++)for(let i=r;i<t;i++){let t=uA(e[r],e[i],r===i);n[r][i]=t,n[i][r]=t}return n}function uA(e,t,n){let r=Math.min(e.length,t.length),i=0,a=0,o=0;for(let n=0;n<r;n++)Number.isFinite(e[n])&&Number.isFinite(t[n])&&(i++,a+=e[n],o+=t[n]);if(i<3)return NaN;let s=a/i,c=o/i,l=0,u=0,d=0;for(let n=0;n<r;n++){if(!Number.isFinite(e[n])||!Number.isFinite(t[n]))continue;let r=e[n]-s,i=t[n]-c;l+=r*i,u+=r*r,d+=i*i}return u===0||d===0?NaN:n?1:Math.max(-1,Math.min(1,l/Math.sqrt(u*d)))}var dA=e=>e.toFixed(2);function fA(e,t,n,r){return!t||!e?!0:e===`lower`?r<=n:r>=n}function pA(e,t,n,r,i){let a=e.rows.slice(0,200),o=(e.columns??e.rows).slice(0,200),s=e.columns===void 0||e.columns.length===e.rows.length&&e.columns.every((t,n)=>t===e.rows[n]),c=[];for(let t=0;t<a.length;t++)for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];Number.isFinite(r)&&fA(e.triangle,s,t,n)&&c.push(r)}let l=Nf(c,r,e.colorScale),u={cells:[],rowLabels:[],columnLabels:[],grid:{x:0,y:0,width:0,height:0},pitch:0,scale:l,bar:null,at:[]};if(a.length===0||o.length===0||t<=0||n<=0)return u;let d=Math.min(t*.3,Math.max(...a.map(e=>i(e,11)))),f=Math.max(...o.map(e=>i(e,11))),p=e.legend===!1?0:28,m=iA+d+aA,h=t-m-iA,g=e=>Math.min(oA,h/o.length,(n-e-iA-p)/a.length),_=iA+11+aA,v=g(_),y=f>v-4,b=f;if(y&&(b=Math.min(f,n*.33/cA),_=iA+b*cA+11,v=g(_)),!(v>0))return u;let x=v-+(v>=8),S=m+Math.max(0,(h-o.length*v)/2);y&&(b=Math.max(0,Math.min(b,(S+x/2-2-11*cA/2)/cA))),u.grid={x:S,y:_,width:o.length*v,height:a.length*v},u.pitch=v;let C=e.valueFormat??dA,w=e.showValues!==!1,T=Math.max(8,Math.min(11,v/3));for(let t=0;t<a.length;t++){u.at.push([]);for(let n=0;n<o.length;n++){let r=e.values[t]?.[n];if(!Number.isFinite(r)||!fA(e.triangle,s,t,n))continue;let c=Pf(r,l),d=w?C(r):``,f=w&&v>=18&&i(d,T)<=v-4,p={x:S+n*v,y:_+t*v,size:x,cell:{row:a[t],column:o[n],value:r,rowIndex:t,columnIndex:n},color:c,text:f?d:null,textColor:Lf(c)};u.cells.push(p),u.at[t][n]=p}}let E=Math.max(1,Math.ceil(11/v)),D=Math.max(1,Math.ceil(11/(y?v*cA:v)));for(let e=0;e<a.length;e+=E)u.rowLabels.push({text:Ef(a[e],d,i),index:e,x:S-aA,y:_+e*v+x/2});for(let e=0;e<o.length;e+=D)u.columnLabels.push({text:Ef(o[e],b,i),index:e,x:S+e*v+x/2,y:_-aA,rotated:y});return p>0&&(u.bar={x:S,y:_+a.length*v+8,width:Math.min(u.grid.width,t-S-iA),height:p-8}),u}function mA(e,t,n){let{grid:r,pitch:i}=e;return i<=0||t<r.x||n<r.y||t>=r.x+r.width||n>=r.y+r.height?null:e.at[Math.floor((n-r.y)/i)]?.[Math.floor((t-r.x)/i)]??null}function hA(e,t,n,r,i,a,o=pA(r,t,n,i,df(e,i))){let s=r.valueFormat??dA;e.fillStyle=i.background,e.fillRect(0,0,t,n);let c=a&&r.crosshair!==!1?mA(o,a.x,a.y):null;e.save();let l=Math.max(8,Math.min(11,o.pitch/3));e.textAlign=`center`,e.textBaseline=`middle`,e.font=J(i,l);for(let t of o.cells)e.fillStyle=t.color,e.fillRect(t.x,t.y,t.size,t.size),t.text&&(e.fillStyle=t.textColor,e.fillText(t.text,t.x+t.size/2,t.y+t.size/2));c&&(e.strokeStyle=i.text,e.lineWidth=1.5,e.strokeRect(c.x+.75,c.y+.75,c.size-1.5,c.size-1.5)),e.font=J(i,11),e.fillStyle=i.textSecondary,e.textAlign=`right`;for(let t of o.rowLabels)e.fillStyle=c&&c.cell.rowIndex===t.index?i.text:i.textSecondary,e.fillText(t.text,t.x,t.y);for(let t of o.columnLabels)e.fillStyle=c&&c.cell.columnIndex===t.index?i.text:i.textSecondary,t.rotated?(e.save(),e.translate(t.x,t.y),e.rotate(sA),e.textAlign=`right`,e.fillText(t.text,0,0),e.restore()):(e.textAlign=`center`,e.textBaseline=`bottom`,e.fillText(t.text,t.x,t.y),e.textBaseline=`middle`);if(e.restore(),o.bar&&Rf(e,o.bar,o.scale,s,i),c&&a){let{cell:r}=c;mf(e,[{text:`${r.row} × ${r.column}`,bold:!0,color:c.color},{text:s(r.value)}],a,{x:0,y:0,width:t,height:n},i)}return o}var gA=12,_A=18,vA=20,yA=10,bA=.2,xA=2e3,SA=1e-9;function CA(e,t,n=1/0){let r=Number.isFinite(t)?Math.max(1,Math.floor(t)):25,i=[],a=Math.max(r-1,e.length-(Number.isFinite(n)?Math.max(1,Math.floor(n)):e.length));for(let t=a;t<e.length;t++){let n=0,a=0;for(let i=t-r+1;i<=t;i++)n+=e[i].volume,a+=e[i].close;i.push({time:e[t].time,volume:n/r,price:a/r})}return i}var wA=(e,t)=>t-e>SA*Math.max(Math.abs(e),Math.abs(t));function TA(e){if(e.length<2)return null;let t=1/0,n=-1/0,r=1/0,i=-1/0;for(let a of e)t=Math.min(t,a.volume),n=Math.max(n,a.volume),r=Math.min(r,a.price),i=Math.max(i,a.price);let a=e[e.length-2],o=e[e.length-1],s=wA(t,n)?(o.volume-a.volume)/(n-t):0,c=wA(r,i)?(o.price-a.price)/(i-r):0;if(Math.abs(s)<1e-6&&Math.abs(c)<1e-6)return null;let l=(Math.atan2(c,s)+2*Math.PI)%(2*Math.PI);return Math.round(l/(Math.PI/4))%8+1}function EA(e,n,r,i,a){let o=CA(e.data,e.period??25,DA(e)),s=1/0,c=-1/0,l=1/0,u=-1/0;for(let e of o)s=Math.min(s,e.volume),c=Math.max(c,e.volume),l=Math.min(l,e.price),u=Math.max(u,e.price);o.length>0&&!wA(s,c)&&(c=s),o.length>0&&!wA(l,u)&&(u=l);let d=$d(o.length>0?s:0,o.length>0?c:1,Math.max(2,Math.floor(n/110))),f=$d(o.length>0?l:0,o.length>0?u:1,Math.max(2,Math.floor(r/60))),p=e.priceFormat??q(f,e.locale),m=e.volumeFormat??q(d,e.locale),h=gA+Math.max(0,...f.ticks.map(e=>a(p(e),11)))+8+(e.yLabel?_A:0),g=gA+a(m(d.max),11)/2,_=gA,v=gA+vA+(e.xLabel?_A:0),y={x:h,y:_,width:Math.max(1,n-h-g),height:Math.max(1,r-_-v)},b=Math.max(1,o.length-1);return{plot:y,xScale:d,yScale:f,points:o.map((e,t)=>({px:G(d,e.volume,y.x,y.width),py:G(f,e.price,y.y,y.height,!0),alpha:bA+(1-bA)*t/b,point:e})),phase:TA(o),color:e.color??t.TC_SERIES_COLORS[0]}}function DA(e){let t=e.points??60;return Number.isFinite(t)?Math.min(xA,Math.max(2,Math.floor(t))):60}function OA(e,t,n){let r=null,i=yA*yA;for(let a=e.points.length-1;a>=0;a--){let o=e.points[a],s=(o.px-t)**2+(o.py-n)**2;s<i&&(r=o,i=s)}return r}function kA(e,n,r,i,a,o,s=EA(i,n,r,a,df(e,a))){let{plot:c,points:l,color:u}=s,d=i.timeFormat??of(i.locale,{year:`numeric`,month:`short`,day:`numeric`}),f=i.priceFormat??K(i.locale),p=i.volumeFormat??K(i.locale);e.fillStyle=a.background,e.fillRect(0,0,n,r),Tf(e,c,s.yScale,`vertical`,a,i.priceFormat??q(s.yScale,i.locale)),Tf(e,c,s.xScale,`horizontal`,a,i.volumeFormat??q(s.xScale,i.locale)),AA(e,c,i,a),e.save(),e.lineWidth=1.5,e.lineJoin=`round`;for(let n=1;n<l.length;n++)e.strokeStyle=(0,t.withAlpha)(u,l[n].alpha),e.beginPath(),e.moveTo(l[n-1].px,l[n-1].py),e.lineTo(l[n].px,l[n].py),e.stroke();for(let n of l)e.fillStyle=(0,t.withAlpha)(u,n.alpha),e.beginPath(),e.arc(n.px,n.py,2,0,Math.PI*2),e.fill();let m=l[l.length-1];m&&(e.fillStyle=u,e.strokeStyle=a.background,e.lineWidth=2,e.beginPath(),e.arc(m.px,m.py,5,0,Math.PI*2),e.fill(),e.stroke()),e.restore();let h=o&&i.crosshair!==!1?OA(s,o.x,o.y):null;return h&&o&&(e.save(),e.strokeStyle=a.text,e.lineWidth=1.5,e.beginPath(),e.arc(h.px,h.py,5,0,Math.PI*2),e.stroke(),e.restore(),mf(e,[{text:d(h.point.time),bold:!0,color:u},{text:`${i.yLabel??`Price`}: ${f(h.point.price)}`},{text:`${i.xLabel??`Volume`}: ${p(h.point.volume)}`}],o,{x:0,y:0,width:n,height:r},a)),s}function AA(e,t,n,r){e.save(),e.font=J(r,11),e.fillStyle=r.textSecondary,e.textAlign=`center`,n.xLabel&&(e.textBaseline=`bottom`,e.fillText(n.xLabel,t.x+t.width/2,t.y+t.height+vA+_A)),n.yLabel&&(e.translate(gA+4,t.y+t.height/2),e.rotate(-Math.PI/2),e.textBaseline=`middle`,e.fillText(n.yLabel,0,0)),e.restore()}exports.ABCDPatternTool=Xv,exports.ADXIndicator=Es,exports.ALMAIndicator=Oc,exports.ATRIndicator=Ts,exports.AXIS_LABEL_HEIGHT=ee,exports.AcceleratorOscillatorIndicator=mc,exports.AccumulationDistributionIndicator=wc,exports.AccumulativeSwingIndexIndicator=yu,exports.AdvanceDeclineIndicator=xu,exports.AlertDragHandler=zd,exports.AlertManager=MT,exports.AlligatorIndicator=ds,exports.AnchoredNoteTool=Vy,exports.AnchoredTextTool=By,exports.AnchoredVWAPIndicator=ns,exports.AnchoredVWAPTool=ov,exports.Animator=sD,exports.ArcTool=db,exports.AreaRenderer=$e,exports.AroonIndicator=js,exports.ArrowMarkTool=Ty,exports.ArrowTool=X_,exports.AverageDayRangeIndicator=el,exports.AveragePriceIndicator=cl,exports.AwesomeOscillatorIndicator=bs,exports.AxisDragHandler=Rd,exports.BalanceOfPowerIndicator=$s,exports.BalloonTool=zy,exports.BarCountdown=fe,exports.BarRenderer=et,exports.BarsPatternTool=Kb,exports.BaseFinanceChart=uD,exports.BaselineRenderer=rt,exports.BinanceAdapter=aw,exports.BollingerBandWidthIndicator=Vc,exports.BollingerBandsIndicator=zo,exports.BollingerPercentBIndicator=Bc,exports.BracketTool=eS,exports.BrushTool=ib,exports.BybitAdapter=yw,exports.CANDLE_PATTERNS=Yl,exports.CCIIndicator=ks,exports.CMFIndicator=Ps,exports.COUNTDOWN_HEIGHT=de,exports.CROSSHAIR_CURSORS=Qf,exports.CalloutTool=gy,exports.CandlestickRenderer=le,exports.CanvasLayer=c,exports.ChaikinOscillatorIndicator=xs,exports.ChaikinVolatilityIndicator=sc,exports.ChandeKrollStopIndicator=Lc,exports.ChandeMomentumIndicator=tc,exports.ChandelierExitIndicator=us,exports.ChartLegend=Jw,exports.ChartMarkManager=BE,exports.ChartStateManager=uE,exports.ChopZoneIndicator=Tu,exports.ChoppinessIndexIndicator=Ls,exports.CircleTool=ey,exports.CoinbaseAdapter=pw,exports.CompareRenderer=Wr,exports.CompareSymbolIndicator=no,exports.CompareSymbolPaneIndicator=ro,exports.ConnorsRSIIndicator=Vs,exports.CoppockIndicator=Us,exports.CorrelationCoefficientIndicator=co,exports.CorrelationLogIndicator=lo,exports.CrossLineTool=Mv,exports.CrosshairHandler=Hf,exports.CrosshairTooltip=gp,exports.CurrentPriceLine=GS,exports.CurveTool=ub,exports.CyclicLinesTool=cy,exports.CypherPatternTool=$v,exports.DEFAULT_LEGEND_CONFIG=qw,exports.DEFAULT_MAX_PIXEL_RATIO=n,exports.DEFAULT_MAX_WEBGL_CHARTS=e.t,exports.DEFAULT_SESSION_HOURS=hT,exports.DEMAIndicator=Ec,exports.DENSE_BAR_WIDTH=e.u,exports.DOUBLE_TAP_MS=md,exports.DOUBLE_TAP_PX=hd,exports.DPRManager=o,exports.DataExporter=yE,exports.DateAndPriceRangeTool=iy,exports.DateRangeTool=z_,exports.DepthHeatmapBuffer=Qt,exports.DepthHeatmapRenderer=$t,exports.DepthOverlay=NS,exports.DepthOverlayLayer=PS,exports.DetrendedPriceOscillatorIndicator=Qs,exports.DisjointChannelTool=Og,exports.DisparityIndexIndicator=_c,exports.DonchianChannelIndicator=Qo,exports.DrawingBase=Y,exports.DrawingManager=Xm,exports.DrawingRenderer=ih,exports.EMAIndicator=Ro,exports.EaseOfMovementIndicator=ic,exports.Easing=oD,exports.ElderRayIndicator=qs,exports.ElliottCorrectionTool=A_,exports.ElliottDoubleComboTool=M_,exports.ElliottImpulseTool=k_,exports.ElliottTriangleTool=j_,exports.ElliottTripleComboTool=N_,exports.ElliottWaveTool=O_,exports.EllipseTool=Yg,exports.Emitter=zS,exports.EnvelopeIndicator=hs,exports.EquivolumeRenderer=ut,exports.EventBus=Op,exports.ExtendedLineTool=vg,exports.FibArcsTool=kb,exports.FibChannelTool=Bv,exports.FibCirclesTool=Ob,exports.FibExtensionTool=Kg,exports.FibRetracementTool=Wg,exports.FibSpeedResistanceFanTool=qv,exports.FibSpiralTool=Mb,exports.FibTimeZonesTool=yv,exports.FibWedgeTool=Ab,exports.FinanceCrosshair=dD,exports.FisherTransformIndicator=Zs,exports.FlagTool=Sy,exports.FlatTopBottomTool=kg,exports.ForceIndexIndicator=Bs,exports.ForecastTool=Wb,exports.GROUP_HEADER=HD,exports.GannBoxTool=iv,exports.GannFanTool=$_,exports.GannSquareTool=Nb,exports.GridRenderer=e.o,exports.GuppyMMAIndicator=al,exports.HLCAreaRenderer=ft,exports.HammingMAIndicator=fu,exports.HeadAndShouldersTool=Zv,exports.HiLoRenderer=_t,exports.HighlighterTool=ab,exports.HistoricalVolatilityIndicator=Uc,exports.HollowCandleRenderer=tt,exports.HorizontalLineTool=pg,exports.HorizontalRayTool=mg,exports.HullMAIndicator=as,exports.ICON_GLYPHS=Ey,exports.INDICATOR_CATEGORIES=Fu,exports.INDICATOR_WORKER_MIN_BARS=Do,exports.INTERVAL_LIMITS=Da,exports.INTERVAL_UNITS=Ea,exports.IchimokuIndicator=Jo,exports.IconTool=Oy,exports.IndicatorBase=I,exports.IndicatorEngine=Io,exports.IndicatorValueMap=L,exports.IndicatorWorkerClient=qu,exports.IndicatorWorkerHost=Wu,exports.IndicatorWorkerPool=Yu,exports.InfoLineTool=Pv,exports.InteractionManager=Td,exports.KAMAIndicator=kc,exports.KEPT_BUCKETS=XS,exports.KSTIndicator=Ws,exports.KagiRenderer=at,exports.KeltnerChannelIndicator=Zo,exports.KeyboardHandler=ap,exports.KlingerIndicator=Xs,exports.KrakenAdapter=Ew,exports.LSMAIndicator=Ac,exports.LayerManager=l,exports.LineRenderer=Qe,exports.LineWithMarkersRenderer=mt,exports.LinearRegressionChannelIndicator=is,exports.LinearRegressionSlopeIndicator=Qc,exports.MACDIndicator=Cs,exports.MAChannelIndicator=cu,exports.MACrossIndicator=Pc,exports.MADoubleIndicator=gu,exports.MARK_BADGE_SIZE=TE,exports.MARK_ROW_HEIGHT=kE,exports.MARibbonIndicator=ol,exports.MATripleIndicator=_u,exports.MAX_ALERT_BARS=CT,exports.MAX_BASE_RATIO=JS,exports.MAX_BASE_REQUESTS=qS,exports.MFIIndicator=As,exports.MIN_ALERT_BARS=wT,exports.MIN_BAR_UNIT=Fe,exports.MIN_BAR_UNIT_LIMIT=Ie,exports.MTFMovingAverageIndicator=cs,exports.MajorityRuleIndicator=Su,exports.ManualFeed=Gw,exports.MarketProfileRenderer=Lt,exports.MassIndexIndicator=ec,exports.McGinleyDynamicIndicator=jc,exports.MeasureOverlay=YE,exports.MeasureTool=B_,exports.MedianPriceIndicator=ll,exports.MockAdapter=ow,exports.ModifiedSchiffPitchforkTool=n_,exports.MomentumIndicator=Hc,exports.NetVolumeIndicator=tl,exports.NoteTool=hy,exports.OBVIndicator=Ds,exports.OrderDraftTool=oS,exports.OrderRenderer=Nx,exports.PRICE_AXIS_ADD_STRIP=Od,exports.PRICE_SCALE_MARGIN=ze,exports.PanHandler=Id,exports.PaneResizeHandler=Bd,exports.PaperExecutionAdapter=IS,exports.ParabolicSARIndicator=Yo,exports.ParallelChannelTool=xg,exports.PathTool=ob,exports.PercentagePriceOscillatorIndicator=fc,exports.PeriodLevelsRenderer=Ht,exports.PinnedTooltip=wp,exports.PitchfanTool=jb,exports.PitchforkTool=e_,exports.PivotMarkersRenderer=Jt,exports.PivotPointsIndicator=es,exports.PointAndFigureRenderer=ct,exports.PollingAdapter=lw,exports.PolylineTool=sb,exports.PositionRenderer=Gx,exports.PrettyGoodOscillatorIndicator=yc,exports.PriceAxis=D,exports.PriceAxisAddButton=kd,exports.PriceLabelTool=Xy,exports.PriceLines=yT,exports.PriceOscillatorIndicator=Ou,exports.PriceRangeTool=I_,exports.PriceVolumeTrendIndicator=ac,exports.ProjectionTool=Gb,exports.QstickIndicator=vc,exports.RANGE_PRESETS=Ue,exports.ROCIndicator=Ms,exports.RSIIndicator=Ss,exports.RayTool=_g,exports.ReconnectManager=US,exports.RectangleTool=Jg,exports.RegressionChannelTool=Eg,exports.RelativeMomentumIndexIndicator=gc,exports.RelativeVigorIndicator=cc,exports.RelativeVolatilityIndexIndicator=Xc,exports.RenderEngine=je,exports.RenderLoop=u,exports.RenkoRenderer=it,exports.ReplayController=BC,exports.ReplayManager=VT,exports.ResamplingAdapter=sC,exports.ReshapeMemo=Zr,exports.RiskRewardTool=jv,exports.RotatedRectangleTool=Ag,exports.SELECTION_BOX_MIN_SIZE=iD,exports.SMAIndicator=Lo,exports.SMIErgodicIndicator=Du,exports.SMMAIndicator=Dc,exports.SNAPSHOT_VERSION=UT,exports.SYMBOL_INDICATOR_IDS=eo,exports.SYMBOL_ZONE_WAIT_MS=YS,exports.SchaffTrendCycleIndicator=Js,exports.SchiffPitchforkTool=t_,exports.Screenshot=rT,exports.SelectionBoxOverlay=aD,exports.SessionBreaks=cT,exports.SessionShading=gT,exports.SessionVWAPIndicator=ls,exports.SignalMarkerManager=wE,exports.SignpostTool=Ry,exports.SineLineTool=Rb,exports.SpreadIndicator=io,exports.StandardErrorBandsIndicator=nl,exports.StandardErrorIndicator=$c,exports.StdDevIndicator=bc,exports.StepLineRenderer=pt,exports.StochasticIndicator=ws,exports.StochasticMomentumIndexIndicator=Yc,exports.StochasticRSIIndicator=lc,exports.StreamManager=zC,exports.SupertrendIndicator=Xo,exports.SymbolSeriesStore=tn,exports.TEMAIndicator=ys,exports.TOUCH_REACH=pd,exports.TRIXIndicator=nc,exports.TSIIndicator=Ns,exports.TapTracker=gd,exports.TextAnnotationTool=J_,exports.ThreeDrivesTool=Qv,exports.TickAggregator=HS,exports.TickBarAdapter=fC,exports.TickBarBuilder=dC,exports.TimeAxis=ld,exports.TimeCyclesTool=Lb,exports.TradeZoneManager=GE,exports.TradingContextMenu=Jx,exports.TradingDragHandler=qx,exports.TradingManager=SS,exports.TradingRenderer=CS,exports.TrendAngleTool=$h,exports.TrendLineTool=fg,exports.TrendStrengthIndexIndicator=Zc,exports.TriangleTool=Xg,exports.TypicalPriceIndicator=ul,exports.UPBIT_MAX_CANDLES=jw,exports.UlcerIndexIndicator=Kc,exports.UltimateOscillatorIndicator=Rs,exports.UndoRedoManager=dE,exports.UpbitAdapter=Iw,exports.VOLUME_HEIGHT_RATIO=vt,exports.VROCIndicator=Tc,exports.VWAPIndicator=Go,exports.VWMAIndicator=ps,exports.VerticalLineTool=gg,exports.Viewport=Ve,exports.VolatilityIndexIndicator=vu,exports.VolatilityOHLCIndicator=ju,exports.VolatilityZeroTrendIndicator=Mu,exports.VolumeCandleRenderer=lt,exports.VolumeDeltaIndicator=Fs,exports.VolumeOscillatorIndicator=Wc,exports.VolumeProfileIndicator=Cc,exports.VolumeProfileRangeTool=hv,exports.VolumeProfileRenderer=St,exports.VolumeRenderer=yt,exports.VortexIndicator=Is,exports.WMAIndicator=ms,exports.Watermark=iT,exports.WebSocketAdapter=cw,exports.WilliamsADIndicator=oc,exports.WilliamsFractalsIndicator=Ic,exports.WilliamsRIndicator=Os,exports.XABCDPatternTool=Yv,exports.ZigZagIndicator=rs,exports.ZoomHandler=Ld,exports.adapterFromFeed=TC,exports.alignAxisTags=pe,exports.alignOutput=wa,exports.arcPoints=lb,exports.assignSessionLetters=Ft,exports.axisFormat=q,exports.axisTimes=si,exports.barIndexToTime=e.C,exports.barIndexToX=e.w,exports.barTimeStep=e.T,exports.barTimeStepMs=e.E,exports.barsToColumns=uo,exports.bracketRiskReward=Xx,exports.canvasMeasure=df,exports.cappedPixelRatio=r,exports.claimGpuContext=e.n,exports.classifyPivots=Wt,exports.cleanIntervals=ja,exports.columnsToBars=fo,exports.columnsToOutput=So,exports.computeBarLayout=tk,exports.computeBracketDefaults=Yx,exports.computeCalendarLayout=tA,exports.computeCounterClockLayout=EA,exports.computeDepthLayout=yD,exports.computeDonutLayout=pk,exports.computeEquityLayout=ND,exports.computeHistogramLayout=Lk,exports.computeMarketProfile=Nt,exports.computeMatrixLayout=pA,exports.computePeriodLevels=Vt,exports.computeScatterLayout=wk,exports.computeSessionProfiles=It,exports.computeWaterfallLayout=lO,exports.correlationMatrix=lA,exports.counterClockPhase=TA,exports.counterClockPoints=CA,exports.createIndicatorWorker=Gu,exports.curvePoints=cb,exports.dayToIso=Yk,exports.defaultFormat=cf,exports.depthBars=jS,exports.describeInputs=Hu,exports.detectCandlePatterns=$l,exports.drawAxisValueLabels=ae,exports.drawIcon=fx,exports.drawingAxisSpan=Bm,exports.drawnKeys=Wi,exports.feedFromAdapter=DC,exports.fillTag=A,exports.financeTheme=lD,exports.findDominantSwing=ah,exports.findPivots=Gt,exports.forEachPixelColumn=e.d,exports.forecastOutcome=Ub,exports.formatTooltipTime=pp,exports.getIntParam=H,exports.getNumberParam=V,exports.getVisibleData=He,exports.gpuContextsLeft=e.r,exports.hasHistogram=$i,exports.hasTrades=hC,exports.histogramBins=Mk,exports.hitBar=nk,exports.hitCategory=rk,exports.hitDay=nA,exports.hitHistogramBar=Rk,exports.hitMatrixCell=mA,exports.hitSlice=mk,exports.hitWaterfallBar=uO,exports.idleCssCursor=ip,exports.indicatorCategory=Lu,exports.indicatorValuePrecision=j,exports.indicatorWorkerPool=Xu,exports.inferOrderType=rS,exports.inputSource=xa,exports.isCrosshairCursor=$f,exports.isDataFeed=xC,exports.isDense=e.f,exports.isInWindow=pT,exports.isPriceLevelAlert=ET,exports.isRegularSession=mT,exports.isSeriesPalette=Na,exports.isUpTone=Gi,exports.isWorkerResponse=Uu,exports.labelTextColor=ne,exports.layoutAxisValueLabels=ie,exports.layoutGroupedTreemap=UD,exports.layoutLegend=ff,exports.layoutSquarifiedTreemap=BD,exports.layoutUniformGrid=ID,exports.lineSourceBars=Ca,exports.lineSpace=Xp,exports.loadWebGL=Ne,exports.loadWebGLRenderer=Pe,exports.lttbDownsample=Ye,exports.lttbVisibleIndices=Ze,exports.mergeSessionHours=dT,exports.minuteOfDay=fT,exports.nearestCounterClockPoint=OA,exports.nearestPoint=Tk,exports.niceScale=$d,exports.numberFormat=K,exports.outputToColumns=_o,exports.paneLogRange=Zi,exports.paneValueRange=Xi,exports.parseDay=Jk,exports.pastTimeStep=e.D,exports.percentFormat=af,exports.plotColor=Yi,exports.plotLook=Ji,exports.plotShown=Ki,exports.pointAndFigureColumns=vi,exports.priceBucketRow=e.O,exports.priceScaleText=d,exports.priceSourceBars=Sa,exports.priceToY=e.k,exports.priceToYMapper=e.A,exports.rangePresetStart=Je,exports.readAlertOptions=PT,exports.readableText=Lf,exports.registerBuiltInDrawingTools=qb,exports.registerBuiltInIndicators=Pu,exports.renderAxisValueLabels=oe,exports.renderBarChart=ik,exports.renderCalendar=rA,exports.renderCounterClock=kA,exports.renderDenseBars=e.p,exports.renderDepthChart=SD,exports.renderDonut=hk,exports.renderEquityCurve=FD,exports.renderGauge=JO,exports.renderHeatmap=$D,exports.renderHistogram=zk,exports.renderMatrix=hA,exports.renderPlots=ea,exports.renderScatter=Ek,exports.renderSparkline=fD,exports.renderWaterfall=mO,exports.resolveBarIndex=e.j,exports.resolveColorScale=Nf,exports.scaleColor=Pf,exports.servesTimeframe=rC,exports.setMaxWebGLCharts=e.i,exports.shownCount=DA,exports.shownOnInterval=Aa,exports.sourceParam=ba,exports.spreadLabels=te,exports.streamAdapterOf=SC,exports.timeToX=e.M,exports.timestampToBarIndex=e.N,exports.toHeikinAshi=Gr,exports.toKagi=mi,exports.toLineBreak=pi,exports.toPointAndFigure=_i,exports.toRangeBars=Li,exports.toRenko=ci,exports.tpoLetter=Pt,exports.waveLabel=w_,exports.whenGpuContextFree=e.a,exports.withResampling=tC,exports.withTickBars=mC,exports.xToBarIndex=e.P,exports.xToTime=e.F,exports.yToPrice=e.I;
26
26
  //# sourceMappingURL=index.cjs.map