@barchart/chart-lib 2.414.0 → 2.414.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- chart-lib/barchart.chart.js +3 -3
- chart-lib/package.json +1 -1
chart-lib/barchart.chart.js
CHANGED
|
@@ -16,7 +16,7 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
|
|
|
16
16
|
`)?`${e}${i.op} ${r}`:`${e} ${i.op} ${r}`;break;case`sym`:o=`{${t}}.${n}`;break;default:throw Error(`Unrecognized binary operator ${i.op}`)}}return a&&i.trailingComment!==void 0?`${o} // ${i.trailingComment}\n`:o}function df(e){let t=[];for(let n of e.panes)for(let e of n.axes)for(let n of e.plots)t.push(n);return t}function ff(e,t,n){return!df(e).some(e=>e.uid===t&&e.uid!==n)}function pf(e,t,n){if(!ff(e,t,n))throw Error(`Plot uid '${t}' is already in use on this chart.`)}function mf(e){return df(e).find(e=>e.main===!0)}function hf(e,t){let n=0;for(let r=0;r<e.panes.length;r++){let i=e.panes[r].axes;for(let e=0;e<i.length;e++){let a=i[e].plots;for(let i=0;i<a.length;i++){if(n===t)return{pane:r,axis:e,plot:i};n++}}}return null}function gf(){return{plots:[]}}function _f(e,t){let n=e.panes[t],r=n.axes.map(e=>e.plots.reduce((e,t)=>e+ +!!t.detachedScale,0)),i=n.axes.length;return n.axes.forEach((e,t)=>{let a=r[t],o=e.plots.length;if(!(a===0||a<o)&&a===o){if(i>1&&a===1){let a=(t+1)%i;if(r[a]<n.axes[a].plots.length){let t=e.plots.find(e=>e.detachedScale);t&&(n.axes[a].plots.push(t),e.plots=e.plots.filter(e=>!e.detachedScale),r[a]++)}}else{let t=e.plots.find(e=>e.detachedScale);t&&(t.detachedScale=!1)}}}),e}function vf(e,t,n){let r=hf(e,t);if(r===null)return e;let i=e.panes[r.pane],a=i.axes[r.axis].plots[r.plot];return n===r.axis?delete a.detachedScale:(delete a.detachedScale,i.axes.length<2&&n>0&&i.axes.push(gf()),i.axes[n].plots.push(a),i.axes[r.axis].plots.splice(r.plot,1)),gp(_f(e,r.pane))}function yf(e,t){let n=hf(e,t);if(n===null)return e;let r=e.panes[n.pane].axes[n.axis].plots[n.plot];return r.detachedScale=!0,gp(_f(e,n.pane))}function bf(e,t){let n=df(e).find(e=>e.uid===t.uid);if(!n||n.type!==`Seasonal`)return null;let r=n.offsets;return!Array.isArray(r)||!r.includes(t.offset)?null:n}function xf(e,t){let n=t??{kind:`main`};return n.kind===`main`?mf(e)??null:n.kind===`seasonal`?bf(e,n):null}function Sf(e,t,n){let r=xf(e,n);return r?r.type===`Forward`?{eligible:!1,reason:`it cannot be based on a forward plot`}:r.type===`Expression`&&zc(t)?{eligible:!1,reason:`it cannot be based on an expression; the study needs more than "OHLCV" fields`}:r.type===`Seasonal`&&!Bc(t)?{eligible:!1,reason:`it cannot be based on a seasonal plot`}:{eligible:!0}:{eligible:!1,reason:`its basis does not resolve to an existing target plot`}}var Cf=`..plots{.main === true}`;function wf(e){return V(e,Cf)[0]}function Tf(e){let t=V(e,`..panes{${Cf}}`)[0];return{mainPane:t,mainAxis:V(t,`..axes{${Cf}}`)[0]}}function Ef(e,t,n){let r=wf(t);if(r[r.type.toLowerCase()]===z.PLACEHOLDER_SYMBOL_NAME){let r=wf(e),{mainAxis:i}=Tf(t),a=i.annotations,o=Nf(t,r);if(n){let{mainAxis:e}=Tf(o);e.annotations=a}return o}return t}var Df=`Symbol`,Of=`Expression`,kf=`Forward`,Af=`Seasonal`,jf=[Df,Of,kf,Af];function Mf(e){let t=ef(e),n=$d(t),r=n?0:t.symbols.length,i=!n&&r>0?t.symbols[0]:null;return{clean:n?void 0:t.clean,hasErrors:n,symbolCount:r,firstSymbol:i,error:n?t.error:void 0}}function Nf(e,t){let n=wf(e);N(t.uid)&&pf(e,t.uid,n.uid);let r=e=>n.type===e,i=e=>N(t[e.toLowerCase()]),a=jf.find(e=>i(e)),o=a.toLowerCase(),s=t[o],c=s===z.PLACEHOLDER_SYMBOL_NAME,l=i(Of)||i(kf)||i(Af),u=jf.some(e=>i(e)&&!r(e)),d=$().config.cachedAnnotationsCount||0,f=d>0,{mainAxis:p}=Tf(e);u&&(p.comparison=`None`);let m=Mf(s),h=e=>{throw Error(e)};c||(l?(m.hasErrors&&h(`[Main Plot] "${s}" is an invalid expression.\n${m.error}`),s=m.clean):m.hasErrors||h(`[Main Plot] "${s}" is an expression, unsupported for ${o}.`));let g=(e,t)=>e.findIndex(e=>e.symbol===t),_=(e,t)=>{if(e===z.PLACEHOLDER_SYMBOL_NAME)return;let n=t.annotations||[],r=t.annCache||[],i=g(r,e);if(i!==-1&&r.splice(i,1),n.length>0){let t={symbol:e,annotations:n};r.length+1>d&&r.splice(0,r.length+1-d),r.push(t)}t.annCache=r},v=(e,t)=>{let n=t.annCache||[],r=g(n,e);r!==-1&&(t.annotations=n[r].annotations)},y=e=>{let a=n;if(r(Df))_(a.symbol,e);else if(r(Of))_(a.expression,e);else if(r(Af)){let t=Mf(a.seasonal);t.symbolCount===1&&_(t.firstSymbol,e)}delete e.annotations,i(Df)?v(t.symbol,e):i(Of)?v(t.expression,e):i(Af)&&m.symbolCount===1&&v(t.seasonal,e)};if(f){let t=V(e,`..axes`);for(let e of t)y(e)}let b=i(Of)&&r(Df)||i(Df)&&r(Of),x=H(e,Cf,e=>(N(t.uid)&&(e.uid=t.uid),u&&(delete e.expression,delete e.symbol,delete e.showPrevious,delete e.forward,delete e.offsets,delete e.seasonal,e.type=a,b||(e.curves=[{}]),(i(kf)||i(Af))&&(e.offsets=[0])),e[o]=s,e));if(i(Df)&&ki(s)&&(x.data.aggregation.contractRoll=Wi(s)?`expiration`:`combined`),u){if(i(kf))x.data.aggregation={unit:`Month`},x.display.period=`P10Y`;else if(i(Af)&&!fd(x.data.aggregation).isEndOfDay)x.data.aggregation={unit:`Day`},x.display.period=i(Af)?`P9M`:`P1Y10D`;else if(r(kf)||r(Af)){x.data.aggregation=$().getDefaultAggregation(),x.data.maxDataPoints=z.DEFAULT_MAX_RECORDS;let e=$().getDefaultPeriod();N(e)&&(x.display.period=e)}else i(Of)&&r(Df)&&(Pd.includes(n.curves[0].style)&&(x=H(x,Cf,e=>(delete e.inputs,e))),x.data.aggregation.spec===`PerRange`&&(x.data.aggregation={unit:`Day`}))}let ee=/* @__PURE__ */ new Map([[`..plots{.type === "Study"}`,e=>{let t=B(e.study);return M(t)&&Sf(x,t,e.basis).eligible?e:z.NULL_OBJECT}],[`..plots{.type === "BalanceSheet" || .type === "IncomeStatement"}`,e=>i(Df)?(e.symbol=s,e):z.NULL_OBJECT],[`..plots{..events}`,e=>(i(Df)||delete e.events,e)]]);for(let[e,t]of ee)x=H(x,e,t);return u&&!b&&(x=Fd(x,{type:a,curves:[{}]})),x=gp(x),x}function Pf(e){let t=$().getDefaultDensity();N(t)&&(e.display.density=t)}function Ff(e,t){return H(e,`..plots{.type === "Study" && (.study === "VOL" || .study === "MAVOL")}.curves{.fields === "TradeSize" || .fields === "Volume"}`,e=>(e.fields=t?[W.TradeSize.id]:[W.Volume.id],e))}function If(e,t){let n=fd(e.data.aggregation),r=n.isTick&&!n.hasSpec,i=fd(t),a=i.isTick&&!i.hasSpec,o=e=>e.isIntraday&&e.hasSpec&&e.spec===_.PerRange,s=o(n),c=o(i),l=H(e,`${Cf}.curves[0]`,e=>{let t=[W.Open.id,W.High.id,W.Low.id,W.Close.id,W.Change.id].slice();if(!s&&c)return jd(`Range`,!0);if(s&&!c&&(e.style=`OHLC`),!a&&r){let n=$().getDefaultMultiFieldCurve();if(n!==null)return n;e.fields=t,e.style!==`Candlestick`&&e.style!==`OHLC`&&e.style!==`HLC`&&(e.style=`Candlestick`,e.colors=[`#ff6961`,`#77dd77`],e.varyColorPerBar=!0),e.style===`HLC`&&e.fields.splice(0,1)}else a&&!r&&(e.fields=[W.Last.id,W.Change.id],e.style=`Line`,e.colors=[`#0055cc`],e.varyColorPerBar=!1);return e});return l=Ff(l,a),gt(l.data.aggregation,t),(n.unit!==i.unit||n.size!==i.size)&&(Sd(l),xd(l),Pf(l),bd(l)),l}function Lf(e){return N(e)&&e!==z.AUTOFIT_PERIOD}function Rf(e){e.display?.density?(Sd(e),xd(e)):Lf(e.display?.period)&&xd(e)}var zf=/* @__PURE__ */ new Set([`OHLC`,`HLC`,`HL`,`Candlestick`,`HollowCandles`,`HeikinAshi`,`ElderImpulseSystem`,`Range`,`Renko`,`LineBreak`,`PointAndFigure`,`Kagi`,`Column`,`MultiColumn`,`StackedColumn`]);function Bf(e){let t=it(e.display,null,`chart`,`bar`);if(N(t)){let[n]=V(e,Cf),r=n?.curves?.some(e=>M(e.style)&&zf.has(e.style))?z.MINIMUM_WIDE_BAR_WIDTH:z.MINIMUM_BAR_WIDTH,[i,a]=bt(t.width||0,t.spacing||0,r,z.MAXIMUM_BAR_WIDTH);t.width=i,t.spacing=a}}function Vf(e){let t=V(e,`..annotations{.id === 'RewardRisk' || .id === 'ProfitLoss' }`);t.length>0&&t.forEach(e=>{e.traits.prices=e.traits.prices.map(e=>typeof e==`string`?Number.parseFloat(e):e),e.id===`RewardRisk`&&(e.traits.ratio=Math.abs(e.traits.ratio),e.traits.textLines=e.traits.textLines.map(e=>e.match(/Ratio/)?e.replace(`-`,``):e))})}function Hf(e){let t=V(e,`..annotations{.traits.fill.color === null}`);t.length>0&&t.forEach(e=>{e.traits.fill.color=`rgba(0, 0, 0, 0)`})}function Uf(e){let{from:t,to:n}=e.display?.xAxis?.visibleRange||{},r=t===null,i=n===null;r&&delete e.display.xAxis.visibleRange.from,i&&delete e.display.xAxis.visibleRange.to,r&&i&&delete e.display.xAxis.visibleRange}function Wf(e){let t=V(e,`..panes[0].axes[0].scale`);if(t.length===1){let n=t[0],r=V(e,`..panes[0]..axes`);r.length>0&&r.forEach(e=>e.scale=n)}}function Gf(e){let[t]=V(e,Cf);N(t)&&t.type===S[S.Symbol]&&!Pd.includes(t.curves[0].style)&&N(t.inputs)&&delete t.inputs}function Kf(e){let[t]=V(e,Cf);N(t)&&t.type===S[S.Symbol]&&t.curves[0].style===h[h.Renko]&&N(t.inputs)&&t.inputs.map(e=>e.value).some(e=>e===void 0)&&(t.inputs=P(z.DEFAULT_RENKO_INPUTS))}function qf(e){let[t]=V(e,Cf);if(N(t)&&t.type===S[S.Expression]){let n=t.curves[0].style,r=n===h[h.Range],i=n===h[h.Baseline],a=Pd.includes(n);r&&e.data?.aggregation.spec===_[_.PerRange]&&(e.data.aggregation={unit:`Day`}),!i&&(a||r)&&(delete t.inputs,t.curves[0]=jd(`Candlestick`,!0))}}function Jf(e){let t=H(e,`..annCache{!.annotations}`,e=>z.NULL_OBJECT);t=H(t,`..annCache`,e=>{let t=Yi(e.symbol);return t===null?e:li(t,yi(/* @__PURE__ */ new Date,3))?z.NULL_OBJECT:e}),t=H(t,`..annotations{.id === 'ComputedText' && !.traits.textLines}`,e=>z.NULL_OBJECT);let n=t.data.aggregation,r=n.unit===`Tick`&&n.spec===`None`;return Ff(t,r)}function Yf(e){V(e,`..annotations`).forEach(e=>{let{id:t,traits:n}=e;au(t,n),iu(t,n)})}function Xf(e){try{jc(!1),V(e,`..plots{.type === "Study" && .curves.zones}`).forEach(e=>{let t=B(e.study).defaults;for(let n=0;n<(e.curves?.length??0);n++){let r=e.curves[n];if(r.zones&&(r.colors?.length??0)<(t.curves[n].colors?.length??0)){let e=t.curves[n].colors.slice(r.colors?.length??0);r.colors?.length?r.colors.push(...e):r.colors=e}}})}finally{jc(!0)}}function Zf(e){let t=e=>parseInt(e,16)*17;for(let n of V(e,`..curves`))Array.isArray(n.colors)&&(n.colors=n.colors.map(e=>{if(!/^#[0-9a-f]{4}$/i.test(e))return e;let[n,r,i,a]=e.slice(1).split(``).map(t);return`rgba(${n}, ${r}, ${i}, ${Ze(a/255,2)})`}))}function Qf(e){let[t]=V(e,Cf);if(t.type===`Symbol`&&t.curves?.length===1){let e=t.curves[0];if(e.style===`HLC`){let t=e.colors?.length;if(t===1){let t=e.colors[0];e.colors=[t,t],e.varyColorPerBar=!0,e.attributes=[`OpenVsClose`]}else t===2&&!e.attributes&&(e.attributes=[`OpenVsClose`])}}}function $f(e){$()?.config?.mode===`cmdtyView`&&(delete e.data?.extendedHours,delete e.data?.buildContinuation)}function ep(e){let t=e.data?.aggregation,n=e.data?.extendedHours,r=M(n);t&&t.spec===`FormT`&&(t.spec=`None`,r||(e.data.extendedHours=!0))}function tp(e){let t=e.data?.buildContinuation,n=M(t),r=e.data?.aggregation;n&&r&&(r.spec===`Continue`&&!t&&(r.spec=`None`),t&&(r.spec=`Continue`))}function np(e){try{jc(!1),V(e,`..plots{.type === "Study" && .curves.varyColorPerBar}`).forEach(e=>{let t=B(e.study).defaults;if(e?.curves?.length===t?.curves.length&&t?.curves.length>0)for(let n=0;n<e.curves.length;n++)e.curves[n].varyColorPerBar=t.curves[n].varyColorPerBar})}finally{jc(!0)}}function rp(e){V(e,`..plots{.type === "Study" && .study === "AVWAP"}`).forEach(e=>Fc(e.inputs))}function ip(e){try{jc(!1),V(e,`..plots{.type === "Study"}`).forEach(e=>{let t=B(e.study).defaults;M(e.inputs)&&e.inputs.forEach((e,n)=>{let r=t.inputs?.[n]?.value;!M(e.value)&&M(r)&&(e.value=r)}),M(e.levels)&&e.levels.forEach((e,n)=>{let r=t.levels?.[n]?.value;!M(e.value)&&M(r)&&(e.value=r)}),M(e.bands)&&e.bands.forEach((e,n)=>{let r=t.bands?.[n]?.range;!M(e.range.from)&&M(r?.from)&&(e.range.from=r.from),!M(e.range.to)&&M(r?.to)&&(e.range.to=r.to)})})}finally{jc(!0)}}function ap(e){let t=V(e,`..axes{.annotations{.points{!.price || !.time}}}`);t.length>0&&t.forEach(e=>{let t=e.annotations.map(e=>{let t=e.points.find(e=>N(e.price)),n=e.points.find(e=>N(e.time));return!N(t)||!N(n)?null:(e.points.forEach(e=>{N(e.price)||(e.price=t.price),N(e.time)||(e.time=n.time)}),e)}).filter(e=>N(e));t.length>0?e.annotations=t:delete e.annotations});let n=V(e,`..panes`),r=e=>N(e.height)?e.height:1,i=n.map(e=>r(e)),a=Math.min(...i),o=a<.01?5/a:1;n.forEach(e=>e.height=Ze(o*r(e),4));let s=$().config.showResizeHandles||!1;e.display.xAxis.resizeHandles=s;let c=`wheel+shift`,l=$().config.scrollBehavior||c;Object.values(ae).filter(e=>typeof e==`string`).includes(l)||(l=c),e.display.scrollBehavior=l;let u=V(e,`..plots{.type === "Study" && .study === "RSI"}`);return u.length>0&&u.forEach(e=>{if(N(e.bands)&&e.bands.length>0){let t=e.inputs&&e.inputs.length===1&&e.inputs[0].name===z.INPUT_PERIOD?e.inputs[0].value:null,n=B(`RSI`).defaults;e.curves=n.curves,e.inputs=n.inputs,N(t)&&(e.inputs[0].value=t),delete e.bands,e.levels=n.levels}}),Rf(e),Bf(e),Hf(e),Uf(e),Wf(e),Gf(e),Kf(e),qf(e),Yf(e),Xf(e),Zf(e),Qf(e),Vf(e),$f(e),ep(e),tp(e),np(e),ip(e),Ec(e),rp(e),Jf(e)}var op=/* @__PURE__ */ o(((e,t,n)=>{(function(){var e=function(t){if(typeof t!=`object`||!t)return t;var n;if(t instanceof Date)return n=/* @__PURE__ */ new Date,n.setTime(t.getTime()),n;if(t instanceof RegExp)return n=new RegExp(t),n;if(t instanceof Array){n=[];for(var r=0,i=t.length;r<i;r++)n[r]=e(t[r]);return n}if(t instanceof Object){for(var a in n={},t)t.hasOwnProperty(a)&&(n[a]=e(t[a]));return n}throw Error(`Unable to clone object!`)},n=function(t){for(var n=[e(t[0])],r=n[0].key,i=n[0].object,a=1,o=t.length;a<o;a++)i=i[r],r=t[a].key,n.push({object:i,key:r});return n},r=function(e,t){var n=e.length-1,r=e[n].key;t[n].object[r]=e[n].object[r]},i={type:!0,not:!0,anyOf:!0,allOf:!0,oneOf:!0,$ref:!0,$schema:!0,id:!0,exclusiveMaximum:!0,exclusiveMininum:!0,properties:!0,patternProperties:!0,additionalProperties:!0,items:!0,additionalItems:!0,required:!0,default:!0,title:!0,description:!0,definitions:!0,dependencies:!0},a={null:function(e){return e===null},string:function(e){return typeof e==`string`},boolean:function(e){return typeof e==`boolean`},number:function(e){return typeof e==`number`&&e===e},integer:function(e){return typeof e==`number`&&e%1==0},object:function(e){return e&&typeof e==`object`&&!Array.isArray(e)},array:function(e){return Array.isArray(e)},date:function(e){return e instanceof Date}},o={alpha:function(e){return/^[a-zA-Z]+$/.test(e)},alphanumeric:function(e){return/^[a-zA-Z0-9]+$/.test(e)},identifier:function(e){return/^[-_a-zA-Z0-9]+$/.test(e)},hexadecimal:function(e){return/^[a-fA-F0-9]+$/.test(e)},numeric:function(e){return/^[0-9]+$/.test(e)},"date-time":function(e){return!isNaN(Date.parse(e))&&e.indexOf(`/`)===-1},uppercase:function(e){return e===e.toUpperCase()},lowercase:function(e){return e===e.toLowerCase()},hostname:function(e){return e.length<256&&/^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])(\.([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]{0,61}[a-zA-Z0-9]))*$/.test(e)},uri:function(e){return/[-a-zA-Z0-9@:%_\+.~#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~#?&//=]*)?/.test(e)},email:function(e){return/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/.test(e)},ipv4:function(e){return!!(/^(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)\.(\d?\d?\d)$/.test(e)&&e.split(`.`).sort()[3]<=255)},ipv6:function(e){return/^((?=.*::)(?!.*::.+::)(::)?([\dA-F]{1,4}:(:|\b)|){5}|([\dA-F]{1,4}:){6})((([\dA-F]{1,4}((?!\3)::|:\b|$))|(?!\2\3)){2}|(((2[0-4]|1\d|[1-9])?\d|25[0-5])\.?\b){4})$/.test(e)}},s={readOnly:function(e,t){return!1},minimum:function(e,t,n){return!(e<t||n.exclusiveMinimum&&e<=t)},maximum:function(e,t,n){return!(e>t||n.exclusiveMaximum&&e>=t)},multipleOf:function(e,t){return e/t%1==0||typeof e!=`number`},pattern:function(e,t){if(typeof e!=`string`)return!0;var n,r;return typeof t==`string`?n=t:(n=t[0],r=t[1]),new RegExp(n,r).test(e)},minLength:function(e,t){return e.length>=t||typeof e!=`string`},maxLength:function(e,t){return e.length<=t||typeof e!=`string`},minItems:function(e,t){return e.length>=t||!Array.isArray(e)},maxItems:function(e,t){return e.length<=t||!Array.isArray(e)},uniqueItems:function(e,t){for(var n={},r,i=0,a=e.length;i<a;i++){if(r=JSON.stringify(e[i]),n.hasOwnProperty(r))return!1;n[r]=!0}return!0},minProperties:function(e,t){if(typeof e!=`object`)return!0;var n=0;for(var r in e)e.hasOwnProperty(r)&&(n+=1);return n>=t},maxProperties:function(e,t){if(typeof e!=`object`)return!0;var n=0;for(var r in e)e.hasOwnProperty(r)&&(n+=1);return n<=t},constant:function(e,t){return JSON.stringify(e)==JSON.stringify(t)},enum:function(e,t){var n,r,i;if(typeof e==`object`){for(i=JSON.stringify(e),n=0,r=t.length;n<r;n++)if(i===JSON.stringify(t[n]))return!0}else for(n=0,r=t.length;n<r;n++)if(e===t[n])return!0;return!1}},c=function(e){return e.indexOf(`://`)===-1?e:e.split(`#`)[0]},l=function(e,t,n){var r,i,a=n.indexOf(`#`),o;if(a===-1)return e.schema.hasOwnProperty(n)?[e.schema[n]]:null;if(a>0){if(o=n.substr(0,a),n=n.substr(a+1),e.schema.hasOwnProperty(o))t=[e.schema[o]];else if(t&&t[0].id===o)t=[t[0]];else return null}else{if(!t)return null;n=n.substr(1)}if(n===``)return[t[0]];if(n.charAt(0)===`/`){for(n=n.substr(1),r=t[0],i=n.split(`/`);i.length>0;){if(!r.hasOwnProperty(i[0]))return null;r=r[i[0]],t.push(r),i.shift()}return t}return null},u=function(e,t){var n,r,i=e.length-1,a,o,s=/^(\d+)/.exec(t);if(s){if(t=t.substr(s[0].length),a=parseInt(s[1],10),a<0||a>i)return;if(o=e[i-a],t===`#`)return o.key}else o=e[0];if(r=o.object[o.key],t===``)return r;if(t.charAt(0)===`/`){for(t=t.substr(1),n=t.split(`/`);n.length>0;){if(n[0]=n[0].replace(/~1/g,`/`).replace(/~0/g,`~`),!r.hasOwnProperty(n[0]))return;r=r[n[0]],n.shift()}return r}},d=function(e,t,a,o){var s,c,f,p,m,h,g,_=!1,v={},y,b,x,ee=t.length-1,S=t[ee],C,w=a.length-1,te=a[w].object,T=a[w].key,E=te[T],ne,re;if(S.hasOwnProperty(`$ref`))return t=l(e,t,S.$ref),t?d(e,t,a,o):{$ref:S.$ref};if(S.hasOwnProperty(`type`)){if(typeof S.type==`string`){if(o.useCoerce&&e.coerceType.hasOwnProperty(S.type)&&(E=te[T]=e.coerceType[S.type](E)),!e.fieldType[S.type](E))return{type:S.type}}else{for(_=!0,s=0,c=S.type.length;s<c&&_;s++)e.fieldType[S.type[s]](E)&&(_=!1);if(_)return{type:S.type}}}if(S.hasOwnProperty(`allOf`)){for(s=0,c=S.allOf.length;s<c;s++)if(y=d(e,t.concat(S.allOf[s]),a,o),y)return y}if(!o.useCoerce&&!o.useDefault&&!o.removeAdditional){if(S.hasOwnProperty(`oneOf`)){for(re=1/0,s=0,c=S.oneOf.length,f=0;s<c;s++)if(y=d(e,t.concat(S.oneOf[s]),a,o),y)ne=y.schema?Object.keys(y.schema).length:1,ne<re&&(re=ne,v=y);else if(f+=1,f>1)break;if(f>1)return{oneOf:!0};if(f<1)return v;v={}}if(S.hasOwnProperty(`anyOf`)){for(v=null,re=1/0,s=0,c=S.anyOf.length;s<c;s++)if(y=d(e,t.concat(S.anyOf[s]),a,o),y)ne=y.schema?Object.keys(y.schema).length:1,ne<re&&(re=ne,v=y);else{v=null;break}if(v)return v}if(S.hasOwnProperty(`not`)&&(y=d(e,t.concat(S.not),a,o),!y))return{not:!0}}else{if(S.hasOwnProperty(`oneOf`)){for(re=1/0,s=0,c=S.oneOf.length,f=0;s<c;s++)if(C=n(a),y=d(e,t.concat(S.oneOf[s]),C,o),y)ne=y.schema?Object.keys(y.schema).length:1,ne<re&&(re=ne,v=y);else{if(f+=1,f>1)break;r(C,a)}if(f>1)return{oneOf:!0};if(f<1)return v;v={}}if(S.hasOwnProperty(`anyOf`)){for(v=null,re=1/0,s=0,c=S.anyOf.length;s<c;s++)if(C=n(a),y=d(e,t.concat(S.anyOf[s]),C,o),y)ne=y.schema?Object.keys(y.schema).length:1,ne<re&&(re=ne,v=y);else{r(C,a),v=null;break}if(v)return v}if(S.hasOwnProperty(`not`)&&(C=n(a),y=d(e,t.concat(S.not),C,o),!y))return{not:!0}}if(S.hasOwnProperty(`dependencies`)){for(h in S.dependencies)if(S.dependencies.hasOwnProperty(h)&&E.hasOwnProperty(h)){if(Array.isArray(S.dependencies[h])){for(s=0,c=S.dependencies[h].length;s<c;s++)if(!E.hasOwnProperty(S.dependencies[h][s]))return{dependencies:!0}}else if(y=d(e,t.concat(S.dependencies[h]),a,o),y)return y}}if(Array.isArray(E)){if(S.hasOwnProperty(`items`)){if(Array.isArray(S.items)){for(s=0,c=S.items.length;s<c;s++)y=d(e,t.concat(S.items[s]),a.concat({object:E,key:s}),o),y!==null&&(v[s]=y,_=!0);if(E.length>c&&S.hasOwnProperty(`additionalItems`)){if(typeof S.additionalItems==`boolean`){if(!S.additionalItems)return{additionalItems:!0}}else for(s=c,c=E.length;s<c;s++)y=d(e,t.concat(S.additionalItems),a.concat({object:E,key:s}),o),y!==null&&(v[s]=y,_=!0)}}else for(s=0,c=E.length;s<c;s++)y=d(e,t.concat(S.items),a.concat({object:E,key:s}),o),y!==null&&(v[s]=y,_=!0)}else if(S.hasOwnProperty(`additionalItems`)&&typeof S.additionalItems!=`boolean`)for(s=0,c=E.length;s<c;s++)y=d(e,t.concat(S.additionalItems),a.concat({object:E,key:s}),o),y!==null&&(v[s]=y,_=!0);if(_)return{schema:v}}else{for(h in b=[],v={},E)E.hasOwnProperty(h)&&b.push(h);if(o.checkRequired&&S.required)for(s=0,c=S.required.length;s<c;s++)E.hasOwnProperty(S.required[s])||(v[S.required[s]]={required:!0},_=!0);if(p=S.hasOwnProperty(`properties`),m=S.hasOwnProperty(`patternProperties`),p||m)for(s=b.length;s--;){if(x=!1,p&&S.properties.hasOwnProperty(b[s])&&(x=!0,y=d(e,t.concat(S.properties[b[s]]),a.concat({object:E,key:b[s]}),o),y!==null&&(v[b[s]]=y,_=!0)),m)for(h in S.patternProperties)S.patternProperties.hasOwnProperty(h)&&b[s].match(h)&&(x=!0,y=d(e,t.concat(S.patternProperties[h]),a.concat({object:E,key:b[s]}),o),y!==null&&(v[b[s]]=y,_=!0));x&&b.splice(s,1)}if(o.useDefault&&p&&!_)for(h in S.properties)S.properties.hasOwnProperty(h)&&!E.hasOwnProperty(h)&&S.properties[h].hasOwnProperty(`default`)&&(E[h]=S.properties[h].default);if(o.removeAdditional&&p&&S.additionalProperties!==!0&&typeof S.additionalProperties!=`object`)for(s=0,c=b.length;s<c;s++)delete E[b[s]];else if(S.hasOwnProperty(`additionalProperties`)){if(typeof S.additionalProperties==`boolean`){if(!S.additionalProperties)for(s=0,c=b.length;s<c;s++)v[b[s]]={additional:!0},_=!0}else for(s=0,c=b.length;s<c;s++)y=d(e,t.concat(S.additionalProperties),a.concat({object:E,key:b[s]}),o),y!==null&&(v[b[s]]=y,_=!0)}if(_)return{schema:v}}for(g in S)S.hasOwnProperty(g)&&!i.hasOwnProperty(g)&&(g===`format`?e.fieldFormat.hasOwnProperty(S[g])&&!e.fieldFormat[S[g]](E,S,a,o)&&(v[g]=!0,_=!0):e.fieldValidate.hasOwnProperty(g)&&!e.fieldValidate[g](E,S[g].hasOwnProperty(`$data`)?u(a,S[g].$data):S[g],S,a,o)&&(v[g]=!0,_=!0));return _?v:null},f={useDefault:!1,useCoerce:!1,checkRequired:!0,removeAdditional:!1};function p(){if(!(this instanceof p))return new p;this.coerceType={},this.fieldType=e(a),this.fieldValidate=e(s),this.fieldFormat=e(o),this.defaultOptions=e(f),this.schema={}}p.prototype={validate:function(e,t,n){var r=[e],i=null,a=[{object:{__root__:t},key:`__root__`}];if(typeof e==`string`&&(r=l(this,null,e),!r))throw Error(`jjv: could not find schema '`+e+`'.`);if(!n)n=this.defaultOptions;else for(var o in this.defaultOptions)this.defaultOptions.hasOwnProperty(o)&&!n.hasOwnProperty(o)&&(n[o]=this.defaultOptions[o]);return i=d(this,r,a,n),i?{validation:i.hasOwnProperty(`schema`)?i.schema:i}:null},resolveRef:function(e,t){return l(this,e,t)},addType:function(e,t){this.fieldType[e]=t},addTypeCoercion:function(e,t){this.coerceType[e]=t},addCheck:function(e,t){this.fieldValidate[e]=t},addFormat:function(e,t){this.fieldFormat[e]=t},addSchema:function(e,t){if(!t&&e&&(t=e,e=void 0),t.hasOwnProperty(`id`)&&typeof t.id==`string`&&t.id!==e){if(t.id.charAt(0)===`/`)throw Error(`jjv: schema id's starting with / are invalid.`);this.schema[c(t.id)]=t}else if(!e)throw Error(`jjv: schema needs either a name or id attribute.`);e&&(this.schema[c(e)]=t)}},t!==void 0&&t.exports!==void 0?t.exports=p:typeof define==`function`&&define.amd?define(function(){return p}):this.jjv=p}).call(n)})),sp=/* @__PURE__ */ c((/* @__PURE__ */ o(((e,t)=>{t.exports=op()})))(),1),cp=null;function lp(e){let{id:t,context:n}=e,r=e=>N(n[e]),i=(e,t)=>{if(!N(n[e]))throw Error(`${t} plot accessor: you must provide '${e}'`)},a=(e,t)=>{if(!e.some(e=>r(e)))throw Error(`${t} plot accessor: you must provide either '${e[0]}' or '${e[1]}'`)},o=e=>{if(r(`placement`)&&n.placement===`clone`&&!r(`cloneUid`)&&!r(`cloneIndex`))throw Error(`${e} plot accessor: when placement is 'clone', you must provide either 'cloneUid' or 'cloneIndex'.`)};if(t===`Plot`)switch(n.id){case`Add`:switch(i(`type`,`Add`),n.type){case`Study`:i(`studyId`,`Add`),o(`Add`);break;case`IncomeStatement`:case`BalanceSheet`:i(`fundamentalId`,`Add`);break;case`Expression`:i(`expression`,`Add`)}break;case`Get`:if(!r(`main`)&&!r(`type`))throw Error(`Get plot accessor: you must provide either 'main' or 'type'`);break;case`Delete`:i(`type`,`Delete`),a([`uid`,`index`],`Delete`);break;case`Update`:switch(i(`type`,`Update`),r(`main`)||a([`uid`,`index`],`Update`),o(`Update`),n.type){case`Forward`:if(!N(n.forward)){if(!N(n.curves)||!N(n.offsets))throw Error(`Update forward plot accessor: you must provide either 'forward' or 'curves' and 'offsets'`);if(n.curves.length!==n.offsets.length)throw Error(`Update forward plot accessor: you must provide same number of elements for 'curves' and 'offsets'`)}break;case`Seasonal`:if(!N(n.seasonal)){if(!N(n.curves)||!N(n.offsets))throw Error(`Update seasonal plot accessor: you must provide either 'seasonal' or 'curves' and 'offsets'`);if(n.curves.length!==n.offsets.length&&n.curves.length!==n.offsets.length+1)throw Error(`Update seasonal plot accessor: you must provide either same number of elements for 'curves' and 'offsets' or one curve more`)}break;case`Study`:{i(`studyId`,`Update`),o(`Update`);let e=e=>e.reduce((e,t)=>e.concat(t.fields),[]),t=B(n.studyId),r=e=>`Update study plot accessor: you must provide same number of elements for '${e}' of the study as defined in the taxonomy`,a=e=>`Update study plot accessor: incoming list of ${e} is different from the ${e} as defined in the taxonomy`;if(N(n.curves)){if(n.curves.length!==t.defaults.curves.length)throw Error(r(`curves`));let i=e(n.curves);if(k(e(t.defaults.curves),i).length!==0)throw Error(a(`fields`))}break}}}}function up(){cp===null&&(cp=(0,sp.default)(),cp.defaultOptions.useDefault=!0,[z.CHART_SCHEMA,z.STUDIES_SCHEMA,z.FIELDS_SCHEMA,z.ACCESSOR_SCHEMA].forEach(e=>{cp.addSchema(e,Dc(e))}))}function dp(e,t){cp.addSchema(e,t)}function fp(e){V(e,`..plots{.type}`).forEach(e=>{N(e.uid)||(e.uid=xt())}),V(e,`..plots{.type==="${S[S.Study]}"}`).forEach(e=>{let t=B(e.study);N(t)&&dt(e,t.defaults)})}function pp(e){return e===z.CHART_SCHEMA}function mp(e){return e===z.ACCESSOR_SCHEMA}function hp(e,t){up();let n=ud(e,t);pp(t)&&(fp(n),n=ap(n));let r=cp.validate(t,n);if(r){let e=JSON.stringify(r,null,4);throw Error(`Document not valid according to schema ${t}; error is ${e}`)}return mp(t)&&lp(n),n}function gp(e){return H(H(e,`..panes{.axes{!.plots}}`,e=>(e.axes.length===1?e.axes=[]:e.axes[1].plots.length===0&&(e.axes.pop(),e.axes[0].plots.length===0&&(e.axes=[])),e)),`..panes{!.axes}`,e=>z.NULL_OBJECT)}var _p=/*#__PURE__*/ JSON.parse(`[{"id":"DateTime","type":"Date"},{"id":"Open"},{"id":"High"},{"id":"Low"},{"id":"Close"},{"id":"TradeSize","format":"AsInteger"},{"id":"Volume","format":"UseMetricUnit","shortName":"VOL"},{"id":"OpenInterest","format":"UseMetricUnit","shortName":"OI"},{"id":"Last"},{"id":"Bid"},{"id":"BidSize","format":"AsInteger"},{"id":"Ask"},{"id":"AskSize","format":"AsInteger"},{"id":"Symbol","type":"String"},{"id":"Change"},{"id":"PercentChange","format":"AsPercent"},{"id":"TradingDay"},{"id":"PreviousClose"},{"id":"PreviousOpen"},{"id":"PreviousHigh"},{"id":"PreviousLow"},{"id":"WeekPreviousClose"},{"id":"WeekPreviousHigh"},{"id":"WeekPreviousLow"},{"id":"MonthPreviousClose"},{"id":"MonthPreviousHigh"},{"id":"MonthPreviousLow"},{"id":"YearHigh"},{"id":"YearLow"},{"id":"Projection","name":"Projection"},{"id":"BarIndex","name":"Bar Index"},{"id":"Dividends","type":"String","category":"Event","name":"Dividend","shortName":"D"},{"id":"Splits","type":"String","category":"Event","name":"Split","shortName":"S"},{"id":"Earnings","type":"String","category":"Event","shortName":"E"},{"id":"Buy","category":"Event","name":"BuySignal","shortName":"B"},{"id":"Sell","category":"Event","name":"SellSignal","shortName":"S"},{"id":"Custom","category":"Event","name":"CustomEvent","shortName":"Z"},{"id":"Call","category":"Option"},{"id":"Put","category":"Option"},{"id":"Delta","category":"Option"},{"id":"Gamma","category":"Option"},{"id":"Theta","category":"Option"},{"id":"Vega","category":"Option"},{"id":"WeighImplVolHigh","category":"Option","name":"Implied Volatility High","shortName":"WeighImplVolHigh"},{"id":"WeighImplVolLow","category":"Option","name":"Implied Volatility Low","shortName":"WeighImplVolLow"},{"id":"WeighImplVol","category":"Option","name":"Implied Volatility","shortName":"WeighImplVol"},{"id":"WeighImplVolHigh5D","category":"Option","name":"Weighted Implied Volatility High 5D","shortName":"WeighImplVolHigh5D"},{"id":"WeighImplVolLow5D","category":"Option","name":"Weighted Implied Volatility Low 5D","shortName":"WeighImplVolLow5D"},{"id":"WeighImplVol5D","category":"Option","name":"Weighted Implied Volatility 5D","shortName":"WeighImplVol5D"},{"id":"WeighImplVolHigh1M","category":"Option","name":"Weighted Implied Volatility High 1M","shortName":"WeighImplVolHigh1M"},{"id":"WeighImplVolLow1M","category":"Option","name":"Weighted Implied Volatility Low 1M","shortName":"WeighImplVolLow1M"},{"id":"WeighImplVol1M","category":"Option","name":"Weighted Implied Volatility 1M","shortName":"WeighImplVol1M"},{"id":"WeighImplVolHigh3M","category":"Option","name":"Weighted Implied Volatility High 3M","shortName":"WeighImplVolHigh3M"},{"id":"WeighImplVolLow3M","category":"Option","name":"Weighted Implied Volatility Low 3M","shortName":"WeighImplVolLow3M"},{"id":"WeighImplVol3M","category":"Option","name":"Weighted Implied Volatility 3M","shortName":"WeighImplVol3M"},{"id":"WeighImplVolHigh6M","category":"Option","name":"Weighted Implied Volatility High 6M","shortName":"WeighImplVolHigh6M"},{"id":"WeighImplVolLow6M","category":"Option","name":"Weighted Implied Volatility Low 6M","shortName":"WeighImplVolLow6M"},{"id":"WeighImplVol6M","category":"Option","name":"Weighted Implied Volatility 6M","shortName":"WeighImplVol6M"},{"id":"WeighImplVolHigh1Y","category":"Option","name":"Weighted Implied Volatility High 1Y","shortName":"WeighImplVolHigh1Y"},{"id":"WeighImplVolLow1Y","category":"Option","name":"Weighted Implied Volatility Low 1Y","shortName":"WeighImplVolLow1Y"},{"id":"WeighImplVol1Y","category":"Option","name":"Weighted Implied Volatility 1Y","shortName":"WeighImplVol1Y"},{"id":"WeighImplVolHighYTD","category":"Option","name":"Weighted Implied Volatility High YTD","shortName":"WeighImplVolHighYTD"},{"id":"WeighImplVolLowYTD","category":"Option","name":"Weighted Implied Volatility Low YTD","shortName":"WeighImplVolLowYTD"},{"id":"WeighImplVolYTD","category":"Option","name":"Weighted Implied Volatility YTD","shortName":"WeighImplVolYTD"},{"id":"WeighImplVolChg","category":"Option","name":"Weighted Implied Volatility Change","shortName":"WeighImplVolChg"},{"id":"ImplVolRank5D","category":"Option","name":"Implied Volatility Rank 5D","shortName":"ImplVolRank5D"},{"id":"ImplVolRank1M","category":"Option","name":"Implied Volatility Rank 1M","shortName":"ImplVolRank1M"},{"id":"ImplVolRank3M","category":"Option","name":"Implied Volatility Rank 3M","shortName":"ImplVolRank3M"},{"id":"ImplVolRank6M","category":"Option","name":"Implied Volatility Rank 6M","shortName":"ImplVolRank6M"},{"id":"ImplVolRank1Y","category":"Option","name":"Implied Volatility Rank","shortName":"ImplVolRank1Y"},{"id":"ImplVolRankYTD","category":"Option","name":"Implied Volatility Rank YTD","shortName":"ImplVolRankYTD"},{"id":"ImplVolPerc5D","category":"Option","name":"Implied Volatility Perc. 5D","shortName":"ImplVolPerc5D"},{"id":"ImplVolPerc1M","category":"Option","name":"Implied Volatility Perc. 1M","shortName":"ImplVolPerc1M"},{"id":"ImplVolPerc3M","category":"Option","name":"Implied Volatility Perc. 3M","shortName":"ImplVolPerc3M"},{"id":"ImplVolPerc6M","category":"Option","name":"Implied Volatility Perc. 6M","shortName":"ImplVolPerc6M"},{"id":"ImplVolPerc1Y","category":"Option","name":"Implied Volatility Percentile","shortName":"ImplVolPerc1Y"},{"id":"ImplVolPercYTD","category":"Option","name":"Implied Volatility Perc. YTD","shortName":"ImplVolPercYTD"},{"id":"OptTotVol","category":"Option","name":"Options Total Volume","shortName":"OptTotVol","format":"UseMetricUnit"},{"id":"OptCallVol","category":"Option","name":"Options Call Volume","shortName":"OptCallVol","format":"UseMetricUnit"},{"id":"OptPutVol","category":"Option","name":"Options Put Volume","shortName":"OptPutVol","format":"UseMetricUnit"},{"id":"PutCallVolRatio","category":"Option","name":"Put Call Volume Ratio","shortName":"PutCallVolRatio"},{"id":"TotalOpenInt","category":"Option","name":"Total Open Interest","shortName":"Total OI","format":"UseMetricUnit"},{"id":"CallOpenInt","category":"Option","name":"Call Open Interest","shortName":"Call OI","format":"UseMetricUnit"},{"id":"PutOpenInt","category":"Option","name":"Put Open Interest","shortName":"Put OI","format":"UseMetricUnit"},{"id":"PutCallOIRatio","category":"Option","name":"Put Call OI Ratio","shortName":"Put Call OI Ratio"},{"id":"CallIVCurve","category":"Option","name":"Call IV Curve","shortName":"Call IV Curve"},{"id":"PutIVCurve","category":"Option","name":"Put IV Curve","shortName":"Put IV Curve"},{"id":"CallTheoretical","category":"Option","name":"Call Theoretical","shortName":"Call Theoretical"},{"id":"PutTheoretical","category":"Option","name":"Put Theoretical","shortName":"Put Theoretical"},{"id":"HL/2","category":"Study","name":"(High+Low)/2","shortName":"(H+L)/2"},{"id":"OC/2","category":"Study","name":"(Open+Close)/2","shortName":"(O+C)/2"},{"id":"HLC/3","category":"Study","name":"(High+Low+Close)/3","shortName":"(H+L+C)/3"},{"id":"OHLC/4","category":"Study","name":"(Open+High+Low+Close)/4","shortName":"(O+H+L+C)/4"},{"id":"HLCC/4","category":"Study","name":"(High+Low+Close+Close)/4","shortName":"(H+L+C+C)/4"},{"id":"AVG","category":"Study","name":"Average","shortName":"AVG"},{"id":"FRAMA","category":"Study","name":"FRAMA","shortName":"FRAMA"},{"id":"MA","category":"Study","name":"MA-Simple","shortName":"MA"},{"id":"MACLD1","category":"Study","name":"MA-Cloud-Fast","shortName":"MACLD1"},{"id":"MACLD2","category":"Study","name":"MA-Cloud-Slow","shortName":"MACLD2"},{"id":"MA1","category":"Study","name":"MA1-Simple","shortName":"MA1"},{"id":"MA2","category":"Study","name":"MA2-Simple","shortName":"MA2"},{"id":"MA3","category":"Study","name":"MA3-Simple","shortName":"MA3"},{"id":"MA4","category":"Study","name":"MA4-Simple","shortName":"MA4"},{"id":"MA5","category":"Study","name":"MA5-Simple","shortName":"MA5"},{"id":"MA6","category":"Study","name":"MA6-Simple","shortName":"MA6"},{"id":"MA7","category":"Study","name":"MA7-Simple","shortName":"MA7"},{"id":"MA8","category":"Study","name":"MA8-Simple","shortName":"MA8"},{"id":"MA9","category":"Study","name":"MA9-Simple","shortName":"MA9"},{"id":"MA10","category":"Study","name":"MA10-Simple","shortName":"MA10"},{"id":"MAS","category":"Study","name":"MA-Shorter","shortName":"MAS"},{"id":"MAL","category":"Study","name":"MA-Longer","shortName":"MAL"},{"id":"CMBCI","category":"Study","name":"Composite Index","shortName":"CMBCI"},{"id":"CMBCIF","category":"Study","name":"Fast Ma","shortName":"CMBCIF"},{"id":"CMBCIS","category":"Study","name":"Slow Ma","shortName":"CMBCIS"},{"id":"COTI","category":"Study","name":"COT Index","shortName":"COTI"},{"id":"CHEXL","category":"Study","name":"ChandelierExitLong","shortName":"CHEXL"},{"id":"CHEXS","category":"Study","name":"ChandelierExitShort","shortName":"CHEXS"},{"id":"SUPTR","category":"Study","name":"Supertrend","shortName":"SUPTR"},{"id":"BARCOLIX","category":"Study","name":"BarColorIndex","shortName":"BARCOLIX"},{"id":"BARKIND","category":"Study","name":"BarKind","shortName":"BARKIND"},{"id":"BREL","category":"Study","name":"BarRelation","shortName":"BREL"},{"id":"EMA","category":"Study","name":"MA-Exp","shortName":"MA(EXP)"},{"id":"MAHI","category":"Study","name":"MA-High","shortName":"MA(HI)"},{"id":"MALO","category":"Study","name":"MA-Low","shortName":"MA(LO)"},{"id":"MACD","category":"Study","name":"MACD","shortName":"MACD"},{"id":"MACDS","category":"Study","name":"MACD-Signal","shortName":"MACD(S)"},{"id":"MACDH","category":"Study","name":"MACD-Histogram","shortName":"MACD(H)"},{"id":"MACDV","category":"Study","name":"MACD-V","shortName":"MACD-V"},{"id":"MACDVS","category":"Study","name":"MACD-V-Signal","shortName":"MACD-V(S)"},{"id":"MACDVH","category":"Study","name":"MACD-V-Histogram","shortName":"MACD-V(H)"},{"id":"ENVU","category":"Study","name":"Envelope-Up","shortName":"ENV(UP)"},{"id":"ENVD","category":"Study","name":"Envelope-Down","shortName":"ENV(DN)"},{"id":"ENVEXPU","category":"Study","name":"Envelope-Exponential-Up","shortName":"ENVEXP(UP)"},{"id":"ENVEXPD","category":"Study","name":"Envelope-Exponential-Down","shortName":"ENVEXP(DN)"},{"id":"ENVSMOU","category":"Study","name":"Envelope-Smoothed-Up","shortName":"ENVSMO(UP)"},{"id":"ENVSMOD","category":"Study","name":"Envelope-Smoothed-Down","shortName":"ENVSMO(DN)"},{"id":"SMA","category":"Study","name":"MA-Smoothed","shortName":"MA(S)"},{"id":"CSHO","category":"Study","name":"Cash-Overlay","shortName":"CSHO"},{"id":"CSHB","category":"Study","name":"Cash-Basis","shortName":"CSHB"},{"id":"MKTCAP","category":"Study","name":"Market-Cap","format":"UseMetricUnit","shortName":"MktCap"},{"id":"TMA","category":"Study","name":"MA-Triangular","shortName":"MA(TRI)"},{"id":"WMA","category":"Study","name":"MA-Weighted","shortName":"MA(W)"},{"id":"VOLMA","category":"Study","format":"UseMetricUnit","name":"MA-Volume","shortName":"VOLMA"},{"id":"OSC","category":"Study","name":"OSC","shortName":"OSC"},{"id":"VOSC","category":"Study","format":"UseMetricUnit","name":"OSC-Volume","shortName":"VOLOSC"},{"id":"RSI","category":"Study","name":"RSI","shortName":"RSI"},{"id":"RSIAVG","category":"Study","name":"RSI-Average","shortName":"RSIAVG"},{"id":"RSA","category":"Study","name":"RSA","shortName":"RSA"},{"id":"RSAAVG","category":"Study","name":"RSA-Average","shortName":"RSIAVG"},{"id":"STORSI","category":"Study","name":"StochRSI","shortName":"STOCHRSI"},{"id":"STORSIAVG","category":"Study","name":"StochRSIAvg","shortName":"STOCHRSIAVG"},{"id":"HH","category":"Study","name":"HighestHigh","shortName":"HHIGH"},{"id":"LL","category":"Study","name":"LowestLow","shortName":"LLOW"},{"id":"PercK","category":"Study","name":"%K","shortName":"PCNTK"},{"id":"PercD","category":"Study","name":"%D","shortName":"PCNTD"},{"id":"PercR","category":"Study","name":"%R","shortName":"PCNTR"},{"id":"WGCL","category":"Study","name":"WeightedClose","shortName":"WTCL"},{"id":"WGALPH","category":"Study","name":"WeightedAlpha","shortName":"WGALPH"},{"id":"UPVOL","category":"Study","format":"UseMetricUnit","name":"UpVol","shortName":"UPVOL"},{"id":"DNVOL","category":"Study","format":"UseMetricUnit","name":"DownVol","shortName":"DNVOL"},{"id":"TOTVOL","category":"Study","format":"UseMetricUnit","name":"TotVol","shortName":"TOTVOL"},{"id":"POC","category":"Study","name":"PointOfControl","shortName":"POC"},{"id":"VAREA","category":"Study","name":"ValueArea","shortName":"VAREA"},{"id":"BARBACK","category":"Study","name":"Background","shortName":"BARBACK"},{"id":"BOLLBU","category":"Study","name":"Bollinger-Upper","shortName":"BOLL(U)"},{"id":"BOLLBL","category":"Study","name":"Bollinger-Lower","shortName":"BOLL(L)"},{"id":"BOLLBM","category":"Study","name":"Bollinger-Mid","shortName":"BOLL(M)"},{"id":"BOLLW","category":"Study","name":"Bollinger-Width","shortName":"BOLL(W)"},{"id":"BOLLP","category":"Study","name":"Bollinger-Percent","shortName":"BOLL(%B)"},{"id":"BOLLBW","category":"Study","name":"Bollinger-BandWidth","shortName":"BOLL(BW)"},{"id":"BOLLBWA","category":"Study","name":"Bollinger-BandWidthAvg","shortName":"BOLL(BWA)"},{"id":"PCUP1","category":"Study","name":"ProbCone-Up1","shortName":"PCUP1"},{"id":"PCDN1","category":"Study","name":"ProbCone-Down1","shortName":"PCDN1"},{"id":"PCUP2","category":"Study","name":"ProbCone-Up2","shortName":"PCUP2"},{"id":"PCDN2","category":"Study","name":"ProbCone-Down2","shortName":"PCDN2"},{"id":"PCUP3","category":"Study","name":"ProbCone-Up3","shortName":"PCUP3"},{"id":"PCDN3","category":"Study","name":"ProbCone-Down3","shortName":"PCDN3"},{"id":"PCTD","category":"Study","name":"ProbCone-TgtDate","shortName":"PCTD"},{"id":"PCTP","category":"Study","name":"ProbCone-TgtPrice","shortName":"PCTP"},{"id":"MBBUO","category":"Study","name":"ModifiedBoll-UppOut","shortName":"MBOLL(UO)"},{"id":"MBBUI","category":"Study","name":"ModifiedBoll-UppIn","shortName":"MBOLL(UI)"},{"id":"MBBM","category":"Study","name":"ModifiedBoll-Mid","shortName":"MBOLL(M)"},{"id":"MBBLI","category":"Study","name":"ModifiedBoll-LowIn","shortName":"MBOLL(LI)"},{"id":"MBBLO","category":"Study","name":"ModifiedBoll-LowOut","shortName":"MBOLL(LO)"},{"id":"OBVOL","category":"Study","format":"UseMetricUnit","name":"OnBalanceVol","shortName":"OBVOL"},{"id":"OBVOLAVG","category":"Study","format":"UseMetricUnit","name":"OnBalanceVolAvg","shortName":"OBVOL"},{"id":"TR","category":"Study","name":"TrueRange","shortName":"TR"},{"id":"ATR","category":"Study","name":"AvgTrueRange","shortName":"ATR"},{"id":"ATRMA","category":"Study","name":"MA-ATR","shortName":"MA(ATR)"},{"id":"ADJATR","category":"Study","name":"AdjAvgTrueRange","shortName":"ADJATR"},{"id":"COTR","category":"Study","name":"ChgOverTrueRange","shortName":"COTR"},{"id":"ATRP","category":"Study","name":"AvgTrueRangePerc","shortName":"ATRP"},{"id":"STOMOMIX","category":"Study","name":"StochMomIndex","shortName":"STOMOMIX"},{"id":"CHDMOMOSC","category":"Study","name":"ChandeMomOsc","shortName":"CHDMOMOSC"},{"id":"CHDMOMOSCAVG","category":"Study","name":"ChandeMomOsc-Avg","shortName":"CHDMOMOSCAVG"},{"id":"PDI","category":"Study","name":"+DI","shortName":"+DI"},{"id":"MDI","category":"Study","name":"-DI","shortName":"-DI"},{"id":"PLVI","category":"Study","name":"+VI","shortName":"+VI"},{"id":"MNVI","category":"Study","name":"-VI","shortName":"-VI"},{"id":"ADX","category":"Study","name":"ADX","shortName":"ADX"},{"id":"ADXM","category":"Study","name":"ADX-Modified","shortName":"ADXM"},{"id":"ADL","category":"Study","format":"UseMetricUnit","name":"AccDist","shortName":"ACCDIS"},{"id":"ADWM","category":"Study","name":"AccDistWill","shortName":"ACCDISWIL"},{"id":"ADWMMA","category":"Study","name":"AccDistWillMovAvg","shortName":"ACCDISWILMA"},{"id":"MCGD","category":"Study","name":"McGinleyDyn","shortName":"MCGD"},{"id":"HMA","category":"Study","name":"HullMovAvg","shortName":"HMA"},{"id":"COPP","category":"Study","name":"CoppCurve","shortName":"COPP"},{"id":"CHAOSC","category":"Study","format":"UseMetricUnit","name":"ChaikinOsc","shortName":"CHAIKOSC"},{"id":"TP","category":"Study","name":"TypicalPrice","shortName":"TP"},{"id":"KCUP","category":"Study","name":"KeltChan-Up","shortName":"KELT(UP)"},{"id":"KCMID","category":"Study","name":"KeltChan-Mid","shortName":"KELT(MID)"},{"id":"KCLOW","category":"Study","name":"KeltChan-Low","shortName":"KELT(LO)"},{"id":"KBUP","category":"Study","name":"KeltBands-Up","shortName":"KELB(UP)"},{"id":"KBMID","category":"Study","name":"KeltBands-Mid","shortName":"KELB(MID)"},{"id":"KBLOW","category":"Study","name":"KeltBands-Low","shortName":"KELB(LO)"},{"id":"DONUP","category":"Study","name":"Donchian-Up","shortName":"DON(U)"},{"id":"DONMID","category":"Study","name":"Donchian-Mid","shortName":"DON(M)"},{"id":"DONLOW","category":"Study","name":"Donchian-Low","shortName":"DON(L)"},{"id":"DONW","category":"Study","name":"Donchian-Width","shortName":"DON(W)"},{"id":"PVT","category":"Study","format":"UseMetricUnit","name":"PriceVolChange","shortName":"PVOL"},{"id":"TRIX","category":"Study","name":"Triple-MA-Exp","shortName":"TRIX"},{"id":"ROC","category":"Study","name":"RateOfChange","shortName":"ROC"},{"id":"PVPT","category":"Study","name":"PivotPoint","shortName":"PVMOV"},{"id":"PVPTR","category":"Study","name":"PvtPt-Resistance","shortName":"PVMOV(R)"},{"id":"PVPTS","category":"Study","name":"PvtPt-Support","shortName":"PVMOV(S)"},{"id":"FISHER","category":"Study","name":"Fisher","shortName":"Fisher"},{"id":"FISHTRG","category":"Study","name":"Fisher-Trigger","shortName":"Trigger"},{"id":"ARNUP","category":"Study","name":"Aroon-Up","shortName":"ARN(UP)"},{"id":"ARNLOW","category":"Study","name":"Aroon-Down","shortName":"ARN(DN)"},{"id":"VSTOPUP","category":"Study","name":"VolaStop-Up","shortName":"VSTOP(UP)"},{"id":"VSTOPLOW","category":"Study","name":"VolaStop-Down","shortName":"VSTOP(DN)"},{"id":"ARNOSC","category":"Study","name":"Aroon-Osci","shortName":"ARNOSC"},{"id":"TCHNUP","category":"Study","name":"TurtleChn-Up","shortName":"TCH(UP)"},{"id":"TCHNLOW","category":"Study","name":"TurtleChn-Low","shortName":"TCH(LO)"},{"id":"TCHRE","category":"Study","name":"TurtleChnRetrace","shortName":"TCHRE"},{"id":"ALJAW","category":"Study","name":"Alligator-Jaw","shortName":"AL(J)"},{"id":"ALTEETH","category":"Study","name":"Alligator-Teeth","shortName":"AL(T)"},{"id":"ALLIPS","category":"Study","name":"Alligator-Lips","shortName":"AL(L)"},{"id":"PLTLN","category":"Study","name":"PlotLine","shortName":"LINE"},{"id":"AWOS","category":"Study","name":"AwesomeOsc","shortName":"AWOSC"},{"id":"AWOSMA","category":"Study","name":"AwesomeOsc-MA","shortName":"AWOSC(MA)"},{"id":"MFMUL","category":"Study","name":"MoneyFlowMul"},{"id":"CLV","category":"Study","name":"CloseLocationValue","shortName":"CLV"},{"id":"CHOP","category":"Study","name":"ChoppinessIndex","shortName":"ChopIx"},{"id":"CHAMF","category":"Study","name":"ChaikinMoneyFlow","shortName":"CHAIKMF"},{"id":"CHAVOL","category":"Study","name":"ChaikinVolatility","shortName":"CHAIKVOL"},{"id":"DPO","category":"Study","name":"DetrendedPriceOsc","shortName":"DPO"},{"id":"CCI","category":"Study","name":"CommodityChannelIndex","shortName":"CCI"},{"id":"EMV","category":"Study","name":"EaseOfMovement","shortName":"EOM"},{"id":"EMVMA","category":"Study","name":"EaseOfMovementMA","shortName":"EOM(MA)"},{"id":"ERBLPOW","category":"Study","name":"ElderRayBullPow","shortName":"ER(BULL)"},{"id":"ERBRPOW","category":"Study","name":"ElderRayBearPow","shortName":"ER(BEAR)"},{"id":"FI","category":"Study","format":"UseMetricUnit","name":"ForceIndex","shortName":"FORCE"},{"id":"MI","category":"Study","name":"MassIndex","shortName":"MASS"},{"id":"MOM","category":"Study","name":"Momentum","shortName":"MOM"},{"id":"MOMMA","category":"Study","name":"MA-Momentum","shortName":"MA(MOM)"},{"id":"MFI","category":"Study","name":"MoneyFlowIndex","shortName":"MFI"},{"id":"MSD","category":"Study","name":"MovingStdDev","shortName":"MSD"},{"id":"PCTCHG","category":"Study","name":"PercentChange","shortName":"PCTCHG"},{"id":"LINRUP","category":"Study","name":"LinRegUpper","shortName":"LINRUP"},{"id":"LINRMID","category":"Study","name":"LinRegMiddle","shortName":"LINRMID"},{"id":"LINRLOW","category":"Study","name":"LinRegLower","shortName":"LINRLOW"},{"id":"NVI","category":"Study","name":"NegativeVolIndex","shortName":"NVI"},{"id":"NVIEMA","category":"Study","name":"NegativeVolIndexEMA","shortName":"NVI(EMA)"},{"id":"PVI","category":"Study","name":"PositiveVolIndex","shortName":"PVI"},{"id":"PVIEMA","category":"Study","name":"PositiveVolIndexEMA","shortName":"PVI(EMA)"},{"id":"PPO","category":"Study","name":"PercPriceOsc","shortName":"PPO"},{"id":"PPOS","category":"Study","name":"PPO-Signal","shortName":"PPO(S)"},{"id":"PPOH","category":"Study","name":"PPO-Histogram","shortName":"PPO(H)"},{"id":"PVO","category":"Study","name":"PercVolOsc","shortName":"PVO"},{"id":"PVOS","category":"Study","name":"PVO-Signal","shortName":"PVO(S)"},{"id":"PVOH","category":"Study","name":"PVO-Histogram","shortName":"PVO(H)"},{"id":"HV","category":"Study","name":"HistVolatility","shortName":"HISTVOL"},{"id":"PERF","category":"Study","name":"Performance","shortName":"PERF"},{"id":"STC","category":"Study","name":"SchaffTrendCycle","shortName":"STC"},{"id":"MCCLO","category":"Study","name":"McClellanOsc","shortName":"MCCLO"},{"id":"BTI","category":"Study","name":"BreadthThrust","shortName":"BTI"},{"id":"NHLAI","category":"Study","name":"NewHiLoAccIx","shortName":"NHLAI"},{"id":"KST","category":"Study","name":"KnowSureThing","shortName":"KST"},{"id":"KSTSIG","category":"Study","name":"KST-Signal","shortName":"KSTSIG"},{"id":"WASI","category":"Study","name":"WilderAccSwingIndex","shortName":"WACCSW"},{"id":"WWVSARU","category":"Study","name":"WilderVolSarUp","shortName":"WVOL-UP"},{"id":"WWVSARD","category":"Study","name":"WilderVolSarDown","shortName":"WVOL-DN"},{"id":"PARSARS","category":"Study","name":"ParabolicSarShort","shortName":"SHORT"},{"id":"PARSARL","category":"Study","name":"ParabolicSarLong","shortName":"LONG"},{"id":"REATRS","category":"Study","name":"RetraceATRStop","shortName":"REATRS"},{"id":"MOVLR","category":"Study","name":"MovingLinRegression","shortName":"MOVLINREG"},{"id":"TRSP1","category":"Study","name":"TrendSeeker®","shortName":"TREND"},{"id":"TRSP2","category":"Study","name":"TrendSeeker®","shortName":"TREND"},{"id":"TARGP","category":"Study","name":"Target Price","shortName":"TARGP"},{"id":"COTLCCMSP","category":"Study","name":"Comm Spec","shortName":"COT(C)"},{"id":"COTLCLGSP","category":"Study","name":"Large Spec","shortName":"COT(L)"},{"id":"COTLCSMSP","category":"Study","name":"Small Spec","shortName":"COT(S)"},{"id":"COTDAGPRO","category":"Study","name":"Producers","shortName":"COTDIS(P)"},{"id":"COTDAGSPD","category":"Study","name":"Swap Dealers","shortName":"COTDIS(S)"},{"id":"COTDAGMNM","category":"Study","name":"Managed Money","shortName":"COTDIS(M)"},{"id":"COTDAGOTH","category":"Study","name":"Other Report","shortName":"COTDIS(O)"},{"id":"COTFTRDLI","category":"Study","name":"Dealer Intermediary","shortName":"COTFIN(D)"},{"id":"COTFTRASM","category":"Study","name":"Asset Manager","shortName":"COTFIN(A)"},{"id":"COTFTRLVF","category":"Study","name":"Leveraged Funds","shortName":"COTFIN(L)"},{"id":"COTFTROTH","category":"Study","name":"Other Report","shortName":"COTFIN(O)"},{"id":"PPTPIV","category":"Study","name":"Pivot Point","shortName":"PPT(P)"},{"id":"PPTR1","category":"Study","name":"1st Resistance","shortName":"PPT(R1)"},{"id":"PPTR2","category":"Study","name":"2nd Resistance","shortName":"PPT(R2)"},{"id":"PPTR3","category":"Study","name":"3rd Resistance","shortName":"PPT(R3)"},{"id":"PPTS1","category":"Study","name":"1st Support","shortName":"PPT(S1)"},{"id":"PPTS2","category":"Study","name":"2nd Support","shortName":"PPT(S2)"},{"id":"PPTS3","category":"Study","name":"3rd Support","shortName":"PPT(S3)"},{"id":"CPPH4","category":"Study","name":"4th Camarilla Res","shortName":"CPP(H4)"},{"id":"CPPH3","category":"Study","name":"3rd Camarilla Res","shortName":"CPP(H3)"},{"id":"CPPH2","category":"Study","name":"2nd Camarilla Res","shortName":"CPP(H2)"},{"id":"CPPH1","category":"Study","name":"1st Camarilla Res","shortName":"CPP(H1)"},{"id":"CPPL1","category":"Study","name":"1st Camarilla Supp","shortName":"CPP(L1)"},{"id":"CPPL2","category":"Study","name":"2nd Camarilla Supp","shortName":"CPP(L2)"},{"id":"CPPL3","category":"Study","name":"3rd Camarilla Supp","shortName":"CPP(L3)"},{"id":"CPPL4","category":"Study","name":"4th Camarilla Supp","shortName":"CPP(L4)"},{"id":"IMPVOL","category":"Study","name":"Implied Volatility","shortName":"IV"},{"id":"CTM","category":"Study","name":"Cycle Trading Momentum","shortName":"CTM"},{"id":"CPMI","category":"Study","name":"Principal Momentum","shortName":"CPMI"},{"id":"CTPI","category":"Study","name":"Turning Point","shortName":"CTPI"},{"id":"CTLTM","category":"Study","name":"Long-Term Momentum","shortName":"LTM"},{"id":"CTLTMF","category":"Study","name":"Long-Term Momentum, Fast","shortName":"LTM(F)"},{"id":"DEMA","category":"Study","name":"Double EMA","shortName":"DEMA"},{"id":"EOSC","category":"Study","name":"Exponential Oscillator","shortName":"EOSC"},{"id":"TEMA","category":"Study","name":"Triple EMA","shortName":"TEMA"},{"id":"TSI","category":"Study","name":"True Strength Index","shortName":"Tsi"},{"id":"TSISIG","category":"Study","name":"True Strength Index Signal","shortName":"TsiSig"},{"id":"GMMA3","category":"Study","name":"GMMA-EMA3","shortName":"GMMA(3)"},{"id":"GMMA5","category":"Study","name":"GMMA-EMA5","shortName":"GMMA(5)"},{"id":"GMMA8","category":"Study","name":"GMMA-EMA8","shortName":"GMMA(8)"},{"id":"GMMA10","category":"Study","name":"GMMA-EMA10","shortName":"GMMA(10)"},{"id":"GMMA12","category":"Study","name":"GMMA-EMA12","shortName":"GMMA(12)"},{"id":"GMMA15","category":"Study","name":"GMMA-EMA15","shortName":"GMMA(15)"},{"id":"GMMA30","category":"Study","name":"GMMA-EMA30","shortName":"GMMA(30)"},{"id":"GMMA35","category":"Study","name":"GMMA-EMA35","shortName":"GMMA(35)"},{"id":"GMMA40","category":"Study","name":"GMMA-EMA40","shortName":"GMMA(40)"},{"id":"GMMA45","category":"Study","name":"GMMA-EMA45","shortName":"GMMA(45)"},{"id":"GMMA50","category":"Study","name":"GMMA-EMA50","shortName":"GMMA(50)"},{"id":"GMMA60","category":"Study","name":"GMMA-EMA60","shortName":"GMMA(60)"},{"id":"CONVLN","category":"Study","name":"ConversionLine","shortName":"ConvLn"},{"id":"BASELN","category":"Study","name":"BaseLine","shortName":"BaseLn"},{"id":"LEADSP1","category":"Study","name":"LeadingSpanA","shortName":"LeadSpA"},{"id":"LEADSP2","category":"Study","name":"LeadingSpanB","shortName":"LeadSpB"},{"id":"LAGGSP","category":"Study","name":"LaggingSpan","shortName":"LaggSp"},{"id":"VWAP","category":"Study","name":"VWAP","shortName":"VWAP"},{"id":"AVWAP","category":"Study","name":"Anchored VWAP","shortName":"Anch-VWAP"},{"id":"VWAPSD1U","category":"Study","name":"VWAP Stdev1 Upper","shortName":"VWAP-Std1-Up"},{"id":"VWAPSD1L","category":"Study","name":"VWAP Stdev1 Lower","shortName":"VWAP-Std1-Lo"},{"id":"VWAPSD2U","category":"Study","name":"VWAP Stdev2 Upper","shortName":"VWAP-Std2-Up"},{"id":"VWAPSD2L","category":"Study","name":"VWAP Stdev2 Lower","shortName":"VWAP-Std2-Lo"},{"id":"DIFA","category":"Study","name":"Distance From Average","shortName":"DistAvg"},{"id":"DOSCH","category":"Study","name":"Derivative Oscillator","shortName":"DerOsc"},{"id":"DOSCS","category":"Study","name":"Derivative Oscillator Signal","shortName":"DerOscSig"},{"id":"TTMSQZON","category":"Study","name":"TTM Squeeze On","shortName":"TtmSqzOn"},{"id":"TTMSQZOFF","category":"Study","name":"TTM Squeeze Off","shortName":"TtmSqzOff"},{"id":"TTMSQZOSC","category":"Study","name":"TTM Squeeze Osc","shortName":"TtmSqzOsc"},{"id":"CRS","category":"Study","name":"CompRelStrength","shortName":"CRS"},{"id":"CRSAVG","category":"Study","name":"CompRelStrengthAvg","shortName":"CRS-Avg"},{"id":"DRS","category":"Study","name":"DorseyRelStrength","shortName":"DRS"},{"id":"MRS","category":"Study","name":"MansfieldRelStrength","shortName":"MRS"},{"id":"PMO","category":"Study","name":"PriceMomOsc","shortName":"PMO"},{"id":"PMOS","category":"Study","name":"PriceMomOscSig","shortName":"PMOS"},{"id":"RVOL","category":"Study","name":"Relative Volume","shortName":"RVOL"},{"id":"AccountsPayable","category":"BalanceSheet","format":"UseMetricUnit","name":"Accounts Payable","shortName":"AcctsPay"},{"id":"AccruedExpenses","category":"BalanceSheet","format":"UseMetricUnit","name":"Accrued Expenses","shortName":"AccrdExp"},{"id":"Cash","category":"BalanceSheet","format":"UseMetricUnit","name":"Cash & Cash Equivalents","shortName":"Cash&CashEqv"},{"id":"CommonShares","category":"BalanceSheet","format":"UseMetricUnit","name":"Common Shares","shortName":"CommonShares"},{"id":"SharesOutstanding","category":"BalanceSheet","format":"UseMetricUnit","name":"Shares Outstanding","shortName":"SharesOutstanding"},{"id":"DeferredIncomeTax","category":"BalanceSheet","format":"UseMetricUnit","name":"Deferred Income Tax","shortName":"DefIncTax"},{"id":"DeferredLongRevenues","category":"BalanceSheet","format":"UseMetricUnit","name":"Deferred Revenues","shortName":"DefRev"},{"id":"EquityOtherInvestments","category":"BalanceSheet","format":"UseMetricUnit","name":"Other Equity Investments","shortName":"OthEquityInvest"},{"id":"IncomeTaxPayable","category":"BalanceSheet","format":"UseMetricUnit","name":"Income Tax Payable","shortName":"IncTaxPayble"},{"id":"Intangibles","category":"BalanceSheet","format":"UseMetricUnit","name":"Intangibles","shortName":"Intangibles"},{"id":"Inventories","category":"BalanceSheet","format":"UseMetricUnit","name":"Inventories","shortName":"Inventory"},{"id":"LongTermDebt","category":"BalanceSheet","format":"UseMetricUnit","name":"Long Term Debt","shortName":"LTDebt"},{"id":"MarketableSec","category":"BalanceSheet","format":"UseMetricUnit","name":"Liquid Securities","shortName":"LiqSecurities"},{"id":"OtherCurrentAssets","category":"BalanceSheet","format":"UseMetricUnit","name":"Miscellaneous Current Assets","shortName":"MiscCurrAssets"},{"id":"OtherCurrentLiabilities","category":"BalanceSheet","format":"UseMetricUnit","name":"Other Current Liabilities","shortName":"OthCurrLiab"},{"id":"OtherEquity","category":"BalanceSheet","format":"UseMetricUnit","name":"Other Equity","shortName":"OthEquity"},{"id":"OtherNonCurrentAssets","category":"BalanceSheet","format":"UseMetricUnit","name":"Other Non-Current Assets","shortName":"OthNonCurrAssets"},{"id":"OtherNonCurrentLiabilities","category":"BalanceSheet","format":"UseMetricUnit","name":"Other Non-Current Liabilities","shortName":"OthNonCurrLiab"},{"id":"PpeNet","category":"BalanceSheet","format":"UseMetricUnit","name":"PPE Net","shortName":"PPENet"},{"id":"PrepaidExpenses","category":"BalanceSheet","format":"UseMetricUnit","name":"Prepaid Expenses","shortName":"PpdExp"},{"id":"Receivables","category":"BalanceSheet","format":"UseMetricUnit","name":"Receivables","shortName":"Receivables"},{"id":"RetainedEarnings","category":"BalanceSheet","format":"UseMetricUnit","name":"Retained Earnings","shortName":"RetEarnings"},{"id":"ShorttermDebt","category":"BalanceSheet","format":"UseMetricUnit","name":"Short-Term Debt","shortName":"ShortTermDebt"},{"id":"TotalAssets","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Assets","shortName":"TotAssets"},{"id":"TotalCurrentAssets","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Current Assets","shortName":"TotCurrAssets"},{"id":"TotalCurrentLiabilities","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Current Liabilities","shortName":"TotCurrLiab"},{"id":"TotalLiabilities","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Liabilities","shortName":"TotalLiab"},{"id":"TotalLiabilitiesAndEquity","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Liabilities & Equity","shortName":"TotLiab&Equity"},{"id":"TotalNonCurrentAssets","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Non-Current Assets","shortName":"TotNonCurrAssets"},{"id":"TotalNonCurrentLiabilities","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Non-Current Liabilities","shortName":"TotNonCurrLiabs"},{"id":"TotalShareholdersEquity","category":"BalanceSheet","format":"UseMetricUnit","name":"Total Shareholders Equity","shortName":"TotShareEquity"},{"id":"BasicEpsContOp","category":"IncomeStatement","format":"UseMetricUnit","name":"Basic EPS Continued Operations","shortName":"EPSContOps"},{"id":"BasicEpsTotalOp","category":"IncomeStatement","format":"UseMetricUnit","name":"Basic EPS Total Operations","shortName":"EPSTotOps"},{"id":"CostGoods","category":"IncomeStatement","format":"UseMetricUnit","name":"Cost of Goods","shortName":"COGS"},{"id":"DilutedEpsContOp","category":"IncomeStatement","format":"UseMetricUnit","name":"Diluted EPS Continued Operations","shortName":"DilutedEPSContOps"},{"id":"DilutedEpsTotalOp","category":"IncomeStatement","format":"UseMetricUnit","name":"Diluted EPS Total Operations","shortName":"DilutedEPSTotOps"},{"id":"Ebitda","category":"IncomeStatement","format":"UseMetricUnit","name":"EBITDA","shortName":"EBITDA"},{"id":"GrossProfit","category":"IncomeStatement","format":"UseMetricUnit","name":"Gross Profit","shortName":"GrProfit"},{"id":"IncomeTax","category":"IncomeStatement","format":"UseMetricUnit","name":"Income Tax","shortName":"IncomeTax"},{"id":"InterestExpense","category":"IncomeStatement","format":"UseMetricUnit","name":"Interest Expense","shortName":"IntExp"},{"id":"NetIncome","category":"IncomeStatement","format":"UseMetricUnit","name":"Net Income Less Expenses & Tax","shortName":"NetIncome"},{"id":"OperatingExpenses","category":"IncomeStatement","format":"UseMetricUnit","name":"Operating Expenses","shortName":"OpExpense"},{"id":"OperatingIncome","category":"IncomeStatement","format":"UseMetricUnit","name":"Operating Income","shortName":"OpIncome"},{"id":"OtherIncomeExpenses","category":"IncomeStatement","format":"UseMetricUnit","name":"Other Income","shortName":"OthInc"},{"id":"PreTaxIncome","category":"IncomeStatement","format":"UseMetricUnit","name":"Pretax Income","shortName":"PretaxInc"},{"id":"Sales","category":"IncomeStatement","format":"UseMetricUnit","name":"Sales","shortName":"Sales"},{"id":"JPIB","category":"Study","name":"JPI-Buy","shortName":"Buy"},{"id":"JPIS","category":"Study","name":"JPI-Sell","shortName":"Sell"},{"id":"TDIPRC","category":"Study","name":"TDI Price Line","shortName":"PriceLn"},{"id":"TDITSL","category":"Study","name":"TDI Trade Signal","shortName":"TradeSig"},{"id":"TDIMBL","category":"Study","name":"TDI Market Base","shortName":"MktBase"},{"id":"TDIUPR","category":"Study","name":"TDI Upper Band","shortName":"UpperBnd"},{"id":"TDILWR","category":"Study","name":"TDI Lower Band","shortName":"LowerBnd"},{"id":"PPS","category":"Study","name":"PricePercentStop","shortName":"PPS"},{"id":"RCI","category":"Study","name":"RankCorrelationIndex","shortName":"RCI"},{"id":"RCISIG","category":"Study","name":"RCI Signal","shortName":"RCISig"},{"id":"ZZPIVOT","category":"Study","name":"ZigZag Pivot","shortName":"ZZPivot"},{"id":"ADR","category":"Study","name":"AvgDailyRange","shortName":"ADR"},{"id":"ADRP","category":"Study","name":"AvgDailyRangePerc","shortName":"ADRP"},{"id":"BOP","category":"Study","name":"BalanceOfPower","shortName":"BOP"},{"id":"BOPAVG","category":"Study","name":"BalanceOfPowerAvg","shortName":"BOPAVG"},{"id":"CORR","category":"Study","name":"CorrelationCoefficient","shortName":"Corr"},{"id":"RVI","category":"Study","name":"RelativeVigorIndex","shortName":"RVI"},{"id":"RVISIG","category":"Study","name":"RVI Signal","shortName":"RVISig"},{"id":"ATREXTAVG","category":"Study","name":"ATR Extension Average","shortName":"ATREXTAVG"},{"id":"ATREXTUP","category":"Study","name":"ATR Extension Upper","shortName":"ATREXTUP"},{"id":"ATREXTLOW","category":"Study","name":"ATR Extension Lower","shortName":"ATREXTLOW"},{"id":"DIDIS","category":"Study","name":"DIDI Short","shortName":"DIDIS"},{"id":"DIDIL","category":"Study","name":"DIDI Long","shortName":"DIDIL"},{"id":"DIDIUP","category":"Study","name":"DIDI Crossover","shortName":"DIDIUP"},{"id":"DIDIDN","category":"Study","name":"DIDI Crossunder","shortName":"DIDIDN"}]`),vp=class{id;type;category;name;format;shortName;constructor(e,t=v.Number,n=b.Common,r,i=y.FromMetaData,a){this.id=e,this.type=t,this.category=n,this.name=r,this.format=i,this.shortName=a;let o=e.charAt(0)===`_`;r??(this.name=o?e:this.id.replace(/([A-Z])/g,` $1`).trim()),this.shortName=a??this.name}},yp={},bp=!1;function xp(e){hp(e,z.FIELDS_SCHEMA).map(e=>{yp[e.id]=new vp(e.id,v[e.type],b[e.category],e.name,y[e.format],e.shortName)})}function Sp(){return bp||=(xp(_p),!0),yp}var W=Sp(),G={CH_ALL:`ch`,CH_DIDBECOMEACTIVE:`ch.didbecomeactive`,CH_RECREATED:`ch.recreated`,CH_RESET:`ch.reset`,CH_ANNOTATIONCHANGED:`ch.annotationchanged`,CH_ANNNEEDSCONTEXTMENU:`ch.annneedscontextmenu`,CH_CHTNEEDSCONTEXTMENU:`ch.chtneedscontextmenu`,CH_ANNSELECTIONCHANGED:`ch.annselectionchanged`,CH_ANNPOINTPICKED:`ch.annpointpicked`,CH_ANNMODIFIEDBYTOOL:`ch.annmodifiedbytool`,CH_PANEHEIGHTSCHANGED:`ch.paneheightschanged`,CH_PANESREORDERED:`ch.panesreordered`,CH_AXISSCALECHANGED:`ch.axisscalechanged`,CH_CHTLAYOUTCHANGED:`ch.chtlayoutchanged`,CH_NODATAFORMAINSYMBOL:`ch.nodataformainsymbol`,CH_CARDPLOTCLICKED:`ch.cardplotclicked`,CH_CARDPLOTREMOVED:`ch.cardplotremoved`,CH_CARDPLOTVISIBILITYCHANGED:`ch.cardplotvisibilitychanged`,CH_TOOLTIPCHANGED:`ch.tooltipchanged`,CH_LOGOCLICKED:`ch.logoclicked`,CH_SHUTDOWN:`ch.shutdown`,CH_ZOOMCHANGED:`ch.zoomchanged`,CH_ALL_DATA_PROJECTED:`ch.all.data.projected`,CH_API_ACTIONS_RECEIVED:`ch.api.actions.received`,CH_HOST_PROPS_CHANGED:`ch.host.props.changed`,CH_DEFINITION_CHANGED:`ch.definition.changed`,CH_PLOTNEEDSCONTEXTMENU:`ch.plotneedscontextmenu`,DF_ALL:`df`,DF_STREAMRECONNECTED:`df.streamreconnected`,TS_ALL:`ts`,TS_LOADING:`ts.loading`,TS_MANYCHANGED:`ts.manychaged`,TS_DATAPOINTADDED:`ts.datapointadded`,TS_DATAPOINTCHANGED:`ts.datapointchanged`,TS_TIMELINECORRECTION:`ts.timelinecorrection`,TS_EVENTSCHANGED:`ts.eventschanged`,TS_QUOTEMARKER:`ts.quotemarker`,MD_ALL:`md`,MD_CHANGED:`md.changed`,RT_ALL:`rt`,RT_QUOTE:`rt.quote`,RT_QUOTEGROUP:`rt.quotegroup`,RT_TRADE:`rt.trade`,RT_VOLUME:`rt.volume`,TL_CHANGED:`tl.changed`,ME_ALL:`me`,ME_MOUSE_OUT_SERIES:`me.mouse.out.series`,ME_MOUSE_OVER_SERIES:`me.mouse.over.series`},Cp=[W.Open,W.High,W.Low,W.Close,W.Volume,W.Change,W.PercentChange,W.PreviousClose].reduce((e,t,n)=>(e.set(t.id,1<<n),e),/* @__PURE__ */ new Map);function wp(...e){return e.reduce((e,t)=>Cp.has(t.id)?e|Cp.get(t.id):e,0)}var Tp=class{symbol;storage;fields=[];_updated=0;isValid=!1;constructor(e=``){this.symbol=e,this.storage=/* @__PURE__ */ new Map,this.isValid=!1,this.resetUpdated()}get updated(){return this._updated}resetUpdated(){this._updated=0}addFields(...e){this.fields=xe(this.fields,e),this.fields.forEach(e=>{this.storage.has(e.id)||this.storage.set(e.id,null)})}update(e,t){if(this.hasField(e)){let n=e.id,r=this.storage.get(n);this.storage.set(n,t);let i=r!==t;return i&&Cp.has(n)&&(this._updated|=Cp.get(n)),i}}computeWellKnown(){let e=this.getValue(W.Close),t=this.getValue(W.PreviousClose);N(e,t)&&(this.hasField(W.Change)&&this.update(W.Change,e-t),this.hasField(W.PercentChange)&&this.update(W.PercentChange,(e-t)/t))}hasField(e){return N(this.fields)&&this.fields.some(t=>t.id===e.id)}hasSymbol(e){return!1}getValue(e){return this.hasField(e)?this.storage.get(e.id):null}shutdown(){}async ready(){return!1}},Ep=class extends Tp{translated;constructor(e){super(),this.symbol=e,this.translated=co(this.symbol)}hasSymbol(e){return this.symbol===e}},Dp=class extends Tp{actual;constructor(e){super(z.PLACEHOLDER_SYMBOL_NAME),this.actual=e}async ready(){return!1}},Op=class extends Tp{constructor(e){super(),this.symbol=e}hasSymbol(e){return this.symbol===e}async ready(){return!0}hasField(e){return!1}getValue(e){return null}},kp={previousOpen:W.PreviousOpen,previousClose:W.PreviousClose,previousHigh:W.PreviousHigh,previousLow:W.PreviousLow,weeklyPreviousClose:W.WeekPreviousClose,weeklyPreviousHigh:W.WeekPreviousHigh,weeklyPreviousLow:W.WeekPreviousLow,monthlyPreviousClose:W.MonthPreviousClose,monthlyPreviousHigh:W.MonthPreviousHigh,monthlyPreviousLow:W.MonthPreviousLow,fiftyTwoWkHigh:W.YearHigh,fiftyTwoWkLow:W.YearLow},Ap={open:W.Open,high:W.High,low:W.Low,close:W.Close,lastPrice:W.Last,volume:W.Volume,netChange:W.Change,percentChange:W.PercentChange},jp=Object.values(kp),Mp=Object.keys(kp),Np=Object.keys(Ap),Pp=class extends Ep{triedFetchingExtraValues=!1;includeBaseFields=!1;async ready(){return ma.call(this,async()=>{let e=$().getMetaDataSource().getMetaData(this.symbol);return this.isValid=await e.ready(),this.isValid})}shutdown(){}getValue(e){return this.hasField(e)&&jp.some(t=>t.id===e.id)&&super.getValue(e)===null&&!this.triedFetchingExtraValues&&this.supplementPreviousValues(),super.getValue(e)}supplementPreviousValues(){this.triedFetchingExtraValues=!0,uI(`ondemand`,`/getQuote.json?symbols=${this.translated}&fields=${Mp.join(`,`)}`).then(e=>{try{let t=JSON.parse(e);if(t.status.code===200&&t.results.length===1){let e=t.results[0];Mp.forEach(t=>this.update(kp[t],e[t])),this.includeBaseFields&&Np.forEach(t=>this.update(Ap[t],e[t])),$().getRecordSource().subject.next({topic:G.RT_QUOTE,data:{symbol:this.symbol}})}}catch{F(`Failed to fetch extra values for ${this.translated}`,`error`)}})}},Fp=class extends Pp{constructor(e){super(e),this.includeBaseFields=!0,this.supplementPreviousValues()}async ready(){return Promise.resolve(!0)}},Ip=class extends Ep{isValid=!1;constructor(e){super(e)}addOptionalField(e,t){N(t)&&(this.addFields(e),this.update(e,t))}async ready(){return ma.call(this,async()=>{let e=$().config.environment===l[l.NodeJs]?null:ra(`#${z.INLINE_DATA_ELEMENT_ID}`);if(!N(e))this.isValid=!1;else{let t=JSON.parse(e);if(!(this.translated in t))this.isValid=!1;else{let e=t[this.translated].quote;this.update(W.Open,e.open),this.update(W.High,e.high),this.update(W.Low,e.low),this.update(W.Close,e.close),this.update(W.PreviousClose,e.previousClose),this.update(W.Volume,e.volume),Mp.filter(e=>e!==`previousClose`).forEach(t=>{this.addOptionalField(kp[t],e[t])}),this.isValid=!0}}return this.isValid})}},Lp=[W.Open,W.High,W.Low,W.Close,W.PreviousClose],Rp=class extends Tp{mapping;resolved;model;constructor(e,t){super();let n=e=>$().getRecordSource().getRecord(e);this.resolved=e.map(([e,t])=>t),this.mapping=new Map(e.map(([e,t])=>[e,n(t)])),this.model=t;let r=Lp.concat(W.Change,W.PercentChange);this.addFields(...r.filter(e=>e!==W.Volume))}async ready(){return ma.call(this,async()=>{let e=Array.from(this.mapping.values()).map(e=>e.ready());return this.isValid=(await Promise.all(e)).every(e=>e),this.isValid&&this.evaluate(),this.isValid})}hasSymbol(e){return this.resolved.includes(e)}getOneValue(e){return t=>this.mapping.get(t).getValue(e)}evaluate(){Lp.forEach(e=>{let t=tf(this.model,this.getOneValue(e));this.update(e,Number.isFinite(t)?t:null)}),this.computeWellKnown()}};function zp(e,t){return n=>n.topic===e&&n.data.symbol===t}var Bp=function(e,t){return Bp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Bp(e,t)};function Vp(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Bp(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function Hp(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Up(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function Wp(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Gp(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function Kp(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function qp(e){return this instanceof qp?(this.v=e,this):new qp(e)}function Jp(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof qp?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Yp(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Wp==`function`?Wp(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Xp(e){return typeof e==`function`}function Zp(e){var t=e(function(e){Error.call(e),e.stack=(/* @__PURE__ */ Error()).stack});return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Qp=Zp(function(e){return function(t){e(this),this.message=t?t.length+` errors occurred during unsubscription:
|
|
17
17
|
`+t.map(function(e,t){return t+1+`) `+e.toString()}).join(`
|
|
18
18
|
`):``,this.name=`UnsubscriptionError`,this.errors=t}});function $p(e,t){if(e){var n=e.indexOf(t);0<=n&&e.splice(n,1)}}var em=function(){function e(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return e.prototype.unsubscribe=function(){var e,t,n,r,i;if(!this.closed){this.closed=!0;var a=this._parentage;if(a){if(this._parentage=null,Array.isArray(a))try{for(var o=Wp(a),s=o.next();!s.done;s=o.next())s.value.remove(this)}catch(t){e={error:t}}finally{try{s&&!s.done&&(t=o.return)&&t.call(o)}finally{if(e)throw e.error}}else a.remove(this)}var c=this.initialTeardown;if(Xp(c))try{c()}catch(e){i=e instanceof Qp?e.errors:[e]}var l=this._finalizers;if(l){this._finalizers=null;try{for(var u=Wp(l),d=u.next();!d.done;d=u.next()){var f=d.value;try{rm(f)}catch(e){i??=[],e instanceof Qp?i=Kp(Kp([],Gp(i)),Gp(e.errors)):i.push(e)}}}catch(e){n={error:e}}finally{try{d&&!d.done&&(r=u.return)&&r.call(u)}finally{if(n)throw n.error}}}if(i)throw new Qp(i)}},e.prototype.add=function(t){if(t&&t!==this){if(this.closed)rm(t);else{if(t instanceof e){if(t.closed||t._hasParent(this))return;t._addParent(this)}(this._finalizers=this._finalizers??[]).push(t)}}},e.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},e.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},e.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&$p(t,e)},e.prototype.remove=function(t){var n=this._finalizers;n&&$p(n,t),t instanceof e&&t._removeParent(this)},e.EMPTY=(function(){var t=new e;return t.closed=!0,t})(),e}(),tm=em.EMPTY;function nm(e){return e instanceof em||e&&`closed`in e&&Xp(e.remove)&&Xp(e.add)&&Xp(e.unsubscribe)}function rm(e){Xp(e)?e():e.unsubscribe()}var im={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1},am={setTimeout:function(e,t){var n=[...arguments].slice(2),r=am.delegate;return r?.setTimeout?r.setTimeout.apply(r,Kp([e,t],Gp(n))):setTimeout.apply(void 0,Kp([e,t],Gp(n)))},clearTimeout:function(e){return(am.delegate?.clearTimeout||clearTimeout)(e)},delegate:void 0};function om(e){am.setTimeout(function(){var t=im.onUnhandledError;if(t)t(e);else throw e})}function sm(){}var cm=(function(){return dm(`C`,void 0,void 0)})();function lm(e){return dm(`E`,void 0,e)}function um(e){return dm(`N`,e,void 0)}function dm(e,t,n){return{kind:e,value:t,error:n}}var fm=null;function pm(e){if(im.useDeprecatedSynchronousErrorHandling){var t=!fm;if(t&&(fm={errorThrown:!1,error:null}),e(),t){var n=fm,r=n.errorThrown,i=n.error;if(fm=null,r)throw i}}else e()}function mm(e){im.useDeprecatedSynchronousErrorHandling&&fm&&(fm.errorThrown=!0,fm.error=e)}var hm=function(e){Vp(t,e);function t(t){var n=e.call(this)||this;return n.isStopped=!1,t?(n.destination=t,nm(t)&&t.add(n)):n.destination=Cm,n}return t.create=function(e,t,n){return new ym(e,t,n)},t.prototype.next=function(e){this.isStopped?Sm(um(e),this):this._next(e)},t.prototype.error=function(e){this.isStopped?Sm(lm(e),this):(this.isStopped=!0,this._error(e))},t.prototype.complete=function(){this.isStopped?Sm(cm,this):(this.isStopped=!0,this._complete())},t.prototype.unsubscribe=function(){this.closed||(this.isStopped=!0,e.prototype.unsubscribe.call(this),this.destination=null)},t.prototype._next=function(e){this.destination.next(e)},t.prototype._error=function(e){try{this.destination.error(e)}finally{this.unsubscribe()}},t.prototype._complete=function(){try{this.destination.complete()}finally{this.unsubscribe()}},t}(em),gm=Function.prototype.bind;function _m(e,t){return gm.call(e,t)}var vm=function(){function e(e){this.partialObserver=e}return e.prototype.next=function(e){var t=this.partialObserver;if(t.next)try{t.next(e)}catch(e){bm(e)}},e.prototype.error=function(e){var t=this.partialObserver;if(t.error)try{t.error(e)}catch(e){bm(e)}else bm(e)},e.prototype.complete=function(){var e=this.partialObserver;if(e.complete)try{e.complete()}catch(e){bm(e)}},e}(),ym=function(e){Vp(t,e);function t(t,n,r){var i=e.call(this)||this,a;if(Xp(t)||!t)a={next:t??void 0,error:n??void 0,complete:r??void 0};else{var o;i&&im.useDeprecatedNextContext?(o=Object.create(t),o.unsubscribe=function(){return i.unsubscribe()},a={next:t.next&&_m(t.next,o),error:t.error&&_m(t.error,o),complete:t.complete&&_m(t.complete,o)}):a=t}return i.destination=new vm(a),i}return t}(hm);function bm(e){im.useDeprecatedSynchronousErrorHandling?mm(e):om(e)}function xm(e){throw e}function Sm(e,t){var n=im.onStoppedNotification;n&&am.setTimeout(function(){return n(e,t)})}var Cm={closed:!0,next:sm,error:xm,complete:sm},wm=(function(){return typeof Symbol==`function`&&Symbol.observable||`@@observable`})();function Tm(e){return e}function Em(e){return e.length===0?Tm:e.length===1?e[0]:function(t){return e.reduce(function(e,t){return t(e)},t)}}var Dm=function(){function e(e){e&&(this._subscribe=e)}return e.prototype.lift=function(t){var n=new e;return n.source=this,n.operator=t,n},e.prototype.subscribe=function(e,t,n){var r=this,i=Am(e)?e:new ym(e,t,n);return pm(function(){var e=r,t=e.operator,n=e.source;i.add(t?t.call(i,n):n?r._subscribe(i):r._trySubscribe(i))}),i},e.prototype._trySubscribe=function(e){try{return this._subscribe(e)}catch(t){e.error(t)}},e.prototype.forEach=function(e,t){var n=this;return t=Om(t),new t(function(t,r){var i=new ym({next:function(t){try{e(t)}catch(e){r(e),i.unsubscribe()}},error:r,complete:t});n.subscribe(i)})},e.prototype._subscribe=function(e){return this.source?.subscribe(e)},e.prototype[wm]=function(){return this},e.prototype.pipe=function(){return Em([...arguments])(this)},e.prototype.toPromise=function(e){var t=this;return e=Om(e),new e(function(e,n){var r;t.subscribe(function(e){return r=e},function(e){return n(e)},function(){return e(r)})})},e.create=function(t){return new e(t)},e}();function Om(e){return e??im.Promise??Promise}function km(e){return e&&Xp(e.next)&&Xp(e.error)&&Xp(e.complete)}function Am(e){return e&&e instanceof hm||km(e)&&nm(e)}function jm(e){return Xp(e?.lift)}function Mm(e){return function(t){if(jm(t))return t.lift(function(t){try{return e(t,this)}catch(e){this.error(e)}});throw TypeError(`Unable to lift unknown Observable type`)}}function Nm(e,t,n,r,i){return new Pm(e,t,n,r,i)}var Pm=function(e){Vp(t,e);function t(t,n,r,i,a,o){var s=e.call(this,t)||this;return s.onFinalize=a,s.shouldUnsubscribe=o,s._next=n?function(e){try{n(e)}catch(e){t.error(e)}}:e.prototype._next,s._error=i?function(e){try{i(e)}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._error,s._complete=r?function(){try{r()}catch(e){t.error(e)}finally{this.unsubscribe()}}:e.prototype._complete,s}return t.prototype.unsubscribe=function(){var t;if(!this.shouldUnsubscribe||this.shouldUnsubscribe()){var n=this.closed;e.prototype.unsubscribe.call(this),!n&&((t=this.onFinalize)==null||t.call(this))}},t}(hm),Fm=Zp(function(e){return function(){e(this),this.name=`ObjectUnsubscribedError`,this.message=`object unsubscribed`}}),Im=function(e){Vp(t,e);function t(){var t=e.call(this)||this;return t.closed=!1,t.currentObservers=null,t.observers=[],t.isStopped=!1,t.hasError=!1,t.thrownError=null,t}return t.prototype.lift=function(e){var t=new Lm(this,this);return t.operator=e,t},t.prototype._throwIfClosed=function(){if(this.closed)throw new Fm},t.prototype.next=function(e){var t=this;pm(function(){var n,r;if(t._throwIfClosed(),!t.isStopped){t.currentObservers||=Array.from(t.observers);try{for(var i=Wp(t.currentObservers),a=i.next();!a.done;a=i.next())a.value.next(e)}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}}})},t.prototype.error=function(e){var t=this;pm(function(){if(t._throwIfClosed(),!t.isStopped){t.hasError=t.isStopped=!0,t.thrownError=e;for(var n=t.observers;n.length;)n.shift().error(e)}})},t.prototype.complete=function(){var e=this;pm(function(){if(e._throwIfClosed(),!e.isStopped){e.isStopped=!0;for(var t=e.observers;t.length;)t.shift().complete()}})},t.prototype.unsubscribe=function(){this.isStopped=this.closed=!0,this.observers=this.currentObservers=null},Object.defineProperty(t.prototype,"observed",{get:function(){return this.observers?.length>0},enumerable:!1,configurable:!0}),t.prototype._trySubscribe=function(t){return this._throwIfClosed(),e.prototype._trySubscribe.call(this,t)},t.prototype._subscribe=function(e){return this._throwIfClosed(),this._checkFinalizedStatuses(e),this._innerSubscribe(e)},t.prototype._innerSubscribe=function(e){var t=this,n=this,r=n.hasError,i=n.isStopped,a=n.observers;return r||i?tm:(this.currentObservers=null,a.push(e),new em(function(){t.currentObservers=null,$p(a,e)}))},t.prototype._checkFinalizedStatuses=function(e){var t=this,n=t.hasError,r=t.thrownError,i=t.isStopped;n?e.error(r):i&&e.complete()},t.prototype.asObservable=function(){var e=new Dm;return e.source=this,e},t.create=function(e,t){return new Lm(e,t)},t}(Dm),Lm=function(e){Vp(t,e);function t(t,n){var r=e.call(this)||this;return r.destination=t,r.source=n,r}return t.prototype.next=function(e){var t,n;(n=(t=this.destination)?.next)==null||n.call(t,e)},t.prototype.error=function(e){var t,n;(n=(t=this.destination)?.error)==null||n.call(t,e)},t.prototype.complete=function(){var e,t;(t=(e=this.destination)?.complete)==null||t.call(e)},t.prototype._subscribe=function(e){return this.source?.subscribe(e)??tm},t}(Im),Rm={now:function(){return(Rm.delegate||Date).now()},delegate:void 0},zm=function(e){Vp(t,e);function t(t,n){return e.call(this)||this}return t.prototype.schedule=function(e,t){return t===void 0&&(t=0),this},t}(em),Bm={setInterval:function(e,t){var n=[...arguments].slice(2),r=Bm.delegate;return r?.setInterval?r.setInterval.apply(r,Kp([e,t],Gp(n))):setInterval.apply(void 0,Kp([e,t],Gp(n)))},clearInterval:function(e){return(Bm.delegate?.clearInterval||clearInterval)(e)},delegate:void 0},Vm=function(e){Vp(t,e);function t(t,n){var r=e.call(this,t,n)||this;return r.scheduler=t,r.work=n,r.pending=!1,r}return t.prototype.schedule=function(e,t){if(t===void 0&&(t=0),this.closed)return this;this.state=e;var n=this.id,r=this.scheduler;return n!=null&&(this.id=this.recycleAsyncId(r,n,t)),this.pending=!0,this.delay=t,this.id=this.id??this.requestAsyncId(r,this.id,t),this},t.prototype.requestAsyncId=function(e,t,n){return n===void 0&&(n=0),Bm.setInterval(e.flush.bind(e,this),n)},t.prototype.recycleAsyncId=function(e,t,n){if(n===void 0&&(n=0),n!=null&&this.delay===n&&this.pending===!1)return t;t!=null&&Bm.clearInterval(t)},t.prototype.execute=function(e,t){if(this.closed)return/* @__PURE__ */ Error(`executing a cancelled action`);this.pending=!1;var n=this._execute(e,t);if(n)return n;this.pending===!1&&this.id!=null&&(this.id=this.recycleAsyncId(this.scheduler,this.id,null))},t.prototype._execute=function(e,t){var n=!1,r;try{this.work(e)}catch(e){n=!0,r=e||/* @__PURE__ */ Error(`Scheduled action threw falsy error`)}if(n)return this.unsubscribe(),r},t.prototype.unsubscribe=function(){if(!this.closed){var t=this,n=t.id,r=t.scheduler,i=r.actions;this.work=this.state=this.scheduler=null,this.pending=!1,$p(i,this),n!=null&&(this.id=this.recycleAsyncId(r,n,null)),this.delay=null,e.prototype.unsubscribe.call(this)}},t}(zm),Hm=function(){function e(t,n){n===void 0&&(n=e.now),this.schedulerActionCtor=t,this.now=n}return e.prototype.schedule=function(e,t,n){return t===void 0&&(t=0),new this.schedulerActionCtor(this,e).schedule(n,t)},e.now=Rm.now,e}(),Um=new(function(e){Vp(t,e);function t(t,n){n===void 0&&(n=Hm.now);var r=e.call(this,t,n)||this;return r.actions=[],r._active=!1,r}return t.prototype.flush=function(e){var t=this.actions;if(this._active)t.push(e);else{var n;this._active=!0;do if(n=e.execute(e.state,e.delay))break;while(e=t.shift());if(this._active=!1,n){for(;e=t.shift();)e.unsubscribe();throw n}}},t}(Hm))(Vm),Wm=Um;function Gm(e){return e&&Xp(e.schedule)}function Km(e){return e[e.length-1]}function qm(e){return Gm(Km(e))?e.pop():void 0}var Jm=(function(e){return e&&typeof e.length==`number`&&typeof e!=`function`});function Ym(e){return Xp(e?.then)}function Xm(e){return Xp(e[wm])}function Zm(e){return Symbol.asyncIterator&&Xp(e?.[Symbol.asyncIterator])}function Qm(e){return/* @__PURE__ */ TypeError(`You provided `+(typeof e==`object`&&e?`an invalid object`:`'`+e+`'`)+` where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`)}function $m(){return typeof Symbol!=`function`||!Symbol.iterator?`@@iterator`:Symbol.iterator}var eh=$m();function th(e){return Xp(e?.[eh])}function nh(e){return Jp(this,arguments,function(){var t,n,r,i;return Up(this,function(a){switch(a.label){case 0:t=e.getReader(),a.label=1;case 1:a.trys.push([1,,9,10]),a.label=2;case 2:return[4,qp(t.read())];case 3:return n=a.sent(),r=n.value,i=n.done,i?[4,qp(void 0)]:[3,5];case 4:return[2,a.sent()];case 5:return[4,qp(r)];case 6:return[4,a.sent()];case 7:return a.sent(),[3,2];case 8:return[3,10];case 9:return t.releaseLock(),[7];case 10:return[2]}})})}function rh(e){return Xp(e?.getReader)}function ih(e){if(e instanceof Dm)return e;if(e!=null){if(Xm(e))return ah(e);if(Jm(e))return oh(e);if(Ym(e))return sh(e);if(Zm(e))return lh(e);if(th(e))return ch(e);if(rh(e))return uh(e)}throw Qm(e)}function ah(e){return new Dm(function(t){var n=e[wm]();if(Xp(n.subscribe))return n.subscribe(t);throw TypeError(`Provided object does not correctly implement Symbol.observable`)})}function oh(e){return new Dm(function(t){for(var n=0;n<e.length&&!t.closed;n++)t.next(e[n]);t.complete()})}function sh(e){return new Dm(function(t){e.then(function(e){t.closed||(t.next(e),t.complete())},function(e){return t.error(e)}).then(null,om)})}function ch(e){return new Dm(function(t){var n,r;try{for(var i=Wp(e),a=i.next();!a.done;a=i.next()){var o=a.value;if(t.next(o),t.closed)return}}catch(e){n={error:e}}finally{try{a&&!a.done&&(r=i.return)&&r.call(i)}finally{if(n)throw n.error}}t.complete()})}function lh(e){return new Dm(function(t){dh(e,t).catch(function(e){return t.error(e)})})}function uh(e){return lh(nh(e))}function dh(e,t){var n,r,i,a;return Hp(this,void 0,void 0,function(){var o,s;return Up(this,function(c){switch(c.label){case 0:c.trys.push([0,5,6,11]),n=Yp(e),c.label=1;case 1:return[4,n.next()];case 2:if(r=c.sent(),r.done)return[3,4];if(o=r.value,t.next(o),t.closed)return[2];c.label=3;case 3:return[3,1];case 4:return[3,11];case 5:return s=c.sent(),i={error:s},[3,11];case 6:return c.trys.push([6,,9,10]),r&&!r.done&&(a=n.return)?[4,a.call(n)]:[3,8];case 7:c.sent(),c.label=8;case 8:return[3,10];case 9:if(i)throw i.error;return[7];case 10:return[7];case 11:return t.complete(),[2]}})})}function fh(e,t,n,r,i){r===void 0&&(r=0),i===void 0&&(i=!1);var a=t.schedule(function(){n(),i?e.add(this.schedule(null,r)):this.unsubscribe()},r);if(e.add(a),!i)return a}function ph(e){return e instanceof Date&&!isNaN(e)}function mh(e,t){return Mm(function(n,r){var i=0;n.subscribe(Nm(r,function(n){r.next(e.call(t,n,i++))}))})}function hh(e,t,n){e===void 0&&(e=0),n===void 0&&(n=Wm);var r=-1;return t!=null&&(Gm(t)?n=t:r=t),new Dm(function(t){var i=ph(e)?+e-n.now():e;i<0&&(i=0);var a=0;return n.schedule(function(){t.closed||(t.next(a++),0<=r?this.schedule(void 0,r):t.complete())},i)})}function gh(e,t){return e===void 0&&(e=0),t===void 0&&(t=Um),e<0&&(e=0),hh(e,e,t)}function _h(e,t){return Mm(function(n,r){var i=0;n.subscribe(Nm(r,function(n){return e.call(t,n,i++)&&r.next(n)}))})}function vh(e){var t=[...arguments].slice(1),n=qm(t)??Um,r=t[0]??null,i=t[1]||1/0;return Mm(function(t,a){var o=[],s=!1,c=function(e){var t=e.buffer;e.subs.unsubscribe(),$p(o,e),a.next(t),s&&l()},l=function(){if(o){var t=new em;a.add(t);var r={buffer:[],subs:t};o.push(r),fh(t,n,function(){return c(r)},e)}};r!==null&&r>=0?fh(a,n,l,r,!0):s=!0,l();var u=Nm(a,function(e){var t,n,r=o.slice();try{for(var a=Wp(r),s=a.next();!s.done;s=a.next()){var l=s.value,u=l.buffer;u.push(e),i<=u.length&&c(l)}}catch(e){t={error:e}}finally{try{s&&!s.done&&(n=a.return)&&n.call(a)}finally{if(t)throw t.error}}},function(){for(;o?.length;)a.next(o.shift().buffer);u?.unsubscribe(),a.complete(),a.unsubscribe()},void 0,function(){return o=null});t.subscribe(u)})}function yh(e){return Mm(function(t,n){var r=null,i=null,a=function(){i?.unsubscribe();var t=r;r=[],t&&n.next(t),ih(e()).subscribe(i=Nm(n,a,sm))};a(),t.subscribe(Nm(n,function(e){return r?.push(e)},function(){r&&n.next(r),n.complete()},void 0,function(){return r=i=null}))})}var bh=/* @__PURE__ */ o(((e,t)=>{function n(e){return e&&e.__esModule?e:{default:e}}t.exports=n,t.exports.__esModule=!0,t.exports.default=t.exports})),xh=/* @__PURE__ */ o(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;function n(e){if(e===null||e===!0||e===!1)return NaN;var t=Number(e);return isNaN(t)?t:t<0?Math.ceil(t):Math.floor(t)}t.exports=e.default})),Sh=/* @__PURE__ */ o(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;function n(e){var t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),e.getTime()-t.getTime()}t.exports=e.default}));function Ch(e,t){var n=Oh(t);return n.formatToParts?Th(n,e):Eh(n,e)}var wh={year:0,month:1,day:2,hour:3,minute:4,second:5};function Th(e,t){try{for(var n=e.formatToParts(t),r=[],i=0;i<n.length;i++){var a=wh[n[i].type];a>=0&&(r[a]=parseInt(n[i].value,10))}return r}catch(e){if(e instanceof RangeError)return[NaN];throw e}}function Eh(e,t){var n=e.format(t),r=/(\d+)\/(\d+)\/(\d+),? (\d+):(\d+):(\d+)/.exec(n);return[r[3],r[1],r[2],r[4],r[5],r[6]]}var Dh={};function Oh(e){if(!Dh[e]){var t=new Intl.DateTimeFormat(`en-US`,{hourCycle:`h23`,timeZone:`America/New_York`,year:`numeric`,month:`2-digit`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}).format(/* @__PURE__ */ new Date(`2014-06-25T04:00:00.123Z`));Dh[e]=t===`06/25/2014, 00:00:00`||t===`06/25/2014 00:00:00`?new Intl.DateTimeFormat(`en-US`,{hourCycle:`h23`,timeZone:e,year:`numeric`,month:`numeric`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`}):new Intl.DateTimeFormat(`en-US`,{hour12:!1,timeZone:e,year:`numeric`,month:`numeric`,day:`2-digit`,hour:`2-digit`,minute:`2-digit`,second:`2-digit`})}return Dh[e]}function kh(e,t,n,r,i,a,o){var s=/* @__PURE__ */ new Date(0);return s.setUTCFullYear(e,t,n),s.setUTCHours(r,i,a,o),s}var Ah=36e5,jh=6e4,Mh={timezone:/([Z+-].*)$/,timezoneZ:/^(Z)$/,timezoneHH:/^([+-]\d{2})$/,timezoneHHMM:/^([+-])(\d{2}):?(\d{2})$/};function Nh(e,t,n){var r,i;if(!e||(r=Mh.timezoneZ.exec(e),r))return 0;var a;if(r=Mh.timezoneHH.exec(e),r)return a=parseInt(r[1],10),Lh(a)?-(a*Ah):NaN;if(r=Mh.timezoneHHMM.exec(e),r){a=parseInt(r[2],10);var o=parseInt(r[3],10);return Lh(a,o)?(i=Math.abs(a)*Ah+o*jh,r[1]===`+`?-i:i):NaN}if(zh(e)){t=new Date(t||Date.now());var s=Fh(n?t:Ph(t),e);return-(n?s:Ih(t,s,e))}return NaN}function Ph(e){return kh(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds())}function Fh(e,t){var n=Ch(e,t),r=kh(n[0],n[1]-1,n[2],n[3]%24,n[4],n[5],0).getTime(),i=e.getTime(),a=i%1e3;return i-=a>=0?a:1e3+a,r-i}function Ih(e,t,n){var r=e.getTime()-t,i=Fh(new Date(r),n);if(t===i)return t;r-=i-t;var a=Fh(new Date(r),n);return i===a?i:Math.max(i,a)}function Lh(e,t){return-23<=e&&e<=23&&(t==null||0<=t&&t<=59)}var Rh={};function zh(e){if(Rh[e])return!0;try{return new Intl.DateTimeFormat(void 0,{timeZone:e}),Rh[e]=!0,!0}catch{return!1}}var Bh=/(Z|[+-]\d{2}(?::?\d{2})?| UTC| [a-zA-Z]+\/[a-zA-Z_]+(?:\/[a-zA-Z_]+)?)$/,Vh=/* @__PURE__ */ c(xh()),Hh=/* @__PURE__ */ c(Sh()),Uh=36e5,Wh=6e4,Gh=2,Kh={dateTimePattern:/^([0-9W+-]+)(T| )(.*)/,datePattern:/^([0-9W+-]+)(.*)/,plainTime:/:/,YY:/^(\d{2})$/,YYY:[/^([+-]\d{2})$/,/^([+-]\d{3})$/,/^([+-]\d{4})$/],YYYY:/^(\d{4})/,YYYYY:[/^([+-]\d{4})/,/^([+-]\d{5})/,/^([+-]\d{6})/],MM:/^-(\d{2})$/,DDD:/^-?(\d{3})$/,MMDD:/^-?(\d{2})-?(\d{2})$/,Www:/^-?W(\d{2})$/,WwwD:/^-?W(\d{2})-?(\d{1})$/,HH:/^(\d{2}([.,]\d*)?)$/,HHMM:/^(\d{2}):?(\d{2}([.,]\d*)?)$/,HHMMSS:/^(\d{2}):?(\d{2}):?(\d{2}([.,]\d*)?)$/,timeZone:Bh};function qh(e,t){if(arguments.length<1)throw TypeError(`1 argument required, but only `+arguments.length+` present`);if(e===null)return/* @__PURE__ */ new Date(NaN);var n=t||{},r=n.additionalDigits==null?Gh:(0,Vh.default)(n.additionalDigits);if(r!==2&&r!==1&&r!==0)throw RangeError(`additionalDigits must be 0, 1 or 2`);if(e instanceof Date||typeof e==`object`&&Object.prototype.toString.call(e)===`[object Date]`)return new Date(e.getTime());if(typeof e==`number`||Object.prototype.toString.call(e)===`[object Number]`)return new Date(e);if(typeof e!=`string`&&Object.prototype.toString.call(e)!==`[object String]`)return/* @__PURE__ */ new Date(NaN);var i=Jh(e),a=Yh(i.date,r),o=a.year,s=a.restDateString,c=Xh(s,o);if(isNaN(c))return/* @__PURE__ */ new Date(NaN);if(c){var l=c.getTime(),u=0,d;if(i.time&&(u=Zh(i.time),isNaN(u)))return/* @__PURE__ */ new Date(NaN);if(i.timeZone||n.timeZone){if(d=Nh(i.timeZone||n.timeZone,new Date(l+u)),isNaN(d))return/* @__PURE__ */ new Date(NaN)}else d=(0,Hh.default)(new Date(l+u)),d=(0,Hh.default)(new Date(l+u+d));return new Date(l+u+d)}return/* @__PURE__ */ new Date(NaN)}function Jh(e){var t={},n=Kh.dateTimePattern.exec(e),r;if(n?(t.date=n[1],r=n[3]):(n=Kh.datePattern.exec(e),n?(t.date=n[1],r=n[2]):(t.date=null,r=e)),r){var i=Kh.timeZone.exec(r);i?(t.time=r.replace(i[1],``),t.timeZone=i[1].trim()):t.time=r}return t}function Yh(e,t){var n=Kh.YYY[t],r=Kh.YYYYY[t],i=Kh.YYYY.exec(e)||r.exec(e);if(i){var a=i[1];return{year:parseInt(a,10),restDateString:e.slice(a.length)}}if(i=Kh.YY.exec(e)||n.exec(e),i){var o=i[1];return{year:parseInt(o,10)*100,restDateString:e.slice(o.length)}}return{year:null}}function Xh(e,t){if(t===null)return null;var n,r,i,a;if(e.length===0)return r=/* @__PURE__ */ new Date(0),r.setUTCFullYear(t),r;if(n=Kh.MM.exec(e),n)return r=/* @__PURE__ */ new Date(0),i=parseInt(n[1],10)-1,ng(t,i)?(r.setUTCFullYear(t,i),r):/* @__PURE__ */ new Date(NaN);if(n=Kh.DDD.exec(e),n){r=/* @__PURE__ */ new Date(0);var o=parseInt(n[1],10);return rg(t,o)?(r.setUTCFullYear(t,0,o),r):/* @__PURE__ */ new Date(NaN)}if(n=Kh.MMDD.exec(e),n){r=/* @__PURE__ */ new Date(0),i=parseInt(n[1],10)-1;var s=parseInt(n[2],10);return ng(t,i,s)?(r.setUTCFullYear(t,i,s),r):/* @__PURE__ */ new Date(NaN)}if(n=Kh.Www.exec(e),n)return a=parseInt(n[1],10)-1,ig(t,a)?Qh(t,a):/* @__PURE__ */ new Date(NaN);if(n=Kh.WwwD.exec(e),n){a=parseInt(n[1],10)-1;var c=parseInt(n[2],10)-1;return ig(t,a,c)?Qh(t,a,c):/* @__PURE__ */ new Date(NaN)}return null}function Zh(e){var t=Kh.HH.exec(e),n,r;if(t)return n=parseFloat(t[1].replace(`,`,`.`)),ag(n)?n%24*Uh:NaN;if(t=Kh.HHMM.exec(e),t)return n=parseInt(t[1],10),r=parseFloat(t[2].replace(`,`,`.`)),ag(n,r)?n%24*Uh+r*Wh:NaN;if(t=Kh.HHMMSS.exec(e),t){n=parseInt(t[1],10),r=parseInt(t[2],10);var i=parseFloat(t[3].replace(`,`,`.`));return ag(n,r,i)?n%24*Uh+r*Wh+i*1e3:NaN}return null}function Qh(e,t,n){t||=0,n||=0;var r=/* @__PURE__ */ new Date(0);r.setUTCFullYear(e,0,4);var i=r.getUTCDay()||7,a=t*7+n+1-i;return r.setUTCDate(r.getUTCDate()+a),r}var $h=[31,28,31,30,31,30,31,31,30,31,30,31],eg=[31,29,31,30,31,30,31,31,30,31,30,31];function tg(e){return e%400==0||e%4==0&&e%100!=0}function ng(e,t,n){if(t<0||t>11)return!1;if(n!=null){if(n<1)return!1;var r=tg(e);if(r&&n>eg[t]||!r&&n>$h[t])return!1}return!0}function rg(e,t){if(t<1)return!1;var n=tg(e);return!(n&&t>366||!n&&t>365)}function ig(e,t,n){return!(t<0||t>52||n!=null&&(n<0||n>6))}function ag(e,t,n){return!(e!=null&&(e<0||e>=25)||t!=null&&(t<0||t>=60)||n!=null&&(n<0||n>=60))}var og=/* @__PURE__ */ o(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=n;function n(e,t){if(e==null)throw TypeError(`assign requires that input parameter not be null or undefined`);for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}t.exports=e.default})),sg=/* @__PURE__ */ o(((e,t)=>{var n=bh().default;Object.defineProperty(e,"__esModule",{value:!0}),e.default=i;var r=n(og());function i(e){return(0,r.default)({},e)}t.exports=e.default}));function cg(e,t,n){var r=qh(e,n),i=Nh(t,r,!0),a=new Date(r.getTime()-i),o=/* @__PURE__ */ new Date(0);return o.setFullYear(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate()),o.setHours(a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds()),o}var lg=/* @__PURE__ */ c(sg());function ug(e,t,n){if(typeof e==`string`&&!e.match(Bh)){var r=(0,lg.default)(n);return r.timeZone=t,qh(e,r)}var i=qh(e,n),a=kh(i.getFullYear(),i.getMonth(),i.getDate(),i.getHours(),i.getMinutes(),i.getSeconds(),i.getMilliseconds()).getTime(),o=Nh(t,new Date(a));return new Date(a+o)}var dg=`__barchartChartDebug`,fg=/* @__PURE__ */ new WeakMap,pg=1;function mg(){try{let e=globalThis.localStorage?.getItem(dg);if(!e)return{};let t=JSON.parse(e);return typeof t==`object`&&t?t:{}}catch{return{}}}function hg(){let e=globalThis,t=e.barchart_namespace?.chartDebug,n=e.__barchartChartDebug;return{...mg(),...t||{},...n||{}}}function gg(e){return typeof e==`boolean`?e:null}function _g(){return gg(hg().traceLifecycle)===!0}function vg(e){return e===`record:post-init:stale`?{kind:`warn`,labelStyle:`color: #fff; background: #7a271a; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #7a271a; font-weight: 700;`}:e===`record:evict`||e===`openfeed:unsubscribe`?{kind:`warn`,labelStyle:`color: #fff; background: #b42318; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #b42318; font-weight: 700;`}:e===`record:subscribe`||e===`openfeed:subscribe`?{kind:`info`,labelStyle:`color: #fff; background: #027a48; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #027a48; font-weight: 700;`}:e.startsWith(`gc:`)?{kind:`info`,labelStyle:`color: #111827; background: #f59e0b; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #b54708; font-weight: 700;`}:e.startsWith(`chart:`)||e.startsWith(`plot:`)?{kind:`info`,labelStyle:`color: #fff; background: #175cd3; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #175cd3; font-weight: 700;`}:{kind:`info`,labelStyle:`color: #fff; background: #475467; font-weight: 700; padding: 1px 4px; border-radius: 2px;`,eventStyle:`color: #344054; font-weight: 700;`}}function yg(e,t){if(!_g())return;let{kind:n,labelStyle:r,eventStyle:i}=vg(e);t&&Object.keys(t).length>0?F(`%c[chart-debug]%c `+e,n,r,i,t):F(`%c[chart-debug]%c `+e,n,r,i)}function bg(e){if(!e)return null;let t=fg.get(e);return t||(t=pg++,fg.set(e,t)),t}var xg=[W.Open,W.High,W.Low,W.Last,W.Close,W.TradingDay,W.PreviousClose,W.PreviousHigh,W.PreviousLow,W.PreviousOpen,W.Volume,W.Change,W.PercentChange,W.YearHigh,W.YearLow,W.WeekPreviousClose,W.WeekPreviousHigh,W.WeekPreviousLow,W.MonthPreviousClose,W.MonthPreviousHigh,W.MonthPreviousLow],Sg=class{recordCache;translateSymbolBack;_subject;constructor(){this.recordCache=/* @__PURE__ */ new Map,this.translateSymbolBack=/* @__PURE__ */ new Map}traceRecord(e,t,n={}){let r=t;yg(e,{symbol:r?.symbol??null,translated:r?.translated??r?.symbol??null,recordId:bg(t),...n})}get subject(){if(!N(this._subject)){let e=gh(Math.max(z.MINIMUM_THROTTLE,$().config.throttleMillis||0)),t=gh(z.BACKGROUND_TAB_THROTTLE),n=()=>globalThis.document?.hidden?t:e;this._subject=new Im().pipe(yh(n),_h(e=>e.length>0))}return this._subject}addRecordForSymbol(e,t){let n=co(e);n!==e&&this.translateSymbolBack.set(n,e),this.recordCache.set(e,t)}removeRecordForSymbol(e){this.recordCache.delete(e);let t=co(e);this.translateSymbolBack.has(t)&&this.translateSymbolBack.delete(t)}findRecordForSymbol(e){let t=this.translateSymbolBack.has(e)?this.translateSymbolBack.get(e):e;return this.recordCache.get(t)}getSupportedFields(){return xg}makeAndCacheRecord(e,t){if(e===z.PLACEHOLDER_SYMBOL_NAME)return new Dp(z.PLACEHOLDER_SYMBOL_NAME);if(this.recordCache.has(e))return this.recordCache.get(e);let n=t(e),r=this.getSupportedFields();return n.addFields(...r),this.traceRecord(`record:create`,n),this.addRecordForSymbol(e,n),this.initializeRecord(e,n),n}initializeRecord(e,t){t.ready().then(n=>{let r=this.recordCache.get(e)??null,i=r===t;this.traceRecord(i?`record:post-init`:`record:post-init:stale`,t,{isValid:n,isCurrent:i,currentRecordId:bg(r)}),i&&this.postInit(n,t)})}refresh(e=new Set(this.recordCache.values())){for(let t of e)t.isValid||t.symbol===z.PLACEHOLDER_SYMBOL_NAME||(ha.call(t),this.initializeRecord(t.symbol,t))}evictUnused(e,t){for(let[n,r]of this.recordCache)e.has(r)||(t(r),this.removeRecordForSymbol(n))}postInit(e,t){}},Cg=class extends Sg{getRecord(e){return this.makeAndCacheRecord(e,()=>new Ip(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}},wg=class extends Sg{getRecord(e){return this.makeAndCacheRecord(e,()=>new Fp(e))}evictUnused(e){super.evictUnused(e,e=>e.shutdown())}},Tg=class extends Sg{constructor(){super(),this.onMarketUpdate=this.onMarketUpdate.bind(this)}evictUnused(e){super.evictUnused(e,e=>{e.shutdown(),$().connection.off(`marketUpdate`,this.onMarketUpdate,e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new Pp(e))}postInit(e,t){e&&$().connection.on(`marketUpdate`,this.onMarketUpdate,t.translated)}onMarketUpdate(e){if(e.type===z.REALTIME_INITIAL_QUOTE){let t=this.updateFromQuote(e,!0);this.subject.next({topic:G.RT_QUOTE,data:e,updated:t})}else if(e.type===z.REALTIME_TRADE){let t=$().connection.getMarketState().getQuote(e.symbol),n=this.updateFromQuote(t);this.subject.next({topic:G.RT_TRADE,data:e,updated:n}),e.symbol===z.DEBUG_SYMBOL&&F(`Trade\nSymbol: ${e.symbol} \t%cPrice: ${e.tradePrice} \t%cSize: ${e.tradeSize} \t%cTime: ${$r(e.time,z.DEBUG_TIME_FORMAT)} \t%cSession: ${e.session}`,`log`,`color:#0f0`,`color:#a7a`,`color:#f96`,`color:#bee`)}else if(e.type===z.REALTIME_VOLUME){let t=this.updateFromVolume(e);t!==0&&(this.subject.next({topic:G.RT_VOLUME,data:e,updated:t}),e.symbol===z.DEBUG_SYMBOL&&F(`Volume\n Symbol: ${e.symbol} \t%cValue: ${e.value} \t%cSession: ${e.session}`,`log`,`color:#a7a`,`color:#bee`))}}updateFromQuote(e,t=!1){let n=this.findRecordForSymbol(e.symbol);n.resetUpdated(),n.update(W.Open,e.openPrice),n.update(W.High,e.highPrice),n.update(W.Low,e.lowPrice),n.update(W.Last,e.lastPrice),n.update(W.Close,e.lastPrice);let r=(e,t)=>{N(t)&&n.update(e,t)};return r(W.Volume,e.volume),n.update(W.PreviousClose,e.previousPrice),t&&(r(W.PreviousOpen,e.previousOpenPrice),r(W.PreviousHigh,e.previousHighPrice),r(W.PreviousLow,e.previousLowPrice)),n.computeWellKnown(),n.updated}updateFromVolume(e){let t=this.findRecordForSymbol(e.symbol);return t.resetUpdated(),t.update(W.Volume,e.value),t.updated}},Eg=class extends Sg{localTimeZone;constructor(){super(),this.localTimeZone=Intl.DateTimeFormat().resolvedOptions().timeZone}get feed(){return $()}evictUnused(e){super.evictUnused(e,e=>{this.traceRecord(`record:evict`,e,{symbol:e.translated}),e.shutdown(),this.feed.unsubscribe(e.translated)})}getRecord(e){return this.makeAndCacheRecord(e,()=>new Pp(e))}postInit(e,t){e&&(this.traceRecord(`record:subscribe`,t,{symbol:t.translated}),this.feed.subscribe(t.translated))}onSnapshot(e,t){let n=this.findRecordForSymbol(t),r=$().metaDataSource.getMetaData(t);if(!r.isReady)return;let i=(e,t)=>{if(M(t)){let i=r.asPrice(t);return n.update(e,i),i}};n.resetUpdated();let a=i(W.Open,e.open?.price),o=i(W.High,e.high?.price),s=i(W.Low,e.low?.price),c=i(W.Last,e.last?.price);if(M(i(W.Close,e.close?.price))||M(i(W.Close,e.settlement?.price))||i(W.Close,e.last?.price),M(e.instrumentStatus?.tradeDate)){let t=e.instrumentStatus.tradeDate%100;n.update(W.TradingDay,t)}M(e.volume?.volume)&&n.update(W.Volume,r.asQuantity(e.volume.volume));let l=this.toExchangeTime(e.transactionTime,r.timeZone);M(i(W.PreviousClose,e.prevClose?.price))||i(W.PreviousClose,e.previousSession?.settlement?.price),i(W.PreviousOpen,e.previousSession?.open?.price),i(W.PreviousHigh,e.previousSession?.high?.price),i(W.PreviousLow,e.previousSession?.low?.price),i(W.YearHigh,e.yearHigh?.price),i(W.YearLow,e.yearLow?.price),n.computeWellKnown();let u={topic:`rt.quote`,data:{symbol:t,openPrice:a,highPrice:o,lowPrice:s,lastPrice:c,tradeTime:l},updated:n.updated};this.subject.next(u)}skip(e){return e===void 0||e.blockTrade||e.doesNotUpdateLast||e.doesNotUpdateVolume}asDate(e){return!M(e)||e.isZero()?null:new Date(e.div(1e6).toNumber())}toExchangeTime(e,t){let n=this.asDate(e);return n===null?null:cg(ug(n,this.localTimeZone),t)}onUpdate(e,t){if(!this.recordCache.has(t)){F(`[OpenFeed] update for unsubscribed symbol: ${t}`,`warn`);return}let n=$().metaDataSource.getMetaData(t);if(!n.isReady)return;let r=this.toExchangeTime(e.transactionTime,n.timeZone);if(e.trades?.trades)for(let{trade:i}of e.trades.trades){if(this.skip(i))continue;let e=n.asPrice(i.price);if(e===null)continue;let a=n.asQuantity(i.quantity),o=this.toExchangeTime(i.transactionTime,n.timeZone),s=this.findRecordForSymbol(t),[c,l,u,d]=[`High`,`Low`,`Volume`,`TradingDay`].map(e=>W[e]).map(e=>s.getValue(e));(!M(l)||e<l)&&s.update(W.Low,e),(!M(c)||e>c)&&s.update(W.High,e),s.update(W.Last,e),s.update(W.Close,e),s.update(W.Volume,(M(u)?u:0)+a),s.computeWellKnown();let f={data:{symbol:t,tradePrice:e,tradeSize:a,session:i.session,time:o??r,tradingDay:d},topic:`rt.trade`,updated:s.updated};this.subject.next(f)}}};function Dg(e,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return n.length>=t?e.apply(null,n.slice(0,t).reverse()):function(){var r=[...arguments];return Dg(e,t,n.concat(r))}}var Og=Dg(mn,2),kg=Dg(En,2),Ag=Dg(hn,2),jg=Dg(Dn,2),Mg=Dg(On,2),Ng=Dg(kn,2),Pg=Dg(An,2),Fg=Dg($r,2),Ig=Dg(vi,2);function Lg(e,t){let{unit:n}=e;return n===g.Year?or(t):n===g.Quarter?rr(t):n===g.Month?ir(t):n===g.Week?bn(t):n===g.Day?Sn(t):t}function Rg(e,t){switch(e){case g.Tick:return Mg(t);case g.Intraday:return kg(t);case g.Day:return Og(t);case g.Week:return Ng(t);case g.Month:return Ag(t);case g.Quarter:return jg(t);case g.Year:return Pg(t);default:throw Error(`Unexpected aggregation unit ${g[e]}`)}}function zg(e){switch(e.unit){case g.Tick:case g.Intraday:case g.Day:return Rg(e.unit,e.size);case g.Week:case g.Month:case g.Quarter:case g.Year:return Rg(e.unit,1);default:throw Error(`Unexpected aggregation unit ${g[e.unit]}`)}}function Bg(e,t){return t.getFullYear()-1-(t.getFullYear()-1)%e}function Vg(e){return Bg(10,e)}function Hg(e){return Bg(100,e)}function Ug(e,t){return Vg(e)===Vg(t)}function Wg(e,t){return Hg(e)===Vg(t)}function Gg(e){return new Date(e*z.OPTIONS_DATA_INCREMENT+z.OPTIONS_DATA_BASE)}function Kg(e){return(e.valueOf()-z.OPTIONS_DATA_BASE)/z.OPTIONS_DATA_INCREMENT}function qg(e,t=z.ZERO_DATE){let n=/* @__PURE__ */ new Date(`${e}T00:00:00`);return zn(n)?n:t}function Jg(e,t=z.ZERO_DATE){let n=new Date(e.replace(` `,`T`));return zn(n)?n:t}function Yg(e){return e.size-1}var Xg=class{container;supportsChunks=!0;retryCountForChunk=1;constructor(){this.container=null}get base(){return this.container}ready(){return Promise.resolve()}processRetrieved(){}getFirstDate(e){return this.base.getTimeData()[0]}getLastDate(){return this.base.getLastDataPoint(W.DateTime)}prepend(e){this.base.prepend(e),this.processRetrieved()}append(e){this.base.append(e),this.processRetrieved()}},Zg=class extends Xg{constructor(e){super(),this.container=e,this.retryCountForChunk=z.FETCH_TICK_CHUNK_RETRY_COUNT}getFirstDate(e){let t=super.getFirstDate(0);return e>0&&e<this.retryCountForChunk?Xn(vi(t,e)):t}process(e){let t=this.container,n=t.size>0?t.getLastDataPoint(W.Last):null,r=t.getLastDataPoint(W.DateTime),i=e.time;return r!==void 0&&i<=r&&(i=_n(r,1)),t.addDataPoint(W.DateTime,i),t.addDataPoint(W.Last,e.tradePrice),t.addDataPoint(W.TradeSize,e.tradeSize),t.addDataPoint(W.Change,N(n)?e.tradePrice-n:null),t.hasField(W.TradingDay)&&t.addDataPoint(W.TradingDay,e.tradingDay),{isUpdate:!1,time:i.getTime(),index:Yg(t)}}},Qg=class extends Xg{agg;durationAdd;constructor(e,t){super(),this.agg=t,this.container=e,this.durationAdd=zg(t)}isSameBar(e,t){switch(this.agg.unit){case g.Tick:case g.Intraday:case g.Day:return li(t,this.durationAdd(e));case g.Week:return pi(e,t);case g.Month:return hi(e,t);case g.Quarter:return gi(e,t);case g.Year:return _i(e,t);default:throw Error(`Unexpected aggregation unit ${g[this.agg.unit]}`)}}fixupTimeBasedAggregationTimestamp(e){return e}isCorrection(e,t){let n=li(t,e);return n&&F(`Currently not handling data corrections (updates of the past historical data)`,`error`),n}computeNextStamp(e,t){if(this.isCorrection(e,t))return null;let n=e;for(;!this.isSameBar(n,t);)n=this.durationAdd(n);return n}isUpdate(e,t,n,r){return ui(n,e)}getPosition(e){if(this.container.size===0){let t=this.fixupTimeBasedAggregationTimestamp(e.time);return{lastTimestamp:null,newTimestamp:t,nextTimestamp:t,isUpdate:!1}}let t=this.container.getLastDataPoint(W.DateTime),n=e.time,r=this.computeNextStamp(t,n);if(r===null)return null;let i=this.isUpdate(t,n,r,e);return i===null?null:{lastTimestamp:t,newTimestamp:n,nextTimestamp:r,isUpdate:i}}createBar(e,t,n,r,i,a,o){let s=this.container,c=s.size>0?s.getLastDataPoint(W.Close):null;s.addDataPoint(W.DateTime,a),s.addDataPoint(W.Open,e),s.addDataPoint(W.High,t),s.addDataPoint(W.Low,n),s.addDataPoint(W.Close,r),s.addDataPoint(W.Change,N(c)?r-c:null),s.addDataPoint(W.Volume,i),s.hasField(W.OpenInterest)&&s.addDataPoint(W.OpenInterest,null),s.hasField(W.TradingDay)&&s.addDataPoint(W.TradingDay,o??null)}addBar(e,t){let{nextTimestamp:n}=t,{tradePrice:r,tradingDay:i}=e;return this.createBar(r,r,r,r,e.tradeSize,n,i),{isUpdate:!1,time:n.getTime(),index:Yg(this.container)}}updateLastBar(e,t,n,r){let i=this.container,a=e=>i.getLastDataPoint(e);if(N(e)&&e>a(W.High)&&i.setLastDataPoint(W.High,e),N(t)&&t<a(W.Low)&&i.setLastDataPoint(W.Low,t),N(n)){i.setLastDataPoint(W.Close,n);let e=i.getData(W.Close)[i.size-2];i.setLastDataPoint(W.Change,n-e)}if(N(r)){let e=i.getLastDataPoint(W.Volume)+r;i.setLastDataPoint(W.Volume,e)}}changeLastBar(e,t){let{lastTimestamp:n}=t;if(n==null)return null;let r=e.tradePrice;return this.updateLastBar(r,r,r,e.tradeSize),{isUpdate:!0,time:n.getTime(),index:Yg(this.container)}}process(e){let t=this.getPosition(e);if(t===null)return null;let n=Fg(z.DEBUG_TIME_FORMAT);return t.isUpdate?(e.symbol===z.DEBUG_SYMBOL&&F(`Adding ${this.agg.describe()} Bar\nBars %cnot same %c${n(t.lastTimestamp)} < ${n(t.newTimestamp)} %cnext is %c${n(t.nextTimestamp)}`,`log`,`color:#f00`,`color:#f96`,``,`color:#fff`),this.changeLastBar(e,t)):N(e.tradePrice)?(e.symbol===z.DEBUG_SYMBOL&&F(`Updating ${this.agg.describe()} Bar\nBars %csame %c${n(t.lastTimestamp)} == ${n(t.newTimestamp)}`,`log`,`color:#0f0`,`color:#f96`),this.addBar(e,t)):null}alignToQuote(e){if(N(e.lastPrice,e.time))return this.updateLastBar(e.highPrice,e.lowPrice,e.lastPrice,void 0),{isUpdate:!0,time:e.time.getTime(),index:Yg(this.container)}}},$g=class extends Qg{innerBuilder;constructor(e,t,n){super(t,n),this.innerBuilder=e,this.processRetrieved()}get base(){return this.innerBuilder.container}fixupTimeBasedAggregationTimestamp(e){return vi(e,Un(e,z.START_OF_LAST_CENTURY)%this.agg.size)}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.base.getData(W.DateTime)[e],tradeSize:0,tradePrice:0,tradingDay:0};[W.Open,W.High,W.Low].forEach(n=>{t.tradePrice=this.base.getData(n)[e],super.process(t)}),t.tradePrice=this.base.getData(W.Close)[e],t.tradeSize=this.base.getData(W.Volume)[e],super.process(t)}}process(e){return this.innerBuilder.process(e),super.process(e)}},e_=class{fields;storage={};constructor(e){this.fields=e,this.clear()}clear(){this.storage={},this.fields.forEach(e=>{this.storage[e.id]=[]})}fixupTransition(e,t){if(e!==W.Change||!this.hasField(W.Close)||t<1)return;let n=this.storage[e.id],r=this.storage[W.Close.id];n[t]=r[t]-r[t-1]}concat(e,t,n){this.storage[e.id]=t.concat(n),this.fixupTransition(e,t.length)}prependData(e,t){this.checkField(e),this.concat(e,t,this.getData(e))}prepend(e){let t=e.getLastDataPoint(W.DateTime),n=this.getTimeData()[0],r=N(t)&&N(n)&&t.getTime()===n.getTime(),i=e.size;e.fields.forEach(t=>{r&&e.getData(t).splice(i-1,1),this.prependData(t,e.getData(t))})}appendData(e,t){this.checkField(e),this.concat(e,this.getData(e),t)}append(e){let t=e.getTimeData()[0],n=this.getLastDataPoint(W.DateTime),r=N(t)&&N(n)&&t.getTime()===n.getTime(),i=this.size;return e.fields.forEach(t=>{r&&this.getData(t).splice(i-1,1),this.appendData(t,e.getData(t))}),e.size-+!!r}getTimeData(){return this.getData(W.DateTime)}getData(e){return this.storage[e.id]}setData(e,t){this.checkField(e),this.storage[e.id]=t}hasField(e){return this.fields.findIndex(t=>t.id===e.id)!==-1}get size(){return this.fields.length===0?0:this.getData(this.fields[0]).length}get isEmpty(){return this.size===0}checkField(e){if(!this.hasField(e))throw Error(`This container does not store values for field ${e.id}`)}addDataPoint(e,t){this.checkField(e),this.getData(e).push(t)}getLastDataPoint(e){return this.checkField(e),Ce(this.getData(e))}setLastDataPoint(e,t){this.checkField(e);let n=this.getData(e);n[n.length-1]=t}keepOnlyLast(e){if(this.size<=e)return;let t=this.size-e;this.fields.forEach(e=>this.getData(e).splice(0,t))}},t_=class extends e_{constructor(){super([])}get size(){return 0}},n_=class extends e_{wrapper;constructor(e,t){super(e),this.wrapper=t}isWrapped(e){return rt(this.wrapper,e.id)}hasField(e){return this.isWrapped(e)||super.hasField(e)}getData(e){return this.isWrapped(e)?this.wrapper[e.id]():super.getData(e)}},r_=z.RENKO_KAGI_NAMES;function i_(e){let{Method:t,Period:n,Source:r,BrickSize:i}=ft(e);return{method:tt(t,[r_.ATR,r_.TRD,r_.PCT],r_.ATR),period:Number.isFinite(n)?n:14,source:tt(r,[r_.CLS,r_.HL],r_.CLS),brickSize:Number.isFinite(i)?i:10}}function a_(e,t,n){return e.getData(t)[n]}function o_(e,t){let[n,r]=[W.High,W.Low].map(n=>a_(e,n,t)),i=a_(e,W.Close,t-1);return Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}function s_(e,t){let n=Math.ceil(t);if(!Number.isFinite(n)||n<1||e.size<n)return null;let r=n-1,i=[];i.push(a_(e,W.High,0)-a_(e,W.Low,0));for(let t=1;t<n;++t)i.push(o_(e,t));let a=he(i);for(let t=n;t<e.size;++t){let i=o_(e,t);a=(a*r+i)/n}return a}var c_=e=>W[e],l_=[`DateTime`,`Open`,`High`,`Low`,`Close`,`Volume`].map(c_),u_=l_.concat([`Change`,`Projection`,`BarIndex`].map(c_)),d_=class extends Xg{innerBuilder;inputs;brickSize;lastFinalBrick;projectionCount;refPrices;constructor(e,t){super(),this.supportsChunks=!1,this.innerBuilder=e,this.inputs=P(t.inputs),this.brickSize=null,this.container=new e_(u_),this.processRetrieved()}get base(){return this.innerBuilder.container}baseVal(e,t){return this.base.getData(e)[t]}isLastBase(e){return e===this.base.size-1}getValuesAt(e,t){let[n,r,i,a,o,s]=l_.map(n=>t.getData(n)[e]);return{date:n,open:r,high:i,low:a,close:o,volume:s}}getBrickAt(e){return this.getValuesAt(e,this.container)}getBarAt(e){return this.getValuesAt(e,this.base)}getBricksCount(e){return Math.floor(e/this.brickSize)}getMove(e,t,n){let[r,i]=this.refPrices(t.close,t.high,t.low),a=r-e.high,o=e.low-i;return{climbing:(n&&a>0||a>=this.brickSize)&&a>=o,falling:(n&&o>0||o>=this.brickSize)&&o>a,moveUp:a,moveDown:o}}initFirstBrick(e,t){e.open=e.high=e.low=e.close=Math.max(this.brickSize,Ze(t.close-t.close%this.brickSize,4)),e.date=t.date,e.volume=e.change=0}findSafeStartIndex(){let e=0,t=this.base.size-1,n=2*z.RENKO_MAX_BARS;for(;t>0&&e<n;){let n=o_(this.base,t);e+=Math.floor(n/this.brickSize),t--}return t}processRetrieved(){let e=i_(this.inputs),{method:t,period:n,source:r}=e;if(this.brickSize=e.brickSize,t===r_.ATR)this.brickSize=s_(this.base,n);else if(t===r_.PCT){if((this.base?.size??0)>0){let e=this.base.getLastDataPoint(W.Close);this.brickSize=e*this.brickSize/100}else this.brickSize=null}if(!N(this.brickSize))return;let i=(e,t,n)=>[t,n],a=(e,t,n)=>[e,e];this.refPrices=r===r_.HL?i:a;let o={},s=this.findSafeStartIndex();for(let e=s;e<this.base.size;e++){let t=this.getBarAt(e);if(e===s){this.initFirstBrick(o,t);continue}let n=this.isLastBase(e),{climbing:r,falling:i,moveUp:a,moveDown:c}=this.getMove(o,t,n);if(!r&&!i){o.volume+=t.volume;continue}o.proj=Number(n),o.barIndex=e;let l=t.date.getTime();if(r){let e=this.getBricksCount(a);for(let t=0;t<e;++t)this.constructClimbing(o,l,t,this.brickSize);n&&(this.constructClimbing(o,l,e,a%this.brickSize),this.projectionCount=e+1)}else if(i){let e=this.getBricksCount(c);for(let t=0;t<e;++t)this.constructFalling(o,l,t,this.brickSize);n&&(this.constructFalling(o,l,e,c%this.brickSize),this.projectionCount=e+1)}n||(this.lastFinalBrick=this.container.size-1,o.volume=0)}this.container.keepOnlyLast(z.RENKO_MAX_BARS)}constructClimbing(e,t,n,r,i=!0){let a=e.high,o=e.close;e.open=e.low=a,e.high=e.close=a+r,e.date=new Date(t+n),e.change=e.close-o,i?this.addToContainer(e):this.updateLastDataPoint(e)}constructFalling(e,t,n,r,i=!0){let a=e.low,o=e.close;e.open=e.high=a,e.low=e.close=a-r,e.date=new Date(t+n),e.change=e.close-o,i?this.addToContainer(e):this.updateLastDataPoint(e)}process(e){let t=this.innerBuilder.process(e);return this.processUpdate(t)}alignToQuote(e){let t=this.innerBuilder.alignToQuote(e);return this.processUpdate(t)}rebuild(){return this.container.clear(),this.processRetrieved(),{isUpdate:!1,time:0,index:-1}}processUpdate(e){if(!Number.isFinite(this.lastFinalBrick))return null;let t=this.base.size-1,n=this.getBarAt(t),r=this.getBrickAt(this.lastFinalBrick),{climbing:i,falling:a,moveUp:o,moveDown:s}=this.getMove(r,n,!0),c=this.container.getLastDataPoint(W.Projection)===1;if(!i&&!a)return c?this.rebuild():null;let l=i?o:s,u=this.getBricksCount(l)+1;if(c&&this.projectionCount===u){let e=this.getBrickAt(this.container.size-1),r=this.getBrickAt(Math.min(this.container.size-2,0));return e.proj=1,e.barIndex=t,e.open===e.high?e.low=e.close=n.close:e.open===e.low&&(e.high=e.close=n.close),e.change=e.close-r.close,this.updateLastDataPoint(e),{isUpdate:!0,time:e.date.getTime(),index:this.container.size-1}}return this.rebuild()}addToContainer(e){let t=this.container;t.addDataPoint(W.DateTime,e.date),t.addDataPoint(W.Open,e.open),t.addDataPoint(W.Close,e.close),t.addDataPoint(W.High,e.high),t.addDataPoint(W.Low,e.low),t.addDataPoint(W.Change,e.change),t.addDataPoint(W.Volume,e.volume),t.addDataPoint(W.Projection,e.proj),t.addDataPoint(W.BarIndex,e.barIndex)}updateLastDataPoint(e){let t=this.container;t.setLastDataPoint(W.DateTime,e.date),t.setLastDataPoint(W.Open,e.open),t.setLastDataPoint(W.Close,e.close),t.setLastDataPoint(W.High,e.high),t.setLastDataPoint(W.Low,e.low),t.setLastDataPoint(W.Change,e.change),t.setLastDataPoint(W.Volume,e.volume),t.setLastDataPoint(W.Projection,e.proj),t.setLastDataPoint(W.BarIndex,e.barIndex)}},f_=[W.DateTime,W.TradingDay,W.Last,W.TradeSize,W.Change],p_=[W.DateTime,W.Open,W.High,W.Low,W.Close,W.Volume,W.Change],m_=[...p_,W.OpenInterest],h_=[...m_,W.Symbol],g_=[W.Open,W.High,W.Low,W.Close,W.Change];function __(e,t){let n=Gi(e);if(t.isTick)return f_;{let e=p_;return t.isMultiContract?e=h_:(n||t.isEndOfDay)&&(e=m_),t.isIntraday?[...e,W.TradingDay]:e}}var v_=class{useLastTrade;symbol;aggregation;offset;container;previousTime;timeZone;isFuture;needsResolution;hasOpenInterest;padded;constructor(e,t,n=0,r=!1,i=!1){this.useLastTrade=i,this.symbol=e,this.aggregation=t,this.offset=n||0,this.previousTime=/* @__PURE__ */ new Date(0),this.timeZone=this.getTimeZone(),this.isFuture=ki(e),this.padded=r,this.needsResolution=Wi(e),this.hasOpenInterest=Gi(e)}makeContainer(){return new e_(__(this.symbol,this.aggregation))}parse(e){this.container=this.makeContainer();let t=e.split(`
|
|
19
|
-
`),n=this.getParseFunc();if(n!==null){let e=n.bind(this);t.forEach(t=>{let n=t.trim();if(n){let t=n.split(`,`);e(t)}})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){let t=e.length-5;(t===0||t===1)&&(this.container.addDataPoint(W.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(W.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(W.Last,parseFloat(e[3+t])),this.container.addDataPoint(W.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(W.Change,this.calculateChange(W.Last)))}nullify(e){return e==null||e===0?null:e}parseMinutes(e){let t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,n=+!!t;e.length===7+n&&(this.container.hasField(W.Symbol)&&this.container.addDataPoint(W.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(W.DateTime,this.parseDate(e[0+n])),this.container.addDataPoint(W.TradingDay,parseInt(e[1+n])),this.container.addDataPoint(W.Open,parseFloat(e[2+n])),this.container.addDataPoint(W.High,parseFloat(e[3+n])),this.container.addDataPoint(W.Low,parseFloat(e[4+n])),this.container.addDataPoint(W.Close,parseFloat(e[5+n])),this.container.addDataPoint(W.Volume,this.nullify(parseInt(e[6+n]))),this.container.addDataPoint(W.Change,this.calculateChange()))}parseFloatOrNull(e){let t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){let t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){let t=this.aggregation.isMultiContract,n=+!!this.useLastTrade,r=7+n+ +!!this.hasOpenInterest;if(e.length!==r)return;t&&this.container.addDataPoint(W.Symbol,e[0]),this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(W.High,parseFloat(e[3])),this.container.addDataPoint(W.Low,parseFloat(e[4]));let i=this.useLastTrade&&e[5]!==``?e[5]:e[5+n];this.container.addDataPoint(W.Close,parseFloat(i)),this.container.addDataPoint(W.Volume,this.nullify(this.parseIntOrNull(e[6+n]))),this.hasOpenInterest&&this.container.addDataPoint(W.OpenInterest,this.nullify(this.parseIntOrNull(e[7+n]))),this.container.addDataPoint(W.Change,this.calculateChange())}calculateChange(e=W.Close){let t=this.container.size;if(t>1){let n=this.container.getData(e);return n[t-1]-n[t-2]}return 0}parseTimestamp(e){switch(this.aggregation.unit){case g.Tick:case g.Intraday:return Jg(e);default:return qg(e)}}parseDate(e){let t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?An(t,this.offset):(this.previousTime=ci(t,this.previousTime)?t:_n(this.previousTime,1),this.previousTime)}getTimeZone(){return Ki(this.symbol)}},y_=class extends v_{makeContainer(){return new e_([W.DateTime,W.TradingDay,W.Symbol,W.Bid,W.BidSize,W.Ask,W.AskSize])}getParseFunc(){return this.parseTopOfBook}getTopOfBookPayload(e){if(e.length<7)return null;let t=e[0],n=t===`Q`||t===`T`;if(n&&t!==`Q`)return null;let r=+!!n,i=7+r;if(e.length!==i&&e.length!==i+1)return null;let a=e.length===i+1,o=r+ +!!a,s=o+1,c=o+3,l=o+4,u=o+5,d=o+6;return{symbol:a?e[o-1]:this.symbol,timestamp:e[o],tradingDay:parseInt(e[s]),bid:parseFloat(e[c]),bidSize:parseInt(e[l]),ask:parseFloat(e[u]),askSize:parseInt(e[d])}}parseTopOfBook(e){let t=this.getTopOfBookPayload(e);t!==null&&(this.container.addDataPoint(W.DateTime,this.parseDate(t.timestamp)),this.container.addDataPoint(W.TradingDay,t.tradingDay),this.container.addDataPoint(W.Symbol,t.symbol),this.container.addDataPoint(W.Bid,t.bid),this.container.addDataPoint(W.BidSize,t.bidSize),this.container.addDataPoint(W.Ask,t.ask),this.container.addDataPoint(W.AskSize,t.askSize))}},{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:b_,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:x_}=z,S_=[_.PerCount,_.PerVolume,_.PerSeconds],C_=class{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case g.Tick:return z.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case g.Intraday:return t&&e.spec===_.Nearest?b_:x_;case g.Day:case g.Week:case g.Month:case g.Quarter:case g.Year:return z.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return``}}addExtraParams(e){}makeUrl(e){let t={},n=co(e.symbol);t.symbol=n;let r=e.aggregation,i=this.getDataParam(r);i.length>0&&(t.data=i),r.size>1&&r.unit===g.Intraday&&(t.interval=(r.spec===_.PerRange?1:r.size).toString());let[a,o]=e.range,s=a!==null,c=o!==null;if(s&&(t.start=this.toHistoricalFeedDate(a,r)),!s||e.alwaysUseBarsToFetch){let n=e.barsToFetch||z.DEFAULT_MAX_RECORDS;r.unit===g.Tick&&S_.includes(r.spec)&&(n*=z.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=n.toString()}c&&(t.end=this.toHistoricalFeedDate(o,r)),t.volume=r.isContractVolume?`contract`:`total`,t.order=`asc`,t.dividends=r.dividendsAdjust.toString(),t.backadjust=r.backAdjust.toString(),t.daystoexpiration=r.daysToExpiration.toString(),t.contractroll=r.contractRoll,r.isTick&&(t.type=`T`,t.skipOldEmulation=`true`),r.isEndOfDay&&e.useLastTrade&&(t.lasttrade=`true`),e.extendedHours===!0&&(t.formt=`true`),t.splits=(e?.splits??!0).toString(),t.padded=(e.padded??!1).toString(),this.addExtraParams(t);let l=ht(t),u=ki(n);return`/${this.getPageNameFor(r,u)}?${l}`}toHistoricalFeedDate(e,t){return $r(e,t.isTick||t.isIntraday?z.FMT_HIST_FEED_PARAM_DATE_TIME:z.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t=``,n=this.getSpecPart(e);switch(e.unit){case g.Tick:case g.Intraday:break;case g.Day:t=`daily${n}`;break;case g.Week:t=`weekly${n}`;break;case g.Month:t=`monthly${n}`;break;case g.Quarter:t=`quarterly${n}`;break;case g.Year:t=`yearly${n}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===_.Continue?`continue`:`nearest`:``}getParser(e){return new v_(co(e.symbol),e.aggregation,e.offset,e.padded,e.useLastTrade)}async retrieve(e){let t=this.makeUrl(e),n=await uI(e.aggregation.unit===g.Tick?`timeseriesNew`:`timeseries`,t);return this.getParser(e).parse(n)}},w_=class extends C_{addExtraParams(e){e.type=`B`}getParser(e){return new y_(co(e.symbol),e.aggregation,e.offset)}async retrieve(e){let t=await uI(`timeseriesNew`,this.makeUrl(e));return this.getParser(e).parse(t)}},T_=class{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){let t=co(e.symbol),n=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==g.Day)return n;let r={symbol:t};this.addExtraParams(r);let i=await uI(`ondemand`,`/${this.getPageName()}.json?${ht(r)}`);try{let e=JSON.parse(i);if(e.status.code===200){let t=e.results;if(this.iterateForward)for(let e=0;e<t.length;e++)this.processRow(t[e],e,n);else for(let e=t.length-1;e>=0;e--)this.processRow(t[e],e,n);return n}}catch(e){F(`Failed parsing the JSON result from OnDemand, error is ${e.message}`)}return n}},E_={WeighImplVolHigh:`weightedImpliedVolatility`,WeighImplVolLow:`weightedImpliedVolatility`,WeighImplVol:`weightedImpliedVolatility`,WeighImplVolHigh5D:`weightedImpliedVolatilityHigh5d`,WeighImplVolLow5D:`weightedImpliedVolatilityLow5d`,WeighImplVol5D:`weightedImpliedVolatility5d`,WeighImplVolHigh1M:`weightedImpliedVolatilityHigh1m`,WeighImplVolLow1M:`weightedImpliedVolatilityLow1m`,WeighImplVol1M:`weightedImpliedVolatility1m`,WeighImplVolHigh3M:`weightedImpliedVolatilityHigh3m`,WeighImplVolLow3M:`weightedImpliedVolatilityLow3m`,WeighImplVol3M:`weightedImpliedVolatility3m`,WeighImplVolHigh6M:`weightedImpliedVolatilityHigh6m`,WeighImplVolLow6M:`weightedImpliedVolatilityLow6m`,WeighImplVol6M:`weightedImpliedVolatility6m`,WeighImplVolHigh1Y:`weightedImpliedVolatilityHigh1y`,WeighImplVolLow1Y:`weightedImpliedVolatilityLow1y`,WeighImplVol1Y:`weightedImpliedVolatility1y`,WeighImplVolHighYTD:`weightedImpliedVolatilityHighYtd`,WeighImplVolLowYTD:`weightedImpliedVolatilityLowYtd`,WeighImplVolYTD:`weightedImpliedVolatilityYtd`,WeighImplVolChg:`weightedImpliedVolatilityChange`,ImplVolRank5D:`impliedVolatilityRank5d`,ImplVolRank1M:`impliedVolatilityRank1m`,ImplVolRank3M:`impliedVolatilityRank3m`,ImplVolRank6M:`impliedVolatilityRank6m`,ImplVolRank1Y:`impliedVolatilityRank1y`,ImplVolRankYTD:`impliedVolatilityRankYtd`,ImplVolPerc5D:`impliedVolatilityPercentile5d`,ImplVolPerc1M:`impliedVolatilityPercentile1m`,ImplVolPerc3M:`impliedVolatilityPercentile3m`,ImplVolPerc6M:`impliedVolatilityPercentile6m`,ImplVolPerc1Y:`impliedVolatilityPercentile1y`,ImplVolPercYTD:`impliedVolatilityPercentileYtd`,OptTotVol:`totalVolume`,OptCallVol:`callVolume`,OptPutVol:`putVolume`,PutCallVolRatio:`putCallVolumeRatio`,TotalOpenInt:`totalOpenInterest`,CallOpenInt:`callOpenInterest`,PutOpenInt:`putOpenInterest`,PutCallOIRatio:`putCallOpenInterestRatio`,DateTime:`date`},D_=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){let t=co(e.symbol).replace(/\.bz$/i,``),n=e.fields.concat(W.DateTime),r=()=>new e_(n);if(e.aggregation.unit!==g.Day)return r();let i=await uI(`options`,`/get?${ht({symbol:t,apiKey:`default`,fields:n.map(e=>E_[e.id]).join(`,`)})}`);try{let e=JSON.parse(i).data,t=r(),a=e=>Number.parseFloat(e.replace(/,/g,``));return e.forEach(e=>{n.forEach(n=>{n===W.DateTime?t.addDataPoint(W.DateTime,qg(e.date)):t.addDataPoint(n,a(e[E_[n.id]]))})}),t}catch(e){F(`Failed parsing options JSON historical data result, error is ${e.message}`)}return r()}},O_=class extends Qg{innerBuilder;isBuildingBars;constructor(e,t,n){super(t,n),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=z.FETCH_TICK_CHUNK_RETRY_COUNT,this.processRetrieved()}get base(){return this.innerBuilder.container}getFirstDate(e){return this.innerBuilder.getFirstDate(e)}get startFromIndex(){return 0}processRetrieved(){this.container.clear(),this.isBuildingBars=!0;let[e,t,n,r]=[W.DateTime,W.TradeSize,W.Last,W.TradingDay].map(e=>this.base.getData(e));for(let i=this.startFromIndex;i<this.base.size;i++){let a={isTrade:!0,time:e[i],tradeSize:t[i],tradePrice:n[i],tradingDay:r[i]};super.process(a)}this.isBuildingBars=!1}process(e){let t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}},k_=class extends O_{constructor(e,t,n){super(e,t,n)}fixupTimeBasedAggregationTimestamp(e){return bi(e,er(e,ir(yi(e,1)))%this.agg.size)}},A_=class extends O_{series;constructor(e,t,n,r){super(e,n,r),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}},j_=new vp(`_TICK_COUNT`),M_=class extends A_{anchorTimestamp=null;constructor(e,t,n,r){super(e,t,n,r)}get startFromIndex(){let e=0,t=this.base.getTimeData();if(N(this.anchorTimestamp))e=Te(t,e=>e===this.anchorTimestamp);else{let n=this.base.size;if(n>2)for(let r=n-2;r>2;--r){let n=t[r].valueOf();if(n-t[r-1].valueOf()>1&&t[r+1].valueOf()-n>1){e=r;break}}this.anchorTimestamp=t[e]}return e>this.agg.size&&(e%=this.agg.size),Math.max(e,0)}addBar(e,t){let n=super.addBar(e,t);return this.container.addDataPoint(j_,1),n}changeLastBar(e,t){let n=super.changeLastBar(e,t),r=this.container.getLastDataPoint(j_);return this.container.setLastDataPoint(j_,r+1),n}isUpdate(e,t,n,r){return this.container.getLastDataPoint(j_)<this.agg.size}},N_=new vp(`_VOLUME_TALLY`),P_=class extends A_{constructor(e,t,n,r){super(e,t,n,r)}addBar(e,t){let n=this.container,r=(n.getLastDataPoint(N_)||0)+e.tradeSize,i=Math.floor(r/this.agg.size),a=r%this.agg.size,o=r<this.agg.size;n.size>0&&(n.setLastDataPoint(W.Volume,o?1:i),n.setLastDataPoint(N_,r));let s=super.addBar(e,t);return n.setLastDataPoint(W.Volume,1),n.addDataPoint(N_,o?0:a),s}changeLastBar(e,t){let n=this.container,r=super.changeLastBar(e,t);n.setLastDataPoint(W.Volume,1);let i=n.getLastDataPoint(N_)??0;return n.setLastDataPoint(N_,i+e.tradeSize),r}isUpdate(e,t,n,r){if(!Ln(e,t))return!1;let i=this.container.getLastDataPoint(N_)??0;return r.tradeSize+i<this.agg.size}},F_=class extends Qg{innerBuilder;metadata;range;step;constructor(e,t,n,r){super(t,n),this.innerBuilder=e,this.range=n.size,this.step=1;let i=$().getMetaDataSource();this.metadata=i.getMetaData(r)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return ma.call(this,async()=>{let e=await this.metadata.ready();return e&&(this.step=this.metadata.minMovement,this.processRetrieved()),e})}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){let t=this.base.getData(W.Volume)[e],n=this.useHighOrLow(e);if(!N(n)){this.updateLastBar(void 0,void 0,void 0,t);continue}let r={isTrade:!0,time:this.base.getData(W.DateTime)[e],tradeSize:t,tradePrice:n,tradingDay:0};super.process(r)}}useHighOrLow(e){let t=this.base.getData(W.Close)[e];if(this.container.size==0)return t;let n=this.container.getLastDataPoint(W.High),r=this.container.getLastDataPoint(W.Low),i=this.base.getData(W.High)[e],a=this.base.getData(W.Low)[e],o=i>n,s=a<r;if(o&&s)return i-t<t-a?i:a;if(o)return i;if(s)return a}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}isUpdate(e,t,n,r){return!0}process(e){return this.innerBuilder.process(e),super.process(e)}changeLastBar(e,t){let n=e.tradePrice,r=this.container.getLastDataPoint(W.Low)+this.priceRange;if(n>r)return this.changeAndAddBar(r,e,t);let i=this.container.getLastDataPoint(W.High)-this.priceRange;return n<i?this.changeAndAddBar(i,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,n){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(W.Projection,0),this.addBar(t,n)}addBar(e,t){return this.container.addDataPoint(W.Projection,1),super.addBar(e,t)}},I_=[W.Open,W.High,W.Low,W.Close],L_=[W.BARCOLIX,W.High,W.Low],R_=z.RENKO_KAGI_NAMES;function z_(e){let{BoxSizeMethod:t,Period:n,ReversalAmount:r}=ft(e);return{method:tt(t,[R_.ATR,R_.TRD],R_.ATR),period:Number.isFinite(n)?n:14,reversal:Number.isFinite(r)?r:30}}var B_=class extends Qg{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,n){super(t,n.aggregation),this.innerBuilder=e,this.inputs=P(n.inputs),this.reversal=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,n){return e.getData(t)[n]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}addBar(e,t){if(super.addBar(e,t),this.container.addDataPoint(W.BARCOLIX,null),this.container.size>1){let e=this.dataAt(W.Close,this.container.size-2);this.setLast(W.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,n,r){let i=r.tradePrice,a=e=>e>=0,o=i-this.getLast(W.Close),s=a(o),c=Math.abs(o)>=this.reversal,[l,u,d,f]=I_.map(e=>this.getLast(e)),p=f-l,m=a(p)!==s||p===0;return m&&!c||!m&&(s?i<u:i>d)?null:Math.abs(p)<this.reversal||!m||!c}computeBarColor(){let e=e=>this.dataAt(W.Close,e)>this.dataAt(W.Open,e),t=this.container.size;if(t>1){let n=e(t-1),[r,i,a]=L_.map(e=>this.dataAt(e,t-2)),[,o,s]=L_.map(e=>this.dataAt(e,t-1)),c=r;r===0&&n&&o>i?c=1:r===1&&!n&&s<a&&(c=0),this.setLast(W.BARCOLIX,c)}else this.setLast(W.BARCOLIX,+!!e(0))}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);let t=super.process(e);return this.computeBarColor(),t}processRetrieved(){let{method:e,period:t,reversal:n}=z_(this.inputs);if(this.reversal=n,e===R_.ATR&&(this.reversal=s_(this.base,t)),N(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(W.DateTime,e),tradePrice:this.baseAt(W.Close,e),tradeSize:this.baseAt(W.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}};function V_(e){let{LineCount:t}=ft(e);return{lineBreak:Number.isFinite(t)?t:3}}var H_=class extends Qg{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,n,r){super(t,n),this.innerBuilder=e,this.inputs=P(r.inputs);let i=V_(this.inputs);this.lineBreak=i.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(W.DateTime)[e],tradeSize:this.base.getData(W.Volume)[e],tradePrice:this.base.getData(W.Close)[e],tradingDay:0}}processRetrieved(){if(this.container.clear(),!(this.base.size<2)){this.startLine(this.readTrade(1));for(let e=1;e<this.base.size-1;e++){let t=this.readTrade(e);this.insertBar(t,t.time)}super.process(this.readTrade(this.base.size-1))}}process(e){return this.innerBuilder.process(e),super.process(e)}updateLastBar(e,t,n,r){let i=this.findOpen(n,0,1);this.currentVolume+=r,i===null?this.resetProjection():(super.updateLastBar(void 0,void 0,n,void 0),this.container.setLastDataPoint(W.Open,i),this.container.setLastDataPoint(W.Low,Math.min(i,n)),this.container.setLastDataPoint(W.High,Math.max(i,n)))}resetProjection(){let e=this.container;e.setLastDataPoint(W.High,null),e.setLastDataPoint(W.Low,null),e.setLastDataPoint(W.Open,null),e.setLastDataPoint(W.Close,null),e.setLastDataPoint(W.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(W.DateTime,t.nextTimestamp);let n=this.changeLastBar(e,t);return n.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},n}addBar(e,t){let n=this.container,{nextTimestamp:r}=t;if(n.getLastDataPoint(W.Projection)===1){let r=n.getLastDataPoint(W.Close);if(this.findOpen(r,this.lineBreak,1)!==null)n.setLastDataPoint(W.Projection,0),n.setLastDataPoint(W.Volume,this.currentVolume),this.currentVolume=0;else return this.updateProjection(e,t)}return(this.isProjection(r)||!this.insertBar(e,r))&&!this.addProjection(e,r)?null:{isUpdate:!1,time:r.getTime(),index:this.container.size-1}}insertBar(e,t){this.currentVolume+=e.tradeSize;let n=e.tradePrice,r=this.findOpen(n,this.lineBreak);return r!==null&&(this.createBar(r,Math.max(r,n),Math.min(r,n),n,this.currentVolume,t),this.container.addDataPoint(W.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;let n=e.tradePrice,r=this.findOpen(n,0);return r!==null&&(this.createBar(r,Math.max(r,n),Math.min(r,n),n,0,t),this.container.addDataPoint(W.Projection,1),!0)}findOpen(e,t,n=0){if(!N(e))return null;let r=this.container,i=r.size-1-n,a=r.getData(W.Close)[i],o=r.getData(W.Open)[i];if(a>o){if(e<=a){if(e>=o)return null;for(let n=0;n<Math.min(r.size,t);n++)if(e>=r.getData(W.Low)[i-n])return null;return o}return a}if(e>=a){if(e<=o)return null;for(let n=0;n<Math.min(r.size,t);n++)if(e<=r.getData(W.High)[i-n])return null;return o}return a}startLine(e){this.container.addDataPoint(W.Projection,0);let t=this.readTrade(0);this.createBar(t.tradePrice,Math.max(t.tradePrice,e.tradePrice),Math.min(t.tradePrice,e.tradePrice),e.tradePrice,e.tradeSize+t.tradeSize,e.time)}},U_=z.RENKO_KAGI_NAMES,W_={Positive:1,Negative:2,Both:3};function G_(e){switch(e){case z.BARKIND_OX:case z.BARKIND_XO:return!0;default:return!1}}function K_(e){switch(e){case z.BARKIND_O:case z.BARKIND_XO:return!0;default:return!1}}function q_(e){switch(e){case z.BARKIND_X:case z.BARKIND_OX:return!0;default:return!1}}function J_(e){let t=ft(e),{Source:n,BoxSizeMethod:r,Period:i}=t,{ReversalAmount:a,BoxSize:o,OneStepBack:s}=t,c=tt(n,[U_.CLS,U_.HL],U_.CLS),l=tt(r,[U_.ATR,U_.TRD],U_.ATR),u=Number.isFinite(i)?i:14,d=Number.isFinite(a)?a:3;return{method:l,period:u,source:c,boxSize:Number.isFinite(o)?o:20,reversal:d,oneStepBack:s===`Yes`}}var Y_=class extends Qg{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,n){super(t,n.aggregation),this.innerBuilder=e,this.inputs=P(n.inputs),this.boxSize=this.reversal=this.source=this.firstTrend=this.oneStepBack=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,n){return e.getData(t)[n]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}roundToBox(e){return e-e%this.boxSize}roundedDiff(e,t,n){let r=Math.abs(t-e);return e+n*this.roundToBox(r)}get closeBased(){return this.source===U_.CLS}get currentKind(){return this.getLast(W.BARKIND)}getTrendField(e){return this.closeBased?W.Close:e?W.Low:W.High}getTrendPrice(e,t){if(this.closeBased)return e.tradePrice;let n=e;return t?n._lowPrice:n._highPrice}changeLastBar(e,t){let n=K_(this.currentKind),r=n?-1:1,i=this.getLast(this.getTrendField(n)),a=this.getTrendPrice(e,n);return e.tradePrice=this.roundedDiff(i,a,r),super.changeLastBar(e,t),null}addBar(e,t){let n=this.container.size===0,r=K_(this.currentKind),i=r?1:-1,a=n?null:this.getLast(W.Close),o=this.getTrendPrice(e,!r);if(e.tradePrice=(n?this.roundToBox(this.baseAt(W.Open,0)):a)+i*(n?0:this.boxSize),super.addBar(e,t),!n){let e=this.roundedDiff(a,o,i);this.updateLastBar(e,e,e)}return this.container.addDataPoint(W.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){let e=K_(this.currentKind)?z.BARKIND_OX:z.BARKIND_XO;this.setLast(W.BARKIND,e)}canInplaceReverse(){return!G_(this.currentKind)&&this.getLast(W.High)===this.getLast(W.Low)}isUpdate(e,t,n,r){let i=K_(this.currentKind),a=this.getTrendPrice(r,i),o=this.getTrendPrice(r,!i),s=e=>e>=0,c=a-this.getLast(W.Close),l=s(c),u=Math.abs(c)>=this.boxSize,d=o-this.getLast(W.Close),f=s(d),p=Math.abs(d)>=this.reversal*this.boxSize;return i?!l&&u?!0:f&&p?!this.oneStepBack||!this.canInplaceReverse()?!1:(this.inplaceReverse(),!0):null:l&&u?!0:!f&&p?!this.oneStepBack||!this.canInplaceReverse()?!1:(this.inplaceReverse(),!0):null}findFirstDiffLargerThanBox(e,t){let n=this.baseAt(W.Open,0),r=this.innerBuilder.container.size;for(let i=1;i<r;++i){let r=this.baseAt(e,i)-n;if(Math.abs(r)>this.boxSize){if(t===W_.Positive&&r>0)return[i,z.BARKIND_X];if(t===W_.Negative&&r<0)return[i,z.BARKIND_O];if(t===W_.Both)return[i,r>0?z.BARKIND_X:z.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){let[,e]=this.findFirstDiffLargerThanBox(W.Close,W_.Both);return e}{let[e,t]=this.findFirstDiffLargerThanBox(W.High,W_.Positive),[n,r]=this.findFirstDiffLargerThanBox(W.Low,W_.Negative);return t===null&&r===null?null:r===null?t:t===null?r:e<n?t:r}}computeBarColor(){let e=this.container.size,t=this.firstTrend;e>1&&(t=K_(this.dataAt(W.BARKIND,e-2))?z.BARKIND_X:z.BARKIND_O),this.setLast(W.BARKIND,t)}process(e){return this.isProcessingRetrieved||this.innerBuilder.process(e),this.firstTrend===null?null:super.process(e)}processRetrieved(){let{method:e,period:t,reversal:n,source:r,boxSize:i,oneStepBack:a}=J_(this.inputs);if(this.reversal=n,this.source=r,this.boxSize=e===U_.ATR?s_(this.base,t):i,N(this.reversal,this.boxSize)&&(this.oneStepBack=a&&this.reversal===1,this.container.clear(),this.firstTrend=this.findFirstBarTrend(),this.firstTrend!==null)){this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(W.DateTime,e),tradePrice:this.baseAt(W.Close,e),_highPrice:this.baseAt(W.High,e),_lowPrice:this.baseAt(W.Low,e),tradeSize:this.baseAt(W.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}},X_=new yd(g.Intraday,0),Z_=class extends Zg{constructor(e){super(e)}process(e){return{isUpdate:!1,time:0,index:-1}}},Q_=class{query;container;canLoadMoreData=!0;alignToQuote=!1;isCached;record;isLoading=!1;serverComputedSeries;builder;retriever;streamingSubscription;records;constructor(e){this.query=e,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new Dp(e.symbol)}get isTotalVolumeMode(){let e=this.query.symbol,t=this.query.aggregation;return ki(e)&&!t.isContractVolume&&t.isEndOfDay}getHasVisible(e){return this.query.visibleRange!=null&&this.query.visibleRange[e]!=null}get hasVisibleFrom(){return this.getHasVisible(`from`)}get hasVisibleTo(){return this.getHasVisible(`to`)}get hasHistoricalData(){return this.hasData&&!this.container.isEmpty}refresh(){yg(`ts:refresh`,{symbol:this.query.symbol??null,hasData:this.hasData,hasHistoricalData:this.hasHistoricalData,isCached:this.isCached??!1}),this.hasHistoricalData?this.query.aggregation.isEndOfDay?this.alignToQuote=!0:this.loadMoreData(!1):(ha.call(this),this.ready().then(e=>{yg(`ts:refresh:result`,{symbol:this.query.symbol??null,hasData:e,containerSize:this.container?.size??null}),e&&Ke(G.TS_MANYCHANGED,{series:this,part:ie.Unspecified})}))}makeInnerBuilder(e){let t=this.query.aggregation;if(t.isTick)switch(t.spec){case _.None:case _.PerSeconds:case _.PerCount:case _.PerVolume:return new Zg(e);default:throw Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}else return new Qg(e,t)}makeBuilder(e){let t=this.makeInnerBuilder(e),n=this.query.aggregation,r=(e,t=[])=>new e_(__(this.query.symbol,e).concat(t)),i=t;switch(this.query.curveStyle){case h.Renko:return new d_(i,this.query);case h.Kagi:return new B_(i,r(X_,[W.BARCOLIX]),this.query);case h.PointAndFigure:return new Y_(i,r(X_,[W.BARKIND]),this.query);case h.LineBreak:return new H_(i,r(n,[W.Projection]),n,this.query)}if(n.isIntraday&&n.spec===_.PerRange)return new F_(i,r(X_,[W.Projection]),n,this.query.symbol);let a=t;if(n.isTick)switch(n.spec){case _.PerSeconds:return new k_(a,r(X_),n);case _.PerCount:{let e=r(X_,[j_]);return new M_(a,this,e,n)}case _.PerVolume:{let e=r(X_,[N_]);return new P_(a,this,e,n)}}return n.unit===g.Day&&n.size>1?new $g(i,r(n),n):t}onStreamingUpdates(e){this.isLoading||e.map(e=>{if(`isTrade`in e)return this.builder.process(e);if(`isQuote`in e&&(Ke(G.TS_QUOTEMARKER,{series:this}),this.alignToQuote&&this.query.aggregation.isEndOfDay&&this.query.useLastTrade&&(this.alignToQuote=!1),this.alignToQuote)){let t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>N(e)).filter((e,t,n)=>{if(t===0)return!0;let r=n[t-1];return r.isUpdate!==e.isUpdate||r.time!==e.time||e.timeCorrection}).forEach(e=>{if(e.index===-1)Ke(G.TS_MANYCHANGED,{series:this,part:ie.Unspecified});else{let t={series:this,index:e.index};Ke(e.isUpdate?G.TS_DATAPOINTCHANGED:G.TS_DATAPOINTADDED,t)}e.timeCorrection&&Ke(G.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return this.container!==null}getRetriever(){return new C_}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>{let t=this.query.aggregation.isEndOfDay,n=this.record,r=n?.symbol;if(!r)return[];let i=zp(G.RT_TRADE,r),a=e.filter(i).filter(e=>N(e.data.time)).filter(e=>e.data.session!==`T`||this.query.extendedHours&&!t).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay}));if(this.isTotalVolumeMode&&this.records){let t=this.getSiblingVolume(e);if(t>0&&a.length>0)a[0].tradeSize+=t;else if(t>0&&a.length===0){let e=n.getValue(W.Last)??n.getValue(W.Close);if(N(e)){let r=/* @__PURE__ */ new Date;a.push({isTrade:!0,tradePrice:e,tradeSize:t,time:r,tradingDay:n.getValue(W.TradingDay)})}}}let o=a.reduce((e,t)=>{let n=Ce(e);return N(n)&&N(n.tradePrice)&&N(t.tradePrice)&&n.tradePrice===t.tradePrice&&n.time.getTime()===t.time.getTime()&&n.tradingDay===t.tradingDay?n.tradeSize+=t.tradeSize:e.push(ct(t)),e},[]),s=zp(G.RT_QUOTE,r);return o.concat(e.filter(s).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}getSiblingVolume(e){return this.records?e.filter(e=>e.topic===G.RT_TRADE&&e.data.symbol in this.records).filter(e=>N(e.data.time)).filter(e=>e.data.session!==`T`).reduce((e,t)=>e+t.data.tradeSize,0):0}async loadMoreData(e=!0){if(this.isLoading||!this.builder||!this.retriever||!this.builder.supportsChunks||!this.retriever.supportsChunks||!this.canLoadMoreData)return Promise.resolve();this.isLoading=!0,e?await this.loadHeadChunk():await this.loadTailChunk(),this.isLoading=!1}async loadTailChunk(){let e=this.query.duplicate(),t=this.builder.getLastDate();N(e.offset)&&e.offset!==0&&(t=An(t,-e.offset)),e.range=[t,null];let n=await this.retriever.retrieve(e),r=this.container.size;this.builder.append(n);let i=this.container.size-r;Ke(G.TS_MANYCHANGED,{series:this,part:ie.Tail,count:i,index:r})}async loadHeadChunk(){let e=!1,t=null;for(let n=0;n<this.builder.retryCountForChunk&&!e;++n){let r=this.query.duplicate(),i=this.builder.getFirstDate(n);N(r.offset)&&r.offset!==0&&(i=An(i,-r.offset)),r.range=[null,i],t=await this.retriever.retrieve(r),e=t.size>1}this.canLoadMoreData=e,e&&t!==null&&(this.builder.prepend(t),Ke(G.TS_MANYCHANGED,{series:this,part:ie.Head}))}async applyNearbyFixup(e){let t=this.query.aggregation,n=t.spec===_.Nearest,r=this.query.symbol,i=ki(r);return!i||!t.isMultiContract||!n||e.size<1||this.serverComputedSeries?i&&Wi(r)?await Di(r):r:e.getLastDataPoint(W.Symbol)}async ready(){return ma.call(this,async()=>{try{yg(`ts:ready:start`,{symbol:this.query.symbol??null,isCached:this.isCached??!1,hasVisibleFrom:this.hasVisibleFrom,hasVisibleTo:this.hasVisibleTo}),this.retriever=this.getRetriever();let e=await this.retriever.retrieve(this.query);yg(`ts:ready:retrieved`,{symbol:this.query.symbol??null,containerSize:e.size});let t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=$().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.isTotalVolumeMode&&await this.setupTotalVolumeSubscriptions(),this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,yg(`ts:ready:done`,{symbol:this.query.symbol??null,recordSymbol:this.record?.symbol??null,containerSize:this.container?.size??null}),this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0}catch(e){return yg(`ts:ready:failed`,{symbol:this.query.symbol??null,message:e.message}),F(`Failed loading the historical data for ${this.query.symbol}, error is ${e.message}`,`warn`),this.builder=void 0,this.container=null,!1}})}async setupTotalVolumeSubscriptions(){let e=this.query.symbol,t=Ji(e);if(t)try{let n=await qi(t),r=this.record?.symbol??e,i=n.map(e=>e.name).filter(e=>e!==r),a=$().getRecordSource();this.records={};for(let e of i)this.records[e]=a.getRecord(e);await Promise.all(Object.values(this.records).map(e=>e.ready()))}catch{this.records=void 0}}getCacheableEntities(e){e.add(this)}shutdown(){N(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.records=void 0}},$_=class extends Q_{getRetriever(){return new w_}makeBuilder(e){return new Z_(e)}getStreamingSubscription(){}onStreamingUpdates(e){}},ev=class{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new t_}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw Error(`Should not be called.`)}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}},tv=class{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return this.container!==null}loadMoreData(e){throw Error(`Should not be called.`)}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}},nv=class{query;container;supplyCustomDemoData;canLoadMoreData=!0;isLoading=!0;constructor(e){this.query=e,this.container=null,this.supplyCustomDemoData=$().config.mode===`DemoSite`}refresh(){}loadMoreData(e){throw Error(`Should not be called.`)}get hasData(){return this.container!==null}shutdown(){}parseEvents(e){let t=new e_([W.DateTime,W.Dividends,W.Earnings,W.Splits,W.Custom]),n=e.split(`
|
|
19
|
+
`),n=this.getParseFunc();if(n!==null){let e=n.bind(this);t.forEach(t=>{let n=t.trim();if(n){let t=n.split(`,`);e(t)}})}return this.container}getParseFunc(){return this.aggregation.isTick?this.parseTick:this.aggregation.isIntraday?this.parseMinutes:this.parseEod}parseTick(e){let t=e.length-5;(t===0||t===1)&&(this.container.addDataPoint(W.DateTime,this.parseDate(e[0+t])),this.container.addDataPoint(W.TradingDay,parseInt(e[1+t])),this.container.addDataPoint(W.Last,parseFloat(e[3+t])),this.container.addDataPoint(W.TradeSize,parseInt(e[4+t])),this.container.addDataPoint(W.Change,this.calculateChange(W.Last)))}nullify(e){return e==null||e===0?null:e}parseMinutes(e){let t=this.aggregation.isMultiContract&&this.isFuture||this.needsResolution,n=+!!t;e.length===7+n&&(this.container.hasField(W.Symbol)&&this.container.addDataPoint(W.Symbol,t?e[0]:this.symbol),this.container.addDataPoint(W.DateTime,this.parseDate(e[0+n])),this.container.addDataPoint(W.TradingDay,parseInt(e[1+n])),this.container.addDataPoint(W.Open,parseFloat(e[2+n])),this.container.addDataPoint(W.High,parseFloat(e[3+n])),this.container.addDataPoint(W.Low,parseFloat(e[4+n])),this.container.addDataPoint(W.Close,parseFloat(e[5+n])),this.container.addDataPoint(W.Volume,this.nullify(parseInt(e[6+n]))),this.container.addDataPoint(W.Change,this.calculateChange()))}parseFloatOrNull(e){let t=parseFloat(e);return isNaN(t)&&this.padded?null:t}parseIntOrNull(e){let t=parseInt(e);return isNaN(t)&&this.padded?null:t}parseEod(e){let t=this.aggregation.isMultiContract,n=+!!this.useLastTrade,r=7+n+ +!!this.hasOpenInterest;if(e.length!==r)return;t&&this.container.addDataPoint(W.Symbol,e[0]),this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.Open,this.parseFloatOrNull(e[2])),this.container.addDataPoint(W.High,parseFloat(e[3])),this.container.addDataPoint(W.Low,parseFloat(e[4]));let i=this.useLastTrade&&e[5]!==``?e[5]:e[5+n];this.container.addDataPoint(W.Close,parseFloat(i)),this.container.addDataPoint(W.Volume,this.nullify(this.parseIntOrNull(e[6+n]))),this.hasOpenInterest&&this.container.addDataPoint(W.OpenInterest,this.nullify(this.parseIntOrNull(e[7+n]))),this.container.addDataPoint(W.Change,this.calculateChange())}calculateChange(e=W.Close){let t=this.container.size;if(t>1){let n=this.container.getData(e);return n[t-1]-n[t-2]}return 0}parseTimestamp(e){switch(this.aggregation.unit){case g.Tick:case g.Intraday:return Jg(e);default:return qg(e)}}parseDate(e){let t=this.parseTimestamp(e);return this.aggregation.isEndOfDay?An(t,this.offset):(this.previousTime=ci(t,this.previousTime)?t:_n(this.previousTime,1),this.previousTime)}getTimeZone(){return Ki(this.symbol)}},y_=class extends v_{makeContainer(){return new e_([W.DateTime,W.TradingDay,W.Symbol,W.Bid,W.BidSize,W.Ask,W.AskSize])}getParseFunc(){return this.parseTopOfBook}getTopOfBookPayload(e){if(e.length<7)return null;let t=e[0],n=t===`Q`||t===`T`;if(n&&t!==`Q`)return null;let r=+!!n,i=7+r;if(e.length!==i&&e.length!==i+1)return null;let a=e.length===i+1,o=r+ +!!a,s=o+1,c=o+3,l=o+4,u=o+5,d=o+6;return{symbol:a?e[o-1]:this.symbol,timestamp:e[o],tradingDay:parseInt(e[s]),bid:parseFloat(e[c]),bidSize:parseInt(e[l]),ask:parseFloat(e[u]),askSize:parseInt(e[d])}}parseTopOfBook(e){let t=this.getTopOfBookPayload(e);t!==null&&(this.container.addDataPoint(W.DateTime,this.parseDate(t.timestamp)),this.container.addDataPoint(W.TradingDay,t.tradingDay),this.container.addDataPoint(W.Symbol,t.symbol),this.container.addDataPoint(W.Bid,t.bid),this.container.addDataPoint(W.BidSize,t.bidSize),this.container.addDataPoint(W.Ask,t.ask),this.container.addDataPoint(W.AskSize,t.askSize))}},{BARCHART_HIST_SRV_NEAREST_INTRADAY_PAGE_NAME:b_,BARCHART_HIST_SRV_INTRADAY_PAGE_NAME:x_}=z,S_=[_.PerCount,_.PerVolume,_.PerSeconds],C_=class{supportsChunks;constructor(){this.supportsChunks=!0}getPageNameFor(e,t){switch(e.unit){case g.Tick:return z.BARCHART_HIST_SRV_TICKS_PAGE_NAME;case g.Intraday:return t&&e.spec===_.Nearest?b_:x_;case g.Day:case g.Week:case g.Month:case g.Quarter:case g.Year:return z.BARCHART_HIST_SRV_EOD_PAGE_NAME;default:return``}}addExtraParams(e){}makeUrl(e){let t={},n=co(e.symbol);t.symbol=n;let r=e.aggregation,i=this.getDataParam(r);i.length>0&&(t.data=i),r.size>1&&r.unit===g.Intraday&&(t.interval=(r.spec===_.PerRange?1:r.size).toString());let[a,o]=e.range,s=a!==null,c=o!==null;if(s&&(t.start=this.toHistoricalFeedDate(a,r)),!s||e.alwaysUseBarsToFetch){let n=e.barsToFetch||z.DEFAULT_MAX_RECORDS;r.unit===g.Tick&&S_.includes(r.spec)&&(n*=z.TICK_CUSTOM_AGG_MULTIPLIER),t.maxrecords=n.toString()}c&&(t.end=this.toHistoricalFeedDate(o,r)),t.volume=r.isContractVolume?`contract`:`total`,t.order=`asc`,t.dividends=r.dividendsAdjust.toString(),t.backadjust=r.backAdjust.toString(),t.daystoexpiration=r.daysToExpiration.toString(),t.contractroll=r.contractRoll,r.isTick&&(t.type=`T`,t.skipOldEmulation=`true`),e.usesLastTrade&&(t.lasttrade=`true`),e.extendedHours===!0&&(t.formt=`true`),t.splits=(e?.splits??!0).toString(),t.padded=(e.padded??!1).toString(),this.addExtraParams(t);let l=ht(t),u=ki(n);return`/${this.getPageNameFor(r,u)}?${l}`}toHistoricalFeedDate(e,t){return $r(e,t.isTick||t.isIntraday?z.FMT_HIST_FEED_PARAM_DATE_TIME:z.FMT_HIST_FEED_PARAM_DATE_ONLY)}getDataParam(e){let t=``,n=this.getSpecPart(e);switch(e.unit){case g.Tick:case g.Intraday:break;case g.Day:t=`daily${n}`;break;case g.Week:t=`weekly${n}`;break;case g.Month:t=`monthly${n}`;break;case g.Quarter:t=`quarterly${n}`;break;case g.Year:t=`yearly${n}`}return t}getSpecPart(e){return e.isMultiContract?e.spec===_.Continue?`continue`:`nearest`:``}getParser(e){return new v_(co(e.symbol),e.aggregation,e.offset,e.padded,e.usesLastTrade)}async retrieve(e){let t=this.makeUrl(e),n=await uI(e.aggregation.unit===g.Tick?`timeseriesNew`:`timeseries`,t);return this.getParser(e).parse(n)}},w_=class extends C_{addExtraParams(e){e.type=`B`}getParser(e){return new y_(co(e.symbol),e.aggregation,e.offset)}async retrieve(e){let t=await uI(`timeseriesNew`,this.makeUrl(e));return this.getParser(e).parse(t)}},T_=class{supportsChunks;constructor(){this.supportsChunks=!1}addExtraParams(e){}async retrieve(e){let t=co(e.symbol),n=this.emptyContainer(t,e.aggregation);if(e.aggregation.unit!==g.Day)return n;let r={symbol:t};this.addExtraParams(r);let i=await uI(`ondemand`,`/${this.getPageName()}.json?${ht(r)}`);try{let e=JSON.parse(i);if(e.status.code===200){let t=e.results;if(this.iterateForward)for(let e=0;e<t.length;e++)this.processRow(t[e],e,n);else for(let e=t.length-1;e>=0;e--)this.processRow(t[e],e,n);return n}}catch(e){F(`Failed parsing the JSON result from OnDemand, error is ${e.message}`)}return n}},E_={WeighImplVolHigh:`weightedImpliedVolatility`,WeighImplVolLow:`weightedImpliedVolatility`,WeighImplVol:`weightedImpliedVolatility`,WeighImplVolHigh5D:`weightedImpliedVolatilityHigh5d`,WeighImplVolLow5D:`weightedImpliedVolatilityLow5d`,WeighImplVol5D:`weightedImpliedVolatility5d`,WeighImplVolHigh1M:`weightedImpliedVolatilityHigh1m`,WeighImplVolLow1M:`weightedImpliedVolatilityLow1m`,WeighImplVol1M:`weightedImpliedVolatility1m`,WeighImplVolHigh3M:`weightedImpliedVolatilityHigh3m`,WeighImplVolLow3M:`weightedImpliedVolatilityLow3m`,WeighImplVol3M:`weightedImpliedVolatility3m`,WeighImplVolHigh6M:`weightedImpliedVolatilityHigh6m`,WeighImplVolLow6M:`weightedImpliedVolatilityLow6m`,WeighImplVol6M:`weightedImpliedVolatility6m`,WeighImplVolHigh1Y:`weightedImpliedVolatilityHigh1y`,WeighImplVolLow1Y:`weightedImpliedVolatilityLow1y`,WeighImplVol1Y:`weightedImpliedVolatility1y`,WeighImplVolHighYTD:`weightedImpliedVolatilityHighYtd`,WeighImplVolLowYTD:`weightedImpliedVolatilityLowYtd`,WeighImplVolYTD:`weightedImpliedVolatilityYtd`,WeighImplVolChg:`weightedImpliedVolatilityChange`,ImplVolRank5D:`impliedVolatilityRank5d`,ImplVolRank1M:`impliedVolatilityRank1m`,ImplVolRank3M:`impliedVolatilityRank3m`,ImplVolRank6M:`impliedVolatilityRank6m`,ImplVolRank1Y:`impliedVolatilityRank1y`,ImplVolRankYTD:`impliedVolatilityRankYtd`,ImplVolPerc5D:`impliedVolatilityPercentile5d`,ImplVolPerc1M:`impliedVolatilityPercentile1m`,ImplVolPerc3M:`impliedVolatilityPercentile3m`,ImplVolPerc6M:`impliedVolatilityPercentile6m`,ImplVolPerc1Y:`impliedVolatilityPercentile1y`,ImplVolPercYTD:`impliedVolatilityPercentileYtd`,OptTotVol:`totalVolume`,OptCallVol:`callVolume`,OptPutVol:`putVolume`,PutCallVolRatio:`putCallVolumeRatio`,TotalOpenInt:`totalOpenInterest`,CallOpenInt:`callOpenInterest`,PutOpenInt:`putOpenInterest`,PutCallOIRatio:`putCallOpenInterestRatio`,DateTime:`date`},D_=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){let t=co(e.symbol).replace(/\.bz$/i,``),n=e.fields.concat(W.DateTime),r=()=>new e_(n);if(e.aggregation.unit!==g.Day)return r();let i=await uI(`options`,`/get?${ht({symbol:t,apiKey:`default`,fields:n.map(e=>E_[e.id]).join(`,`)})}`);try{let e=JSON.parse(i).data,t=r(),a=e=>Number.parseFloat(e.replace(/,/g,``));return e.forEach(e=>{n.forEach(n=>{n===W.DateTime?t.addDataPoint(W.DateTime,qg(e.date)):t.addDataPoint(n,a(e[E_[n.id]]))})}),t}catch(e){F(`Failed parsing options JSON historical data result, error is ${e.message}`)}return r()}},O_=class extends Qg{innerBuilder;isBuildingBars;constructor(e,t,n){super(t,n),this.innerBuilder=e,this.isBuildingBars=!1,this.retryCountForChunk=z.FETCH_TICK_CHUNK_RETRY_COUNT,this.processRetrieved()}get base(){return this.innerBuilder.container}getFirstDate(e){return this.innerBuilder.getFirstDate(e)}get startFromIndex(){return 0}processRetrieved(){this.container.clear(),this.isBuildingBars=!0;let[e,t,n,r]=[W.DateTime,W.TradeSize,W.Last,W.TradingDay].map(e=>this.base.getData(e));for(let i=this.startFromIndex;i<this.base.size;i++){let a={isTrade:!0,time:e[i],tradeSize:t[i],tradePrice:n[i],tradingDay:r[i]};super.process(a)}this.isBuildingBars=!1}process(e){let t=this.innerBuilder.process(e);return e.time=new Date(t.time),super.process(e)}},k_=class extends O_{constructor(e,t,n){super(e,t,n)}fixupTimeBasedAggregationTimestamp(e){return bi(e,er(e,ir(yi(e,1)))%this.agg.size)}},A_=class extends O_{series;constructor(e,t,n,r){super(e,n,r),this.series=t}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}},j_=new vp(`_TICK_COUNT`),M_=class extends A_{anchorTimestamp=null;constructor(e,t,n,r){super(e,t,n,r)}get startFromIndex(){let e=0,t=this.base.getTimeData();if(N(this.anchorTimestamp))e=Te(t,e=>e===this.anchorTimestamp);else{let n=this.base.size;if(n>2)for(let r=n-2;r>2;--r){let n=t[r].valueOf();if(n-t[r-1].valueOf()>1&&t[r+1].valueOf()-n>1){e=r;break}}this.anchorTimestamp=t[e]}return e>this.agg.size&&(e%=this.agg.size),Math.max(e,0)}addBar(e,t){let n=super.addBar(e,t);return this.container.addDataPoint(j_,1),n}changeLastBar(e,t){let n=super.changeLastBar(e,t),r=this.container.getLastDataPoint(j_);return this.container.setLastDataPoint(j_,r+1),n}isUpdate(e,t,n,r){return this.container.getLastDataPoint(j_)<this.agg.size}},N_=new vp(`_VOLUME_TALLY`),P_=class extends A_{constructor(e,t,n,r){super(e,t,n,r)}addBar(e,t){let n=this.container,r=(n.getLastDataPoint(N_)||0)+e.tradeSize,i=Math.floor(r/this.agg.size),a=r%this.agg.size,o=r<this.agg.size;n.size>0&&(n.setLastDataPoint(W.Volume,o?1:i),n.setLastDataPoint(N_,r));let s=super.addBar(e,t);return n.setLastDataPoint(W.Volume,1),n.addDataPoint(N_,o?0:a),s}changeLastBar(e,t){let n=this.container,r=super.changeLastBar(e,t);n.setLastDataPoint(W.Volume,1);let i=n.getLastDataPoint(N_)??0;return n.setLastDataPoint(N_,i+e.tradeSize),r}isUpdate(e,t,n,r){if(!Ln(e,t))return!1;let i=this.container.getLastDataPoint(N_)??0;return r.tradeSize+i<this.agg.size}},F_=class extends Qg{innerBuilder;metadata;range;step;constructor(e,t,n,r){super(t,n),this.innerBuilder=e,this.range=n.size,this.step=1;let i=$().getMetaDataSource();this.metadata=i.getMetaData(r)}get priceRange(){return this.step*this.range}get base(){return this.innerBuilder.container}ready(){return ma.call(this,async()=>{let e=await this.metadata.ready();return e&&(this.step=this.metadata.minMovement,this.processRetrieved()),e})}processRetrieved(){this.container.clear();for(let e=0;e<this.base.size;e++){let t=this.base.getData(W.Volume)[e],n=this.useHighOrLow(e);if(!N(n)){this.updateLastBar(void 0,void 0,void 0,t);continue}let r={isTrade:!0,time:this.base.getData(W.DateTime)[e],tradeSize:t,tradePrice:n,tradingDay:0};super.process(r)}}useHighOrLow(e){let t=this.base.getData(W.Close)[e];if(this.container.size==0)return t;let n=this.container.getLastDataPoint(W.High),r=this.container.getLastDataPoint(W.Low),i=this.base.getData(W.High)[e],a=this.base.getData(W.Low)[e],o=i>n,s=a<r;if(o&&s)return i-t<t-a?i:a;if(o)return i;if(s)return a}computeNextStamp(e,t){return this.isCorrection(e,t)?null:t}isUpdate(e,t,n,r){return!0}process(e){return this.innerBuilder.process(e),super.process(e)}changeLastBar(e,t){let n=e.tradePrice,r=this.container.getLastDataPoint(W.Low)+this.priceRange;if(n>r)return this.changeAndAddBar(r,e,t);let i=this.container.getLastDataPoint(W.High)-this.priceRange;return n<i?this.changeAndAddBar(i,e,t):super.changeLastBar(e,t)}changeAndAddBar(e,t,n){return this.updateLastBar(e,e,e,0),this.container.setLastDataPoint(W.Projection,0),this.addBar(t,n)}addBar(e,t){return this.container.addDataPoint(W.Projection,1),super.addBar(e,t)}},I_=[W.Open,W.High,W.Low,W.Close],L_=[W.BARCOLIX,W.High,W.Low],R_=z.RENKO_KAGI_NAMES;function z_(e){let{BoxSizeMethod:t,Period:n,ReversalAmount:r}=ft(e);return{method:tt(t,[R_.ATR,R_.TRD],R_.ATR),period:Number.isFinite(n)?n:14,reversal:Number.isFinite(r)?r:30}}var B_=class extends Qg{innerBuilder;inputs;reversal;isProcessingRetrieved=!1;constructor(e,t,n){super(t,n.aggregation),this.innerBuilder=e,this.inputs=P(n.inputs),this.reversal=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,n){return e.getData(t)[n]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}addBar(e,t){if(super.addBar(e,t),this.container.addDataPoint(W.BARCOLIX,null),this.container.size>1){let e=this.dataAt(W.Close,this.container.size-2);this.setLast(W.Open,e),this.updateLastBar(e,e)}return null}isUpdate(e,t,n,r){let i=r.tradePrice,a=e=>e>=0,o=i-this.getLast(W.Close),s=a(o),c=Math.abs(o)>=this.reversal,[l,u,d,f]=I_.map(e=>this.getLast(e)),p=f-l,m=a(p)!==s||p===0;return m&&!c||!m&&(s?i<u:i>d)?null:Math.abs(p)<this.reversal||!m||!c}computeBarColor(){let e=e=>this.dataAt(W.Close,e)>this.dataAt(W.Open,e),t=this.container.size;if(t>1){let n=e(t-1),[r,i,a]=L_.map(e=>this.dataAt(e,t-2)),[,o,s]=L_.map(e=>this.dataAt(e,t-1)),c=r;r===0&&n&&o>i?c=1:r===1&&!n&&s<a&&(c=0),this.setLast(W.BARCOLIX,c)}else this.setLast(W.BARCOLIX,+!!e(0))}process(e){this.isProcessingRetrieved||this.innerBuilder.process(e);let t=super.process(e);return this.computeBarColor(),t}processRetrieved(){let{method:e,period:t,reversal:n}=z_(this.inputs);if(this.reversal=n,e===R_.ATR&&(this.reversal=s_(this.base,t)),N(this.reversal)){this.container.clear(),this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(W.DateTime,e),tradePrice:this.baseAt(W.Close,e),tradeSize:this.baseAt(W.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}};function V_(e){let{LineCount:t}=ft(e);return{lineBreak:Number.isFinite(t)?t:3}}var H_=class extends Qg{innerBuilder;lineBreak;currentVolume;inputs;constructor(e,t,n,r){super(t,n),this.innerBuilder=e,this.inputs=P(r.inputs);let i=V_(this.inputs);this.lineBreak=i.lineBreak,this.currentVolume=0,this.processRetrieved()}get base(){return this.innerBuilder.container}readTrade(e){return{isTrade:!0,time:this.base.getData(W.DateTime)[e],tradeSize:this.base.getData(W.Volume)[e],tradePrice:this.base.getData(W.Close)[e],tradingDay:0}}processRetrieved(){if(this.container.clear(),!(this.base.size<2)){this.startLine(this.readTrade(1));for(let e=1;e<this.base.size-1;e++){let t=this.readTrade(e);this.insertBar(t,t.time)}super.process(this.readTrade(this.base.size-1))}}process(e){return this.innerBuilder.process(e),super.process(e)}updateLastBar(e,t,n,r){let i=this.findOpen(n,0,1);this.currentVolume+=r,i===null?this.resetProjection():(super.updateLastBar(void 0,void 0,n,void 0),this.container.setLastDataPoint(W.Open,i),this.container.setLastDataPoint(W.Low,Math.min(i,n)),this.container.setLastDataPoint(W.High,Math.max(i,n)))}resetProjection(){let e=this.container;e.setLastDataPoint(W.High,null),e.setLastDataPoint(W.Low,null),e.setLastDataPoint(W.Open,null),e.setLastDataPoint(W.Close,null),e.setLastDataPoint(W.Change,null)}isProjection(e){return this.agg.isIntraday||this.durationAdd(e).getTime()>Date.now()}updateProjection(e,t){this.container.setLastDataPoint(W.DateTime,t.nextTimestamp);let n=this.changeLastBar(e,t);return n.timeCorrection={from:t.lastTimestamp,to:t.nextTimestamp},n}addBar(e,t){let n=this.container,{nextTimestamp:r}=t;if(n.getLastDataPoint(W.Projection)===1){let r=n.getLastDataPoint(W.Close);if(this.findOpen(r,this.lineBreak,1)!==null)n.setLastDataPoint(W.Projection,0),n.setLastDataPoint(W.Volume,this.currentVolume),this.currentVolume=0;else return this.updateProjection(e,t)}return(this.isProjection(r)||!this.insertBar(e,r))&&!this.addProjection(e,r)?null:{isUpdate:!1,time:r.getTime(),index:this.container.size-1}}insertBar(e,t){this.currentVolume+=e.tradeSize;let n=e.tradePrice,r=this.findOpen(n,this.lineBreak);return r!==null&&(this.createBar(r,Math.max(r,n),Math.min(r,n),n,this.currentVolume,t),this.container.addDataPoint(W.Projection,0),this.currentVolume=0,!0)}addProjection(e,t){this.currentVolume+=e.tradeSize;let n=e.tradePrice,r=this.findOpen(n,0);return r!==null&&(this.createBar(r,Math.max(r,n),Math.min(r,n),n,0,t),this.container.addDataPoint(W.Projection,1),!0)}findOpen(e,t,n=0){if(!N(e))return null;let r=this.container,i=r.size-1-n,a=r.getData(W.Close)[i],o=r.getData(W.Open)[i];if(a>o){if(e<=a){if(e>=o)return null;for(let n=0;n<Math.min(r.size,t);n++)if(e>=r.getData(W.Low)[i-n])return null;return o}return a}if(e>=a){if(e<=o)return null;for(let n=0;n<Math.min(r.size,t);n++)if(e<=r.getData(W.High)[i-n])return null;return o}return a}startLine(e){this.container.addDataPoint(W.Projection,0);let t=this.readTrade(0);this.createBar(t.tradePrice,Math.max(t.tradePrice,e.tradePrice),Math.min(t.tradePrice,e.tradePrice),e.tradePrice,e.tradeSize+t.tradeSize,e.time)}},U_=z.RENKO_KAGI_NAMES,W_={Positive:1,Negative:2,Both:3};function G_(e){switch(e){case z.BARKIND_OX:case z.BARKIND_XO:return!0;default:return!1}}function K_(e){switch(e){case z.BARKIND_O:case z.BARKIND_XO:return!0;default:return!1}}function q_(e){switch(e){case z.BARKIND_X:case z.BARKIND_OX:return!0;default:return!1}}function J_(e){let t=ft(e),{Source:n,BoxSizeMethod:r,Period:i}=t,{ReversalAmount:a,BoxSize:o,OneStepBack:s}=t,c=tt(n,[U_.CLS,U_.HL],U_.CLS),l=tt(r,[U_.ATR,U_.TRD],U_.ATR),u=Number.isFinite(i)?i:14,d=Number.isFinite(a)?a:3;return{method:l,period:u,source:c,boxSize:Number.isFinite(o)?o:20,reversal:d,oneStepBack:s===`Yes`}}var Y_=class extends Qg{innerBuilder;inputs;boxSize;reversal;source;firstTrend;oneStepBack;isProcessingRetrieved=!1;constructor(e,t,n){super(t,n.aggregation),this.innerBuilder=e,this.inputs=P(n.inputs),this.boxSize=this.reversal=this.source=this.firstTrend=this.oneStepBack=null,this.processRetrieved()}get base(){return this.innerBuilder.container}_at(e,t,n){return e.getData(t)[n]}baseAt(e,t){return this._at(this.base,e,t)}dataAt(e,t){return this._at(this.container,e,t)}getLast(e){return this.container.getLastDataPoint(e)}setLast(e,t){this.container.setLastDataPoint(e,t)}computeNextStamp(e,t){return t}roundToBox(e){return e-e%this.boxSize}roundedDiff(e,t,n){let r=Math.abs(t-e);return e+n*this.roundToBox(r)}get closeBased(){return this.source===U_.CLS}get currentKind(){return this.getLast(W.BARKIND)}getTrendField(e){return this.closeBased?W.Close:e?W.Low:W.High}getTrendPrice(e,t){if(this.closeBased)return e.tradePrice;let n=e;return t?n._lowPrice:n._highPrice}changeLastBar(e,t){let n=K_(this.currentKind),r=n?-1:1,i=this.getLast(this.getTrendField(n)),a=this.getTrendPrice(e,n);return e.tradePrice=this.roundedDiff(i,a,r),super.changeLastBar(e,t),null}addBar(e,t){let n=this.container.size===0,r=K_(this.currentKind),i=r?1:-1,a=n?null:this.getLast(W.Close),o=this.getTrendPrice(e,!r);if(e.tradePrice=(n?this.roundToBox(this.baseAt(W.Open,0)):a)+i*(n?0:this.boxSize),super.addBar(e,t),!n){let e=this.roundedDiff(a,o,i);this.updateLastBar(e,e,e)}return this.container.addDataPoint(W.BARKIND,null),this.computeBarColor(),null}inplaceReverse(){let e=K_(this.currentKind)?z.BARKIND_OX:z.BARKIND_XO;this.setLast(W.BARKIND,e)}canInplaceReverse(){return!G_(this.currentKind)&&this.getLast(W.High)===this.getLast(W.Low)}isUpdate(e,t,n,r){let i=K_(this.currentKind),a=this.getTrendPrice(r,i),o=this.getTrendPrice(r,!i),s=e=>e>=0,c=a-this.getLast(W.Close),l=s(c),u=Math.abs(c)>=this.boxSize,d=o-this.getLast(W.Close),f=s(d),p=Math.abs(d)>=this.reversal*this.boxSize;return i?!l&&u?!0:f&&p?!this.oneStepBack||!this.canInplaceReverse()?!1:(this.inplaceReverse(),!0):null:l&&u?!0:!f&&p?!this.oneStepBack||!this.canInplaceReverse()?!1:(this.inplaceReverse(),!0):null}findFirstDiffLargerThanBox(e,t){let n=this.baseAt(W.Open,0),r=this.innerBuilder.container.size;for(let i=1;i<r;++i){let r=this.baseAt(e,i)-n;if(Math.abs(r)>this.boxSize){if(t===W_.Positive&&r>0)return[i,z.BARKIND_X];if(t===W_.Negative&&r<0)return[i,z.BARKIND_O];if(t===W_.Both)return[i,r>0?z.BARKIND_X:z.BARKIND_O]}}return[null,null]}findFirstBarTrend(){if(this.innerBuilder.container.size<2)return null;if(this.closeBased){let[,e]=this.findFirstDiffLargerThanBox(W.Close,W_.Both);return e}{let[e,t]=this.findFirstDiffLargerThanBox(W.High,W_.Positive),[n,r]=this.findFirstDiffLargerThanBox(W.Low,W_.Negative);return t===null&&r===null?null:r===null?t:t===null?r:e<n?t:r}}computeBarColor(){let e=this.container.size,t=this.firstTrend;e>1&&(t=K_(this.dataAt(W.BARKIND,e-2))?z.BARKIND_X:z.BARKIND_O),this.setLast(W.BARKIND,t)}process(e){return this.isProcessingRetrieved||this.innerBuilder.process(e),this.firstTrend===null?null:super.process(e)}processRetrieved(){let{method:e,period:t,reversal:n,source:r,boxSize:i,oneStepBack:a}=J_(this.inputs);if(this.reversal=n,this.source=r,this.boxSize=e===U_.ATR?s_(this.base,t):i,N(this.reversal,this.boxSize)&&(this.oneStepBack=a&&this.reversal===1,this.container.clear(),this.firstTrend=this.findFirstBarTrend(),this.firstTrend!==null)){this.isProcessingRetrieved=!0;for(let e=0;e<this.base.size;e++){let t={isTrade:!0,time:this.baseAt(W.DateTime,e),tradePrice:this.baseAt(W.Close,e),_highPrice:this.baseAt(W.High,e),_lowPrice:this.baseAt(W.Low,e),tradeSize:this.baseAt(W.Volume,e),tradingDay:0};this.process(t)}this.isProcessingRetrieved=!1}}},X_=new yd(g.Intraday,0),Z_=class extends Zg{constructor(e){super(e)}process(e){return{isUpdate:!1,time:0,index:-1}}},Q_=class{query;container;canLoadMoreData=!0;alignToQuote=!1;isCached;record;isLoading=!1;serverComputedSeries;builder;retriever;streamingSubscription;records;constructor(e){this.query=e,this.container=null,this.canLoadMoreData=!0,this.alignToQuote=!1,this.record=new Dp(e.symbol)}get isTotalVolumeMode(){let e=this.query.symbol,t=this.query.aggregation;return ki(e)&&!t.isContractVolume&&t.isEndOfDay}getHasVisible(e){return this.query.visibleRange!=null&&this.query.visibleRange[e]!=null}get hasVisibleFrom(){return this.getHasVisible(`from`)}get hasVisibleTo(){return this.getHasVisible(`to`)}get hasHistoricalData(){return this.hasData&&!this.container.isEmpty}refresh(){yg(`ts:refresh`,{symbol:this.query.symbol??null,hasData:this.hasData,hasHistoricalData:this.hasHistoricalData,isCached:this.isCached??!1}),this.hasHistoricalData?this.query.aggregation.isEndOfDay?this.alignToQuote=!0:this.loadMoreData(!1):(ha.call(this),this.ready().then(e=>{yg(`ts:refresh:result`,{symbol:this.query.symbol??null,hasData:e,containerSize:this.container?.size??null}),e&&Ke(G.TS_MANYCHANGED,{series:this,part:ie.Unspecified})}))}makeInnerBuilder(e){let t=this.query.aggregation;if(t.isTick)switch(t.spec){case _.None:case _.PerSeconds:case _.PerCount:case _.PerVolume:return new Zg(e);default:throw Error(`Custom tick aggregation ${t.describe()} has not been implemented yet`)}else return new Qg(e,t)}makeBuilder(e){let t=this.makeInnerBuilder(e),n=this.query.aggregation,r=(e,t=[])=>new e_(__(this.query.symbol,e).concat(t)),i=t;switch(this.query.curveStyle){case h.Renko:return new d_(i,this.query);case h.Kagi:return new B_(i,r(X_,[W.BARCOLIX]),this.query);case h.PointAndFigure:return new Y_(i,r(X_,[W.BARKIND]),this.query);case h.LineBreak:return new H_(i,r(n,[W.Projection]),n,this.query)}if(n.isIntraday&&n.spec===_.PerRange)return new F_(i,r(X_,[W.Projection]),n,this.query.symbol);let a=t;if(n.isTick)switch(n.spec){case _.PerSeconds:return new k_(a,r(X_),n);case _.PerCount:{let e=r(X_,[j_]);return new M_(a,this,e,n)}case _.PerVolume:{let e=r(X_,[N_]);return new P_(a,this,e,n)}}return n.unit===g.Day&&n.size>1?new $g(i,r(n),n):t}onStreamingUpdates(e){this.isLoading||e.map(e=>{if(`isTrade`in e)return this.builder.process(e);if(`isQuote`in e&&(Ke(G.TS_QUOTEMARKER,{series:this}),this.alignToQuote&&this.query.usesLastTrade&&(this.alignToQuote=!1),this.alignToQuote)){let t=this.builder.alignToQuote(e);return this.alignToQuote=!1,t}return null}).filter(e=>N(e)).filter((e,t,n)=>{if(t===0)return!0;let r=n[t-1];return r.isUpdate!==e.isUpdate||r.time!==e.time||e.timeCorrection}).forEach(e=>{if(e.index===-1)Ke(G.TS_MANYCHANGED,{series:this,part:ie.Unspecified});else{let t={series:this,index:e.index};Ke(e.isUpdate?G.TS_DATAPOINTCHANGED:G.TS_DATAPOINTADDED,t)}e.timeCorrection&&Ke(G.TS_TIMELINECORRECTION,{...e.timeCorrection,series:this})})}get hasData(){return this.container!==null}getRetriever(){return new C_}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>{let t=this.query.aggregation.isEndOfDay,n=this.record,r=n?.symbol;if(!r)return[];let i=zp(G.RT_TRADE,r),a=e.filter(i).filter(e=>N(e.data.time)).filter(e=>e.data.session!==`T`||this.query.extendedHours&&!t).map(e=>({isTrade:!0,tradePrice:e.data.tradePrice,tradeSize:e.data.tradeSize,time:e.data.time,tradingDay:e.data.tradingDay}));if(this.isTotalVolumeMode&&this.records){let t=this.getSiblingVolume(e);if(t>0&&a.length>0)a[0].tradeSize+=t;else if(t>0&&a.length===0){let e=n.getValue(W.Last)??n.getValue(W.Close);if(N(e)){let r=/* @__PURE__ */ new Date;a.push({isTrade:!0,tradePrice:e,tradeSize:t,time:r,tradingDay:n.getValue(W.TradingDay)})}}}let o=a.reduce((e,t)=>{let n=Ce(e);return N(n)&&N(n.tradePrice)&&N(t.tradePrice)&&n.tradePrice===t.tradePrice&&n.time.getTime()===t.time.getTime()&&n.tradingDay===t.tradingDay?n.tradeSize+=t.tradeSize:e.push(ct(t)),e},[]),s=zp(G.RT_QUOTE,r);return o.concat(e.filter(s).map(e=>({isQuote:!0,openPrice:e.data.openPrice,highPrice:e.data.highPrice,lowPrice:e.data.lowPrice,lastPrice:e.data.lastPrice,time:e.data.tradeTime})))}),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}getSiblingVolume(e){return this.records?e.filter(e=>e.topic===G.RT_TRADE&&e.data.symbol in this.records).filter(e=>N(e.data.time)).filter(e=>e.data.session!==`T`).reduce((e,t)=>e+t.data.tradeSize,0):0}async loadMoreData(e=!0){if(this.isLoading||!this.builder||!this.retriever||!this.builder.supportsChunks||!this.retriever.supportsChunks||!this.canLoadMoreData)return Promise.resolve();this.isLoading=!0,e?await this.loadHeadChunk():await this.loadTailChunk(),this.isLoading=!1}async loadTailChunk(){let e=this.query.duplicate(),t=this.builder.getLastDate();N(e.offset)&&e.offset!==0&&(t=An(t,-e.offset)),e.range=[t,null];let n=await this.retriever.retrieve(e),r=this.container.size;this.builder.append(n);let i=this.container.size-r;Ke(G.TS_MANYCHANGED,{series:this,part:ie.Tail,count:i,index:r})}async loadHeadChunk(){let e=!1,t=null;for(let n=0;n<this.builder.retryCountForChunk&&!e;++n){let r=this.query.duplicate(),i=this.builder.getFirstDate(n);N(r.offset)&&r.offset!==0&&(i=An(i,-r.offset)),r.range=[null,i],t=await this.retriever.retrieve(r),e=t.size>1}this.canLoadMoreData=e,e&&t!==null&&(this.builder.prepend(t),Ke(G.TS_MANYCHANGED,{series:this,part:ie.Head}))}async applyNearbyFixup(e){let t=this.query.aggregation,n=t.spec===_.Nearest,r=this.query.symbol,i=ki(r);return!i||!t.isMultiContract||!n||e.size<1||this.serverComputedSeries?i&&Wi(r)?await Di(r):r:e.getLastDataPoint(W.Symbol)}async ready(){return ma.call(this,async()=>{try{yg(`ts:ready:start`,{symbol:this.query.symbol??null,isCached:this.isCached??!1,hasVisibleFrom:this.hasVisibleFrom,hasVisibleTo:this.hasVisibleTo}),this.retriever=this.getRetriever();let e=await this.retriever.retrieve(this.query);yg(`ts:ready:retrieved`,{symbol:this.query.symbol??null,containerSize:e.size});let t=await this.applyNearbyFixup(e);return this.hasVisibleTo||(this.record=$().getRecordSource().getRecord(t)),this.canLoadMoreData=!this.hasVisibleFrom&&e.size>0,this.isTotalVolumeMode&&await this.setupTotalVolumeSubscriptions(),this.builder=this.makeBuilder(e),await this.builder.ready(),this.container=this.builder.container,yg(`ts:ready:done`,{symbol:this.query.symbol??null,recordSymbol:this.record?.symbol??null,containerSize:this.container?.size??null}),this.query.disableStreamingUpdates||(this.streamingSubscription=this.getStreamingSubscription()),!0}catch(e){return yg(`ts:ready:failed`,{symbol:this.query.symbol??null,message:e.message}),F(`Failed loading the historical data for ${this.query.symbol}, error is ${e.message}`,`warn`),this.builder=void 0,this.container=null,!1}})}async setupTotalVolumeSubscriptions(){let e=this.query.symbol,t=Ji(e);if(t)try{let n=await qi(t),r=this.record?.symbol??e,i=n.map(e=>e.name).filter(e=>e!==r),a=$().getRecordSource();this.records={};for(let e of i)this.records[e]=a.getRecord(e);await Promise.all(Object.values(this.records).map(e=>e.ready()))}catch{this.records=void 0}}getCacheableEntities(e){e.add(this)}shutdown(){N(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.records=void 0}},$_=class extends Q_{getRetriever(){return new w_}makeBuilder(e){return new Z_(e)}getStreamingSubscription(){}onStreamingUpdates(e){}},ev=class{query;container;_pretendEmpty;constructor(e,t=!1){this._pretendEmpty=t,this.query=e,this.container=new t_}refresh(){}canLoadMoreData=!1;isLoading=!1;calculable=!1;loadMoreData(e){throw Error(`Should not be called.`)}get hasData(){return this._pretendEmpty}async ready(){return this._pretendEmpty}getCacheableEntities(e){}shutdown(){}},tv=class{query;container;canLoadMoreData=!1;isLoading=!1;constructor(e,t){this.query=e,this.container=t}get hasData(){return this.container!==null}loadMoreData(e){throw Error(`Should not be called.`)}refresh(){}async ready(){return!0}getCacheableEntities(e){}shutdown(){}},nv=class{query;container;supplyCustomDemoData;canLoadMoreData=!0;isLoading=!0;constructor(e){this.query=e,this.container=null,this.supplyCustomDemoData=$().config.mode===`DemoSite`}refresh(){}loadMoreData(e){throw Error(`Should not be called.`)}get hasData(){return this.container!==null}shutdown(){}parseEvents(e){let t=new e_([W.DateTime,W.Dividends,W.Earnings,W.Splits,W.Custom]),n=e.split(`
|
|
20
20
|
`),r=(e,n,r,i)=>{let a=n===r?i:null;t.addDataPoint(e,a)};return n.forEach(e=>{if(e.trim()===``)return;let n=e.split(`,`);if(n.length!==4)return;let i=qg(n[1]);t.addDataPoint(W.DateTime,i),r(W.Dividends,`Dividend`,n[2],n[3]),r(W.Earnings,`Earnings`,n[2],n[3]),r(W.Splits,`Split`,n[2],n[3]),this.supplyCustomDemoData?r(W.Custom,`Custom`,`Custom`,z.FAKE_CUSTOM_EVENT):r(W.Custom,`Custom`,n[2],n[3])}),t}makeUrl(){let e={};return e.symbols=this.query.symbol,e.start=`19700102`,e.end=`20501230`,z.EVENTS_BUILT_IN.forEach(t=>e[t]=this.query[t]),`/queryevents.ashx?${ht(e)}`}async retrieve(){let e=await uI(`timeseries`,this.makeUrl());return this.parseEvents(e)}async ready(){return ma.call(this,async()=>(this.container=await this.retrieve(),this.isLoading=this.canLoadMoreData=!1,!0))}getCacheableEntities(e){e.add(this)}},rv=class{query;container;canLoadMoreData=!1;isLoading=!0;constructor(e){this.query=e,this.query=e,this.container=null}get hasData(){return this.container!==null}refresh(){}loadMoreData(e){throw Error(`Should not be called.`)}shutdown(){}parseFundamental(e){let t=JSON.parse(e),n=t.status.code,r=n===204;if(n!==200&&!r)return null;let i=new e_(this.query.fields.concat(W.DateTime));if(r)return i;let a=this.query.fields[0],o=a.id.substring(0,1).toLowerCase()+a.id.substring(1);return t.results.reverse().forEach(e=>{i.addDataPoint(W.DateTime,qg(e.date)),i.addDataPoint(a,parseFloat(e[o]))}),this.isLoading=!1,i}makeUrl(){let e={count:0,rawData:1};e.symbols=this.query.symbol,e.frequency=this.query.aggregation.unit===g.Quarter?`Quarter`:`Annual`;let t=ht(e);return`/${this.query.seriesKind===C.BalanceSheet?`getBalanceSheets`:`getIncomeStatements`}.json?${t}`}async retrieve(){let e=await uI(`ondemand`,this.makeUrl());return this.parseFundamental(e)}async ready(){return ma.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}};function iv(e,t){let n=e.findIndex(e=>e>t);return Math.max(n<0?e.length:n,0)}var av=class{records;streamingSubscription;setSymbols(e){let t=$().getRecordSource();this.records=e.reduce((e,n)=>{let r=t.getRecord(n);return this.addFieldsToRecord(r,n),e[n]=r,e},{})}getStreamingSubscription(){return $().getRecordSource().subject.pipe(_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}onStreamingUpdates(e){e.forEach(e=>{let t=e.data,n=this.records[t.symbol];N(n)&&this.process(n)}),this.notifyAboutUpdates()}async retrieve(){let e=Object.values(this.records);return(await Promise.all(e.map(e=>e.ready()))).every(de)&&(this.onRecordsReady(),e.forEach(e=>this.process(e)),this.streamingSubscription=this.getStreamingSubscription()),this.hasData}async ready(){return ma.call(this,async()=>await this.retrieve())}shutdown(){N(this.streamingSubscription)&&this.streamingSubscription.unsubscribe()}},ov=class extends av{symbols=[];constructor(e){super(),this.symbols=e,this.setSymbols(e)}addFieldsToRecord(e,t){e.addFields(W.Symbol),e.update(W.Symbol,t)}notifyAboutUpdates(){Ke(G.RT_QUOTEGROUP,{source:this})}process(e){}onRecordsReady(){}get hasData(){return!0}getValue(e){let t=this.records[e];return t===void 0?null:t.getValue(W.Close)}},sv=class extends av{query;dataPoints;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){super(),this.query=e,this.setSymbols(e.symbols),this.dataPoints=e.symbols.length,this.container=null,this.fields=[W.DateTime,W.Close,W.Symbol]}addFieldsToRecord(e,t){e.addFields(W.DateTime,W.Symbol),e.update(W.DateTime,Yi(t)),e.update(W.Symbol,t)}refresh(){}loadMoreData(e){throw Error(`Should not be called.`)}get hasData(){return this.container!==null&&this.container.size===this.dataPoints}notifyAboutUpdates(){Ke(G.TS_MANYCHANGED,{series:this,part:ie.Unspecified})}onRecordsReady(){this.container=new e_(this.fields)}findOrAddIndex(e){let t=this.container.getData(W.Symbol).indexOf(e.symbol);return t<0&&(t=iv(this.container.getData(W.DateTime),Yi(e.symbol)),this.fields.forEach(e=>this.container.getData(e).splice(t,0,null))),t}process(e){let t=this.fields.map(t=>{let n=e.getValue(t);return t.id===`Close`?e.getValue(W.Last)??n:n});if(!ge(t))return;let n=this.findOrAddIndex(e);this.fields.forEach((e,r)=>this.container.getData(e)[n]=t[r])}getCacheableEntities(e){e.add(this)}},cv=class{query;container;fields;canLoadMoreData=!1;isLoading=!1;constructor(e){this.query=e,this.fields=[W.DateTime,W.Close,W.Symbol],this.container=null}get hasData(){return this.container!==null}refresh(){}loadMoreData(e){throw Error(`Should not be called.`)}shutdown(){}insertValues(e,t,n){let r=(t,n,r)=>e.getData(n).splice(t,0,r),i=e.getData(W.DateTime),a=Yi(t),o=iv(i,a);r(o,W.DateTime,a),r(o,W.Close,n),r(o,W.Symbol,t)}parseHistoricalForward(e){let t=new e_(this.fields);return e.split(`
|
|
21
21
|
`).filter(e=>e.trim().length>0).forEach(e=>{let n=e.split(`,`),r=n[0];this.insertValues(t,r,parseFloat(n[5]))}),t}makeUrl(){let e={};return e.symbols=this.query.symbols.join(`,`),e.maxrecords=1,e.data=`daily`,e.end=ue(Ig(this.query.offset),Fg(z.FMT_HIST_FEED_PARAM_DATE_ONLY))(/* @__PURE__ */ new Date),`/querylatesteod.ashx?${ht(e)}`}async retrieve(){let e=await uI(`timeseries`,this.makeUrl());return this.parseHistoricalForward(e)}async ready(){return ma.call(this,async()=>(this.container=await this.retrieve(),!0))}getCacheableEntities(e){e.add(this)}},lv=class extends Q_{constructor(e){super(e)}getRetriever(){return new D_}onStreamingUpdates(e){}},uv=class{cacheSeries;seriesCache;constructor(e=!1){this.cacheSeries=e,this.seriesCache=/* @__PURE__ */ new Map}getTimeSeries(e){return N(e.symbol)&&e.symbol===z.PLACEHOLDER_SYMBOL_NAME?new ev(e):this.getSeries(e)}evictUnused(e){for(let[t,n]of this.seriesCache)!e.has(n)&&n.isCached&&(n.isCached=!1,n.shutdown(),this.seriesCache.delete(t))}refresh(){for(let e of this.seriesCache.values())typeof e.refresh==`function`&&e.refresh()}getSeries(e){let t=(e.cacheMe||this.cacheSeries)&&!(e?.alwaysUseBarsToFetch??!1),n=e.getHashKey();if(t&&this.seriesCache.has(n))return yg(`ts:cache:hit`,{symbol:e.symbol??null,cacheKey:n,cacheSize:this.seriesCache.size}),this.seriesCache.get(n);{let r=this.makeSeries(e);return r.isCached=t,t&&(this.seriesCache.set(n,r),yg(`ts:cache:add`,{symbol:e.symbol??null,cacheKey:n,cacheSize:this.seriesCache.size})),r}}makeSeries(e){switch(e.seriesKind){case C.Normal:return e.aggregation.spec===_.TopOfBook?new $_(e):new Q_(e);case C.BalanceSheet:case C.IncomeStatement:return new rv(e);case C.Events:return new nv(e);case C.Forward:return new sv(e);case C.HistoricalForward:return new cv(e);default:case C.Options:return new lv(e);case C.Study:throw Error(`The series kind '${C[e.seriesKind]}' is not supported yet.`)}}},dv={lessThanXSeconds:{one:`moins d’une seconde`,other:`moins de {{count}} secondes`},xSeconds:{one:`1 seconde`,other:`{{count}} secondes`},halfAMinute:`30 secondes`,lessThanXMinutes:{one:`moins d’une minute`,other:`moins de {{count}} minutes`},xMinutes:{one:`1 minute`,other:`{{count}} minutes`},aboutXHours:{one:`environ 1 heure`,other:`environ {{count}} heures`},xHours:{one:`1 heure`,other:`{{count}} heures`},xDays:{one:`1 jour`,other:`{{count}} jours`},aboutXWeeks:{one:`environ 1 semaine`,other:`environ {{count}} semaines`},xWeeks:{one:`1 semaine`,other:`{{count}} semaines`},aboutXMonths:{one:`environ 1 mois`,other:`environ {{count}} mois`},xMonths:{one:`1 mois`,other:`{{count}} mois`},aboutXYears:{one:`environ 1 an`,other:`environ {{count}} ans`},xYears:{one:`1 an`,other:`{{count}} ans`},overXYears:{one:`plus d’un an`,other:`plus de {{count}} ans`},almostXYears:{one:`presqu’un an`,other:`presque {{count}} ans`}},fv=function(e,t,n){var r,i=dv[e];return r=typeof i==`string`?i:t===1?i.one:i.other.replace(`{{count}}`,String(t)),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?`dans `+r:`il y a `+r:r},pv={date:Lr({formats:{full:`EEEE d MMMM y`,long:`d MMMM y`,medium:`d MMM y`,short:`dd/MM/y`},defaultWidth:`full`}),time:Lr({formats:{full:`HH:mm:ss zzzz`,long:`HH:mm:ss z`,medium:`HH:mm:ss`,short:`HH:mm`},defaultWidth:`full`}),dateTime:Lr({formats:{full:`{{date}} 'à' {{time}}`,long:`{{date}} 'à' {{time}}`,medium:`{{date}}, {{time}}`,short:`{{date}}, {{time}}`},defaultWidth:`full`})},mv={lastWeek:`eeee 'dernier à' p`,yesterday:`'hier à' p`,today:`'aujourd’hui à' p`,tomorrow:`'demain à' p'`,nextWeek:`eeee 'prochain à' p`,other:`P`},hv={code:`fr`,formatDistance:fv,formatLong:pv,formatRelative:function(e,t,n,r){return mv[e]},localize:{ordinalNumber:function(e,t){var n=Number(e),r=t?.unit;return n===0?`0`:n+(n===1?r&&[`year`,`week`,`hour`,`minute`,`second`].includes(r)?`ère`:`er`:`ème`)},era:Vr({values:{narrow:[`av. J.-C`,`ap. J.-C`],abbreviated:[`av. J.-C`,`ap. J.-C`],wide:[`avant Jésus-Christ`,`après Jésus-Christ`]},defaultWidth:`wide`}),quarter:Vr({values:{narrow:[`T1`,`T2`,`T3`,`T4`],abbreviated:[`1er trim.`,`2ème trim.`,`3ème trim.`,`4ème trim.`],wide:[`1er trimestre`,`2ème trimestre`,`3ème trimestre`,`4ème trimestre`]},defaultWidth:`wide`,argumentCallback:function(e){return e-1}}),month:Vr({values:{narrow:[`J`,`F`,`M`,`A`,`M`,`J`,`J`,`A`,`S`,`O`,`N`,`D`],abbreviated:[`janv.`,`févr.`,`mars`,`avr.`,`mai`,`juin`,`juil.`,`août`,`sept.`,`oct.`,`nov.`,`déc.`],wide:[`janvier`,`février`,`mars`,`avril`,`mai`,`juin`,`juillet`,`août`,`septembre`,`octobre`,`novembre`,`décembre`]},defaultWidth:`wide`}),day:Vr({values:{narrow:[`D`,`L`,`M`,`M`,`J`,`V`,`S`],short:[`di`,`lu`,`ma`,`me`,`je`,`ve`,`sa`],abbreviated:[`dim.`,`lun.`,`mar.`,`mer.`,`jeu.`,`ven.`,`sam.`],wide:[`dimanche`,`lundi`,`mardi`,`mercredi`,`jeudi`,`vendredi`,`samedi`]},defaultWidth:`wide`}),dayPeriod:Vr({values:{narrow:{am:`AM`,pm:`PM`,midnight:`minuit`,noon:`midi`,morning:`mat.`,afternoon:`ap.m.`,evening:`soir`,night:`mat.`},abbreviated:{am:`AM`,pm:`PM`,midnight:`minuit`,noon:`midi`,morning:`matin`,afternoon:`après-midi`,evening:`soir`,night:`matin`},wide:{am:`AM`,pm:`PM`,midnight:`minuit`,noon:`midi`,morning:`du matin`,afternoon:`de l’après-midi`,evening:`du soir`,night:`du matin`}},defaultWidth:`wide`})},match:{ordinalNumber:Kr({matchPattern:/^(\d+)(ième|ère|ème|er|e)?/i,parsePattern:/\d+/i,valueCallback:function(e){return parseInt(e)}}),era:Ur({matchPatterns:{narrow:/^(av\.J\.C|ap\.J\.C|ap\.J\.-C)/i,abbreviated:/^(av\.J\.-C|av\.J-C|apr\.J\.-C|apr\.J-C|ap\.J-C)/i,wide:/^(avant Jésus-Christ|après Jésus-Christ)/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/^av/i,/^ap/i]},defaultParseWidth:`any`}),quarter:Ur({matchPatterns:{narrow:/^T?[1234]/i,abbreviated:/^[1234](er|ème|e)? trim\.?/i,wide:/^[1234](er|ème|e)? trimestre/i},defaultMatchWidth:`wide`,parsePatterns:{any:[/1/i,/2/i,/3/i,/4/i]},defaultParseWidth:`any`,valueCallback:function(e){return e+1}}),month:Ur({matchPatterns:{narrow:/^[jfmasond]/i,abbreviated:/^(janv|févr|mars|avr|mai|juin|juill|juil|août|sept|oct|nov|déc)\.?/i,wide:/^(janvier|février|mars|avril|mai|juin|juillet|août|septembre|octobre|novembre|décembre)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^av/i,/^ma/i,/^juin/i,/^juil/i,/^ao/i,/^s/i,/^o/i,/^n/i,/^d/i]},defaultParseWidth:`any`}),day:Ur({matchPatterns:{narrow:/^[lmjvsd]/i,short:/^(di|lu|ma|me|je|ve|sa)/i,abbreviated:/^(dim|lun|mar|mer|jeu|ven|sam)\.?/i,wide:/^(dimanche|lundi|mardi|mercredi|jeudi|vendredi|samedi)/i},defaultMatchWidth:`wide`,parsePatterns:{narrow:[/^d/i,/^l/i,/^m/i,/^m/i,/^j/i,/^v/i,/^s/i],any:[/^di/i,/^lu/i,/^ma/i,/^me/i,/^je/i,/^ve/i,/^sa/i]},defaultParseWidth:`any`}),dayPeriod:Ur({matchPatterns:{narrow:/^(a|p|minuit|midi|mat\.?|ap\.?m\.?|soir|nuit)/i,any:/^([ap]\.?\s?m\.?|du matin|de l'après[-\s]midi|du soir|de la nuit)/i},defaultMatchWidth:`any`,parsePatterns:{any:{am:/^a/i,pm:/^p/i,midnight:/^min/i,noon:/^mid/i,morning:/mat/i,afternoon:/ap/i,evening:/soir/i,night:/nuit/i}},defaultParseWidth:`any`})},options:{weekStartsOn:1,firstWeekContainsDate:4}},gv=/{value:([^}]+)}/,_v=/%([aAdewbBmyYHkIlMpPSL])+/g,vv={Second:{Period:`PT1S`,Multipliers:[.01,.02,.05,.1,.2,.5,1,2,5,10,15,30]},Minute:{Period:`PT1M`,Multipliers:[1,2,5,10,15,30]},Hour:{Period:`PT1H`,Multipliers:[1,2,3,4,6,8,12]},Day:{Period:`P1D`,Multipliers:[1,2]},Week:{Period:`P1W`,Multipliers:[1,2]},Month:{Period:`P1M`,Multipliers:[1,2,3,4,6]},Year:{Period:`P1Y`,Multipliers:[1,2,5,10,25,50,100,250]}};function yv(){let e=Object.keys(vv);return vv.Day.Multipliers[0]===1&&e.forEach(e=>{let t=vv[e],n=yt(t.Period);t.One=1*n,t.Multipliers=t.Multipliers.map(e=>e*n)}),vv}function bv(e){switch(e.agg.unit){case g.Tick:return new Av(e);case g.Intraday:return new Mv(e,e.agg.size);case g.Day:return new Nv(e);case g.Week:return new Pv(e);case g.Month:case g.Quarter:return new Fv(e);case g.Year:return new Iv(e);default:throw Error(`Aggregation unit ${g[e.agg.unit]} not supported.`)}}var xv=/* @__PURE__ */ new Map;function Sv(e){if(!N(e))return null;if(!xv.has(e)){let t=Cv(e);xv.set(e,t)}return xv.get(e)}function Cv(e){return N(e)?e.replace(gv,(e,t)=>t.replace(_v,(e,t)=>z.PHP_TO_UNICODE_TS_35_MAP[t])):e}var wv=class{barWidth;unitWidth;minTickInterval;duration;format;prevDate;size;constructor({barWidth:e,unitWidth:t,formatString:n,minTickInterval:r,duration:i},a){this.size=a,this.barWidth=e,this.unitWidth=t,this.minTickInterval=r,this.duration=i,this.format=Sv(n),this.prevDate=null}get noPrevDate(){return!N(this.prevDate)}formatDate(e,t){return Gv(e,this.format||t)}asTick(e,t,n){return this.prevDate=e,{date:e,priority:t,text:this.formatDate(e,n)}}checkPrev(e){return this.noPrevDate?(this.prevDate=e,!0):!1}},Tv=`yyyy`,Ev=`LLL ''yy`,Dv=()=>Wv()?`d LLL`:`LLL d`,Ov=`EEE`,kv=`HH:mm`,Av=class extends wv{repeatEach;repeatCounter;constructor(e){super(e),this.repeatEach=z.TIME_SCALE_MAX_SPACE_NO_TICKS/this.barWidth,this.repeatCounter=0}asTick(e,t,n){return this.repeatCounter=0,super.asTick(e,t,n)}getTick(e){if(!Ln(this.prevDate,e))return this.asTick(e,1,Ov);if(!fi(this.prevDate,e))return this.asTick(e,2,kv);this.repeatCounter++;let t=this.repeatCounter===this.repeatEach;return!mi(this.prevDate,e)||t?this.asTick(e,t?4:3,kv):null}},jv=e=>er(e,Sn(e)),Mv=class extends wv{getTick(e){let t=this.checkPrev(e),n=this.minTickInterval===0||jv(e)%(this.minTickInterval/1e3)==0,r=!Ln(this.prevDate,e),i=ai(e),a=!fi(this.prevDate,e)||t&&i===0;if(n){if(r)return this.asTick(e,1,Dv());if(a)return this.asTick(e,2,kv);if(i%30==0&&this.size<15)return this.asTick(e,3,kv);if(i%15==0&&this.size<=5)return this.asTick(e,4,kv)}return null}},Nv=class extends wv{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<22*vv.Day.One,this.monthYear=this.duration>22*vv.Day.One&&this.duration<7*vv.Month.One,this.year=this.duration>7*vv.Month.One}useGap(e,t){return t!==null&&Wn(e,t)>1728e5}getTick(e){let t=this.prevDate,n=this.checkPrev(e),r=!n&&!hi(e,t),i=!n&&!_i(e,t);return this.monthDay&&(ri(e)===1||this.useGap(e,t))?this.asTick(e,1,Dv()):this.monthYear&&r?this.asTick(e,1,Ev):this.year&&i?this.asTick(e,1,Tv):(this.prevDate=e,null)}},Pv=class extends wv{monthDay;monthYear;year;constructor(e){super(e),this.monthDay=this.duration<4*vv.Week.One,this.monthYear=this.duration>4*vv.Week.One&&this.duration<6*vv.Month.One,this.year=this.duration>6*vv.Month.One}getTick(e){this.checkPrev(e);let t=!hi(e,this.prevDate),n=!_i(e,this.prevDate);return this.monthDay?this.asTick(e,1,Dv()):this.monthYear?t?this.asTick(e,1,Ev):null:this.year&&n?this.asTick(e,1,Tv):null}},Fv=class extends wv{showMonths;constructor(e){super(e),this.showMonths=this.duration<7*vv.Month.One}getTick(e){this.checkPrev(e);let t=!_i(e,this.prevDate);return this.showMonths?this.asTick(e,1,Ev):t?this.asTick(e,1,Tv):null}},Iv=class extends wv{constructor(e){super(e)}getTick(e){return this.checkPrev(e),_i(e,this.prevDate)?null:this.asTick(e,1,Tv)}};function Lv(e){return Kg(e).toString()}function Rv(e){return N(e)?`${e.toFixed(2)}%`:``}function zv(e,t,n=!1){let r=e.plots[0],i=r.curves[0],a=N(i)&&i.fields.length>0?i.fields[0]:null;if(!N(a))return``;let o={range:e.fullDomain,allDigits:!1,forceTrailingZeros:n};return Sy(r,e.pane.presenter,o),r.metaData.format(t,a,o)}function Bv(e,t,n=!1){return e.comparison===x.Percent?Rv(t):zv(e,t,n)}function Vv(e,t,n){let r=e.view?.xAxis?.overrideFormatter;if(r)return r(t);let i=e.display.xAxis.isOrdinal;if(N(i))return Lv(t);let a=n||e.display.xAxis.format;if(N(a))return Gv(t,Sv(a));let o=e.data.aggregation,s=e.display?.xAxis?.nonEodLabelWithDate??!1;return o.isEndOfDay?Kv(o,t):qv(o,t,s)}function Hv(){let e=$().config,t=it(e,null,`overrides`,`xAxis`,`getLocaleName`);if(N(t)&&typeof t==`function`)try{return t()}catch(e){F(`Failed retrieving the locale name, error is ${e.message}`,`warn`)}}function Uv(){switch(Hv()){case`fr`:return{locale:hv};default:return}}function Wv(){switch(Hv()){case`fr`:return!0;default:return!1}}function Gv(e,t){return $r(e,t,Uv())}function Kv(e,t){if(!zn(t))return``;switch(e.unit){case g.Tick:case g.Intraday:case g.Day:case g.Week:default:return Gv(t,`P`);case g.Month:return Gv(t,`LLL yyyy`);case g.Quarter:return Gv(t,`qqq yyyy`);case g.Year:return Gv(t,`yyyy`)}}function qv(e,t,n){return zn(t)?Gv(t,`${n?`P `:``} ${e.isTick?`pp`:`p`}`):``}var Jv=(e,t)=>e.at(t),Yv=class{presenter;_dates=[];pendingRebuild=!1;constructor(e){this.presenter=e,this._dates=[],this.invalidate()}checkRebuild(){this.pendingRebuild&&this.rebuild()}get withPrologLength(){return this.checkRebuild(),this._dates.length+z.TIMELINE_PROLOG_PADDING_BARS}get withPrologEpilogLength(){return this.withPrologLength+z.TIMELINE_EPILOG_PADDING_BARS}get firstSeriesIndex(){return z.TIMELINE_PROLOG_PADDING_BARS}get lastSeriesIndex(){return this.checkRebuild(),this._dates.length===0?0:this.withPrologLength-1}get withoutPrologEpilogLength(){return this.checkRebuild(),this._dates.length}at(e){if(this.checkRebuild(),e<0||e>=this.withPrologEpilogLength)return null;if(e<z.TIMELINE_PROLOG_PADDING_BARS){let t=we(this._dates),n=e-z.TIMELINE_PROLOG_PADDING_BARS;return this.applyDateShift(t,n)}if(e>=this.withPrologLength){let t=Ce(this._dates),n=e-this.withPrologLength+1;return this.applyDateShift(t,n)}return this._dates[e-z.TIMELINE_PROLOG_PADDING_BARS]}get length(){return this.checkRebuild(),this._dates.length>0?this.withPrologEpilogLength:0}slice(e,t){this.checkRebuild();let n=[];for(let r=e;r<t;++r)n.push(this.at(r));return n}tryToCorrectLastBar(e,t,n=!0){n&&this.checkRebuild();let r=+e,i=A(this._dates,r,Number),a=+this._dates[i];return i===this._dates.length-1&&a===r&&(this._dates[i]=t,!0)}mergeDateIntoTimeline(e,t=!0){t&&this.checkRebuild();let n=+e,r=A(this._dates,n,Number),i=+this._dates[r];if(i!==n){let t=r+ +(n>i);return this._dates.splice(t,0,e),t+this.firstSeriesIndex}return-1}invalidate(){this._dates.length=0,this.pendingRebuild=!0}rebuild(){if(this.presenter.isEmpty)return;let e=this.presenter.mainPlot.timeSeries;if(!e.hasData)return;let t=e.container.getTimeData();for(let e=t.length-1;e>=0;e--)this._dates[e]=t[e];this.presenter.allPlots.forEach(t=>{t.timeSeries!==e&&t.timeSeries.hasData&&t.timeSeries.container.getTimeData().forEach(e=>this.mergeDateIntoTimeline(e,!1))}),this.pendingRebuild=!1}applyDateShift(e,t){let{unit:n,size:r}=this.presenter.data.aggregation;switch(n){case g.Year:return hn(e,t*12);case g.Quarter:return hn(e,t*3);case g.Month:return hn(e,t);case g.Week:return mn(e,t*7);case g.Day:return this.addTradingDays(e,t);case g.Intraday:return _n(e,r*t*z.ONE_MINUTE_MILLIS);case g.Tick:return _n(e,t*1e3)}}addTradingDays(e,t){if(this.presenter.display?.xAxis?.isOrdinal||!e||!Number.isFinite(t)||!Number.isInteger(t))return mn(e,t);let n=t>0?1:-1;if(t===0){let t=e.getDay();return t===0?mn(e,1):t===6?mn(e,2):e}let r=Math.abs(t),i=e,a=i.getDay();if(n>0?a===0?(i=mn(i,1),r--):a===6&&(i=mn(i,2),r--):a===0?(i=mn(i,-2),r--):a===6&&(i=mn(i,-1),r--),r<=0)return i;let o=Math.trunc(r/5);o>0&&(i=mn(i,o*7*n),r-=o*5);let s=14;for(;r>0;){if(--s<0)return mn(e,t);i=mn(i,n),a=i.getDay(),a!==0&&a!==6&&r--}return i}},Xv={delete:`<path d="M225.8 286.2l225.8 225.8-225.8 225.8c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3l-225.8-225.8 225.8-225.8c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>`,circle:`<circle cx="512" cy="512" r="512"/>`,rectangle:`<rect width="1024" height="1024"/>`,chevronUp:`<path d="M798.2 609.8l-256.0-256.0c-16.7-16.7-43.7-16.7-60.3 0.0l-256.0 256.0c-16.7 16.7-16.7 43.7 0.0 60.3s43.7 16.7 60.3 0.0l225.8-225.8 225.8 225.8c16.7 16.7 43.7 16.7 60.3 0.0s16.7-43.7 0.0-60.3z"></path>`,chevronDown:`<path d="M225.8 414.2l256.0 256.0c16.7 16.7 43.7 16.7 60.3 0.0l256.0-256.0c16.7-16.7 16.7-43.7 0.0-60.3s-43.7-16.7-60.3 0.0l-225.8 225.8-225.8-225.8c-16.7-16.7-43.7-16.7-60.3 0.0s-16.7 43.7 0.0 60.3z"></path>`,eye:`<path d="M950.9 411.4q-86.9 134.9-217.7 201.7 34.9-59.4 34.9-128.6 0.0-105.7-75.1-180.9t-180.9-75.1-180.9 75.1-75.1 180.9q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 76.0-117.1 190.6-186.6t248.3-69.4 248.3 69.4 190.6 186.6zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM1024.0 411.4q0.0-19.4-11.4-39.4-80.0-131.4-215.1-210.6t-285.4-79.1-285.4 79.4-215.1 210.3q-11.4 20.0-11.4 39.4t11.4 39.4q80.0 130.9 215.1 210.3t285.4 79.4 285.4-79.4 215.1-210.3q11.4-20.0 11.4-39.4z"></path>`,eyeSlash:`<path d="M317.1 197.1l44.6 80.6q-49.7 36.0-77.7 90.9t-28.0 116.0q0.0 69.1 34.9 128.6-130.9-66.9-217.7-201.7 95.4-147.4 244.0-214.3zM539.4 630.9q0.0 11.4-8.0 19.4t-19.4 8.0q-71.4 0.0-122.6-51.1t-51.1-122.6q0.0-11.4 8.0-19.4t19.4-8.0 19.4 8.0 8.0 19.4q0.0 49.1 34.9 84.0t84.0 34.9q11.4 0.0 19.4 8.0t8.0 19.4zM746.9 740.0q0.0-4.0-0.6-5.1-60.0-107.4-180.0-323.4t-180.6-324.0l-28.0-50.9q-5.7-9.1-16.0-9.1-6.9 0.0-76.6 40.0-9.1 5.7-9.1 16.0 0.0 6.9 25.1 49.7-81.7 37.1-150.6 98.9t-119.1 140.0q-11.4 17.7-11.4 39.4t11.4 39.4q87.4 134.3 217.1 212.0t283.4 77.7q50.9 0.0 102.9-9.7l30.9 55.4q5.7 9.1 16.0 9.1 2.9 0.0 10.3-3.4t17.7-8.9 18.9-10.6 18.0-10.6 11.1-6.6q9.1-5.7 9.1-15.4zM768.0 484.6q0.0-79.4-45.1-144.9t-119.4-94.0l160.0 286.9q4.6-25.7 4.6-48.0zM1024.0 411.4q0.0-20.0-11.4-39.4-22.3-36.6-62.3-82.9-85.7-98.3-198.6-152.6t-239.7-54.3l42.3 75.4q121.1 10.3 224.3 78.3t172.3 175.4q-65.7 102.3-161.1 168.0l36.0 64.0q54.3-36.6 104.3-87.4t82.6-105.1q11.4-19.4 11.4-39.4z"></path>`,moreActions:`<path d="M597.3 512a85.3 85.3 0 1 0-170.6 0 85.3 85.3 0 0 0 170.6 0zm298.7 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0zm-597.3 0a85.3 85.3 0 1 0-170.7 0 85.3 85.3 0 0 0 170.7 0z"></path>`};function Zv(e){return $().config.useAllFieldsForComparison===!0&&e.mainPlot.mainCurve.isOhlc&&e.mainAxis.comparison===x.None&&e.mainPane.axes.map(e=>e.plots).flat().reduce((e,t)=>e+ +!!t.isSymbol,0)>1}function Qv(e){let t=ua(e,`div`);sa(t,{class:z.SVG_ICONS_DOM_NODE}),t.innerHTML=`<svg style="display:none" xmlns="http://www.w3.org/2000/svg" version="1.1"><defs>${Object.keys(Xv).map(e=>`<symbol id="${ry(e)}" viewBox="0 0 1024 1024">${Xv[e]}</symbol>`).join(``)}</defs></svg>`}var $v=new yd;function ey({plots:e,isMultiSymbol:t,isMultiContract:n,date:r,time:i,dateFieldName:a,hideSymbols:o,revealingClose:s}){let c=e=>{let r=e.name?.startsWith(z.FAKE_SYMBOL_PREFIX)??!1;switch(e.type){case S.Expression:return!0;case S.Study:return!e.isMain;case S.Symbol:return(t||n)&&!r?!0:!o;default:return!1}},l=o&&s,u=[ly(a,r,null,`heading`),i?ly(`Time`,i,null,`heading`):``],d=e.map(e=>{if(e.isHidden||e.values.length===0)return null;let t=c(e),n=t&&e.type===S.Study,r=t&&!n?uy(S[e.type],e.name,e.values[0].color):``,i=n?dy(e.name,e.values):e.values.map(t=>ly(t.id===W.Close.id&&l?e.description:t.longName,t.value,t.color));if(e.events&&e.events.length){let t=e.events.map(e=>uy(`${e.field.name} (${Kv($v,e.date)})`,e.value,e.color));i.push(...t)}return N(e.actualSymbol)&&e.actualSymbol!==e.name&&i.unshift(ly(`Contract`,e.actualSymbol,e.values[0].color)),i.unshift(r),N(e.unalignedDate)&&i.unshift(ly(`Date`,e.unalignedDate,e.values[0].color,`heading`)),i}).filter(e=>e!=null).flat();return`<table class="values-table">${u.concat(d).filter(e=>e!==``).join(``)}</table>`}function ty(e,{panes:t,date:n,time:r,isMultiSymbol:i},a=!1,o=!1,s=!1,c=!1,l=!1,u=!1){return t.map((d,f)=>{let p=a?d.plots:d.plots.filter(e=>!e.isMain),m=e.mainPlot.axis.pane.id===d.id,h=at(`${n} ${r||``}`),g=`${s&&m?`<span class="field-name" style="padding-right:5px">${h}</span>`:``}${p.map(t=>ny(t,o,m,i,c,l,u,e)).join(``)}`,_=hy(f,t.length);return{id:`bc-tip-${d.id.substring(0,8)}`,isMainPane:m,content:g,moveContent:_,bounds:d.bounds}})}function ny(e,t,n,r,i,a,o,s){let{uid:c,name:l,actualSymbol:u,type:d,error:f,description:p,values:m,events:h,isMain:g,seasonalOffset:_}=e,v=s.display.tooltip,y=f||p,b=`value-title${g?` value-main`:``}`,x=S[d],ee=x!==`Seasonal`||_===0||!N(_),C=[`Study`,`BalanceSheet`,`IncomeStatement`].includes(x)||[`Symbol`,`Expression`,`Seasonal`].includes(x)&&!g,w=ee&&C&&(!s.hasLegend||!n)?my(c):``,te=ee?ay(c,e.visible):``,T=o&&ee?oy(c):``,E=Zv(s)&&e.type===S.Symbol,ne=(g||E)&&(!r||e.values.length>1),re=e=>ne?e.abbreviation:e.id===`Close`&&a?p+` `:null,ie=t&&!e.isHidden?m.map(e=>py(re(e),e.value,e.color)).join(` `)+cy(h):``,ae=e=>`<div class="box" style="background-color:${ot(e.color)}"></div>`,oe=!g&&x!==`Expression`,D=m.slice(0,oe?m.length:1).map(ae).join(``),se=t?``:D,ce=v.mainTitle===`Name`?l:p,le=i?!e.isHidden&&t?``:`${p}`:`${ce}`,ue=r&&E?`${p} (${le})`:le;v.showMainTitle||(ue=``);let de=at(ue),fe=v.showMainTitle?[ue===l?null:l,u&&u!==l?u:null].filter(Boolean):[],pe=at(fe.join(` · `)),me=fe.length>0?`<span class="field-name" style="padding-left:5px">${pe}</span>`:``,he=e.isMain&&ee?(()=>{let e=s.data?.aggregation.toShortString(),t=s.data?.aggregation.describe();return`<span class="value-main" title="${ot(t??``)}">·${at(e??``)}·</span>`})():``;return`
|
|
22
22
|
<div class="plot">
|
|
@@ -34,9 +34,9 @@ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=
|
|
|
34
34
|
<td class="field-name">${at(e)}</td>
|
|
35
35
|
<td class="field-value">${t.join(` `)}</td>
|
|
36
36
|
</tr>
|
|
37
|
-
`}function py(e,t,n){let r=typeof n==`string`?ot(n):null,i=r===null?``:` style="color: ${r}"`,a=N(e)?at(e):null;return`${a===null?``:`<span class="field-name">${a}</span>`}<span${i} class="field-value">${at(t)}</span>`}function my(e){return`<a class="delete-plot" data-plot-uid="${ot(e)}" title="Delete plot">${iy(`delete`)}</a>`}function hy(e,t){let n=e>0,r=e<t-1;return[`${n?sy(!0,e):``}`,`${r?sy(!1,e):``}`].join(` `).trim()}function gy(e,t){return e.startsWith(z.FAKE_SYMBOL_PREFIX)&&t.length>0?t:e}function _y(e){if(!e.isStudy)return null;let t=e;return t.getStandalonePaneBasisTitle()?t.getStandalonePaneTitle():null}function vy(e,t,n,r,i,a){let o=yy(e,t);o.offset=n,o.lastBarRefresh=!!r||!1,o.chartId=e.elementId;let s=n=>n.axes.map(e=>e.plots).flat().filter(t=>!i||t===e.mainPlot).map(n=>Cy(e,t,a,o,n)).filter(e=>e!==null);return o.panes=e.panes.map(e=>({bounds:by(e),id:e.id,plots:s(e)})),o}function yy(e,t){let n=e.data.aggregation,r=e.display.xAxis,i=r.isOrdinal,a=M(i)&&i,o=a?r.ordinalName??`Value`:`Date`;return{date:a?Lv(t):Kv(n,t),time:n.isEndOfDay||a?null:qv(n,t,!1),isMultiSymbol:wy(e),isMultiContract:n.isMultiContract,dateFieldName:o}}function by(e){let t=e.getBounds();if(!N(t))return;let{x:n,y:r,width:i,height:a}=t,{leftOffset:o,rightOffset:s}=e.presenter.view;return{top:r,left:n+o,right:s,bottom:r+a,width:i,height:a}}function xy(e,t,n,r=!1){let i=e.plot,a=i.timeSeries.container,o=i.axis.pane.presenter.timeline,s=A(o,+n,Number,Jv),c=o.at(s-e.shift);if(c===null)return[null,0];let l=a.getTimeData(),u=A(l,+c,Number);return[!l[u]||l[u].getTime()!==c.getTime()?null:e.dataAt(t,u,!r),u]}function Sy(e,t,n){N(e.precision)?n.overridePrecision=e.precision:e.isStudy&&N(t.mainPlot?.precision)&&!N(Lc(e.model.study).meta.decimals)&&(n.overridePrecision=t.mainPlot.precision)}function Cy(e,t,n,{isMultiContract:r},i){let a=i.isStudy;if(!i.timeSeries.hasData)return null;let o=i.timeSeries.container;i.type,S.Expression;let s=i.axis.comparison!==x.None,c=i.axis.comparison===x.Percent,l=(e,r)=>i.customPlotValues&&r!==W.DateTime?[i.getValueAt(r,t,n),0]:xy(e,r,t,s),u=i,d=_y(i)??i.title,f=a?`${Lc(u.model.study).meta.title} ${u.fullParams}`:i.metaData.name||``,p={isMain:i.main,type:i.type,typeName:S[i.type],name:gy(d,i.metaData.symbol),description:f,exchange:i.metaData.exchange||``,error:u.errorText,id:i.id,uid:i.uid,visible:i.visible,isHidden:!i.isVisible,seasonalOffset:i.isSeasonal?u.offset??void 0:void 0};if(N(u.yearOffset)&&u.yearOffset!=0){let n=e.data.aggregation;p.unalignedDate=Kv(n,xi(t,u.yearOffset))}let m=i.curves[0],g=i.type===S.Symbol&&Wi(i.title);if(r&&i.type===S.Symbol&&o.hasField(W.Symbol)){let e=t.valueOf()===z.ZERO_DATE.valueOf()?i.timeSeries.container?.getLastDataPoint(W.Symbol):l(m,W.Symbol)[0];N(e)&&e.length>0&&(p.actualSymbol=e,g||(p.name=e))}let _={},v={range:i.axis.yScale.domain(),allDigits:!0};Sy(i,e,v);let y=(e,t)=>{let n=(t===W.Change||t===W.PercentChange)&&e>0?`+`:``;return c?n+Rv(e):n+i.metaData.format(e,t,v)},b=Zv(e),ee=/* @__PURE__ */ new Set;return p.values=i.curves.filter(e=>e.visible).map(e=>(!i.main&&i.isSymbol&&b?g_:e.fields).map(t=>{if(ee.has(t))return null;ee.add(t);let[n,r]=l(e,t),o=i.axis.yScale.priceToY(n);_[t.id]=!0;let s=i.customPlotValues?u.getColorOf(t):e.getColor(r,e.style!==h.HollowCandles,t),c=y(n,t).trim();if(N(n)&&t===W.Change){let[t]=l(e,W.PercentChange);N(t)&&(c+=` (${y(t,W.PercentChange)})`)}return{abbreviation:Ty(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${a?u.params:``}`.trim(),color:Ho(s),val:n,y:o,value:c}}).filter(e=>e!==null)).flat(),p.events=i.findEvents(l(m,W.DateTime)).filter(e=>e.field!==W.Custom),p}function wy(e){let t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===S.Symbol&&e.symbol!==t)}function Ty(e){return e.id===W.Change.id?`Δ`:e.id.substring(0,1)}function Ey(e,t,n){let r=N(t),i=N(n),a,o,s=e.pane.getBounds();if(!r)a=e.priceToY(n),o=new rs(s.x,a,s.width,s.y+s.height-a);else if(!i)a=e.priceToY(t),o=new rs(s.x,s.y,s.width,a-s.y);else{let r=e.priceToY(t),i=e.priceToY(n);a=(r+i)/2,o=new rs(s.x,i,s.width,r-i)}return[a,o]}var Dy=(e,t)=>{let n=qo(.6)(e),r=Jo(.6)(e),i=t===`linLighten`;return[i?r:n,e,i?n:r]};function Oy(e,t,n,r,i=!1,a){let o;e.zones.forEach((s,c)=>{let l=s.value,[u,d]=Ey(e,o,l);t.save(),ns(t,d),i&&(n.range=[null,u]);let f=e.zoneColors[c];if(s.gradient){let e=Dy(f,s.gradient),n=t.createLinearGradient(0,d.y,0,d.y+d.height);n.addColorStop(0,e[0]),n.addColorStop(.5,e[1]),n.addColorStop(1,e[2]),f=n}else N(a)&&(f=a(c,f));r(e,t,n,f),t.restore(),o=l})}function ky(e,t,{bar:n,slice:r},i){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=a+(r[1]-r[0])*n.totalWidth,s=i+n.totalWidth/2;return t.x<a-s||t.x>o+s}function Ay(e,t,n,r=1){let i=e.view.xAxis.xScale.xToIndex(t.x)??n.slice[0];return{from:Math.max(n.slice[0]-1,i-r),to:Math.min(n.slice[1]+1,i+r)}}function jy(e,t,n,r,i,a){let o=Math.min(t,t+r)-a,s=Math.max(t,t+r)+a,c=Math.min(n,n+i)-a,l=Math.max(n,n+i)+a;return e.x>=o&&e.x<=s&&e.y>=c&&e.y<=l}function My(e,t,n,r,i,a){let o=r-t,s=i-n,c=e.x-t,l=e.y-n;if(o===0&&s===0)return Math.abs(c)<=a&&Math.abs(l)<=a;let u=o*o+s*s,d=(c*o+l*s)/u,f=Math.max(0,Math.min(1,d)),p=t+f*o,m=n+f*s,h=e.x-p,g=e.y-m;return h*h+g*g<=a*a}function Ny(e,t,n,r){return e.x>=Math.min(t.x,n.x)-r&&e.x<=Math.max(t.x,n.x)+r}function Py(e,t,n,r){return e.y>=Math.min(t,n)-r&&e.y<=Math.max(t,n)+r}function Fy(e,t,n){let r=n.x-t.x;if(r===0)return n.y;let i=(e-t.x)/r;return t.y+(n.y-t.y)*i}function Iy(e,[t,n],r,i){let a=r,o=e.timeSeries.container.size;for(let r=t;r<=n;r++){for(;e.timeSeriesAt(a)<e.timelineAt(r-e.shift)&&a<o;)++a;if(a===o)break;let t=e.timeSeriesAt(a)>e.timelineAt(r-e.shift);i(a,t)}}var Ly={draw(e,t,n){N(e.zones)?Oy(e,t,n,Wy):e.varyColorPerBar?Jy(e,t,n):Wy(e,t,n)},hitTest:By},Ry={draw(e,t,n){N(e.zones)?Oy(e,t,n,Xy):Xy(e,t,n,e.colors[0])},hitTest:Vy},zy={draw:Yy,hitTest:Hy};function By(e,t,n,r){let i=e.pickMainField(),{from:a,to:o}=Ay(e,t,n,z.CONTINUOUS_LINE_HIT_TEST_RADIUS),s=null;for(let n=a;n<=o;n++){let a=e.pointAtTimelineIndex(n,i);if(a!==null){if(s!==null&&My(t,s.x,s.y,a.x,a.y,r))return!0;s=a}}return!1}function Vy(e,t,n,r){let i=e.pickMainField(),{from:a,to:o}=Ay(e,t,n);for(let n=a;n<=o;n++){let a=e.pointAtTimelineIndex(n-1,i),o=e.pointAtTimelineIndex(n,i);if(a===null||o===null)continue;let s={x:o.x,y:a.y};if(My(t,a.x,a.y,s.x,s.y,r)||My(t,s.x,s.y,o.x,o.y,r))return!0}return!1}function Hy(e,t,n,r){let i=e.pickMainField(),a=Math.max(1,e.lineWidth||z.CURVE_STYLE_DOTS_RADIUS)+r,o=a*a,{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let r=e.pointAtTimelineIndex(n,i);if(r===null)continue;let a=t.x-r.x,s=t.y-r.y;if(a*a+s*s<=o)return!0}return!1}function Uy(e,t,n,r,i=1){let a=z.MARKER_SIZE*i,o=a*1.25;switch(r){case`Circle`:e.moveTo(t+a,n),e.arc(t,n,a,0,Math.PI*2);break;case`Square`:e.rect(t-a,n-a,2*a,2*a);break;case`TriangleUp`:e.moveTo(t-o,n+o),e.lineTo(t+o,n+o),e.lineTo(t,n-o),e.lineTo(t-o,n+o);break;case`TriangleDown`:e.moveTo(t-o,n-o),e.lineTo(t+o,n-o),e.lineTo(t,n+o),e.lineTo(t-o,n-o);break;case`Diamond`:e.moveTo(t,n-o),e.lineTo(t+o,n),e.lineTo(t,n+o),e.lineTo(t-o,n),e.lineTo(t,n-o)}}function Wy(e,t,{bar:n,slice:r,start:i},a=null){let o=a||e.getColor(0),s=M(e.lineMarker);s&&(t.fillStyle=o,t.beginPath());let c=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,l=[],u=e.pickMainField();Iy(e,r,i,(r,i)=>{if(!i){let n=e.dataAt(u,r);if(N(n)){let r=e.priceToY(n);s&&Uy(t,c,r,e.lineMarker),l.push({x:c,y:r})}}c+=n.totalWidth}),s&&t.fill(),t.lineWidth=e.lineWidth,e.dashStyle&&t.setLineDash(Vo(e.dashStyle)),M(e.lineSmoothing)?Gy(t,l,o,e.lineSmoothing):qy(t,l,o)}function Gy(e,t,n,r){if(t.length<2)return;let i=Ky(t,r);e.beginPath(),e.strokeStyle=n,e.moveTo(t[0].x,t[0].y);for(let t of i)e.bezierCurveTo(t.cp1x,t.cp1y,t.cp2x,t.cp2y,t.x,t.y);e.stroke()}function Ky(e,t){let n=[];for(let r=0;r<e.length-1;r++){let i=e[r-1]||e[r],a=e[r],o=e[r+1],s=e[r+2]||o,c=a.x+(o.x-i.x)/t,l=a.y+(o.y-i.y)/t,u=o.x-(s.x-a.x)/t,d=o.y-(s.y-a.y)/t;n.push({cp1x:c,cp1y:l,cp2x:u,cp2y:d,x:o.x,y:o.y})}return n}function qy(e,t,n){if(t.length>1){e.beginPath(),e.strokeStyle=n;let r=t[0];e.moveTo(r.x,r.y);for(let n=1;n<t.length;n++){let r=t[n];e.lineTo(r.x,r.y)}e.stroke()}}function Jy(e,t,{bar:n,slice:r,start:i}){t.lineWidth=e.lineWidth,t.lineCap=`square`,e.dashStyle&&t.setLineDash(Vo(e.dashStyle));let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=null,s=null,c=[];Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let n=e.priceToY(i);s=e.getColor(r),o!==s&&(qy(t,c,o),c.length>0&&(c=[c.pop()]),o=s),c.push({x:a,y:n})}}a+=n.totalWidth}),qy(t,c,s)}function Yy(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2;t.fillStyle=e.getColor(0);let o=Math.max(1,e.lineWidth||z.CURVE_STYLE_DOTS_RADIUS),s=Math.PI*2;t.beginPath(),Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let n=e.priceToY(i);t.moveTo(a+o,n),t.arc(a,n,o,0,s)}}a+=n.totalWidth}),t.fill()}function Xy(e,t,{bar:n,slice:r,start:i},a){let o=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,s=Fs();s.prolog(t),t.strokeStyle=a,t.lineWidth=e.lineWidth,e.dashStyle&&t.setLineDash(Vo(e.dashStyle)),t.beginPath();let c=!1,l=null;Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let a=e.priceToY(i);if(c)t.lineTo(o,l),t.lineTo(o,a);else{let i=e.dataAt(n,r-1);if(N(i)){let n=e.priceToY(i);t.moveTo(-1,n),t.lineTo(o,n),t.lineTo(o,a)}else t.moveTo(o,a);c=!0}l=a}}o+=n.totalWidth}),t.stroke(),s.epilog(t)}var Zy={draw(e,t,n){N(e.zones)?Oy(e,t,n,nb,!0):nb(e,t,n,e.colors,!0)},hitTest:tb},Qy={draw:ib,hitTest:tb};function $y(e){let{BaseLevel:t}=ft(e);return{baseLevel:Number.isFinite(t)?St(0,100,t):50}}function eb(e,[t,n]){let{baseLevel:r}=$y(e.plot.inputs);return(t-n)*r/100+n}function tb(e,t,n,r){if(By(e,t,n,r))return!0;let{range:i}=n,a=e.pickMainField(),o=e.isBaseline?eb(e,i):i[1],{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let i=e.pointAtTimelineIndex(n,a),s=e.pointAtTimelineIndex(n+1,a);if(i!==null&&s!==null&&Ny(t,i,s,r)&&Py(t,Fy(t.x,i,s),o,r))return!0}return!1}function nb(e,t,n,r,i=!1){Wy(e,t,n,e.pickAreaStroke(r)),ab(e,t,n,r[0],i)}function rb(e,t,n){let{x:r,width:i}=e.pane.getBoundsWithoutScales();t.save(),t.lineWidth=1,t.strokeStyle=`#888`,t.setLineDash(Vo(`dot`)),vs(t,n,r,r+i),t.restore()}function ib(e,t,n){let[r,i]=n.range,a=eb(e,n.range);e.zones[0].value=e.yToPrice(a),rb(e,t,a),Oy(e,t,n,nb,!0,(e,n)=>{let o=e===1,s=Uo(n,0),c=t.createLinearGradient(0,o?r:i,0,a);return c.addColorStop(0,n),c.addColorStop(1,s),[c,Uo(n,1)]})}function ab(e,t,{bar:n,slice:r,start:i,range:[a,o]},s,c){if(c){let e=t.createLinearGradient(0,a,0,o);e.addColorStop(0,s),e.addColorStop(1,Uo(s,0)),t.fillStyle=e}else t.fillStyle=s;t.beginPath();let l=null,u=e.pickMainField(),d=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,f=!1,p=null;Iy(e,r,i,(r,i)=>{if(!i){let n=e.dataAt(u,r);if(N(n)){let r=e.priceToY(n);f?t.lineTo(d,r):(t.moveTo(l=d,r),f=!0),p=d}}d+=n.totalWidth}),t.lineTo(p,o),t.lineTo(l,o),t.closePath(),t.fill()}var ob={draw(e,t,n){N(e.zones)?Oy(e,t,n,db,!0):db(e,t,{...n,range:[null,null]})},hitTest:cb},sb={draw:ub,hitTest:lb};function cb(e,t,n,r){let{bar:i,slice:a}=n,o=e.view.xAxis.xScale.range()[0],s=e.isMultiColumn,c=s?e.fields.length:1,l=i.width/c,u=s?null:e.pickMainField(),d=e.priceToY(0),{from:f,to:p}=Ay(e,t,n);for(let n=f;n<=p;n++){let f=e.dataIndexAtTimelineIndex(n);if(!N(f))continue;let p=o+i.offset+(n-a[0])*i.totalWidth;for(let n=0;n<c;n++){let i=e.dataAt(s?e.fields[n]:u,f);if(N(i)){let a=e.priceToY(i);if(jy(t,p+n*l,a,l,d-a,r))return!0}}}return!1}function lb(e,t,n,r){let{bar:i,slice:a}=n,o=e.view.xAxis.xScale.range()[0],{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let s=e.dataIndexAtTimelineIndex(n);if(!N(s))continue;let c=o+i.offset+(n-a[0])*i.totalWidth,l=e.priceToY(0),u=0;for(let n=0;n<e.plot.curves.length;n++){let a=e.plot.curves[n];if(!a.visible||!a.isStackedColumn)continue;let o=e.dataAt(a.fields[0],s);if(!N(o))continue;u+=o;let d=e.priceToY(u);if(a===e&&jy(t,c,d,i.width,l-d,r))return!0;l=d}}return!1}function ub(e,t,{bar:n,slice:r,start:i}){if(!e.isFirstVisibleOfStyle())return;let a=e.view.xAxis.xScale.range()[0]+n.offset,o=Fs();o.prolog(t);let s=e.plot.curves.filter(e=>e.isStackedColumn);Iy(e,r,i,(r,i)=>{if(!i){let i=e.priceToY(0),c=0;s.forEach(s=>{if(!s.visible)return;let l=s.fields[0],u=e.dataAt(l,r);if(!N(u))return;c+=u;let d=e.priceToY(c);t.fillStyle=s.getColor(r,!1,l),t.beginPath(),t.rect(o.adjust(a),o.adjust(Math.min(d,i)),o.adjust(n.width),o.adjust(Math.abs(i-d))),t.fill(),i=d})}a+=n.totalWidth}),o.epilog(t)}function db(e,t,{bar:n,slice:r,start:i,range:[a,o]}){let s=e.view.xAxis.xScale.range()[0]+n.offset,c=e.isMultiColumn,l=c?e.fields:[e.pickMainField()],u=n.width/(c?l.length:1),d=Fs();d.prolog(t),Iy(e,r,i,(r,i)=>{i||l.forEach((n,i)=>{let a=e.dataAt(n,r);if(N(a)){N(o)||(o=e.priceToY(0));let c=e.priceToY(a);t.fillStyle=e.getColor(r,!1,n),t.beginPath(),t.rect(d.adjust(s+i*u),d.adjust(Math.min(c,o)),d.adjust(u),d.adjust(Math.abs(o-c))),t.fill()}}),s+=n.totalWidth}),d.epilog(t)}var fb={draw:hb},pb=[W.Open,W.High,W.Low,W.Close],mb=[null,null,null,null];function hb(e,t,{bar:n,slice:r,start:i}){t.lineWidth=Math.max(1,.5*n.width),t.lineJoin=`miter`,t.miterLimit=1.5;let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=Fs();o.prolog(t);let s=null,c=null,l=[];Iy(e,r,i,(r,i)=>{if(!i){let i=t=>pb.map(n=>e.dataAt(n,t)),[u,d,f,p]=i(r),[,m,h]=r<0?mb:i(r-1);if(N(u,d,f,p)){let i=o.adjust(a),g=o.adjust(a-n.totalWidth),_=[u,d,f,p].map(e.priceToY,e).map(o.adjust),v=o.adjust(e.priceToY(d>m?m:h));c=e.getColor(r);let y=N(s)&&s!==c,b=u===d?1:2,x=u===d?2:1;l.push({x:g,y:_[0]}),l.push({x:i,y:_[b]}),y&&(l.push({x:i,y:v}),qy(t,l,s),l=[]),y&&l.push({x:i,y:v}),l.push({x:i,y:_[x]}),s=c}}a+=n.totalWidth}),qy(t,l,c),o.epilog(t)}var gb={draw:yb,hitTest:vb},_b=[W.Open,W.High,W.Low,W.Close];function vb(e,t,n,r){let{bar:i}=n,a=i.width/2,{from:o,to:s}=Ay(e,t,n);for(let n=o;n<=s;n++){let o=e.dataIndexAtTimelineIndex(n);if(!N(o))continue;let s=e.dataAt(W.Open,o),c=e.dataAt(W.High,o),l=e.dataAt(W.Low,o),u=e.dataAt(W.Close,o);if(N(s,c,l,u)){let o=e.view.xAxis.xScale.indexToX(n),d=e.priceToY(s),f=e.priceToY(c),p=e.priceToY(l),m=e.priceToY(u);if(e.isCandle){if(jy(t,o-a,d,i.width,m-d,r)||My(t,o,Math.min(m,d),o,f,r)||My(t,o,Math.max(m,d),o,p,r))return!0}else if(My(t,o,p,o,f,r)||!e.isHlcStyle&&My(t,o-a,d,o,d,r)||My(t,o+a,m,o,m,r))return!0}}return!1}function yb(e,t,{bar:n,slice:r,start:i}){let a=e.presenter.display.chart.showMinMaxArc,o=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,s=Fs();s.prolog(t);let c=null,l=null,u=null,d=null,f=n=>{e.isCandle?(e.isHollowCandles?n.outlineColor=e.getColor(n.ix,!1):(e.colors.length>3&&(n.outlineColor=e.colors[3]),e.colors.length>4&&(n.wickColor=e.colors[4])),Sb(t,n,e.lineWidth)):(e.isOhlcStyle||e.isHlcStyle||e.isElderImpulseSystemStyle||e.isRangeStyle)&&xb(t,n,e.lineWidth,!e.isHlcStyle)};Iy(e,r,i,(t,r)=>{if(!r){let r=_b.map(n=>e.dataAt(n,t)),[i,a,p,m]=r;if(N(i,a,p,m)){let h={x:s.adjust(o),adjust:s.adjust,width:n.width,y:[i,a,p,m].map(e.priceToY,e).map(s.adjust),isMin:!1,isMax:!1,ix:t,color:e.getColor(t)},g=Math.min(...r),_=Math.max(...r);(!N(c)||g<c)&&(c=g,u=h),(!N(l)||_>l)&&(l=_,d=h),f(h)}}o+=n.totalWidth}),a&&(N(u)&&(u.isMin=!0,f(u)),N(d)&&(d.isMax=!0,f(d))),s.epilog(t)}function bb(e,t,n,r,i,a,o,s=3){t&&hs(e,{x:r,y:i+s},o,0,Math.PI),n&&hs(e,{x:r,y:a-s},o,0,Math.PI,!0)}function xb(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,isMin:l,isMax:u},d,f){let p=r/2;e.lineWidth=d,e.strokeStyle=c,e.beginPath(),e.moveTo(t,o),e.lineTo(t,a),f&&(e.moveTo(n(t-p),i),e.lineTo(t,i)),e.moveTo(n(t+p),s),e.lineTo(t,s),e.stroke(),bb(e,l,u,t,o,a,p)}function Sb(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,outlineColor:l,wickColor:u,isMin:d,isMax:f},p){let m=r/2;e.lineWidth=p,e.fillStyle=c,e.strokeStyle=l||c,e.beginPath(),e.rect(n(t-m),Math.min(i,s),r,n(Math.abs(s-i))),e.fill(),e.stroke(),e.strokeStyle=u||l||c,e.beginPath(),e.moveTo(t,Math.min(s,i)),e.lineTo(t,a),e.moveTo(t,Math.max(s,i)),e.lineTo(t,o),e.stroke(),e.strokeStyle=Yo(c).a===0?l:c,bb(e,d,f,t,o,a,m)}var Cb={draw:wb};function wb(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0],o=n.totalWidth/2,s=a+n.offset+n.width/2,c=Fs();c.prolog(t);let l=e.plot.timeSeries.builder.boxSize,u=l/2;Iy(e,r,i,(r,i)=>{if(!i){let[n,i]=[W.High,W.Low].map(t=>e.dataAt(t,r)),a=e.colors[0],d=e.colors[1],f=e.dataAt(W.BARKIND,r),p=q_(f),m=f===z.BARKIND_XO,h=f===z.BARKIND_OX;if(N(n,i))for(let r=n;r>=i;r-=l){let l=c.adjust(s),[f,g]=[l-o,l+o],[_,v,y]=[r,r-u,r+u].map(t=>e.priceToY(t)),b=r===n&&m||r===i&&h?!p:p;t.beginPath(),b?(t.strokeStyle=d,t.moveTo(f,v),t.lineTo(g,y),t.moveTo(f,y),t.lineTo(g,v)):(t.strokeStyle=a,t.ellipse(l,_,o,v-_,0,0,Math.PI*2)),t.stroke()}}s+=n.totalWidth}),c.epilog(t)}var Tb={draw:Eb};function Eb(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2;Iy(e,r,i,(r,i)=>{if(!i){let[i,o]=[W.Open,W.Close].map(t=>e.dataAt(t,r)).map(e.priceToY,e),s=Math.floor(n.totalWidth/2);t.fillStyle=e.getColor(r),t.beginPath(),t.rect(a-s,Math.min(i,o),n.totalWidth,Math.abs(o-i)),t.fill()}a+=n.totalWidth})}var Db={draw(e,t,n){e.varyColorPerBar?Ab(e,t,n):kb(e,t,n,e.colors[0])},hitTest:Ob};function Ob(e,t,n,r){let[i,a]=e.fields,{from:o,to:s}=Ay(e,t,n);for(let n=o;n<=s;n++){let o=e.pointAtTimelineIndex(n,i),s=e.pointAtTimelineIndex(n+1,i),c=e.pointAtTimelineIndex(n,a),l=e.pointAtTimelineIndex(n+1,a);if(o!==null&&s!==null&&c!==null&&l!==null&&Ny(t,o,s,r)&&Py(t,Fy(t.x,o,s),Fy(t.x,c,l),r))return!0}return!1}function kb(e,t,{bar:n,slice:r,start:i},a){t.fillStyle=a;let[o,s]=e.fields,c=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,l=[];if(Iy(e,r,i,(t,r)=>{if(!r){let n=e.dataAt(o,t),r=e.dataAt(s,t);N(n,r)&&l.push({x:c,upY:e.priceToY(n),downY:e.priceToY(r)})}c+=n.totalWidth}),l.length>0){t.beginPath(),t.moveTo(l[0].x,l[0].upY);for(let e=1;e<l.length;++e)t.lineTo(l[e].x,l[e].upY);let e=l.length-1;t.lineTo(l[e].x,l[e].downY);for(let n=e-1;n>=0;--n)t.lineTo(l[n].x,l[n].downY);t.closePath(),t.fill()}}function Ab(e,t,{bar:n,slice:r,start:i}){let[a,o]=e.fields,s=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,c=[],l=e=>{if(c.length>1){t.beginPath(),t.fillStyle=e,t.moveTo(c[0].x,c[0].upY);for(let e=1;e<c.length;++e)t.lineTo(c[e].x,c[e].upY);let n=c.length-1;t.lineTo(c[n].x,c[n].downY);for(let e=n-1;e>=0;--e)t.lineTo(c[e].x,c[e].downY);t.closePath(),t.fill()}},u=null,d=null;Iy(e,r,i,(t,r)=>{if(!r){let n=e.dataAt(a,t),r=e.dataAt(o,t);if(N(n,r)){let i=e.priceToY(n),a=e.priceToY(r);d=e.getColor(t),u!==d&&(l(u),c.length>0&&(c=[c.pop()]),u=d),c.push({x:s,upY:i,downY:a})}}s+=n.totalWidth}),l(d)}var jb=class{plot;id;fields=[];colors=[];style=h.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle=`Solid`;varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=xt(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=N(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(W.Close)}get name(){return this.isOhlc?``:this.fields[0].name}get isHeikinAshiStyle(){return this.style===h.HeikinAshi}get isCandle(){return this.style===h.Candlestick||this.style===h.HollowCandles||this.style===h.HeikinAshi}get isHollowCandles(){return this.style===h.HollowCandles}get isElderImpulseSystemStyle(){return this.style===h.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===h.PercentChange}get isOhlcStyle(){return this.style===h.OHLC}get isHlcStyle(){return this.style===h.HLC}get isRangeStyle(){return this.style===h.Range}get isRenko(){return this.style===h.Renko}get isKagi(){return this.style===h.Kagi}get isPointAndFigure(){return this.style===h.PointAndFigure}get isLineBreak(){return this.style===h.LineBreak}get isBaseline(){return this.style===h.Baseline}get isLineLike(){return[h.Line,h.Area,h.Baseline,h.PercentChange].includes(this.style)}get isColumn(){return this.style===h.Column}get isMultiColumn(){return this.style===h.MultiColumn}get isStackedColumn(){return this.style===h.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>m[e])),this.colors=e.colors,this.fields=e.fields.map(e=>W[e]),this.style=h[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,n=!0){let r=!this.plot.isComparison(x.None),i=e===W.PercentChange,a=e===W.Change,o=i||(!n||r)&&a,s=this.timeSeries.container.hasField(W.Last)?W.Last:W.Close,c=o?s:e,l=(e,t)=>{let n=this.timeSeries.container.getData(e)[t];return e.type===v.Number?this.plot.priceMapper(n,t,e):n},u=l(c,t);if(!o)return u;if(t<=1)return 0;let d=l(c,t-1),f=u-d;return i?d===0?0:f/d:f}timeSeriesAt(e){let t=this.timeSeries.container.getTimeData(),n=t.length;return e<0||e>n-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){let e=this.view.xAxis.xScale;return N(e.extent())?this.shift===0?e.domain():e.extent().map(t=>e.timeline.at(t-this.shift)):null}get yScale(){return this.plot?.yScale??this.axis.yScale}get canHitTest(){return N(Mb(this)?.hitTest)}getCore(){let e=this.timeSeries;if(!e.hasData||!this.visible)return null;let t=this.view.xAxis.xScale.extent();if(!N(t))return null;let n=this.yScale.domain();return N(n)?{ts:e,extent:t,domain:n,range:this.yScale.range()}:null}getDrawInfo(e){let t=e.ts.container.getTimeData(),n=this.shiftedTimeDomain[0];return N(n)?{bar:this.view.xAxis.xScale.bar,domain:e.domain,range:e.range,slice:e.extent,start:A(t,+n,Number)||0}:null}hitTest(e){let t=Mb(this);if(!N(t?.hitTest))return!1;let n=this.getCore();if(n===null)return!1;let r=this.getDrawInfo(n);if(r===null)return!1;let i=z.PLOT_HIT_TEST_TOLERANCE+Math.max(0,this.lineWidth/2);return!ky(this,e,r,i)&&t.hitTest(this,e,r,i)}dataIndexAtTimelineIndex(e){let t=this.timelineAt(e-this.shift);if(!N(t))return null;let n=this.timeSeries.container.getTimeData(),r=A(n,+t,Number),i=n[r];return N(i)&&i.getTime()===t.getTime()?r:null}pointAtTimelineIndex(e,t){let n=this.dataIndexAtTimelineIndex(e);if(!N(n))return null;let r=this.dataAt(t,n);return N(r)?{x:this.view.xAxis.xScale.indexToX(e),y:this.priceToY(r)}:null}drawHover(e,t,n){if(!this.isLineLike||this.getCore()===null)return;let[r,i]=xy(this,this.pickMainField(),t);N(r)&&(e.save(),ns(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=Ho(this.getColor(i)),e.beginPath(),Uy(e,n,this.priceToY(r),this.lineMarker??`Circle`,1.3333),e.fill(),e.restore())}draw(e){let t=this.getCore();if(t===null)return;let n=this.getDrawInfo(t);if(n===null)return;e.save(),e.setLineDash([]);let r=Mb(this);N(r)?r.draw(this,e,n):F(`Drawing of the curve style '${this.style}' is not implemented yet`,`error`),e.restore()}pickMainField(){return this.fields.length===1?this.fields[0]:this.fields.includes(W.Last)?W.Last:this.fields.includes(W.Close)?W.Close:this.fields[0]}get zoneColors(){if(!N(this._zoneColors)){let e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return t===-1&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?Ho(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(W.BARCOLIX))return null;let t=this.dataAt(W.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,n=null){if(this.varyColorPerBar){let n={};if(this.isOhlc||this.isRenko||this.isLineBreak){let t=this.dataAt(W.Open,e),r=this.dataAt(W.High,e),i=this.dataAt(W.Low,e),a=this.dataAt(W.Close,e),o=this.dataAt(W.Change,e);n.open=t,n.high=r,n.low=i,n.close=a,n.change=o}else if(this.plot.isStudy&&![`VOL`,`MAVOL`].includes(this.plot.model.study)){let t=this.pickMainField(),r=this.dataAt(t,e-1),i=this.dataAt(t,e),a=N(r),o=N(i);n.change=a?o?i-r:-1:+!!o}else{let t=this.plot.axis.pane.presenter.data.aggregation;(!t.isTick||t.spec!==_.None)&&(n.open=this.dataAt(W.Open,e),n.close=this.dataAt(W.Close,e)),n.change=this.dataAt(W.Change,e)}let r,i=Nb(this.style,n,this.colors),a=this.getComputedColor(e);switch(this.style){case h.Candlestick:case h.Renko:case h.LineBreak:case h.Range:case h.HeikinAshi:case h.OHLC:case h.HLC:case h.Column:{if(N(a)){r=a;break}let t=i.useSame?i.isUp:i.isUp||i.isSame,n=i.isSame,o=this.attributes||[],s=this.plot.isStudy&&![`HASMO`,`VOL`,`MAVOL`].includes(this.plot.model.study);(o.includes(m.ChangeBased)||s)&&(t=i.useSame?i.isUpPrev:i.isUpPrev||i.isSamePrev,n=i.isSamePrev),r=this.colors[+!!t],i.useSame&&n&&(r=this.colors[2]),(this.isRenko||this.isLineBreak||this.isRangeStyle)&&this.dataAt(W.Projection,e)===1&&(r=qo(.5,!0)(r));break}case h.ElderImpulseSystem:r=this.colors[this.dataAt(W.BREL,e)];break;case h.HollowCandles:{let e=this.colors[i.isUpPrev||i.isSamePrev?1:0];r=t&&(i.isUp||i.isSame)?z.COLOR_TRANSPARENT:e;break}case h.Line:case h.PercentChange:case h.Ribbon:case h.Kagi:if(N(a)){r=a;break}r=this.colors[0];break;case h.PointAndFigure:{let t=+!!q_(this.dataAt(W.BARKIND,e));r=this.colors[t];break}default:throw Error(`Unexpected style ${h[this.style]} for a curve with varying colors`)}return N(r)||(r=this.colors[0]),r}if(this.zones){let t=this.pickMainField(),n=this.dataAt(t,e),r=this.getColorsFromZone(n);return this.style===h.Area?this.pickAreaStroke(r):r.length>0?r[0]:this.colors[0]}return(this.isMultiColumn||this.isStackedColumn)&&N(n)?this.colors[Ae(this.colors,this.fields.findIndex(e=>e===n))]:this.colors[0]}};function Mb(e){return e.isOhlc?gb:e.isRenko||e.isLineBreak?Tb:e.style===h.Ribbon?Db:e.style===h.Area?Zy:e.isColumn||e.isMultiColumn?ob:e.isStackedColumn?sb:e.isBaseline?Qy:e.style===h.Step?Ry:e.isKagi?fb:e.isPointAndFigure?Cb:e.style===h.Dots?zy:e.style===h.Line||e.isPercentChangeStyle?Ly:null}function Nb(e,{open:t,close:n,change:r},i){let a=i.length>2&&e!==h.HLC,o=N(t,n),s=o&&n>t,c=o&&n===t,l=r>0,u=r===0;return{useSame:a,isUp:s,isSame:c,isUpPrev:l,isSamePrev:u,isDown:!s&&!c,isDownPrev:!l&&!u}}function Pb(e){let t=e.duplicate(),n=e;return`disableStreamingUpdates`in n&&(t.disableStreamingUpdates=n.disableStreamingUpdates),`surrogate`in n&&(t.surrogate=n.surrogate),t}var Fb=class e{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;useLastTrade;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,n=C.Normal,r=[null,null]){this.symbol=e,this.aggregation=t,this.range=r,this.seriesKind=n,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(this.curveStyle!==null&&Tc(this.inputs,wc(h[this.curveStyle])),!N(this.curveStyle)||!z.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return`Standard`;switch(this.curveStyle){case h.Renko:{let{method:e,period:t,source:n,brickSize:r}=i_(this.inputs);return`Renko;${e===`ATR`?`ATR;${t}`:`${e};${r}`};${n}`}case h.Kagi:{let{method:e,period:t,reversal:n}=z_(this.inputs);return`Kagi;${e===`ATR`?`ATR;${t}`:`User;${n}`}`}case h.PointAndFigure:{let{method:e,period:t,reversal:n,boxSize:r,source:i,oneStepBack:a}=J_(this.inputs);return`PointAndFigure;${e===`ATR`?`ATR;${t}`:`User;${r}`};${i};${n};${a}`}case h.LineBreak:{let{lineBreak:e}=V_(this.inputs);return`LineBreak;${e}`}default:return h[this.curveStyle]}}get needsExtraKey(){return[C.Options,C.BalanceSheet,C.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(`;`)}`:``}getHashKey(){let e=this.aggregation.getHashKey(),t=this.getBuilderKey(),n=this.getExtraKey(),r=this.extendedHours??!1,i=this.aggregation.isEndOfDay&&(this.useLastTrade??!1);return`${this.symbol}|${i}|${e}|${r}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${n}`}duplicate(){let t=new e(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return t.cacheMe=this.cacheMe,t.barsToFetch=this.barsToFetch,t.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,t.offset=this.offset,t.chartId=this.chartId,t.curveStyle=this.curveStyle,t.useLastTrade=this.useLastTrade,t.extendedHours=this.extendedHours,t.fields=P(this.fields),t.splits=this.splits,t.padded=this.padded,t}},Ib=/* @__PURE__ */ c((/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){var i={};n.PubSub?(i=n.PubSub,console.warn(`PubSub already loaded, using existing version`)):(n.PubSub=i,r(i)),typeof e==`object`?(t!==void 0&&t.exports&&(e=t.exports=i),e.PubSub=i,t.exports=e=i):typeof define==`function`&&define.amd&&define(function(){return i})})(typeof window==`object`&&window||n||global,function(e){var t={},n=-1,r=`*`;function i(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function a(e){return function(){throw e}}function o(e,t,n){try{e(t,n)}catch(e){setTimeout(a(e),0)}}function s(e,t,n){e(t,n)}function c(e,n,r,i){var a=t[n],c=i?s:o,l;if(Object.prototype.hasOwnProperty.call(t,n))for(l in a)Object.prototype.hasOwnProperty.call(a,l)&&c(a[l],e,r)}function l(e,t,n){return function(){var i=String(e),a=i.lastIndexOf(`.`);for(c(e,e,t,n);a!==-1;)i=i.substr(0,a),a=i.lastIndexOf(`.`),c(e,i,t,n);c(e,r,t,n)}}function u(e){var n=String(e);return!!(Object.prototype.hasOwnProperty.call(t,n)&&i(t[n]))}function d(e){for(var t=String(e),n=u(t)||u(r),i=t.lastIndexOf(`.`);!n&&i!==-1;)t=t.substr(0,i),i=t.lastIndexOf(`.`),n=u(t);return n}function f(e,t,n,r){e=typeof e==`symbol`?e.toString():e;var i=l(e,t,r);return d(e)?(n===!0?i():setTimeout(i,0),!0):!1}e.publish=function(t,n){return f(t,n,!1,e.immediateExceptions)},e.publishSync=function(t,n){return f(t,n,!0,e.immediateExceptions)},e.subscribe=function(e,r){if(typeof r!=`function`)return!1;e=typeof e==`symbol`?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var i=`uid_`+String(++n);return t[e][i]=r,i},e.subscribeAll=function(t){return e.subscribe(r,t)},e.subscribeOnce=function(t,n){var r=e.subscribe(t,function(){e.unsubscribe(r),n.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&delete t[n]},e.countSubscriptions=function(e){var n,r,i=0;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0){for(r in t[n])i++;break}return i},e.getSubscriptions=function(e){var n,r=[];for(n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&r.push(n);return r},e.unsubscribe=function(n){var r=typeof n==`string`&&(Object.prototype.hasOwnProperty.call(t,n)||function(e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0)return!0;return!1}(n)),i=!r&&typeof n==`string`,a=typeof n==`function`,o=!1,s,c,l;if(r)e.clearSubscriptions(n);else{for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(c=t[s],i&&c[n]){delete c[n],o=n;break}if(a)for(l in c)Object.prototype.hasOwnProperty.call(c,l)&&c[l]===n&&(delete c[l],o=!0)}return o}}})})))(),1);function Lb(e,t,n){return new Rb(e,t,n)}var Rb=class{exprModel;innerSeries;calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;seasonalAverageOffset;constructor(e,t,n){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[n.mapper(t)]=t,e),{}),this.policy=n,this.exprSymbols=of(e),this.valueSymbols=this.exprSymbols.filter(e=>this.innerLookup[e]===void 0),this.onlyForTimeline=k(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;let t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!N(this.exprModel)}get hasData(){return this.container!==null}get sourceFields(){return this._sourceFields||=Array.from(this.policy.fieldMap.keys()),this._sourceFields}get targetFields(){return this._targetFields||=Array.from(this.policy.fieldMap.values()),this._targetFields}async ready(){return ma.call(this,async()=>{this.basisChangedToken=Ib.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=Ib.default.subscribe(G.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));let e=this.innerSeries.map(e=>e.ready());this.policy.valueProvider!==void 0&&e.push(this.policy.valueProvider.ready());let t=(await Promise.all(e)).every(de);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>N(e.container))&&this.calculateCommon(G.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===d.Manual||e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!N(e.container)))return;let n=this.policy.mapper(t.series);if(!(e===G.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(n)))switch(this.policy.recompute===d.Everything?G.TS_MANYCHANGED:e){case G.TS_MANYCHANGED:this.calculate();break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:this.recalculate(e===G.TS_DATAPOINTADDED);break;case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.basisChangedToken&&Ib.default.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(Ib.default.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,n)=>t===W.Volume?me(this.exprSymbols.map(t=>e.inn[t].values[n]??0)):tf(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[n]??null))}pickMainField(){let e=null;for(let t of this.policy.fieldMap.values())if(e==null)e=t;else if(t===W.Close){e=t;break}return e}calculateLastChange(){let e=this.container,t=e.size;if(t<=1)return;let n=this.pickMainField(),r=e.getData(n)[t-2],i=e.getData(n)[t-1];N(r,i)&&e.setLastDataPoint(W.Change,i-r)}calculateDataPoint(e,t){let n=this.calculateAt(e);if(n===null)return;e.atLeastOne=!0;let[r,i]=De(n,0,3);n[1]=i,n[2]=r,this.targetFields.forEach((e,r)=>{let i=n[r];t?this.container.addDataPoint(e,i):this.container.setLastDataPoint(e,i)}),t&&(this.container.addDataPoint(W.Change,null),this.container.addDataPoint(W.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){Ke(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,n){let r=this.innerLookup[e].container.getData(n);return t<0||t>=r.length?null:r[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,W.DateTime)}timeline(e){return e.container.getData(W.DateTime)}getRangeHelper(){switch(this.policy.missing){case u.UseNext:case u.UseNone:return{begin:Math.min,end:Math.min};case u.UseNextFromLatestStart:return{begin:Math.max,end:Math.min};case u.UsePrevious:return{begin:Math.max,end:Math.max};default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}getRange(){let e=this.getRangeHelper();return{begin:new Date(e.begin(...this.symbols.map(e=>we(this.timeline(this.innerLookup[e]))))),end:new Date(e.end(...this.symbols.map(e=>Ce(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,t){let n=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case u.UseNext:case u.UseNextFromLatestStart:case u.UseNone:return n.findIndex(e=>e.valueOf()>=t.valueOf());case u.UsePrevious:return Te(n,e=>e.valueOf()<=t.valueOf());default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}checkPos(e){let t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!N(e.timeStamp)&&(!this.policy.stretch(e.symbol)||t===1))}fillPosSymbolAt(e,t,n){e.index=t,e.timeStamp=this.timeStampAt(e.symbol,t);let r=(this.policy.missing===u.UseNone||this.policy.skipLeadingEmpty&&!n.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==n.timeStamp.valueOf();return e.values=this.sourceFields.map(n=>r?null:this.fieldValueAt(e.symbol,t,n)),e}skippable(e){return this.innerLookup[e].container.isEmpty?this.policy.noDataApproach===f.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===f.ModelTransformRequired:!1}get symbols(){let e=Object.keys(this.innerLookup);return N(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){let t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return this.symbols.length===0||(this.symbols.forEach(n=>{let r=this.findIndex(n,e),i={symbol:n,index:-1,timeStamp:/* @__PURE__ */ new Date(0),values:[]};t.inn[n]=this.fillPosSymbolAt(i,r,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t)),t}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;N(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>e.timeStamp!==null).map(e=>e.timeStamp.valueOf()))),this.policy.missing===u.UsePrevious?this.getInner(e).forEach(t=>{let n=N(t.timeStamp);(n&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!n&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===u.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){let t=this.container?.getLastDataPoint(W.DateTime),n=e?.timeStamp;return N(t,n)?t.valueOf()<n.valueOf():!1}calculateCommon(e=null,t=null,n=!0){try{if(t)this.calculateDataPoint(t,n);else if(this.container=this.makeContainer(),!this.isExprInError){let e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(e){this.crashedComputationReported||=(F(e,`error`),!0)}}calculate(){let{yes:e,no:t}=O(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===f.ModelTransformRequired){let n=e=>e.map(this.policy.mapper),r=this.policy.modelTransform(n(e),n(t));r!==null&&(this.exprModel=r)}this.calculateCommon(G.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;let t=this.getLastPos(),n=this.shouldAdd(t);this.calculateCommon(n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n)}recalculateAt(e,t,n){return this.recalculate(n)}makeContainer(){return new e_([W.DateTime,W.Change].concat(this.targetFields))}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}};function zb(e){if(!(e instanceof Rb)||e.innerSeries.length!==1||e.exprSymbols.length!==1||e.valueSymbols.length!==0)return e;let t=e.innerSeries[0],n=t.query;return!N(n)||!rt(n,`surrogate`)?e:t}function Bb(e){let{query:t}=e;return t!==void 0&&`duplicate`in t&&`getBuilderKey`in t}function Vb(e,t,n){if(!(e instanceof Rb))return n(e);if(e.valueSymbols.length!==0)return new ev;let r=e.innerSeries.map(n);return new Rb(e.exprModel,r,{...e.policy,fieldMap:/* @__PURE__ */ new Map([[t,t]])})}function Hb(e,t){return Vb(e,t,e=>e)}function Ub(e,t){let n=zb(e);if(!Bb(n))return new ev;let r=Pb(n.query);if(r.symbol===z.PLACEHOLDER_SYMBOL_NAME||r.getBuilderKey()!==`Standard`)return new ev(r);{r.barsToFetch!==0&&(r.barsToFetch*=z.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);let e=t(r);return e.serverComputedSeries=!0,e}}function Wb(e,t,n){return Vb(e,t,e=>Ub(e,n))}function K(e){return new vp(e,v.Number,b.Study,e)}var q=class{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=/* @__PURE__ */ new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=xt(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw Error(`Should not be called.`)}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(let t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){dt(this,e),rt(e,`source`)&&(this.source=e.source??null);let t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return z.EMPTY_ARRAY}get hasData(){return this.container!==null}get source(){if(N(this._source))return this._source;let e=N(this.inputs)?this.inputs[z.INPUT_SOURCE]:null;return N(e)?W[e]:null}set source(e){this._source=e}async ready(){return ma.call(this,async()=>{this.basisChangedToken=this.useNotifications?Ib.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)):null;let e={tag:xt(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(de);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||this.innerSeries.some(e=>!e.hasData)||!this.shouldTriggerOurRecalc(t.series)||this.base===null||this===t.series)return;let n={tag:xt(),src:t.series};switch(e){case G.TS_MANYCHANGED:this.calculate(n);break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:{let r=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(n,r,e===G.TS_DATAPOINTADDED);break}case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.useNotifications&&this.basisChangedToken&&Ib.default.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){let n=this.calculateAt(e);n!==null&&Object.keys(n).forEach(e=>{let r=n[e],i=this.studyFields[e];t?this.container.addDataPoint(i,r):this.container.setLastDataPoint(i,r)})}notify(e,t){Ke(e,{series:this,index:t})}calculateCommon(e,t=null,n=-1,r=!0){let i=n===-1,a=i?t=>{(N(e.src)||!N(t.calcCtx))&&t.calculate(e)}:t=>t.recalculateAt(e,n,r);if(!(this.base===null||this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)){if(this.calcCtx=e,this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>a(e)),i&&(this.container=this.makeContainer()),this.calculateAt!==void 0){if(!i)this.calculateDataPoint(n,r);else{let e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}}t&&(N(e.src)||this.initialNotification)&&this.notify(t,n)}}calculate(e){this.calculateCommon(e,G.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,n){this.computedServerSide||(!n&&M(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,n){let r=this.innCont(e),i=r.size;return n<0||n>i-1?null:r.getData(t)[n]}innHasData(e){let t=this.innCont(e);return N(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(W.DateTime,W.Symbol)}makeContainer(){let e=this.defaultWrappers.concat(this.getWrappers());return new n_(Object.keys(this.studyFields).map(e=>this.studyFields[e],this),this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,n,r=this.base){let i=r?.getData(n);return Array.isArray(i)?i.slice(e-t+1,e+1):[]}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}},Gb=class extends q{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}},Kb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return null}getWrappers(){return[this.wrapInner(this.target,0)]}},qb=class extends Gb{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let[t,n,r,i]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e),this),a=null,o=null,s=null,c=null,l=he([t,n,r,i]);if(e<1)a=he([t,i]),o=n,s=r,c=0;else{let[t,i]=[W.Open,W.Close].map(t=>this.container.getData(t)[e-1],this);a=he([t,i]),o=Math.max(n,a,l),s=Math.min(r,a,l),c=l-i}return{[W.Open.id]:a,[W.High.id]:o,[W.Low.id]:s,[W.Close.id]:l,[W.Change.id]:c}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Jb=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.inputs.PeriodAverage,i=n(t,r,this.source??W.Close,W.ATREXTAVG),a=AO(t,this.inputs.PeriodATR);this.addInner(i,a)}calculateAt(e){let t=this.innVal(1,W.ATREXTAVG,e),n=this.innVal(2,W.ATR,e),r=t!==null&&n!==null,i=n*this.inputs.Multiplier;return{[W.ATREXTUP.id]:r?t+i:null,[W.ATREXTLOW.id]:r?t-i:null}}getWrappers(){return[this.wrapInner(W.ATREXTAVG,1)]}},Yb=class extends q{constructor(e,t){super(e,t),JO(this)}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)&&r.hasField(this.source)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=he(i.filter(fe)):ge(i)&&(t=he(i))}return{[this.target.id]:t}}getWrappers(){return this.source===W.Volume?this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close):[]}},Xb=class extends q{multiplier;constructor(e,t,n){super(e,t),this.multiplier=n(this.period),JO(this)}calculateAt(e){let t=null,[n,r]=YO(this);if(this.atLeast(e,2)&&r.hasField(this.source)){let i=this.container.getData(this.target)[e-1];if(i!==null)t=(this.innVal(n,this.source,e)-i)*this.multiplier+i;else{let n=this.period;if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=he(i.filter(fe)):ge(i)&&(t=he(i))}}}return{[this.target.id]:t}}},Zb=class extends Xb{constructor(e,t){super(e,t,e=>2/(e+1))}},Qb=class extends Xb{constructor(e,t){super(e,t,e=>1/e)}},$b=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,W.High,W.MAHI),r=J(t,this.inputs.Period2,W.Low,W.MALO);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.MAHI,1),this.wrapInner(W.MALO,2)]}},ex=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=W.OpenInterest;return this.base.hasField(n)&&(t=this.baseVal(n,e)),{[n.id]:t}}},tx=class extends ex{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close)}},nx=class extends ex{constructor(e,t){super(e,Hb(t,W.OpenInterest))}getWrappers(){return this.wrapBaseFields(W.TradeSize,W.Change)}},rx={inField:W.MA,outFields:[W.ENVU,W.ENVD],func:J},ix={inField:W.EMA,outFields:[W.ENVEXPU,W.ENVEXPD],func:Y},ax={inField:W.SMA,outFields:[W.ENVSMOU,W.ENVSMOD],func:xO},ox=class extends q{kind;perc;constructor(e,t,n){super(e,n),this.kind=t,this.perc=this.inputs.Percent/100;let r=t.func(n,this.inputs.Period,e.source);this.addInner(r)}calculateAt(e){let t=null,n=null,r=this.innVal(1,this.kind.inField,e);if(r!==null){let e=r*this.perc;t=r+e,n=r-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:n}}},sx=class extends ox{constructor(e,t){super(e,rx,t)}},cx=class extends ox{constructor(e,t){super(e,ix,t)}},lx=class extends ox{constructor(e,t){super(e,ax,t)}},ux=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period,this.source),r=J(n,this.inputs.Period,W.MA,W.TMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.TMA,2)]}},dx=class extends q{triangle;constructor(e,t){super(e,t);let n=this.period;this.triangle=n*(n+1)/2,JO(this)}weightedAverage(e){let t=e.length;if(t===0)return null;let n=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,n)=>e+t*(n+1),0)/n}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=this.weightedAverage(i.filter(fe)):ge(i)&&(t=this.weightedAverage(i))}return{[this.target.id]:t}}},fx=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,this.source),r=J(t,this.inputs.Period2,this.source),i=Z(this.target,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},px={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:J,mapFunc:GO,histogramVaryColor:!0},mx={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:Y,mapFunc:GO,histogramVaryColor:!0},hx={fields:[W.MACD,W.CTLTM,W.CTM],avgFunc:Y,mapFunc:GO,histogramVaryColor:!1},gx={fields:[W.MACD,W.CTLTMF,W.CPMI],avgFunc:Y,mapFunc:GO,histogramVaryColor:!1},_x={fields:[W.PPO,W.PPOS,W.PPOH],avgFunc:Y,mapFunc:KO,histogramVaryColor:!0},vx={fields:[W.PVO,W.PVOS,W.PVOH],avgFunc:Y,mapFunc:KO,histogramVaryColor:!1},yx=class extends q{histogramVaryColor=!1;histogramField;get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){let n=this.container.getData(this.histogramField)[e],r=this.container.getData(this.histogramField)[e-1];if(N(n,r)){let i=n<=0;t=i?1:3,e>0&&(i&&n>r&&(t=0),!i&&n<r&&(t=2))}}return{[W.BARCOLIX.id]:t}}},bx=class extends yx{fields;constructor(e,t,n){super(e,n),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];let r=t.avgFunc(n,e.inputs.Period1,e.source,void 0),i=t.avgFunc(n,e.inputs.Period2,e.source,void 0),a=Z(this.fields[0],t.mapFunc,r,i),o=t.avgFunc(a,e.inputs.Period3,a.target,this.fields[1]),s=Z(this.fields[2],GO,a,o);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}},xx=class extends yx{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=W.MACDVH;let n=$O(e,`EMA`,`Average`),r=n(t,e.inputs.Period1,e.source,void 0),i=n(t,e.inputs.Period2,e.source,void 0),a=AO(t,e.inputs.Period2,e.inputs.Average),o=Z(W.MACDV,(e,t,n,r)=>(t-n)/r*100,r,i,a),s=n(o,e.inputs.Period3,o.target,W.MACDVS),c=Z(W.MACDVH,GO,o,s);this.addInner(o,s,c)}getWrappers(){return[this.wrapInner(W.MACDV,1),this.wrapInner(W.MACDVS,2),this.wrapInner(W.MACDVH,3)]}},Sx=class extends bx{constructor(e,t){super(e,px,t)}},Cx=class extends bx{constructor(e,t){super(e,mx,t)}},wx=class extends bx{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,hx,t)}},Tx=class extends bx{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,gx,t)}},Ex=class extends bx{constructor(e,t){super(e,_x,t)}},Dx=class extends bx{constructor(e,t){super(e,vx,t)}},Ox=K(`_AVG_GAIN`),kx=K(`_AVG_LOSS`),Ax=class extends q{isModified;constructor(e,t){super(e,t);let n=e.inputs.Modified;this.isModified=n}get helpers(){return[Ox,kx]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,n=null,r=null,i=this.period;if(this.atLeast(e,i+1)){if(this.container.getData(this.target)[e-1]!==null&&!this.isModified){let t=this.container.getData(Ox)[e-1],a=this.container.getData(kx)[e-1],o=this.past(e,2,this.source),s=this.gain(1,o),c=this.loss(1,o);n=(t*(i-1)+s)/i,r=(a*(i-1)+c)/i}else{let t=this.past(e,i+1,this.source);if(ge(t)){let e=_e(1,i),a=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));n=he(a),r=he(o)}}n!==null&&r!==null&&(t=100-100/(1+n/r))}return{[Ox.id]:n,[kx.id]:r,[this.target.id]:t}}},jx=class extends q{constructor(e,t,n){super(e,n);let r=FO(n,this.inputs.Period,this.source,W.RSI,t),i=$O(e,`MA`,`Average`)(r,this.inputs.PeriodAvg,W.RSI,W.RSIAVG);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.RSI,1),this.wrapInner(W.RSIAVG,2)]}},Mx=class extends jx{constructor(e,t){super(e,!1,t)}},Nx=class extends jx{constructor(e,t){super(e,!0,t)}},Px=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period,this.source),r=this.inputs.Range,i=X(W.STORSI,function(e){let t=null;if(this.atLeast(e,r)){let n=this.past(e,r,W.RSI,this.base),i=De(n),a=i[0],o=i[1];t=(Ce(n)-a)/(o-a)}return{[W.STORSI.id]:t}},n),a=$O(e,`MA`,`Average`),o=this.inputs.PeriodAvg,s=a(i,o,W.STORSI,W.STORSIAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(W.STORSI,1),this.wrapInner(W.STORSIAVG,2)]}},Fx=class extends q{constructor(e,t){super(e,t);let n=TO(t,this.inputs.Period1,W.High,W.HH,!0),r=TO(t,this.inputs.Period2,W.Low,W.LL,!1);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.HH,1),this.wrapInner(W.LL,2)]}},Ix=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,[n,r,i]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e));return t=(2*n+r+i)/4,{[this.target.id]:t}}},Lx=class extends q{highest;index;constructor(e,t,n,r){super(e,r),this.highest=t,this.index=n}calculateAt(e){let t=null,n=this.inputs.Period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);ge(r)&&(t=this.highest?Math.max(...r):Math.min(...r),this.index&&(t=n-r.indexOf(t)-1))}return{[this.target.id]:t}}},Rx=class extends q{toHighest;field;highField;lowField;constructor(e,t,n){super(e,n),this.toHighest=t;let r=N(e.source),i=e.source,a=r?i:W.Close;this.field=a;let o=r?i:W.High;this.highField=o;let s=r?i:W.Low;this.lowField=s;let c=TO(n,e.inputs.Period,this.highField,W.HH,!0),l=TO(n,e.inputs.Period,this.lowField,W.LL,!1);this.addInner(c,l)}calculateAt(e){let t=null,n=this.baseVal(this.field,e),r=this.innVal(1,W.HH,e),i=this.innVal(2,W.LL,e);if(ge([n,r,i])){let e=this.toHighest?r:i,a=r-i;a!==0&&(t=(n-e)/a*100)}return{[this.target.id]:t}}},zx=class extends Rx{constructor(e,t){super(e,!0,t)}},Bx=K(`RawPercK`),Vx=class extends q{kField;constructor(e,t,n,r){super(e,r);let i=EO(r,this.inputs.Period1,t?Bx:n,!1),a=$O(e,`MA`),o=a(i,this.inputs.Period2,i.target,t?n:W.PercD),s=t?a(o,this.inputs.Period3,o.target,W.PercD):o;this.kField=n,t?this.addInner(o,s):this.addInner(i,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(W.PercD,2)]}},Hx=class extends Vx{constructor(e,t){super(e,!1,W.PercK,t)}},Ux=class extends Vx{constructor(e,t){super(e,!0,W.PercK,t)}},Wx=class extends Vx{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,W.CTPI,t)}};function Gx(e,t,n,r,i){if(i===null)return null;let a=e*i,o=r+a,s=r-a;switch(t){case W.BOLLBU:return o;case W.BOLLBL:return s;case W.BOLLBW:return(o-s)/r*100;default:return null}}var Kx=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t,JO(this);let r=this.inputs.Period,i=this.source,a=J(n,r,i,W.BOLLBM),o=t===`Modified`,s=LO(o?DO(n,i):n,r,o?W.PCTCHG:i),c=this.inputs.Width,l=e=>le(Gx,c,e),u=Z(W.BOLLBU,l(W.BOLLBU),a,s),d=Z(W.BOLLBL,l(W.BOLLBL),a,s),f=Z(W.BOLLBW,l(W.BOLLBW),a,s),p=$O(e,`MA`,`Average`),m=this.inputs.PeriodAvg,h=p(f,m,W.BOLLBW,W.BOLLBWA);this.addInner(a,s,u,d,f,h)}calculateAt(e){let t=+!!this.sourceNeedsCompute,n=this.innVal(3+t,W.BOLLBU,e),r=this.innVal(4+t,W.BOLLBL,e),i=this.innVal(1+t,W.BOLLBM,e),a=this.innVal(5+t,W.BOLLBW,e),o=this.innVal(6+t,W.BOLLBWA,e),s=null;switch(this.kind){case`Regular`:return{[W.BOLLBU.id]:n,[W.BOLLBL.id]:r,[W.BOLLBM.id]:i};case`Width`:return{[W.BOLLW.id]:n-r};case`Percent`:if(N(n,r)){let[t]=YO(this),i=this.innVal(t,this.source,e);N(i)&&(s=(i-r)/(n-r))}return{[W.BOLLP.id]:s};case`BandWidth`:return{[W.BOLLBW.id]:a,[W.BOLLBWA.id]:o};case`Modified`:{let n=null,r=null,a=null,o=null,s=this.innVal(2+t,W.MSD,e);if(N(s)){let e=this.inputs.MultInside,t=this.inputs.MultOutside;n=i+e*s,a=i-e*s,r=i+t*s,o=i-t*s}return{[W.MBBUI.id]:n,[W.MBBLI.id]:a,[W.MBBUO.id]:r,[W.MBBLO.id]:o,[W.MBBM.id]:i}}default:return null}}},qx=class extends Kx{constructor(e,t){super(e,`Regular`,t)}},Jx=class extends Kx{constructor(e,t){super(e,`Width`,t)}},Yx=class extends Kx{constructor(e,t){super(e,`Percent`,t)}},Xx=class extends Kx{constructor(e,t){super(e,`BandWidth`,t)}},Zx=class extends Kx{constructor(e,t){super(e,`Modified`,t)}},Qx=class extends q{constructor(e,t){super(e,t);let n=X(W.OBVOL,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];N(a)||(a=0),t=n>i?a+r:n<i?a-r:a}return{[this.target.id]:t}},t),r=$O(e,`MA`,`Average`),i=this.period,a=r(n,i,W.OBVOL,W.OBVOLAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.OBVOL,1),this.wrapInner(W.OBVOLAVG,2)]}},$x=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);if(e>0){let i=this.baseVal(W.Close,e-1);t=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}else t=n-r;return{[this.target.id]:t}}},eS=K(`_ABS_CHG`),tS=K(`_MA_ABS_CHG`),nS=K(`_CHG`),rS=class extends q{constructor(e,t){super(e,t);let n=kO(t,W.TR),r=$O(e,`SMA`)(n,this.inputs.Period,W.TR,this.target),i=J(r,this.inputs.Period2,W.ATR,W.ATRMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(W.ATRMA,2)]}},iS=class extends q{constructor(e,t){super(e,t);let n=X(eS,ce((e,t)=>{let n=0;return t>0&&(n=this.baseVal(e,t)-this.baseVal(e,t-1)),{[eS.id]:Math.abs(n)}},this.source),t),r=$O(e,`MA`)(n,this.inputs.Period,eS,tS),i=Z(W.ADJATR,(e,t)=>2*t,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.ADJATR,1)]}},aS=class extends q{constructor(e,t){super(e,t);let n=X(nS,e=>{let t=0;return e>0&&(t=this.baseVal(W.Close,e)-this.baseVal(W.Close,e-1)),{[nS.id]:t}},t),r=tk(e),i=this.inputs.Period,a=this.inputs.Smoothing,o=r(t,i,a),s=Z(this.target,(e,t,n)=>!N(t)||!N(n)?null:t/n,n,o);this.addInner(s)}getWrappers(){return[this.wrapInner(this.target,1)]}},oS=K(`_PDM`),sS=K(`_MDM`),cS=K(`_TRS`),lS=K(`_PDS`),uS=K(`_MDS`),dS=K(`_DX`),fS=class extends q{useEma;adxField;multiplier;constructor(e,t,n,r){super(e,r),this.useEma=t,this.adxField=n,this.multiplier=2/(this.inputs.AdxSmoothing+1);let i=kO(r,W.TR);this.addInner(i)}get helpers(){return[oS,sS,cS,lS,uS,dS]}sum(e,t,n,r){let i=null;if(this.atLeast(e-1,r-1)){let a=this.past(e-1,r-1,t,this.container);a.push(n),ge(a)&&(i=a.reduce((e,t,n)=>e+t,0))}return i}smooth1(e,t,n,r){let i=null,a=this.inputs.DiLength,o=this.container.getData(n)[e-1];return i=o===null?this.sum(e,t,r,a):o-o/a+r,i}smooth2(e,t,n,r){let i=this.container.getData(n)[e-1],a=this.inputs.AdxSmoothing;if(i!==null)return this.useEma?(r-i)*this.multiplier+i:(i*(a-1)+r)/a;{let n=this.sum(e,t,r,a);if(n!==null)return n/a}return null}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;if(e>0){let u=this.past(e,2,W.High),d=this.past(e,2,W.Low),f=Math.max(u[1]-u[0],0),p=Math.max(d[0]-d[1],0);t=f>p?f:0,n=p>f?p:0;let m=this.container.getData(W.TR)[e];i=this.smooth1(e,oS,lS,t),a=this.smooth1(e,sS,uS,n),r=this.smooth1(e,W.TR,cS,m),(i>0||a>0)&&r!==0&&(o=i/r*100,s=a/r*100,c=100*Math.abs(o-s)/(o+s),l=this.smooth2(e,dS,this.adxField,c))}return{[oS.id]:t,[sS.id]:n,[cS.id]:r,[lS.id]:i,[uS.id]:a,[W.PDI.id]:o,[W.MDI.id]:s,[dS.id]:c,[this.adxField.id]:l}}getWrappers(){return[this.wrapInner(W.TR,1)]}},pS=class extends fS{constructor(e,t){super(e,!1,W.ADX,t)}},mS=class extends fS{constructor(e,t){super(e,!0,W.ADXM,t)}},hS=class extends q{constructor(e,t){super(e,t);let n=IO(t);this.addInner(n)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,W.MFMUL,e),{[this.target.id]:t}}},gS=class extends q{constructor(e,t){super(e,t);let n=X(W.ADWM,function(e){let t=null,n=null;if(e>0){let r=this.baseVal(W.Close,e-1),i=Math.max(r,this.baseVal(W.High,e)),a=Math.min(r,this.baseVal(W.Low,e)),o=this.baseVal(W.Close,e);t=o>r?o-a:o<r?o-i:0,e>1&&(n=(e>2?this.container.getData(W.ADWM)[e-1]:0)+t)}return{[W.ADWM.id]:n}},t),r=J(n,this.inputs.Period,W.ADWM,W.ADWMMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.ADWM,1),this.wrapInner(W.ADWMMA,2)]}},_S=class extends q{constructor(e,t){super(e,t);let n=W.ADL,r=MO(t,n),i=Y(r,3,n),a=Y(r,10,n),o=Z(e.target,(e,t,n)=>t-n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},vS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=he([W.Close,W.High,W.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},yS=class extends q{calculateAtFunc;constructor(e,t,...n){super(e,...n),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,n)=>{let r=t,i=r.target;return N(i)||(i=r.container.hasField(W.Close)?W.Close:r.container.fields[0]),this.innVal(n,i,e)}),n=null;return ge(t)&&(n=this.calculateAtFunc(e,...t)),{[this.target.id]:n}}};function bS(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:(n+r)/2}}function xS(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:n-r}}var SS=class extends q{calculateAtFunc;constructor(e,t,n){super(e,n),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}},CS=K(`_RANGE`),wS=K(`_MOV_RANGE`),TS={fields:[W.KCUP,W.KCLOW,W.KCMID],midSeries:e=>NO(e,W.TP),midTarget:W.TP,rangeSeries:e=>X(CS,ce(xS,CS),e),rangeTarget:CS,func:`MA`,useMultiplier:!1},ES={fields:[W.KBUP,W.KBLOW,W.KBMID],midSeries:e=>e,midTarget:W.Close,rangeSeries:e=>kO(e,W.TR),rangeTarget:W.TR,func:`EMA`,useMultiplier:!0},DS=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=t.midSeries(n),i=$O(e,t.func,`Average`),a=i(r,this.inputs.Period,t.midTarget,t.fields[2]),o=i(t.rangeSeries(n),this.inputs.Period,t.rangeTarget,wS);this.addInner(a,o)}calculateAt(e){let t=this.innVal(1,this.kind.fields[2],e),n=this.innVal(2,wS,e),r=t!==null&&n!==null,i=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:r?t+n*i:null,[this.kind.fields[1].id]:r?t-n*i:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}},OS=class extends DS{constructor(e,t){super(e,TS,t)}},kS=class extends DS{constructor(e,t){super(e,ES,t)}},AS=class extends q{isWidth;constructor(e,t,n){super(e,n),this.isWidth=t;let r=TO(n,this.inputs.Period,W.High,W.DONUP,!0),i=TO(n,this.inputs.Period,W.Low,W.DONLOW,!1);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.DONUP,e),n=this.innVal(2,W.DONLOW,e),r=t===null&&n===null;return this.isWidth?{[W.DONW.id]:r?null:t-n}:{[W.DONMID.id]:r?null:(t+n)/2}}getWrappers(){return[this.wrapInner(W.DONUP,1),this.wrapInner(W.DONLOW,2)]}},jS=class extends AS{constructor(e,t){super(e,!1,t)}},MS=class extends AS{constructor(e,t){super(e,!0,t)}},NS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];N(a)||(a=0);let o=(n-i)/i*r;t=a+o}return{[this.target.id]:t}}},PS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=PO(i,1,i.target,this.target);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},FS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Z(W.DEMA,(e,t,n)=>2*t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.DEMA,1)]}},IS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period1,this.source),r=Y(t,this.inputs.Period2,this.source),i=Z(W.EOSC,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.EOSC,1)]}},LS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=Z(W.TEMA,(e,t,n,r)=>3*(t-n)+r,n,r,i);this.addInner(a)}getWrappers(){return[this.wrapInner(W.TEMA,1)]}},RS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.baseVal(this.source,e-n);r!==null&&r!==0&&(t=(this.baseVal(this.source,e)-r)/r*100)}return{[this.target.id]:t}}},zS=class extends q{constructor(e,t){super(e,t);let n=NO(t,W.PVPT);this.addInner(n)}calculateAt(e){let t=this.innVal(1,W.PVPT,e),n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);return{[W.PVPTR.id]:t+n-r,[W.PVPTS.id]:t-n+r}}getWrappers(){return[this.wrapInner(W.PVPT,1)]}},BS=K(`_HIND`),VS=K(`_LIND`),HS=class extends q{justWidth;constructor(e,t,n){super(e,n),this.justWidth=t,this.justWidth=t;let r=this.inputs.Period,i=TO(n,r,W.High,BS,!0,!0),a=TO(n,r,W.Low,VS,!1,!0);this.addInner(i,a)}calculateAt(e){let t=null,n=null,r=null,i=this.innVal(1,BS,e),a=this.innVal(2,VS,e);if(i!==null&&a!==null){let e=this.period;t=(e-i)/e*100,n=(e-a)/e*100,r=t-n}return this.justWidth?{[W.ARNOSC.id]:r}:{[W.ARNUP.id]:t,[W.ARNLOW.id]:n}}},US=class extends HS{constructor(e,t){super(e,!1,t)}},WS=class extends HS{constructor(e,t){super(e,!0,t)}},GS=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Range===`Close`,r=rk(t);if(!n&&r){let e=X(W.TCHNUP,(e,t)=>null,t),n=X(W.TCHNLOW,(e,t)=>null,t);this.addInner(e,n)}else{let r=TO(t,e.inputs.PeriodUpper,n?W.Close:W.High,W.TCHNUP,!0),i=TO(t,e.inputs.PeriodLower,n?W.Close:W.Low,W.TCHNLOW,!1);this.addInner(r,i)}}getWrappers(){return[this.wrapInner(W.TCHNUP,1),this.wrapInner(W.TCHNLOW,2)]}},KS=class extends q{constructor(e,t){super(e,t);let n=BO(t,e.inputs.Period,e.inputs.Range);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.TCHNUP,e),r=this.innVal(1,W.TCHNLOW,e),i=this.inputs.Adjustment,a=this.inputs.Retracement;return a===`Long`?t=N(n)?n-i:null:a===`Short`&&(t=N(r)?r+i:null),{[this.target.id]:t}}},qS=K(`_MIDPOINT`),JS=class extends q{constructor(e,t){super(e,t);let n=X(qS,ce(bS,qS),t),r=xO(n,e.inputs.Period1,qS,W.ALJAW),i=xO(n,e.inputs.Period2,qS,W.ALTEETH),a=xO(n,e.inputs.Period3,qS,W.ALLIPS);this.addInner(r,i,a)}calculateAt(e){return{[W.ALJAW.id]:this.innVal(1,W.ALJAW,e),[W.ALTEETH.id]:this.innVal(2,W.ALTEETH,e),[W.ALLIPS.id]:this.innVal(3,W.ALLIPS,e)}}},YS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return{[W.PLTLN.id]:this.inputs.Position}}},XS=K(`_MIDPOINT`),ZS=class extends q{constructor(e,t){super(e,t);let n=X(XS,ce(bS,XS),t),r=J(n,this.inputs.Period1,XS),i=J(n,this.inputs.Period2,XS),a=Z(W.AWOS,(e,t,n)=>t-n,r,i),o=J(a,this.inputs.Period3,a.target,W.AWOSMA);this.addInner(a,o)}getWrappers(){return[this.wrapInner(W.AWOS,1),this.wrapInner(W.AWOSMA,2)]}},QS=class extends q{multiplyVol;constructor(e,t,n){super(e,n),this.multiplyVol=t}calculateAt(e){let[t,n,r,i]=[W.High,W.Low,W.Close,W.Volume].map(t=>this.baseVal(t,e)),a=t===n?0:(r-n-(t-r))/(t-n);return this.multiplyVol&&(a*=i),{[this.target.id]:a}}},$S=class extends QS{constructor(e,t){super(e,!1,t)}},eC=class extends QS{constructor(e,t){super(e,!0,t)}},tC=class extends q{constructor(e,t){super(e,t);let n=IO(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Volume),i=this.past(e,n,W.MFMUL,this.innCont(1));if(ge(r)&&ge(i)){let e=me(r);e!==0&&(t=me(i)/e)}}return{[this.target.id]:t}}},nC=K(`_RANGE`),rC=class extends q{constructor(e,t){super(e,t);let n=PO(Y(X(nC,ce(xS,nC),t),this.inputs.Period1,nC),this.inputs.Period2,W.EMA,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},iC=class extends q{shift;constructor(e,t){super(e,t);let n=this.inputs.Period;this.shift=Math.floor(n/2)+1;let r=J(t,n,e.source);this.addInner(r)}calculateAt(e){let t=null,n=this.shift,r=this.innVal(1,W.MA,e-n);return r!==null&&(t=this.baseVal(this.source,e)-r),{[this.target.id]:t}}},aC=K(`_MATP`),oC=class extends q{constructor(e,t){super(e,t);let n=NO(t),r=J(n,this.inputs.Period,n.target,aC);this.addInner(n,r)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1));if(ge(r)){let n=this.innVal(2,aC,e);if(n!==null){let i=r.reduce((e,t,r)=>e+Math.abs(n-t),0)/this.period;t=(this.innVal(1,W.TP,e)-n)/(.015*i)}}}return{[this.target.id]:t}}},sC=class extends q{constructor(e,t){super(e,t);let n=X(W.EMV,function(e){let t=null;if(e>0){let[n,r,i]=[W.High,W.Low,W.Volume].map(t=>this.baseVal(t,e)),[a,o]=[W.High,W.Low].map(t=>this.baseVal(t,e-1));t=((n+r)/2-(a+o)/2)/(i/1e6/(n-r))}return{[this.target.id]:t}},t),r=J(n,this.inputs.Period,W.EMV,W.EMVMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.EMV,1),this.wrapInner(W.EMVMA,2)]}},cC=class extends q{isBull;constructor(e,t,n){super(e,n),this.isBull=t;let r=Y(n,this.inputs.Period,this.source);this.addInner(r)}calculateAt(e){let t=null,n=this.innVal(1,W.EMA,e);return n!==null&&(t=this.isBull?this.baseVal(W.High,e)-n:this.baseVal(W.Low,e)-n),{[this.isBull?W.ERBLPOW.id:W.ERBRPOW.id]:t}}},lC=class extends cC{constructor(e,t){super(e,!0,t)}},uC=class extends cC{constructor(e,t){super(e,!1,t)}},dC=K(`_FORCE`),fC=class extends q{constructor(e,t){super(e,t);let n=Y(X(dC,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e);t=(n-this.baseVal(W.Close,e-1))*r}return{[this.target.id]:t}},t),this.inputs.Period,dC,W.FI);this.addInner(n)}getWrappers(){return[this.wrapInner(W.FI,1)]}},pC=K(`_RANGE`),mC=K(`_EMA1`),hC=K(`_EMA2`),gC=K(`_RATIO`),_C=class extends q{constructor(e,t){super(e,t);let n=Y(X(pC,ce(xS,pC),t),9,pC,mC),r=Z(gC,(e,t,n)=>t/n,n,Y(n,9,mC,hC));this.addInner(r)}calculateAt(e){let t=null;if(this.atLeast(e,25)){let n=this.past(e,25,gC,this.innCont(1));ge(n)&&(t=me(n))}return{[this.target.id]:t}}},vC=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=X(W.MOM,le(ZO,n,this.source),t),i=J(r,this.inputs.Movement,W.MOM,W.MOMMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.MOM,1),this.wrapInner(W.MOMMA,2)]}},yC=class extends q{constructor(e,t){super(e,t);let n=NO(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period+1;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1)),i=this.past(e,n,W.Volume).map(e=>e??0);if(ge(r)&&ge(i)){let e=0,a=0;for(let t=1;t<n;++t){let n=r[t]*i[t];r[t]>r[t-1]?e+=n:a+=n}t=100-100/(1+e/a)}}return{[this.target.id]:t}}},bC=class extends q{constructor(e,t){super(e,t),JO(this);let n=J(t,this.inputs.Period,this.source);this.addInner(n)}calculateAt(e){let t=null,[n,r]=YO(this),i=this.innVal(n+1,W.MA,e);if(i!==null){let n=this.inputs.Period,a=this.past(e,n,this.source,r);a=a.map(e=>(e-i)*(e-i)),t=Math.sqrt(he(a))}return{[this.target.id]:t}}getWrappers(){let[e]=YO(this);return[this.wrapInner(W.MA,e+1)]}},xC={isNegative:!1,fields:[W.PVI,W.PVIEMA]},SC={isNegative:!0,fields:[W.NVI,W.NVIEMA]},CC=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=X(this.kind.fields[0],ce(function(e,t){let n=1e3;if(t>0){let r=[W.Close,W.Volume],[i,a]=r.map(e=>this.baseVal(e,t)),[o,s]=r.map(e=>this.baseVal(e,t-1)),c=this.container.getData(this.target)[t-1];n=(e?a<s:a>s)?c*((i-o)/o+1):c}return{[this.target.id]:n}},this.kind.isNegative),n),i=Y(r,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}},wC=class extends CC{constructor(e,t){super(e,SC,t)}},TC=class extends CC{constructor(e,t){super(e,xC,t)}},EC=K(`_PRICE_CHANGE`),DC=class extends q{constructor(e,t){super(e,t);let n=this.source??W.Close,r=Math.sqrt(nk(e.aggregation)),i=e.inputs.Calculation===`Absolute`;if(r===0){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let a=function(e,t){let n=null;if(t>0){let r=this.baseVal(e,t),a=this.baseVal(e,t-1);r!==null&&a!==null&&(n=i?r-a:Math.log(r/a))}return{[EC.id]:n}},o=function(e,t){let n=null,r=this.baseVal(W.MSD,t);return r!==null&&(n=(i?1:100)*r*e),{[W.HV.id]:n}},s=LO(X(EC,ce(a,n),t),e.inputs.Period,EC,W.MSD),c=X(W.HV,ce(o,r),s);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},OC=class extends q{noOp;constructor(e,t){super(e,t);let n=this.inputs.Anchor===`VisibleStart`;this.noOp=n}calculateAt(e){let t=null,n=this.baseVal(this.source,0),r=this.baseVal(this.source,e);return this.noOp?t=r:n!==null&&r!==null&&(t=(r-n)/n*100),{[this.target.id]:t}}},kC=K(`_SWING_INDEX`),AC=class extends q{constructor(e,t){super(e,t)}get helpers(){return[kC]}ohlcVals(e){return[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,n,r){let i=Math.abs(e-r),a=Math.abs(t-r),o=Math.abs(e-t),s=Math.max(i,a,o),c=.25*Math.abs(r-n);return s===i?i-.5*a+c:s===a?a-.5*i+c:o+c}calculateAt(e){let t=null,n=null;if(e>0){let r=this.container.getData(kC)[e-1];N(r)||(r=0);let[i,a,o,s]=this.ohlcVals(e),[c,l,u,d]=this.ohlcVals(e-1);if(ge([i,a,o,s,c,d])){let e=Math.max(Math.abs(a-d),Math.abs(o-d)),l=this.inputs.Limit,u=this.obtainR(a,o,c,d);t=50*((s-d+.5*(s-i)+.25*(d-c))/u)*(e/l),n=r+t}}return{[kC.id]:t,[this.target.id]:n}}},jC=K(`_MIN_CLOSE`),MC=K(`_MAX_CLOSE`),NC=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[MC,jC]}calculateAt(e){let t=null,n=null,r=null,i=null,a=this.innVal(1,W.ATR,e);if(a!==null){let o=this.baseVal(W.Close,e),s=this.baseVal(W.Close,e-1),c=this.period;r=Math.max(...this.past(e,c,W.Close)),i=Math.min(...this.past(e,c,W.Close));let l=a*this.inputs.Constant;if(this.innVal(1,W.ATR,e-1)===null)o>s?t=r-l:n=i+l;else{let[a,s,c,u]=[W.WWVSARU,W.WWVSARD,MC,jC].map(t=>this.container.getData(t)[e-1]);r=c,i=u,a===null?o>s?(r=o,t=o-l):(i=Math.min(o,i),n=i+l):o<a?(i=o,n=o+l):(r=Math.max(o,r),t=r-l)}}return{[MC.id]:r,[jC.id]:i,[W.WWVSARU.id]:t,[W.WWVSARD.id]:n}}},PC=K(`_EP`),FC=K(`_AF`),IC=K(`_POS`),LC=1,RC=-1,zC=class extends q{constructor(e,t){super(e,t)}get helpers(){return[PC,FC,IC]}hlcVals(e){return[W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(e>0){let[s,c,l]=this.hlcVals(e),[u,d,f]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),m=this.reciprocal(this.inputs.Limit);if(e===1){a=l>f?LC:RC;let e=a===LC;o=e?d:u,r=e?Math.max(s,u):Math.min(c,d),i=p,e?t=o:n=o}else{let[l,f,h,g,_]=[IC,W.PARSARS,W.PARSARL,PC,FC].map(t=>this.me(t,e-1)),v=l===LC,y=v?h:f,b=_*Math.abs(g-y);a=v?y+b>c?RC:LC:y-b<s?LC:RC;let x=l===a;o=x?v?Math.min(y+b,d,this.baseVal(W.Low,e-2)):Math.max(y-b,u,this.baseVal(W.High,e-2)):g,r=x?v?Math.max(s,g):Math.min(c,g):a===LC?s:c,i=_,x?(v?r>g:r<g)&&_<m&&(i=_+p):i=p,a===LC?t=o:n=o}}return{[PC.id]:r,[FC.id]:i,[IC.id]:a,[W.PARSARS.id]:n,[W.PARSARL.id]:t}}},BC=class extends q{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);let n=this.period;this.xSum=n*(n+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=n*(n+1)*(2*n+1)/6}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);if(ge(r)){let e=me(r),i=(n*me(r.map((e,t)=>e*(t+1)))-this.xSum*e)/(n*this.x2Sum-this.xSum2);t=(e-i*this.xSum)/n+i*n}}return{[this.target.id]:t}}},VC=K(`_IDY`),HC=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],UC=e=>Array(e).fill(0);function WC(e,t){return YC(e,t,10)}function GC(e,t){return YC(e,t,13)}function KC(e,t){return YC(e,t,16)}function qC(e,t){return YC(e,t,4)}function JC(e,t){return YC(e,t,7)}function YC(e,t,n){let r=e[n-1];return t===0&&(r=e[n]),t<0&&(r=e[n+1]),r}function XC(e,t,n,r,i){let a=i[18],o=r+1,s=0;for(let n=0;n<a;++n){let n=0,r=0;for(let i=1;i<6;++i){if(o--,e[o]==null)continue;let a=e[o]-t[o];i==1&&(n=r=a),a>n&&(n=a),a<r&&(r=a)}s=s+n-r}return s=s/a*qC(i,n[r]),s}function ZC(e,t,n,r,i){let a=r,o=JC(i,n[r]),s=0;do a--,e[a]!=null&&s++;while(s<o&&a>0);return t[r]-t[a]}function QC(e,t,n,r,i,a){let o=n;do o--;while(e[o]==null);return t[n]=t[o],e[n]>i&&t[o]<=0&&(t[n]=t[o]+1),e[n]<r&&t[o]>=0&&(t[n]=t[o]-1),a++,t[n]!==t[o]&&(a=1),a}function $C(e,t,n,r,i,a,o,s,c,l){let u=WC(i,n[r]),d=GC(i,n[r]),f=KC(i,n[r]),p=c+l+t[r]-e[r],m=100;i[20]>0&&(m=i[20]);let h=u*s/m;s>d&&(h=u*d/m);let g=l*2,_=e[r]+(p-g)-(p-g)*h,v=e[r]+(p-p*h),y=[a,o];return(s===1||f!==1||_>a)&&(y[0]=_),(s===1||f!==1||v<o)&&(y[1]=v),y}function ew(e,t,n){let r=0,i=-1,a=0,o=1;for(let s=0;s<n;++s){if(t[s]=0,e[s]==null||(r++,r==21&&(o=2),r==31&&(o=3),a+=e[s]*o,r<40))continue;t[s]=a/70;let c=0,l=i+1;for(let t=l;t<n&&!(e[t]!=null&&(c++,c==1&&(i=t),(c==1||c==21||c==31)&&(a-=e[t]),c==31));++t);}}var tw=class extends q{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];let n=[`VelocityUpTrend`,`VelocitySideTrend`,`VelocityDownTrend`].map(t=>e.inputs[t]||`3`).map(Number);HC.splice(6,3,...n)}get helpers(){return[VC]}prepareComputation(){let e=this.base.getData(W.Close),t=0,n=0,r=e.length;for(;n<72&&t<r;)e[t]!=null&&n++,t++;this.haveEnoughData=t<r,this.firstUsefulIndex=t,this.s3=UC(r),this.itr=UC(r),this.haveEnoughData&&ew(e,this.s3,r)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,n){let r=this.base.getData(W.Close),i=r.length;this.haveEnoughData&&ew(r,this.s3,i),super.recalculateAt(e,t,n)}calculateAt(e){let t=null,n=null,r=null,i=t=>this.us(t,e-1);if(e===0)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&this.baseVal(W.Close,e)!==null){let a=i(W.TRSP1),o=i(W.TRSP2);r=i(VC),a===null&&o===null&&(a=o=this.baseVal(W.Close,this.firstUsefulIndex)),r===null&&(r=1);let s=this.base.getData(W.Close);r=QC(s,this.itr,e,a,o,r);let c=ZC(s,this.s3,this.itr,e,HC),l=XC(s,this.s3,this.itr,e,HC);[a,o]=$C(s,this.s3,this.itr,e,HC,a,o,r,c,l),this.itr[e]>=0&&(t=a),this.itr[e]<=0&&(n=o)}return{[VC.id]:r,[W.TRSP1.id]:t,[W.TRSP2.id]:n}}},nw=class extends q{constructor(e,t){super(e,t),this.addInner(NO(t))}get helpers(){return[W.BARCOLIX]}getTarget(e){let t=this.baseVal(W.Close,e),n=this.innVal(1,W.TP,e);if(!N(t,n)||!this.atLeast(e,4))return null;let r=this.innVal(1,W.TP,e-3);return r===null?null:t+(n-r)/3}calculateAt(e){let t=null,n=this.getTarget(e);if(n!==null&&e>0){let r=this.container.getData(W.TARGP)?.[e-1];r!==null&&(t=n===r?this.container.getData(W.BARCOLIX)?.[e-1]??1:+(n>r))}return{[W.TARGP.id]:n,[W.BARCOLIX.id]:t}}},rw=1,iw=2,aw=3,ow={[rw]:{param:`cot`,func:`parseCotLineChart`,fields:[W.DateTime,W.COTLCCMSP,W.COTLCLGSP,W.COTLCSMSP]},[iw]:{param:`cotadv`,func:`parseDisaggregated`,fields:[W.DateTime,W.COTDAGPRO,W.COTDAGSPD,W.COTDAGMNM,W.COTDAGOTH]},[aw]:{param:`cotfin`,func:`parseFinancialTradersReport`,fields:[W.DateTime,W.COTFTRDLI,W.COTFTRASM,W.COTFTRLVF,W.COTFTROTH]}},sw=class extends q{wrappers;constructor(e,t,n){super(e,Ub(n,e=>new cw(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=ow[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}},cw=class extends Q_{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new lw(this.kind)}onStreamingUpdates(e){}},lw=class extends C_{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[ow[this.kind].param]=`y`}getParser(e){return new uw(e.symbol,e.aggregation,e.offset,this.kind)}},uw=class extends v_{kind;constructor(e,t,n,r){super(e,t,n),this.kind=r}makeContainer(){return new e_(ow[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[ow[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(W.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(W.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(W.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(W.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(W.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(W.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(W.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(W.COTFTROTH,parseInt(e[5]))}},dw=class extends sw{constructor(e,t){super(e,rw,t)}},fw=class extends sw{constructor(e,t){super(e,iw,t)}},pw=class extends sw{constructor(e,t){super(e,aw,t)}},mw=[`Day`,`Week`,`Month`,`Year`];function hw(e){return mw.some(t=>t===e)}function gw(e,t){if(hw(e))return e;switch(t?.unit){case g.Tick:return`Day`;case g.Intraday:return t.size<=15?`Day`:`Week`;case g.Day:return`Month`;default:return`Year`}}function _w(e,t){switch(t){case`Day`:return Sn(e);case`Week`:return bn(e,{weekStartsOn:1});case`Month`:return ir(e);case`Year`:return or(e)}}var vw={Day:[W.PreviousHigh,W.PreviousLow,W.PreviousClose],Week:[W.WeekPreviousHigh,W.WeekPreviousLow,W.WeekPreviousClose],Month:[W.MonthPreviousHigh,W.MonthPreviousLow,W.MonthPreviousClose]};function yw(e){return e.length===3&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}var bw=class extends q{disabled;record;streamingSubscription;constructor(e,t,n){if(super(e,n),this.disabled=!t||!N(n.query)||!N(n.query.symbol),!this.disabled){let e=n.query.symbol;e.endsWith(`.BZ`)&&(e=e.slice(0,-3)),this.record=$().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>{let t=zp(G.RT_QUOTE,this.record.symbol);return e.filter(t)}),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return ma.call(this,async()=>N(this.record)?await this.record.ready()&&await super.ready():await super.ready(),`asyncReadyWork2`)}onStreamingUpdates(e){if(this.record){let e={tag:xt(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return vw[e].map(e=>this.record.getValue(e))}},xw=class extends bw{referencePeriod;dynamic;periods=[];constructor(e,t){super(e,e.inputs.Dynamic===`No`?vw[e.inputs.Previous]:void 0,t),this.referencePeriod=gw(e.inputs.Previous,e.aggregation??t.query?.aggregation),this.dynamic=e.inputs.Dynamic!==`No`,this.dynamic&&this.addInner(Ub(t,e=>{let t=new Fb(e.symbol,e.aggregation);return t.aggregation.unit=g[this.referencePeriod],t.aggregation.size=1,t.aggregation.isMultiContract||(t.aggregation.spec=_.None),t.useLastTrade=e.useLastTrade,t.splits=e.splits??!0,t.offset=e.offset,new Q_(t)}))}getPeriods(){return this.base?.size?this.periods:[]}hasHistoryFor(e){if(!this.dynamic)return!0;let t=this.innCont(1)?.getTimeData()[0];return t!==void 0&&+_w(t,this.referencePeriod)<e}loadMoreData(){let e=this.innerSeries[1];return e?.canLoadMoreData&&!e.isLoading?e.loadMoreData():Promise.resolve()}recalculateAt(e,t,n){n&&this.calculate(e)}shutdown(){super.shutdown(),this.innerSeries[1]?.shutdown()}historicalValues(e){let t=this.innCont(1),n=t.getTimeData();if(!n.length)return[];let r=e=>+_w(e,this.referencePeriod),i=A(n,e,r);return r(n[i])>=e&&i--,i<0?[]:[W.High,W.Low,W.Close].map(e=>t.getData(e)?.[i]??null)}calculateAt(e){let t=(t,n=e)=>({key:t,startIndex:e,endIndex:n,levels:this.calculateLevels(t)});if(e===0&&(this.periods=[]),!this.dynamic)return e===0&&this.periods.push(t(0,this.base.size-1)),{};let n=+_w(this.base.getTimeData()[e],this.referencePeriod),r=this.periods.at(-1);return r?.key===n?r.endIndex=e:this.periods.push(t(n)),{}}calculateLevels(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;if(this.dynamic||!this.disabled){let c=this.dynamic?this.historicalValues(e):this.getValues(this.inputs.Previous);if(yw(c)){let[e,l,u]=c;t=(e+l+u)/3;let d=2*t;n=d-l,r=d-e;let f=e-l;i=t+f,a=t-f,o=e+2*(t-l),s=l-2*(e-t)}}return{[W.PPTPIV.id]:t,[W.PPTR1.id]:n,[W.PPTR2.id]:i,[W.PPTR3.id]:o,[W.PPTS1.id]:r,[W.PPTS2.id]:a,[W.PPTS3.id]:s}}},Sw=class extends bw{constructor(e,t){super(e,vw.Day,t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null;if(!this.disabled){let e=this.getValues(`Day`);if(ge(e)){let[l,u,d]=e,f=l-u,[p,m,h,g]=[2,4,6,12].map(e=>1.1/e*f);s=d+p,a=d+m,r=d+h,t=d+g,n=d-g,i=d-h,o=d-m,c=d-p}}return{[W.CPPH4.id]:s,[W.CPPH3.id]:a,[W.CPPH2.id]:r,[W.CPPH1.id]:t,[W.CPPL1.id]:n,[W.CPPL2.id]:i,[W.CPPL3.id]:o,[W.CPPL4.id]:c}}},Cw=class extends q{constructor(e,t){super(e,Wb(t,W.IMPVOL,e=>new ww(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.IMPVOL,0)]}},ww=class extends Q_{constructor(e){super(e)}getRetriever(){return Oi(this.query.symbol)?new Ow:new Tw}onStreamingUpdates(e){}},Tw=class extends C_{addExtraParams(e){e.impl=`y`}getParser(e){return new Dw(e.symbol,e.aggregation,e.offset)}};function Ew(){return new e_([W.DateTime,W.IMPVOL])}var Dw=class extends v_{constructor(e,t,n=0){super(e,t,n)}makeContainer(){return Ew()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.IMPVOL,parseFloat(e[8])))}},Ow=class extends T_{emptyContainer(e,t){return Ew()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date.substring(0,10)));let r=M(e.impliedVolatility);n.addDataPoint(W.IMPVOL,r?e.impliedVolatility*100:null)}},kw=K(`_ABS_CHG`),Aw=K(`_DS1_EMA1`),jw=K(`_DS1_EMA2`),Mw=K(`_DS2_EMA1`),Nw=K(`_DS2_EMA2`),Pw=class extends q{constructor(e,t){super(e,t);let n=(e,t,n,r,i,a)=>Y(Y(e,t,n,r),i,r,a),r=X(kw,ce((e,t)=>({[e.id]:Math.abs(this.baseVal(W.Change,t))}),kw),t),i=n(t,e.inputs.Period1,W.Change,Aw,e.inputs.Period2,jw),a=n(r,e.inputs.Period1,kw,Mw,e.inputs.Period2,Nw),o=Z(W.TSI,(e,t,n)=>100*t/n,i,a),s=Y(o,e.inputs.Period3,W.TSI,W.TSISIG);this.addInner(o,s)}getWrappers(){return[this.wrapInner(W.TSI,1),this.wrapInner(W.TSISIG,2)]}},Fw=class extends q{constructor(e,t){super(e,t);for(let n=1;n<=12;++n){let r=ik(e.inputs,n);this.addInner(Y(t,r,W.Close,e.outFields[n-1]))}}getWrappers(){return _e(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},Iw=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,W.Close);this.addInner(n)}calculateAt(e){let t=null,n=e>0?this.container.getData(this.target)[e-1]:null,r=this.innVal(1,W.EMA,e);if(!M(n))t=r;else{let i=this.baseVal(this.source,e),a=(i/n)**4;t=n+(i-n)/(.6*this.period*a);let o=e=>Math.log10(Math.abs(e-t))>1,s=o(n)||o(r);(!Number.isFinite(t)||s)&&(t=null)}return{[this.target.id]:t}}},Lw=K(`_DIFF`),Rw=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=Math.floor(n/2),i=this.allowEmptyValues,a=SO(Z(Lw,(e,t,n)=>2*t-n,SO(t,r,this.source,W.WMA,i),SO(t,n,this.source,W.WMA,i)),Math.floor(Math.sqrt(n)),Lw,this.target,i);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},zw=K(`_SUM`),Bw=class extends q{constructor(e,t){super(e,t);let n=SO(Z(zw,(e,t,n)=>t+n,PO(t,this.inputs.PeriodRocLong),PO(t,this.inputs.PeriodRocShort)),this.inputs.PeriodWma,zw,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},Vw=K(`_ABS_CHG`),Hw=K(`_HH_LL`),Uw=K(`_MULMA`),Ww=class extends q{constructor(e,t){super(e,t);let n=e.inputs.TurtleChnField===`Close`,r=e.inputs.Direction===`Long`,i=rk(t);if(!n&&i){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let e=J(X(Vw,ce((e,t)=>({[Vw.id]:t>0?e*Math.abs(this.baseVal(W.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,Vw,W.MA),i=r?W.High:W.Low,a=TO(t,this.inputs.PeriodTurtleChn,n?W.Close:i,Hw,r),o=Z(Uw,(e,t)=>this.inputs.FactorAdjATR*t,e),s=r?-1:1,c=Z(this.target,(e,t,n)=>t+s*n,a,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},Gw=class extends q{state;constructor(e,t){super(e,t),this.resetState()}resetState(){let e=this.inputs.ExtendLines??`None`;this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:e===`Left`||e===`Both`,extendRight:e===`Right`||e===`Both`}}calculateAt(e){let t=this.inputs.Period,n=this.inputs.Width,r=this.source;if(e===this.base.size-1&&this.base.size>=t){this.resetState();let e=t*(t+1)/2,i=e*e,a=t*(t+1)*(2*t+1)/6,o=0,s=0,c=1,l=this.base.size-t;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Qe(t))return{};o+=t,s+=c*t,c+=1}let u=(t*s-e*o)/(t*a-i),d=o/t-u*e/t;if(!Qe(u)||!Qe(d))return{};let f=0;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Qe(t))return{};let n=t-(d+u*(e+1));f+=n*n}let p=Math.sqrt(f/t);if(!Qe(p))return{};this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=u,this.state.intercept=d,this.state.stdDevWidth=n*p}return{}}getCurrentState(){return this.state}},Kw=class extends q{computeDone;constructor(e,t){super(e,t,Ub(t,e=>{let t=P(e);return t.symbol=Fi(e.symbol),N(t.symbol)?new Q_(t):new ev(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){let e=this.innCont(0);if(!N(e)||e.size===0)return;let t=this.innCont(1),n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.Close),a=Array(n.length).fill(null);if(!(this.innerSeries[1]instanceof ev)){let o=0,s=e.size,c=t.size;for(let e=0;e<s;++e){for(;o<c&&r[o].getTime()<n[e].getTime();)o++;o<c&&r[o].getTime()===n[e].getTime()&&(a[e]=i[o])}}this.container.setData(this.target,a)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},qw=class extends q{constructor(e,t){let n=zO(t);super(e,t,n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){let t=(t,n)=>N(this.innCont(t))?this.innVal(t,n,e):null,n=t(0,W.Close),r=t(1,W.CSHO);return{[this.target.id]:N(r)&&N(n)?r-n:null}}},Jw=class extends q{computeDone;constructor(e,t){super(e,t,Ub(t,e=>{let t=new Fb(e.symbol,new yd(e.aggregation.unit===g.Year?g.Year:g.Quarter,1),C.BalanceSheet);return t.fields=[W.SharesOutstanding],t.cacheMe=!0,new rv(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){let e=this.innCont(0);if(!N(e)||e.size===0)return;let t=this.innCont(1);if(!N(t)||t.size===0)return;let n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.SharesOutstanding),a=e.getData(W.Close),o=Array(n.length),s=0,c=e.size,l=t.size;for(let e=0;e<c;++e){let t=n[e].getTime();for(;s<l-1&&r[s+1].getTime()<=t;)s++;if(s<l&&r[s].getTime()<=t){let t=i[s],n=a[e];o[e]=N(t,n)?t*n:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},Yw=class extends q{constructor(e,t){super(e,t),JO(this)}calculateAt(e){let t=null,[n]=YO(this);if(e>0){let r=this.innVal(n,this.source,e-1);r!==null&&(t=100*(this.innVal(n,this.source,e)-r)/r)}return{[this.target.id]:t}}},Xw=class extends Gb{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){let n=(e,t)=>this.baseVal(e,t),r=[W.Open,W.High,W.Low,W.Close],i=r.map(t=>n(t,e));if(ge(i)){let a=r.map(t=>n(t,e-1));if(ge(a)){t=i.map((e,t)=>100*(e-a[t])/a[t]);let[n,r]=De(t);if(t[1]=r,t[2]=n,e>1){let n=this.container.getData(W.Close)[e-1];t[4]=t[3]-n}}}}return{[W.Open.id]:t[0],[W.High.id]:t[1],[W.Low.id]:t[2],[W.Close.id]:t[3],[W.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Zw=K(`_DIST`),Qw=K(`_EMA_DIST1`),$w=K(`_EMA_DIST2`),eT=K(`_DIFF`),tT=K(`_EMA_DIFF1`),nT=K(`_EMA_DIFF2`),rT=class extends q{constructor(e,t){super(e,t);let n=TO(t,e.inputs.Period1,W.High,W.HH,!0),r=TO(t,e.inputs.Period1,W.Low,W.LL,!1),i=Y(Y(Z(Zw,(e,t,n)=>this.baseVal(W.Close,e)-(t+n)/2,n,r),e.inputs.Period2,Zw,Qw),e.inputs.Period2,Qw,$w),a=Y(Y(Z(eT,(e,t,n)=>t-n,n,r),e.inputs.Period2,eT,tT),e.inputs.Period2,tT,nT),o=Z(W.STOMOMIX,(e,t,n)=>100*t/n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},iT=K(`_CHG`),aT=K(`_M1`),oT=K(`_M2`),sT=class extends q{constructor(e,t){super(e,t);let n=X(iT,function(e){let t=W.Close,n=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[iT.id]:n}},t),r=(e,t)=>t>=0?t:0,i=(e,t)=>t>=0?0:-t,a=Z(aT,r,n),o=Z(oT,i,n);this.addInner(a,o)}perc(e,t){return 100*e/t}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.past(e,n,aT,this.innCont(1)),i=this.past(e,n,oT,this.innCont(2));if(ge(r)&&ge(i)){let e=me(r),n=me(i);t=this.perc(e-n,e+n)}}return{[W.CHDMOMOSC.id]:t}}},cT=class extends q{constructor(e,t){super(e,t);let n=new sT(e,t),r=$O(e,`MA`,`Average`),i=this.inputs.PeriodAvg,a=r(n,i,W.CHDMOMOSC,W.CHDMOMOSCAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.CHDMOMOSC,1),this.wrapInner(W.CHDMOMOSCAVG,2)]}},lT=K(`_MAX`),uT=K(`_MIN`),dT=K(`_ISUPTREND`),fT=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[lT,uT,dT]}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=1,c=this.baseVal(W.Close,e),l=(e,t)=>N(e)?e:t,u=e=>l(e,0),d=(e,t)=>this.container.getData(e)[t];e>0&&(r=Math.max(u(d(lT,e-1)),c),a=Math.min(u(d(uT,e-1)),c),s=d(dT,e-1));let f=this.inputs.Multiplier,p=this.innVal(1,W.ATR,e);if(N(p)){let l=s===1,u=l?r-f*p:a+f*p,m=d(l?W.VSTOPUP:W.VSTOPLOW,e-1);N(m)||(m=0);let h=l?Math.max(m,u):Math.min(m,u);o=+(c-h>=0);let g=o!=s;n=g?c:r,i=g?c:a,t=g?o===1?n-f*p:i+f*p:h}return{[W.VSTOPUP.id]:o===1?t:null,[W.VSTOPLOW.id]:o===1?null:t,[lT.id]:n,[uT.id]:i,[dT.id]:o}}},pT=K(`_TRENDUP`),mT=K(`_TRENDDOWN`),hT=K(`_TREND`),gT=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[pT,mT,hT,W.BARCOLIX]}calculateAt(e){let t=0,n=0,r=0,i=null,a=0,o=this.innVal(1,W.ATR,e);if(N(o)){let s=(e,t)=>N(e)?e:t,[c,l,u]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e)),d=(l+u)/2,f=this.baseVal(W.Close,e-1),p=this.inputs.Multiplier,m=d-p*o,h=d+p*o,[g,_,v]=[pT,mT,hT].map(t=>this.container.getData(t)[e-1]);t=f>g?Math.max(m,g):m,n=f<_?Math.min(h,_):h,r=c>_?1:c<g?-1:s(v,1);let y=r===1;i=y?t:n,a=+!!y}return{[pT.id]:t,[mT.id]:n,[hT.id]:r,[W.SUPTR.id]:i,[W.BARCOLIX.id]:a}}},_T=class extends q{constructor(e,t){super(e,t);let n=e=>TO(t,e,W.Low,W.LL,!1),r=e=>TO(t,e,W.High,W.HH,!0),i=(e,t,n)=>Z(n,(e,t,n)=>(t+n)/2,e,t),a=(e,t)=>i(n(e),r(e),t),o=a(e.inputs.PeriodConversionLine,W.CONVLN),s=a(e.inputs.PeriodBaseLine,W.BASELN),c=i(o,s,W.LEADSP1),l=a(e.inputs.PeriodLaggingSpan2,W.LEADSP2);this.addInner(o,s,c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(3,W.LEADSP1,e)>this.innVal(4,W.LEADSP2,e));return{[W.LAGGSP.id]:this.baseVal(W.Close,e),[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.CONVLN,1),this.wrapInner(W.BASELN,2),this.wrapInner(W.LEADSP1,3),this.wrapInner(W.LEADSP2,4)]}},vT=K(`_CUM_PRICE`),yT=K(`_CUM_VOL`),bT=K(`_PER_CHG`),xT=e=>e===void 0||e===`Date`;function ST(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function CT(e){switch(e){case g.Tick:case g.Intraday:return`Session`;case g.Day:return`Week`;case g.Week:return`Month`;case g.Month:return`Quarter`;default:return`Year`}}var wT=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,ce(XO,n),t);this.addInner(r)}get helpers(){return[vT,yT,bT]}get vwapField(){return W.VWAP}get hasBands(){return!0}get anchorPeriod(){return this.inputs.AnchorPeriod}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}isSame(e,t){switch(this.anchorPeriod){case`Session`:default:return Ln(e,t);case`Week`:return pi(e,t);case`Month`:return hi(e,t);case`Quarter`:return gi(e,t);case`Year`:return _i(e,t);case`Decade`:return Ug(e,t);case`Century`:return Wg(e,t)}}startsPeriod(e){if(e===0)return!0;if(this.anchorPeriod===`Session`&&this.aggregation&&!this.aggregation.isEndOfDay){let t=this.base.getData(W.TradingDay),n=t?.[e-1],r=t?.[e];if(ST(n)&&ST(r))return n!==r}return!this.isSame(this.dateAt(e-1),this.dateAt(e))}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(this.valueAt(bT,t)===1)return t;return 0}calculateAt(e){let t=!this.startsPeriod(e),n=t?this.valueAt(vT,e-1):0,r=t?this.valueAt(yT,e-1):0,i=this.innVal(0,W.Volume,e),a=n+this.innVal(1,this.source,e)*i,o=r+i,s=a/o;return{[vT.id]:a,[yT.id]:o,[bT.id]:+!t,[this.vwapField.id]:s,...this.hasBands?this.bandsAt(e,s,t):{}}}bandsAt(e,t,n){let r=t,i=t,a=t,o=t;if(n){let n=this.findPrevPeriodChange(e-1),s=this.container.getData(this.vwapField).slice(n,e);s.push(t);let c=he(s),l=s.map(e=>(e-c)*(e-c)),u=Math.sqrt(he(l)),d=this.inputs.Stdev1stMultiplier*u;r=t+d,i=t-d;let f=this.inputs.Stdev2ndMultiplier*u;a=t+f,o=t-f}return{[W.VWAPSD1U.id]:r,[W.VWAPSD1L.id]:i,[W.VWAPSD2U.id]:a,[W.VWAPSD2L.id]:o}}};function TT(e){let t=xT(e.find(e=>e.name===`AnchorPeriod`)?.value);return e.filter(e=>t||e.name!==`Anchor`).map(e=>e.name===`Anchor`?new Date(e.value).toLocaleString():e.value)}var ET=class extends wT{periodStart=0;constructor(e,t){super(e,t)}get vwapField(){return W.AVWAP}get hasBands(){return!1}get anchorPeriod(){let e=super.anchorPeriod;return e===`Auto`?CT(this.aggregation.unit):e}isSameOhlcBar(e,t){let{unit:n,size:r}=this.aggregation;switch(n){case g.Tick:return+e===t;case g.Intraday:return li(t,En(e,r));case g.Day:return li(t,mn(e,r));case g.Week:return pi(e,t);case g.Month:return hi(e,t);case g.Quarter:return gi(e,t);case g.Year:return _i(e,t);default:throw Error(`Unexpected aggregation unit ${g[n]}`)}}findPeriodStart(){let e=this.base.size;if(xT(this.inputs.AnchorPeriod)){let t=this.inputs.Anchor,n=this.base.getTimeData().findIndex(e=>li(t,e)||this.isSameOhlcBar(e,t));return n===-1?e:n}let t=e-1;for(;t>0&&!super.startsPeriod(t);)t--;return Math.max(t,0)}startsPeriod(e){return e===this.periodStart}recalculateAt(e,t,n){n?this.calculate(e):super.recalculateAt(e,t,n)}calculateAt(e){return e===0&&(this.periodStart=this.findPeriodStart()),e>=this.periodStart?super.calculateAt(e):{[vT.id]:null,[yT.id]:null,[bT.id]:null,[W.AVWAP.id]:null}}},DT=K(`_DIFF`),OT=[DT,W.BARCOLIX],kT=[...OT,W.Buy,W.Sell];function AT(e){return e.ShowSignals!==`No`}function jT(e,t,n,r,i){let a=null,o=null,s=null,c=null;N(n,r)&&(s=n-r);let l=t>0?e.getData(DT)[t-1]:null,u=t>0?e.getData(W.BARCOLIX)[t-1]:null;i&&N(s,l)&&(a=s>0&&l<=0?1:null,o=s<0&&l>=0?-1:null),N(s)&&(c=s>0?1:s<0?0:u);let d={[DT.id]:s,[W.BARCOLIX.id]:c};return i&&(d[W.Buy.id]=a,d[W.Sell.id]=o),d}var MT=class extends q{_showSignals;constructor(e,t){super(e,t),this._showSignals=AT(e.inputs)}get helpers(){return this._showSignals??AT(this.inputs)?kT:OT}calculateDiff(e,t,n,r){return jT(e,t,n,r,this._showSignals)}},NT=class extends MT{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MAS),i=n(t,e.inputs.Period2,this.source,W.MAL);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.MAS,e),n=this.innVal(2,W.MAL,e);return this.calculateDiff(this.container,e,t,n)}getWrappers(){return[this.wrapInner(W.MAS,1),this.wrapInner(W.MAL,2)]}},PT=class extends MT{_maIndex;_maTarget;constructor(e,t){super(e,t),JO(this);let n=$O(e,`MA`,`Average`)(t,e.inputs.Period,this.source);this.addInner(n);let[r]=YO(this);this._maIndex=r+1,this._maTarget=n.target}calculateAt(e){let t=this.innVal(this._maIndex,this._maTarget,e),[,n]=YO(this),r=n.getData(this.source)[e],i=this.calculateDiff(this.container,e,r,t);return i[this.target.id]=t,i}},FT=K(`_PVM`),IT=K(`_NVM`),LT=class extends q{constructor(e,t){super(e,t);let n=function(e){return{[FT.id]:e>0?Math.abs(this.baseVal(W.High,e)-this.baseVal(W.Low,e-1)):null}},r=function(e){return{[IT.id]:e>0?Math.abs(this.baseVal(W.Low,e)-this.baseVal(W.High,e-1)):null}},i=X(FT,n,t),a=X(IT,r,t),o=kO(t,W.TR);this.addInner(i,a,o)}calculateAt(e){let t=null,n=null,r=this.period;if(this.atLeast(e,r)){let i=this.past(e,r,FT,this.innCont(1)),a=this.past(e,r,IT,this.innCont(2)),o=this.past(e,r,W.TR,this.innCont(3));if(ge(i)&&ge(a)&&ge(o)){let e=me(i),r=me(a),s=me(o);t=e/s,n=r/s}}return{[W.PLVI.id]:t,[W.MNVI.id]:n}}},RT=K(`_AVG`),zT=class extends q{isPercent;constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.period,i=n(t,r,this.source,RT);this.isPercent=e.inputs.Distance===`Percentage`,this.addInner(i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=this.innVal(1,RT,e),i=this.baseVal(this.source,e);if(r!=null&&r!==0){t=i-r,this.isPercent&&(t=100*t/r);let a=t<=0;if(n=a?1:3,e>0){let r=this.container.getData(this.target)[e-1];r!==null&&(a&&t>r&&(n=0),!a&&t<r&&(n=2))}}return{[this.target.id]:t,[W.BARCOLIX.id]:n}}},BT=class extends q{constructor(e,t){super(e,t);let n=Y(Y(FO(t,this.inputs.PeriodRsi,this.source,W.RSI),this.inputs.PeriodEma1,W.RSI,W.EMA),this.inputs.PeriodEma2,W.EMA,W.EMA),r=J(n,this.inputs.PeriodMa,W.EMA,W.MA),i=Z(W.DOSCH,(e,t,n)=>t-n,n,r),a=J(i,this.inputs.PeriodSig,W.DOSCH,W.DOSCS);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.DOSCH,1),this.wrapInner(W.DOSCS,2)]}},VT=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=this.inputs.Increment,i=Math.min(Math.max(0,this.inputs.Count),10);for(let e=0;e<i;++e){let i=J(t,n+e*r,this.source,this.outFields[e]);this.addInner(i)}}getWrappers(){let e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},HT=K(`_HAO`),UT=K(`_HAH`),WT=K(`_HAL`),GT=K(`_HAC`),KT=class extends q{constructor(e,t){super(e,t);let n=$O(e,`EMA`,`Smoothing1`),r=e.inputs.Period1,i=n(t,r,W.Open),a=n(t,r,W.High),o=n(t,r,W.Low),s=n(t,r,W.Close),c=Z(GT,(e,t,n,r,i)=>(t+n+r+i)/4,i,a,o,s);function l(e,t,n,r){let i=null;if(e>0){let r=this.container.getData(HT)[e-1],a=this.innVal(2,GT,e-1);N(r,a)?i=(r+a)/2:N(t,n)&&(i=(t+n)/2)}return i}let u=Z(HT,l,i,s,c),d=Z(UT,(e,t,n,r)=>N(t,n,r)?Math.max(t,Math.max(n,r)):null,a,u,c),f=Z(WT,(e,t,n,r)=>N(t,n,r)?Math.min(t,Math.min(n,r)):null,o,u,c),p=$O(e,`EMA`,`Smoothing2`),m=e.inputs.Period2,h=p(u,m,HT,W.Open),g=p(d,m,UT,W.High),_=p(f,m,WT,W.Low),v=p(c,m,GT,W.Close),y=X(W.Change,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Close,e-1);N(n,r)?t=n-r:N(n)&&!N(r)&&(t=0)}return{[W.Change.id]:t}},v);this.addInner(h,g,_,v,y)}getWrappers(){return[this.wrapInner(W.Open,1),this.wrapInner(W.High,2),this.wrapInner(W.Low,3),this.wrapInner(W.Close,4),this.wrapInner(W.Change,5)]}},qT=K(`_DELTA`),JT=class extends q{constructor(e,t){super(e,t);let n=e.inputs,r=Y(t,n.PeriodEmaKeltner,W.Close),i=AO(t,n.PeriodAtrKeltner);function a(e,t,n,r){return N(n,r)?n+e*r:null}let o=n.MultiplierKeltner,s=Z(W.KCUP,ce(a,o),r,i),c=Z(W.KCLOW,ce(a,-o),r,i),l=VO(t,n.PeriodBollinger,n.WidthBollinger),u=HO(t,n.PeriodMomentum),d=J(t,n.PeriodMomentum,W.Close);function f(e,t,n,r){let i=null,a=this.innVal(1,W.DONMID,e);return N(a,r)&&(i=t-(a+r)/2),i}let p=UO(Z(qT,f,t,u,d),n.PeriodMomentum,qT,W.TTMSQZOSC);this.addInner(s,c,l,p)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=-1,i=this.innVal(1,W.KCUP,e),a=this.innVal(2,W.KCLOW,e),[o,s]=[W.BOLLBU,W.BOLLBL].map(t=>this.innVal(3,t,e));o<i&&s>a?t=0:n=0;let c=this.innVal(4,W.TTMSQZOSC,e),l=e>0?this.innVal(4,W.TTMSQZOSC,e-1):null;if(N(c)){if(!N(l))r=2;else{let e=c>=0,t=l<c;r=e?t?3:2:+!!t}}return{[W.TTMSQZON.id]:t,[W.TTMSQZOFF.id]:n,[W.BARCOLIX.id]:r}}getWrappers(){return[this.wrapInner(W.TTMSQZOSC,4)]}},YT=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNextFromLatestStart:u.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */ new Map([[W.Close,W.CRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},XT=class extends q{constructor(e,t){if(super(e,t),ak(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.inputs.Symbol.toUpperCase();let i=n.getTimeSeries(r),a=e=>e.query?.symbol,{model:o}=ef(((e,t)=>`{${a(e)}} / {${a(t)}}`)(t,i),!1),s=YT(e.aggregation),c=new Rb(o,[t,i],s),l=$O(e,`MA`,`Average`)(c,this.period,W.CRS,W.CRSAVG);this.addInner(i,c,l),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.CRS,(e,t)=>null,t),r=X(W.CRSAVG,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.CRS,2),this.wrapInner(W.CRSAVG,3)]}},ZT=K(`_DIFF`),QT=K(`_RANK`),$T=K(`_CHG`),eE=K(`_AVG`),tE=K(`_HBRAKE_CHG`),nE=K(`_HEIGHT_DELTA`),rE=K(`_ACTION`),iE=K(`_REVERSAL`),aE=200,oE=10,sE=e=>[e>0,e<0],cE=[null,null,null],lE={None:0,Hold:1,Take:2};function uE([e,t],n){let r=null;if(n>0){let t=this.baseVal(e,n-1);N(t)&&(r=this.baseVal(e,n)-t)}return{[t.id]:r}}var dE=class extends q{useHandbrake;constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,St(1,999,this.inputs.FastPeriod),W.Close),i=St(0,999,this.inputs.SlowPeriod),a=i>0,o=a?n(t,i,W.Close):t,s=Z(ZT,a?(e,t,n)=>t-n:(e,t,n)=>n-t,r,o),c=X($T,ce(uE,[W.Close,$T]),t),l=X(QT,function(e){let t=Math.abs(this.baseVal(ZT,e)),n=null,r=0,i=0;for(let n=e-1;n>=0&&r<aE;--n){let e=Math.abs(this.baseVal(ZT,n));r++,e<t&&i++}return r>0&&(n=Math.floor(i/r*oE)),n===oE&&n--,{[QT.id]:n}},s),u=St(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;let d=n(t,u,W.Close,eE),f=X(tE,ce(uE,[eE,tE]),d);this.addInner(c,s,l,f)}get helpers(){return[nE,W.BARCOLIX,rE,iE]}getStateAt(e){let t=this.innVal(2,ZT,e);return N(t)?sE(t):cE}findPreviousKnownState(e){for(let t=e-1;t>0;t--){let e=this.getStateAt(t);if(e===cE)return cE;let[n,r]=e;if(n||r)return e}return cE}getBuySell(e){let t=this.getStateAt(e);if(t===cE)return cE;let[n,r]=t,i=this.findPreviousKnownState(e),[a,o]=i;if(!n&&!r)return i===cE?cE:[a,o,!1];let s=n!==a||r!==o;return s?[a,o,s]:[n,r,s]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,n=null,r=0,i=-1,a=lE.None,[o,s,c]=this.getBuySell(e),[l,u]=[iE,rE].map(t=>this.getPrev(t,e)),[d,f]=[0,-1].map(t=>this.innVal(4,tE,e+t));if(i=c?oE:this.innVal(3,QT,e),this.useHandbrake&&N(d,f)){let t=o&&f>0||s&&f<0,n=!o&&d>0||!s&&d<0;c?(i=n?oE:12,a=u):(l===!0||u===lE.Hold)&&(t?(i=this.innVal(3,QT,e),a=lE.Take):(i=n?11:13,a=lE.Hold))}if(N(this.innVal(2,ZT,e))){let t=this.innVal(1,$T,e),[n,i]=sE(t),a=Math.abs(t);(o&&n||s&&i)&&(r=a),(o&&i||s&&n)&&(r=-a)}return o?t=1:s&&(n=1),{[W.JPIB.id]:t,[W.JPIS.id]:n,[W.BARCOLIX.id]:i,[nE.id]:r,[rE.id]:a,[iE.id]:c}}},fE=class extends dE{constructor(e,t){e.inputs=ft(B(`JPI`).defaults.inputs.filter(e=>e.name!==`HandbrakePeriod`)),super(e,t)}},pE={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:`EMA`,Height:`Fixed`},mE=class extends dE{constructor(e,t){e.inputs=structuredClone(pE),super(e,t)}},hE=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNextFromLatestStart:u.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */ new Map([[W.Close,W.DRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},gE=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){if(super(e,t),ak(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.indexSymbol;let i=n.getTimeSeries(r),{model:a}=ef(`{${t.query.symbol}} / {${i.query.symbol}} * 100`,!1),o=hE(e.aggregation),s=new Rb(a,[t,i],o);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.DRS,(e,t)=>null,t);this.addInner(e,n),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.DRS,2)]}},_E=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){super(e,t);let n=RO(t,this.indexSymbol,e.aggregation),r=J(n,this.period,W.DRS);this.addInner(n,r),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){let t=this.innVal(1,W.DRS,e),n=this.innVal(2,W.MA,e),r=null;return N(t,n)&&n!==0&&(r=(t/n-1)*100),{[W.MRS.id]:r}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},vE=K(`_SMTH_ROC`),yE=K(`_TEN_SMTH_ROC`);function bE(e,t,n,r,i){return new Xb({source:r,target:i,outFields:[i],aggregation:n,inputs:fO(t)},e,e=>2/e)}var xE=class extends q{constructor(e,t){super(e,t);let n=PO(t,1),r=e.aggregation,i=this.inputs.Period1,a=Z(yE,(e,t)=>10*t,bE(n,i,r,W.ROC,vE)),o=this.inputs.Period2,s=bE(a,o,r,yE,W.PMO),c=Y(s,this.inputs.Period3,W.PMO,W.PMOS);this.addInner(s,c)}getWrappers(){return[this.wrapInner(W.PMO,1),this.wrapInner(W.PMOS,2)]}},SE=K(`_VOL_AVG`),CE=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`)(t,this.period,W.Volume,SE,!0);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(0,W.Volume,e),r=this.innVal(1,SE,e);return N(n,r)&&r!==0&&(t=n/r),{[this.target.id]:t}}},wE=e=>Ze(.5**(1/e),6),TE=52,EE=53,DE=27,OE=5,kE=131,AE=(()=>{let e=wE(51),t=Oe(TE,t=>e**+t),n=TE/me(t);return t.map(e=>e*n)})(),jE=[`Renko`,`Kagi`,`PointAndFigure`,`LineBreak`],ME=class extends q{isDaily;isFeasible=!0;constructor(e,t){super(e,t);let n=zb(t),r=n.query?.curveStyle;this.isFeasible=!(n instanceof ev)&&(!N(r)||!jE.includes(h[r])),this.isDaily=e.aggregation.unit===g.Day}acceptable(e,t,n,r){return this.isDaily?r===0||!pi(this.baseVal(W.DateTime,t),this.baseVal(W.DateTime,n)):e>0&&n-t>=OE}pluckValues(e){let t=0,n=[],r=e+OE;for(let i=0;t<EE&&e-i>0;i++){let a=e-i,o=this.baseVal(this.source,a);this.acceptable(o,a,r,t)&&(n.push(o),r=a,t++)}return n}calculateAt(e){let t=null;if(this.isFeasible&&e>=kE){let n=1,r=this.pluckValues(e),i=r.length;if(i>=DE)for(let e=0;e<i-1;e++){let t=r[e]/r[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*AE[e]+1,n*=t}t=100*(n-1)}return{[this.target.id]:t}}},NE=20;function PE(e,t){switch(e){case g.Intraday:return t>=240?3:t>=120?2:1;case g.Day:default:return 5;case g.Week:return 15;case g.Month:return 60;case g.Quarter:case g.Year:return 240}}function FE(e){return e===_.Continue||e===_.Nearest}var IE=class extends q{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,n){super(e,n,Ub(n,e=>{let t=re[$()?.config.mode??`Unspecified`];if(!Vc(t))return n;let r=e.duplicate(),i=e.aggregation;if(i.hasSpec)return FE(i.spec)?n:new ev(r,!0);let a=i.unit===g.Intraday&&i.size<=5,o=PE(i.unit,i.size);r.aggregation=a?new yd(g.Tick,i.size,_.PerSeconds):new yd(g.Intraday,o);let s=a?1:3;return r.barsToFetch=Math.min(z.MAX_INTRADAY_BARS,s*e.barsToFetch),new Q_(r)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof ev,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){let e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<NE&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,n){if(e.src!==this.innerSeries[0])return;let r=n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED;this.notify(r,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(W.Change,1),this.wrapInner(W.Open,1),this.wrapInner(W.Close,1)]}},LE=class extends IE{constructor(e,t){super(e,!1,t)}},RE=class extends IE{constructor(e,t){super(e,!0,t)}},zE=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.ATR,e),r=this.baseVal(W.Close,e);return N(n,r)&&r>0&&(t=n/r*100),{[W.ATRP.id]:t}}},BE=K(`_DR`),VE=class extends q{constructor(e,t,n){super(e,n);let r=X(BE,e=>{let t=this.baseVal(W.High,e),n=this.baseVal(W.Low,e);return{[BE.id]:N(t,n)?t-n:null}},n),i=$O(e,`MA`)(r,this.inputs.Period,BE,W.ADR);if(t){let e=Z(this.target,(e,t,n)=>!N(t,n)||n===0?null:t/n*100,i,n);this.addInner(e)}else this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},HE=class extends VE{constructor(e,t){super(e,!1,t)}},UE=class extends VE{constructor(e,t){super(e,!0,t)}},WE=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,ce(XO,n),t),i=PO(r,this.inputs.PeriodRoc1,n),a=PO(r,this.inputs.PeriodRoc2,n),o=PO(r,this.inputs.PeriodRoc3,n),s=PO(r,this.inputs.PeriodRoc4,n),c=J(i,this.inputs.PeriodMa1,W.ROC,W.MA1),l=J(a,this.inputs.PeriodMa2,W.ROC,W.MA2),u=J(o,this.inputs.PeriodMa3,W.ROC,W.MA3),d=J(s,this.inputs.PeriodMa4,W.ROC,W.MA4),f=Z(W.KST,(e,t,n,r,i)=>t+2*n+3*r+4*i,c,l,u,d),p=J(f,this.inputs.PeriodSig,W.KST,W.KSTSIG);this.addInner(f,p)}getWrappers(){return[this.wrapInner(W.KST,1),this.wrapInner(W.KSTSIG,2)]}},GE=K(`_EMA1`),KE=K(`_EMA2`),qE=K(`_MACD`),JE=K(`_PCTK`),YE=K(`_PCTD`),XE=K(`_PCTK2`),ZE=class extends q{constructor(e,t){super(e,t);let n=Z(qE,(e,t,n)=>t-n,Y(t,this.inputs.PeriodShort,W.Close,GE),Y(t,this.inputs.PeriodLong,W.Close,KE)),r=this.inputs.PeriodStoch1,i=this.inputs.PeriodStoch2,a=$O(e,`EMA`),o=a(EO(a(EO(n,r,JE,!1,qE),i,JE,YE),r,XE,!1,YE),i,XE,this.target);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},QE=K(`_EMA1`),$E=K(`_EMA2`),eD=K(`_CORE`),tD=class extends q{isEmpty=!1;constructor(e,t){if(super(e,t),ak(t)&&e.aggregation?.isEndOfDay){let n=[`$ADVT`,`$DECT`];switch(this.inputs.Source){case`TotalStocks`:default:break;case`NYSEStocks`:n=[`$ADVN`,`$DECN`];break;case`NasdaqStocks`:n=[`$AVDQ`,`$DECQ`]}let r=this.getSeries(t.query,n[0]),i=this.getSeries(t.query,n[1]),a=this.getTargetSeries(e,r,i);this.addInner(r,i,a),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;let e=X(W.Close,(e,t)=>null,t),n=X(W.Close,(e,t)=>null,t),r=X(this.target,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}get baseIndex(){return+!this.isEmpty}getSeries(e,t){let n=e.duplicate();return n.symbol=t,$().getTimeSeriesDataSource().getTimeSeries(n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e!==this.innerSeries[0]&&(e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}},nD=class extends tD{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=(e,t,n)=>t-n,i=Z(eD,this.inputs.RatioAdjusted===`Yes`?(e,t,n)=>(t-n)/(t+n)*1e3:r,t,n),a=Y(i,this.inputs.Period1,eD,QE),o=Y(i,this.inputs.Period2,eD,$E);return Z(this.target,r,a,o)}},rD=K(`_INN_HL_ACC_IX`),iD=new yd;function aD(e,t,n){return new oD({aggregation:iD,source:null,target:n,outFields:[n],inputs:{...t}},e)}var oD=class extends q{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof ev)this.canLoadMoreData=!1;else{let n=this.inputs.Source===`PriceIndex`?`$MADX`:`$FADX`,r=this.getSeries(t.query,n);if(this.addInner(r),this.isWeekly=e.aggregation.unit===g.Week,this.isWeekly){let e=aD(this.getSeries(t.query,n,iD),this.inputs,rD);this.addInner(e)}this.canLoadMoreData=!0,this.initialNotification=!0}}getSeries(e,t,n){let r=e.duplicate();return r.symbol=t,n&&(r.aggregation=n,r.barsToFetch=z.US_TRADING_DAYS_PER_YEAR*15),$().getTimeSeriesDataSource().getTimeSeries(r)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Close);ge(r)&&(t=me(r))}return{[this.target.id]:t}}calculateAtWeekly(e){let t=this.container?.size??-1,n=null,r=this.innCont(2);if(t>0&&e===t-1)n=r.getLastDataPoint(rD);else{let t=this.container.getTimeData()[e],i=r.getTimeData(),a=A(i,t),o=i[a],s=null;for(;a<r.size&&pi(t,o);)s=a,a+=1,o=i[a];s!==null&&(n=r.getData(rD)[s])}return{[this.target.id]:n}}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e!==this.innerSeries[0]&&e===this.innerSeries[1]&&this.innHasData(1)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},sD=K(`_RSI1`),cD=K(`_RSI1_MOM`),lD=K(`_RSI2`),uD=K(`_RSI2_MA`),dD=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period1Rsi,W.Close,sD),r=X(cD,le(ZO,this.inputs.Period1Mom,sD),n),i=J(FO(t,this.inputs.Period2Rsi,W.Close,lD),this.inputs.Period2Ma,lD,uD),a=Z(W.CMBCI,(e,t,n)=>t+n,r,i),o=J(a,this.inputs.PeriodFastMa,W.CMBCI,W.CMBCIF),s=J(a,this.inputs.PeriodSlowMa,W.CMBCI,W.CMBCIS);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(W.CMBCI,1),this.wrapInner(W.CMBCIF,2),this.wrapInner(W.CMBCIS,3)]}};function fD(e){return new dw({source:W.Close,inputs:{},outFields:yO(`COTLC`)},e)}var pD=class extends q{constructor(e,t){super(e,fD(t));let n=Number.parseInt(this.inputs.History),r=n===6?26:52*n,i=EO(this.innerSeries[0],r,W.COTI,!1,W.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(i)}getWrappers(){return[this.wrapInner(W.COTI,1)]}},mD=K(`_MUL_ATR`),hD=class extends q{isLong;constructor(e,t){super(e,t),this.isLong=this.inputs.Direction===`Long`;let n=this.period,r=AO(t,n),i=this.inputs.Multiplier,a=Z(mD,(e,t)=>t===null?null:i*t,r),o=TO(t,n,W.High,W.HH,!0),s=TO(t,n,W.Low,W.LL,!1);this.addInner(a,o,s)}calculateAt(e){let t=null,n=null,r=this.innVal(1,mD,e);return r!==null&&(this.isLong?t=this.innVal(2,W.HH,e)-r:n=this.innVal(3,W.LL,e)+r),{[W.CHEXL.id]:t,[W.CHEXS.id]:n}}},gD=class extends q{constructor(e,t){let n=e.outFields??[],r=e=>{let t=$().getTimeSeriesDataSource();return e.seriesKind=C.Options,e.fields=n,t.getTimeSeries(e)},i=n.length===1?n[0]:void 0,a=i?Wb(t,i,r):Ub(t,r);super(e,a),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}},_D=class extends gD{},vD=class extends gD{},yD=class extends gD{},bD=class extends gD{},xD=class extends gD{},SD=class extends gD{},CD=class extends gD{},wD=class extends q{constructor(e,t){super(e,t);let n=AO(t,1),r=this.inputs.Period,i=TO(t,r,W.High,W.HH,!0),a=TO(t,r,W.Low,W.LL,!1);this.addInner(n,i,a)}calculateAt(e){let t=null,n=this.period;if(e>n){let r=this.past(e,n,W.ATR,this.innCont(1));if(ge(r)){let i=me(r)/(this.innVal(2,W.HH,e)-this.innVal(3,W.LL,e));t=100*Math.log10(i)/Math.log10(n)}}return{[this.target.id]:t}}},TD=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MACLD1),i=n(t,e.inputs.Period2,this.source,W.MACLD2);this.addInner(r,i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(1,W.MACLD1,e)>this.innVal(2,W.MACLD2,e));return{[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.MACLD1,1),this.wrapInner(W.MACLD2,2)]}},ED=K(`_CORE`),DD=class extends tD{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=Z(ED,(e,t,n)=>t/(t+n),t,n);return $O(e,`MA`,`Average`)(r,this.inputs.Period,ED,this.target)}},OD=class extends q{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=nk(e.aggregation),this.stdDevs=this.toInt(`StandardDeviations`),this.periodForecast=this.inputs.PeriodForecast;let n=this.getHistVolPeriod();if(n!==null){let r=WO(t,n,e.aggregation);this.addInner(r)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return this.volatilityParam===`Custom`}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(W.HV))/100}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(this.haveVolatility){let s=this.base.size-this.periodForecast;if(e>=s){let c=this.base.getLastDataPoint(W.Close),l=this.getVolatilityPercent(),u=e-s+1,d=c*l*Math.sqrt(u/this.unitsPerYear);if(t=c+d,n=c-d,this.stdDevs>1){let e=2*d;if(r=c+e,i=c-e,this.stdDevs>2){let e=3*d;a=c+e,o=c-e}}}}return{[W.PCUP1.id]:t,[W.PCDN1.id]:n,[W.PCUP2.id]:r,[W.PCDN2.id]:i,[W.PCUP3.id]:a,[W.PCDN3.id]:o}}recalculateAt(e,t,n){let r={tag:xt(),src:this.innerSeries[0]};n&&this.calculate(r)}},kD=class extends q{constructor(e,t){super(e,Ub(t,e=>new AD(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.Delta,0),this.wrapInner(W.Gamma,0),this.wrapInner(W.Theta,0),this.wrapInner(W.Vega,0)]}},AD=class extends Q_{constructor(e){super(e)}getRetriever(){return Oi(this.query.symbol)?new ND:Pi(this.query.symbol)?new PD:new MD}};function jD(){return new e_([W.DateTime,W.Delta,W.Gamma,W.Theta,W.Vega])}var MD=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return jD()}},ND=class extends T_{emptyContainer(e,t){return jD()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date.substring(0,10))),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},PD=class extends T_{emptyContainer(e,t){return jD()}addExtraParams(e){e.fields=`delta,gamma,theta,vega`}get iterateForward(){return!0}getPageName(){return`getEquityOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date)),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},FD=K(`_RSI1`),ID=K(`_RSI2`),LD=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period1,this.source,FD),r=FO(t,this.inputs.Period2,this.source,ID),i=Z(W.RSA,(e,t,n)=>(t+n)/2,n,r),a=$O(e,`MA`,`Average`)(i,this.inputs.PeriodAvg,W.RSA,W.RSAAVG);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.RSA,1),this.wrapInner(W.RSAAVG,2)]}},RD=class extends q{constructor(e,t){super(e,t),JO(this);let n=e.inputs.PeriodRSI,r=e.inputs.PeriodTradeSignal,i=e.inputs.PeriodMarketBase,a=e.inputs.PeriodBB,[o]=YO(this),s=this.innerSeries[o],c=FO(s,n,this.source,W.TDIPRC),l=J(c,r,W.TDIPRC,W.TDITSL),u=J(c,i,W.TDIPRC,W.TDIMBL),d=LO(c,a,W.TDIPRC,W.MSD);this.addInner(c,l,u,d)}calculateAt(e){let t=this.inputs.MultiplierBB,n=+!!this.sourceNeedsCompute,r=this.innVal(1+n,W.TDIPRC,e),i=this.innVal(2+n,W.TDITSL,e),a=this.innVal(3+n,W.TDIMBL,e),o=this.innVal(4+n,W.MSD,e),s=null,c=null;if(N(a,o)){let e=t*o;s=a+e,c=a-e}return{[W.TDIPRC.id]:r,[W.TDITSL.id]:i,[W.TDIMBL.id]:a,[W.TDIUPR.id]:s,[W.TDILWR.id]:c}}},zD=K(`_ANCHR`),BD=class extends q{isLong;isPercent;constructor(e,t){super(e,t);let n=e.inputs.Period,r=e.inputs.Range,i=e.inputs.Direction;this.isLong=i===`Long`,this.isPercent=e.inputs.Type===`Percent`;let a=r===`Close`,o=W.Close;a||(o=this.isLong?W.High:W.Low);let s=TO(t,n,o,zD,this.isLong);this.addInner(s)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=this.innVal(1,zD,e),r=this.inputs.StopValue;if(n!==null){let e=this.isPercent?n*r/100:r;t=this.isLong?n-e:n+e}let i=+!!this.isLong;return{[W.PPS.id]:t,[W.BARCOLIX.id]:i}}},VD=K(`_HH_N`),HD=K(`_LL_N`),UD=K(`_HH_H1`),WD=K(`_LL_H1`),GD=K(`_HH_H2`),KD=K(`_LL_H2`),qD=class extends q{constructor(e,t){super(e,t),JO(this);let n=e.inputs.Period,r=Math.floor(n/2),i=TO(t,n,W.High,VD,!0),a=TO(t,n,W.Low,HD,!1),o=TO(t,r,W.High,UD,!0),s=TO(t,r,W.Low,WD,!1),c=TO(t,r,W.High,GD,!0),l=TO(t,r,W.Low,KD,!1);this.addInner(i,a,o,s,c,l)}calculateAt(e){let t=this.period,n=Math.floor(t/2),[,r]=YO(this),i=r.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:i};let a=+!!this.sourceNeedsCompute,o=this.innVal(1+a,VD,e),s=this.innVal(2+a,HD,e),c=this.innVal(3+a,UD,e),l=this.innVal(4+a,WD,e),u=this.innVal(5+a,GD,e-n),d=this.innVal(6+a,KD,e-n);if(!N(o,s,c,l,u,d))return{[this.target.id]:i};let f=(o-s)/t,p=(c-l)/n,m=(u-d)/n,h=0;p>0&&m>0&&f>0&&(h=(Math.log(p+m)-Math.log(f))/Math.log(2));let g=Math.exp(-4.6*(h-1));g=Math.max(.01,Math.min(1,g));let _=e>0?this.container.getData(this.target)[e-1]:i,v=_===null?i:g*i+(1-g)*_;return{[this.target.id]:v}}},JD=K(`_MIDPOINT`),YD=K(`_VALUE`),XD=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Period,r=X(JD,ce(bS,JD),t),i=TO(r,n,JD,W.HH,!0),a=TO(r,n,JD,W.LL,!1);this.addInner(r,i,a)}get helpers(){return[YD]}calculateAt(e){let t=this.innVal(1,JD,e),n=this.innVal(2,W.HH,e),r=this.innVal(3,W.LL,e);if(!N(n,r,t))return{[W.FISHER.id]:null,[W.FISHTRG.id]:null,[YD.id]:null};let i=n-r,a=i===0?.5:(t-r)/i,o=t=>this.container.getData(t)[e-1],s=e>0?o(YD):null,c=.66*(a-.5)+.67*(s??0);c>.99?c=.999:c<-.99&&(c=-.999);let l=e>0?o(W.FISHER):null,u=.5*Math.log((1+c)/(1-c))+.5*(l??0);return{[W.FISHER.id]:u,[W.FISHTRG.id]:l,[YD.id]:c}}},ZD=class extends q{constructor(e,t){super(e,t),JO(this)}computeMidranks(e){let t=e.length,n=e.map((e,t)=>({v:e,i:t}));n.sort((e,t)=>e.v-t.v);let r=Array(t),i=0;for(;i<t;){let e=i,a=n[i].v;for(;e+1<t&&n[e+1].v===a;)e++;let o=(i+1+(e+1))/2;for(let t=i;t<=e;t++)r[n[t].i]=o;i=e+1}return r}pearsonCorrelation(e){let t=e.length;if(t<2)return null;let n=(t+1)/2,r=0;for(let n=0;n<t;n++)r+=e[n];let i=r/t,a=0,o=0,s=0;for(let r=0;r<t;r++){let t=r+1-n,c=e[r]-i;a+=t*c,o+=t*t,s+=c*c}let c=Math.sqrt(o*s);return c===0?null:a/c}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);if(i.every(e=>e!==null)){let e=this.computeMidranks(i),n=this.pearsonCorrelation(e);n!==null&&(t=100*n)}}return{[W.RCI.id]:t}}},QD=class extends q{constructor(e,t){super(e,t);let n=this.source,r=new ZD({source:n,target:W.RCI,inputs:{Period:e.inputs.Period}},t),i=e.inputs.PeriodSignal,a=$O(e,`MA`,`Smoothing`)(r,i,W.RCI,W.RCISIG);this.addInner(r,a)}getWrappers(){return[this.wrapInner(W.RCI,1),this.wrapInner(W.RCISIG,2)]}},$D=K(`_ATR`),eO=class extends q{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow=e.inputs.Method===`High/Low`,this.isAtrMode=e.inputs.PercentMode===`ATR`,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||JO(this),this.isAtrMode){let t=e.inputs.PeriodAtr,[n]=this.useHighLow?[0]:YO(this),r=this.innerSeries[n],i=AO(r,t,`SMA`,$D);this.addInner(i)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(W.High,e);let[,t]=YO(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(W.Low,e);let[,t]=YO(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(W.Close,e);let[,t]=YO(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){let t=!this.useHighLow&&this.sourceNeedsCompute?1:0,n=this.innVal(1+t,$D,e),r=this.getAtrDenom(e);if(n===null||r===null||r===0)return 0;let i=n/r*100;return this.atrMult*i}return this.percent}pct(e,t){return e===0?0:(t-e)/e*100}resetState(){this.state={mode:0,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:/* @__PURE__ */ new Map}}calculateAt(e){let t=this.getHigh(e),n=this.getLow(e),r=this.getDevPct(e);if(t===null||n===null)return{};if(e===0){this.resetState();let n=this.useHighLow?this.baseVal(W.Close,e):t;return this.setPivot(n,e),this.setCandidate(n,e),{}}if(this.state.mode===0)this.pct(this.state.pivotPrice,t)>=r?(this.state.mode=1,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,n)>=r&&(this.state.mode=-1,this.setCandidate(n,e));else if(this.state.mode===1){let i=t>=this.state.candPrice;i&&this.setCandidate(t,e);let a=(this.state.candPrice-n)/this.state.candPrice*100;if(!i&&a>=r){let t=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(t,r),this.setPivot(r,t),this.setCandidate(n,e),this.state.mode=-1}}else if(this.state.mode===-1){let i=n<=this.state.candPrice;i&&this.setCandidate(n,e);let a=(t-this.state.candPrice)/this.state.candPrice*100;if(!i&&a>=r){let n=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(n,r),this.setPivot(r,n),this.setCandidate(t,e),this.state.mode=1}}return{}}getCurrentState(){return this.state}},tO=class extends q{constructor(e,t){super(e,t);let n=X(W.BOP,function(e){let t=null,[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e));if(N(n,r,i,a)){let e=r-i;t=e===0?0:(a-n)/e}return{[this.target.id]:t}},t),r=$O(e,`MA`,`Average`),i=this.period,a=r(n,i,W.BOP,W.BOPAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.BOP,1),this.wrapInner(W.BOPAVG,2)]}};function nO(e,t){let n=e.length;if(n<2||t.length!==n)return null;let r=0,i=0,a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c],l=t[c];r+=n,i+=l,a+=n*n,o+=l*l,s+=n*l}let c=n*s-r*i,l=Math.sqrt((n*a-r*r)*(n*o-i*i));if(l===0||!Number.isFinite(l))return null;let u=c/l;return Number.isFinite(u)?Math.max(-1,Math.min(1,u)):null}var rO=class extends q{constructor(e,t){if(super(e,t),ak(t)){let e=this.inputs.Symbol?.toUpperCase();if(e){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=e;let i=n.getTimeSeries(r);this.addInner(i),this.canLoadMoreData=!0,this.initialNotification=!0}}}compareCloseAt(e){let t=this.innCont(1);if(!t||t.isEmpty)return null;let n=this.baseVal(W.DateTime,e);if(n===null)return null;let r=t.getData(W.DateTime),i=t.getData(W.Close);if(r.length===0)return null;let a=n.valueOf(),o=A(r,a,Number),s=r[o];if(!N(s))return null;let c=s.valueOf()<=a?o:o-1;if(c<0)return null;let l=i[c];return N(l)?l:null}calculateCorrelation(e){let t=this.period;if(!this.atLeast(e,t)||!this.innHasData(1))return null;let n=[],r=[];for(let i=e-t+1;i<=e;i++){let e=this.baseVal(W.Close,i),t=this.compareCloseAt(i);if(!N(e,t))return null;n.push(e),r.push(t)}return nO(n,r)}calculateAt(e){return{[this.target.id]:this.calculateCorrelation(e)}}async loadMoreData(e=!0){if(this.isLoading||this.innerSeries.length<2||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},iO=4,aO=4,oO=K(`_RVI_NUM`),sO=K(`_RVI_DEN`),cO=K(`_RVI_NUMAVG`),lO=K(`_RVI_DENAVG`);function uO(e){if(e.length<aO||!ge(e))return null;let[t,n,r,i]=e;return(t+2*n+2*r+i)/6}var dO={_TR:$x,_RSI:Ax,MA:Yb,MAEXP:Zb,MAHLC:$b,VOL:tx,MAENV:sx,MAENVEXP:cx,MAENVSMO:lx,MATRI:ux,MAWEI:dx,MAVOL:Yb,MASMO:Qb,MACD:Sx,MACDEXP:Cx,MACDV:xx,GMMA:Fw,OSCI:fx,OSCIVOL:fx,RSI:Mx,RSIMOD:Nx,RSISTO:Px,RSA:LD,WPERCR:zx,HHLL:Fx,WGCL:Ix,STOCHF:Hx,STOCHS:Ux,BBANDS:qx,BWIDTH:Jx,BPERC:Yx,OBVOL:Qx,ATR:rS,ADR:HE,ATRP:zE,ADRP:UE,ADX:pS,ADXMOD:mS,ADL:hS,ADWM:gS,CHAOSC:_S,TP:vS,KELCHN:OS,KELBND:kS,DONCHN:jS,DONWIDTH:MS,PVT:NS,ROC:RS,TRIX:PS,PPMOV:zS,PIVPTS:xw,CPP:Sw,ARNUPDW:US,ARNOSC:WS,TCHN:GS,TCHRE:KS,ALLG:JS,PLTLN:YS,AWEOSC:ZS,MFV:eC,CLV:$S,CHAMF:tC,CHAVOL:rC,DPO:iC,CCI:oC,EMV:sC,ERBRPOW:uC,ERBLPOW:lC,FI:fC,MI:_C,MOM:vC,MFI:yC,MSD:bC,NVI:wC,PVI:TC,PPO:Ex,PVO:Dx,HV:DC,PERF:OC,WASI:AC,WWVOL:NC,PARTP:zC,MOVLR:BC,TRSP:tw,TARGP:nw,COTLC:dw,COTDAG:fw,COTFTR:pw,IMPVOL:Cw,CTM:wx,CPMI:Tx,DEMA:FS,EOSC:IS,TEMA:LS,TSI:Pw,ADJATR:iS,COTR:aS,MCGD:Iw,HMA:Rw,COPP:Bw,REATRS:Ww,LINRCHN:Gw,CSHO:Kw,CSHB:qw,MKTCAP:Jw,CTPI:Wx,PCTCHG:Yw,OPINT:nx,STOMOMIX:rT,CHDMOMOSC:cT,VSTOP:fT,ATREXT:Jb,SUPTR:gT,ICHCLD:_T,VWAP:wT,MACROSS:NT,PACROSS:PT,VOIN:LT,DIFA:zT,DOSC:BT,BBANDW:Xx,MARIB:VT,HASMO:KT,TTMSQZ:JT,CRS:XT,JPI:dE,CTTP:fE,CTTI:mE,DRS:gE,MRS:_E,PMO:xE,RVOL:CE,WGALPH:ME,VOLAP:LE,AVWAP:ET,KST:WE,STC:ZE,MCCLO:nD,NHLAI:oD,CMBCI:dD,COTI:pD,CHEXI:hD,MBBANDS:Zx,OPTIV:_D,IVRANK:vD,IVPCTL:yD,OPTVOLPC:bD,OPTOIPC:xD,OPTVOL:SD,OPTOI:CD,CHOP:wD,MACLD:TD,BTI:DD,FRAMA:qD,FISHER:XD,PC:OD,GREEKS:kD,PVACP:RE,TDI:RD,PPS:BD,RCI:QD,BOP:tO,CORR:rO,RVI:class extends q{constructor(e,t){super(e,t);let n=(e,t)=>function(n){let r=this.past(n,aO,e),i=this.past(n,aO,t),a=null;if(ge(r)&&ge(i)){let e=r,t=i;a=uO(e.map((e,n)=>e-t[n]))}return{[this.target.id]:a}},r=X(oO,n(W.Close,W.Open),t),i=X(sO,n(W.High,W.Low),t),a=this.period,o=J(r,a,oO,cO),s=J(i,a,sO,lO),c=Z(W.RVI,(e,t,n)=>n===0?null:t/n,o,s),l=X(W.RVISIG,function(e){return{[this.target.id]:uO(this.past(e,iO,W.RVI))}},c);this.addInner(c,l)}getWrappers(){return[this.wrapInner(W.RVI,1),this.wrapInner(W.RVISIG,2)]}},ZIGZAG:eO,DIDI:class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.source??W.Close,i=n(t,this.inputs.PeriodShort,r),a=n(t,this.inputs.PeriodMedium,r),o=n(t,this.inputs.PeriodLong,r),s=(e,t,n)=>n===0?null:t/n,c=Z(W.DIDIS,s,i,a),l=Z(W.DIDIL,s,o,a);this.addInner(c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=this.innVal(1,W.DIDIS,e),n=this.innVal(2,W.DIDIL,e),r=this.innVal(1,W.DIDIS,e-1),i=this.innVal(2,W.DIDIL,e-1),a=t===null||n===null?-1:+(t>n),o=null,s=null;if(t!==null&&n!==null&&r!==null&&i!==null){let e=(n+i)/2;t>n&&r<=i&&(o=e),n>t&&i<=r&&(s=e)}return{[W.DIDIUP.id]:o,[W.DIDIDN.id]:s,[W.BARCOLIX.id]:a}}getWrappers(){return[this.wrapInner(W.DIDIS,1),this.wrapInner(W.DIDIL,2)]}}};function fO(e){return{[z.INPUT_PERIOD]:e}}function pO(e){return{[z.INPUT_SYMBOL]:e}}function mO(e){return{target:e,source:null,inputs:OO}}function hO(e){return e instanceof Rb&&typeof e.seasonalAverageOffset==`number`&&e.seasonalAverageOffset<0}function gO(e,t){if(!N(e))return e;for(let[n,r]of t.policy.fieldMap.entries())if(r===e)return n;return e}function _O(e,t,n){if(!z.CLIENT_SIDE_SEASONAL_AVERAGE_DISTRIBUTED_STUDIES.has(e)||!hO(n))return null;let r=gO(t.source,n),i=t.target??t.outFields?.[0];if(!M(i))return null;let a=n.innerSeries.map(n=>{let a=vO(e,{...t,source:r??null,target:i,outFields:[i],inputs:P(t.inputs??{})},n);return a.query=n.query,a}),o=new Rb(n.exprModel,a,{...n.policy,fieldMap:/* @__PURE__ */ new Map([[i,i]])});return new Kb({...t,source:r??null,target:i,outFields:[i]},o)}function vO(e,t,n){let r=_O(e,t,n);if(r)return r;if(rt(dO,e))return new dO[e](t,n);let i=$()?.config.extensions?.studyProvider;if(i){let r=i.factory(e,t,n);if(r)return r}throw Error(`Study ${e} has not been implemented yet.`)}function yO(e){return B(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>W[e])}function bO(e,t,n,r){return{source:t,target:n,inputs:fO(e),allowEmptyValues:r}}function J(e,t,n,r=W.MA,i=!1){return vO(`MA`,bO(t,n,r,i),e)}function Y(e,t,n,r=W.EMA,i=!1){return vO(`MAEXP`,bO(t,n,r,i),e)}function xO(e,t,n,r=W.SMA,i=!1){return vO(`MASMO`,bO(t,n,r,i),e)}function SO(e,t,n,r=W.WMA,i=!1){return vO(`MAWEI`,bO(t,n,r,i),e)}function CO(e,t,n,r=W.HMA,i=!1){return vO(`HMA`,bO(t,n,r,i),e)}function wO(e,t,n,r,i=W.Close){return vO(`MACDEXP`,{source:i,inputs:{Period1:t,Period2:n,Period3:r},outFields:[W.MACD,W.MACDS,W.MACDH]},e)}function TO(e,t,n,r,i,a=!1){return new Lx({source:n,target:r,inputs:fO(t)},i,a,e)}function EO(e,t,n,r,i=null){return new Rx({source:i,target:n,inputs:fO(t)},r,e)}function DO(e,t,n=W.PCTCHG){return vO(`PCTCHG`,{source:t,target:n,inputs:OO},e)}var OO={};function kO(e,t=W.TR){return vO(`_TR`,mO(t),e)}function AO(e,t,n=`SMA`,r=W.ATR){return vO(`ATR`,{target:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n},source:null},e)}function jO(e,t,n=`MA`,r=W.Close,i=W.ADJATR){return vO(`ADJATR`,{source:r,target:i,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n}},e)}function MO(e,t=W.ADL){return vO(`ADL`,mO(t),e)}function NO(e,t=W.TP){return vO(`TP`,mO(t),e)}function PO(e,t,n=W.Close,r=W.ROC){return vO(`ROC`,{source:n,target:r,inputs:fO(t)},e)}function FO(e,t,n,r=W.RSI,i=!1){return vO(`_RSI`,{source:n,target:r,inputs:{...fO(t),Modified:i}},e)}function IO(e,t=W.MFMUL){return vO(`MFV`,mO(t),e)}function LO(e,t,n,r=W.MSD){return vO(`MSD`,{source:n,target:r,inputs:fO(t)},e)}function RO(e,t,n,r=W.DRS){return vO(`DRS`,{target:r,inputs:pO(t),aggregation:n,source:null},e)}function zO(e,t=W.CSHO){return vO(`CSHO`,mO(t),e)}function BO(e,t,n){let r=`TCHN`;return vO(r,{inputs:{PeriodUpper:t,PeriodLower:t,Range:n},outFields:yO(r),source:null},e)}function VO(e,t,n,r=W.Close){let i=`BBANDS`,a=yO(i);return vO(i,{source:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_WIDTH]:n},outFields:a},e)}function HO(e,t){let n=`DONCHN`,r=yO(n);return vO(n,{inputs:fO(t),outFields:r,source:null},e)}function UO(e,t,n,r=W.MOVLR){return vO(`MOVLR`,{source:n,inputs:fO(t),target:r},e)}function WO(e,t,n,r=W.Close,i=W.HV){return vO(`HV`,{source:r,target:i,aggregation:n,inputs:fO(t)},e)}function X(e,t,n){return new SS(mO(e),t,n)}function Z(e,t,...n){return new yS(mO(e),t,...n)}function GO(e,t,n){return t-n}function KO(e,t,n){return(t-n)/n*100}function qO(e){switch(e.id){case`HL/2`:case`OC/2`:case`HLC/3`:case`OHLC/4`:case`HLCC/4`:return!0;default:return!1}}function JO(e){let t=e.source;if(e.sourceNeedsCompute=qO(t),e.sourceNeedsCompute){let n=X(t,ce(XO,t),e.innerSeries[0]);e.addInner(n)}}function YO(e){let t=+!!e.sourceNeedsCompute;return[t,e.innCont(t)]}var XO=function(e,t){let[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(e=>this.baseVal(e,t)),o=null,s=e.id;switch(s){case`Open`:o=n;break;case`High`:o=r;break;case`Low`:o=i;break;case`Close`:o=a;break;case`HL/2`:o=(r+i)/2;break;case`OC/2`:o=(n+a)/2;break;case`HLC/3`:o=(r+i+a)/3;break;case`OHLC/4`:o=(n+r+i+a)/4;break;case`HLCC/4`:o=(r+i+a+a)/4}return{[s]:o}},ZO=function(e,t,n){let r=null;if(this.atLeast(n,e+1)){let i=this.baseVal(t,n-e);i!==null&&(r=this.baseVal(t,n)-i)}return{[this.target.id]:r}},QO={sma:xO,ma:J,ema:Y,wma:SO,hma:CO};function $O(e,t,n=`Smoothing`){return QO[(e.inputs[n]??t).toLowerCase()]}var ek={atr:AO,adjatr:jO};function tk(e){return ek[e.inputs.TypeOfATR.toLowerCase()]}function nk(e){switch(e.unit){case g.Day:return 252;case g.Week:return 52;case g.Month:return 12;default:return 0}}function rk(e){let t=[W.High,W.Low];return e instanceof Rb&&Se(e.targetFields,t).length!==2}function ik(e,t){return e[`Period${t}`]}function ak(e){return!(e instanceof ev)&&e.query instanceof Fb}var ok=class extends Gb{constructor(e,t){let n=Y(t,13,W.Close),r=wO(t,12,26,9,W.Close);super(e,t,n,r),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=p.Same,n=this.innVal(1,W.EMA,e),r=this.innVal(1,W.EMA,e-1),i=this.innVal(2,W.MACDH,e),a=this.innVal(2,W.MACDH,e-1);return N(n,r,i,a)&&(n>r&&i>a?t=p.Up:n<r&&i<a&&(t=p.Down)),{[W.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(W.Open,W.High,W.Low,W.Close,W.Change,W.Volume,W.OpenInterest,W.TradingDay)}};function sk(e,t){return N(t)?(this[e]=t,null):this[e]}var ck=class{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return sk.call(this,`_domain`,e)}range(e){return sk.call(this,`_range`,e)}padding(e){return sk.call(this,`_padding`,e)}get ready(){return N(this._domain,this._range)}},lk=1/Math.log2(10),uk=(e,t)=>n=>e*(1-n)+t*n,dk=(e,t)=>(t-=e,t>0?n=>(n-e)/t:e=>de(isNaN(t)?NaN:.5));function fk(e,t){let n=dk(e[0],e[1]),r=uk(t[0],t[1]);return e=>r(n(e))}function pk(e){return Math.sign(e)*Math.log10(1+Math.abs(e/lk))}function mk(e){return Math.sign(e)*lk*(-1+10**Math.abs(e))}var hk=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]],gk=class extends ck{scaleType;axis;constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!ve(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let n=de,r=de;switch(this.scaleType){case ee.Linear:break;case ee.Logarithmic:n=pk,r=mk;break;default:throw Error(`Unexpected scale type (neither linear nor log)`)}let i=this._domain.map(n),a=this.rangeWithPadding(),o=t?fk(a,i):fk(i,a),s=e=>a[1]-e+a[0];return(t?r:s)(o((t?s:n)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];let[t,n]=this._range.map(e=>this.mapValue(e,!0));if(t===n&&e>0)return[t];let[r,i]=this._domain;if(this.scaleType===ee.Linear||r<0||i>1e5)return _k(t,n,e);let a=this.findLogBand(r),o=this.findLogBand(i),s=e*2;return o-a===0?_k(t,n,s):this.getLogTicks(a,o,s,n<t)}findLogBand(e){return hk.findIndex(([t,n])=>e>=t&&e<n)}getLogTicks(e,t,n,r){let i=[...this._domain],a=[];try{for(let o=e;o<=t;o++){let[s,c]=hk[o];o===e?s=i[0]:o===t&&(c=i[1]),this.domain([s,c]);let[l,u]=this._range.map(e=>this.mapValue(e,!0)),d=_k(l,u,n);a=r?d.concat(a):a.concat(d)}}finally{this.domain(i)}return Me(a,r?(e,t)=>e>t:(e,t)=>e<t),a}checkTicks(){return this.scaleType===ee.Logarithmic}};function _k(e,t,n){let r,i=-1,a,o,s;if(t=+t,e=+e,n=+n,e===t&&n>0)return[e];if((r=t<e)&&(a=e,e=t,t=a),(s=vk(e,t,n))===0||!isFinite(s))return[];if(s>0)for(e=Math.ceil(e/s),t=Math.floor(t/s),o=Array(a=Math.ceil(t-e+1));++i<a;)o[i]=(e+i)*s;else for(e=Math.floor(e*s),t=Math.ceil(t*s),o=Array(a=Math.ceil(e-t+1));++i<a;)o[i]=(e-i)/s;return r&&o.reverse(),o}function vk(e,t,n){let r=Math.sqrt(50),i=Math.sqrt(10),a=Math.sqrt(2),o=(t-e)/Math.max(0,n),s=Math.floor(Math.log(o)/Math.LN10),c=o/10**s;return s>=0?(c>=r?10:c>=i?5:c>=a?2:1)*10**s:-(10**-s)/(c>=r?10:c>=i?5:c>=a?2:1)}var yk=[`None`,`Annotations`,`Studies`,`All`],bk=yk[0];function xk(e){return e?.hiddenItems??bk}function Sk(e){let t=xk(e);return t===`Annotations`||t===`All`}function Ck(e){let t=xk(e);return t===`Studies`||t===`All`}function wk(e,t){return e.type===S.Study&&Ck(t)}function Tk(e,t){return e.visible!==!1&&!wk(e,t)}function Ek(e,t){return e.visible!==!1&&!Sk(t)}var Dk={color:z.COLOR_TRANSPARENT},Ok={color:z.COLOR_TRANSPARENT,width:0,dashStyle:`Solid`},kk=[W.Open,W.High,W.Low,W.Close],Ak=new Set(kk.map(e=>e.id)),jk=e=>Ak.has(e.id),Mk=e=>e.visible,Nk=e=>e.visible&&e.canHitTest,Pk=new rs(0,0,0,0),Fk=class{axis;id;uid;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=S.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=xt(),this.uid=this.id,this.record=new Dp(``),this.metaData=new So,this.timeSeries=new ev,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=/* @__PURE__ */ new Map}get title(){return``}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&N(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(S.Symbol)}get isExpression(){return this.is(S.Expression)}get isStudy(){return this.is(S.Study)}get isForward(){return this.is(S.Forward)}get isSeasonal(){return this.is(S.Seasonal)}get isVisible(){return Tk(this,this.presenter?.display)}getValueAt(e,t,n){return null}wrapIfAdvancedStyle(e){let t=e,n=e=>({outFields:e,inputs:{},source:null});return this.mainCurve.isHeikinAshiStyle?t=new qb(n(g_.slice()),e):this.mainCurve.isElderImpulseSystemStyle?t=new ok(n(g_.slice().concat(W.BREL)),e):this.mainCurve.isPercentChangeStyle&&(t=new Xw(n(g_.slice()),e)),t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=S[e.type];let t=e;this.uid=t.uid,this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),N(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{let t=new jb;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new gk(ee.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){N(this.timeSeries)&&N(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){let e=this.axis.pane.presenter,t=new Fb(null,e.data.aggregation,C.Normal,[mt(it(e.data,null,`range`,`from`)),mt(it(e.data,null,`range`,`to`))]);return t.barsToFetch=e.data.maxDataPoints||z.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=it(e.display,null,`xAxis`,`visibleRange`),t.useLastTrade=e.data.useLastTrade,t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return N(this.detachedScale,this.yScale)&&this.detachedScale}hasCurveThat(e){return this.curves.some(e)}get hasVisibleCurves(){return this.hasCurveThat(Mk)}get hasHitTestableCurves(){return this.hasCurveThat(Nk)}getDetachedScaleMargins(){return z.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;let{y:t,height:n}=e,{top:r,bottom:i}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+r*n),Math.floor(t+n-i*n)])}drawLevels(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.levels.filter(e=>e.visible)){let r=this.priceToY(n.value);Gs(e,Ks({line:n.line,fill:Dk})),gs(e,{x:-1,y:r},{x:t,y:r})}e.restore()}drawBands(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.bands){let r=this.priceToY(n.range.to),i=this.priceToY(n.range.from);Gs(e,Ks({fill:n.fill,line:Ok})),ms(e,new rs(-1,r,t,i-r),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return!this.hasEvents||!this.hasEventsData?[]:this.eventsSeries.container.fields.filter(e=>e!==W.DateTime)}getEventsAt(e){let t=this.eventsSeries.container,n=n=>t.getData(n)[e];return this.getEventFields().map(t=>{let r=n(t);if(!N(r))return null;let i=this.getEventFor(t);if(!N(i))return null;let a={field:t,value:r,date:n(W.DateTime),text:i.title,color:i.color};if(t===W.Custom&&r===z.FAKE_CUSTOM_EVENT){let t=e%2==0;return{...a,value:t?`___news`:`___video`,text:t?`N`:`V`}}return a}).filter(e=>e!=null)}getRefEventField(e,t,n,r){let i=r?.container,a=e.fields[0];t&&(a=e.isOhlc?W.High:n.isTick?W.Last:W.Close);let o=[a,e.fields[0]].filter(M);return M(i)?o.find(e=>i.hasField(e))??a:a}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){let n=this.axis.pane.presenter,r=n.view.xAxis.xScale,i=r.domain();if(!N(i)||!N(i[0],i[1]))return;let a=(e,t=W.DateTime)=>e.container.getData(t),o=a(this.eventsSeries),s=this.getRefPlot(n),c=s.timeSeries,l=a(c),u=n.data.aggregation,d=s===n.mainPlot,f=a(c,this.getRefEventField(s.mainCurve,d,u,c));if(!Array.isArray(f))return;let{chart:{fontFamily:p}}=this.axis.pane.presenter.display,m=e=>e.valueOf()>=i[0].valueOf()&&e.valueOf()<=i[1].valueOf(),h=o.flatMap((e,i)=>m(e)?this.getEventsAt(i).map(e=>{let i=Lg(u,e.date),a=A(l,+i,Number);if(a<0||a>=f.length)return null;let o=f[a];if(!Qe(o))return null;t.has(a)||t.set(a,-1);let s=t.get(a);t.set(a,++s);let c=r.timeToX(i),d=n.view.getEventRadius(),p=this.axis.yScale.priceToY(o)-s*(d+d+d);return{visible:!0,...e,x:c,y:p,r:d,rect:Pk}}).filter(M):[]);e.save();let g=!0;h.forEach(t=>{t.rect=ys(e,t,p),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=h,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){let{x:t,y:n,r,date:i,value:a}=e;this.customEventPopup?.show({x:t+2*r,y:n-2*r},i,a)}getCustomEventDataAt(e){if(!this.isVisible||!this._eventsData)return null;let t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===W.Custom?t:null}hitTestCustomEvent(e){return this.getCustomEventDataAt(e)!==null}hitTest(e){if(!this.isVisible)return!1;for(let t=0;t<this.curves.length;t++){let n=this.curves[t];if(n.visible&&n.hitTest(e))return!0}return!1}tryHandleCustomEventClick(e){let t=this.getCustomEventDataAt(e);return N(t)?(this.showCustomEventPopup(t),!0):!1}startHoverDim(e){let t=this.presenter?.shouldDimPlot(this)??!1;return t&&(e.save(),e.globalAlpha*=z.PLOT_HOVER_DIM_ALPHA),t}finishHoverDim(e,t){t&&e.restore()}isEmpty(){let e=this.timeSeries;return N(e)&&e.hasData&&e.container.isEmpty}draw(e){if(!this.isVisible)return;let t=this.startHoverDim(e);N(this.levels)&&this.drawLevels(e),N(this.bands)&&this.drawBands(e);for(let t of this.curves)t.draw(e);this.finishHoverDim(e,t)}drawEventsTopmost(e,t){if(!this.isVisible||!this.hasEventsData)return;let n=this.startHoverDim(e);this.drawEvents(e,t),this.finishHoverDim(e,n)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,n,r){if(!N(e)||!this.timeSeries.hasData||!this.shouldPriceMap(n,r))return e;let[i,a]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!N(i)||!zn(i))return e;if(this._firstVisibleDate!==i){this._firstVisibleDate=i;let e=this.timeSeries.container.getTimeData(),t=t=>A(e,+t,Number);this.visFromIndex=t(i),this.visToIndex=t(a),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(n)||this.canPriceMap(t,n),this.priceMap(e,t,n,!1,r)}isOhlcMapping(e){return this.mainCurve.isOhlc&&jk(e)}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===W.PreviousClose?W.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){let n=this.getRefPriceMapField(t),r=this.dataOf(n),i=null,a=this.visFromIndex;for(;i===null&&a<=this.visToIndex;)i=r[a++];this._priceMapFirstIndex.set(n,i===null?NaN:a-1)}priceMap(e,t,n,r=!1,i=x.None){let a=this.getRefPriceMapField(n),o=this._priceMapFirstIndex.get(a);if(!Number.isFinite(o))return e;let s=this.dataOf(a)[o];return this.isComparison(x.Percent)||i===x.Percent?r?s+s*e/100:(e>=s?1:-1)*(Math.abs(e-s)*100)/Math.abs(s):r?s+e:e-s}shouldPriceMap(e,t){return N(t)?t!==x.None:this.isComparison(x.Percent)||this.isComparison(x.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}},Ik=class extends Fk{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;tracePlot(e,t={}){yg(e,{chartId:this.axis?.pane?.presenter?.elementId,symbol:this.symbol,...t})}get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!N(this.timeSeries)||!N(this.timeSeries.record))return null;let e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(W[e])}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.symbol,this.mainCurve.style){case h.Renko:case h.Kagi:case h.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case h.Range:t.barsToFetch=4e3;break;case h.LineBreak:t.inputs=this.inputs}let n=this.axis.pane;if(N(n.alignedToYear)){let e=Yi(this.resolved??t.symbol);e!==null&&(this.yearOffset=n.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}let r=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(r),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:ie.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){let e=$().getMetaDataSource();this.metaData=e.getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;let e=$().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:C.Events,getHashKey:function(){return Object.values(this).filter(e=>typeof e!=`function`).join(`|`)}};z.EVENTS.forEach(e=>{t[e]=it(this.events,!1,e,`show`)}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(G.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return N(this.events)?z.EVENTS.some(e=>it(this.events,!1,e,`show`)):!1}findEvents(e){if(!this.hasEventsData||e[0]===null||e[1]===null)return[];let t=e[0],n=e[1];if(n>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){let e=this.timeSeries.container.getTimeData()[n-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,n)=>this.compare(e,t)?this.getEventsAt(n):[]).flat()}fromModel(e){super.fromModel(e);let t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=pd(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){let t=this.events[e.id.toLowerCase()];return!N(t)||!t.show?null:t}async initialize(){return ma.call(this,async()=>(this.tracePlot(`plot:init:start`),this.resolved=await Di(this.symbol),this.isShutDown?(this.tracePlot(`plot:init:aborted`,{resolved:this.resolved}),!1):(this.getMetaData(),this.getTimeSeries(),this.tracePlot(`plot:init:ready`,{resolved:this.resolved}),!0)))}},Lk=class extends Ik{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${g[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=g[e.fundamental],super.fromModel(e)}makeQuery(){let e=new Fb(this.symbol,new yd(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}},Rk=class{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){let e=$().config.touchCrosshairDelayMillis;return N(e)&&Number.isFinite(e)?e:z.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,n){Le()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,n),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,n){this.cancelLongPress(),this.performLongPress(e,t,n)}cancelLongPress(){Le()&&N(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,n){}};function zk(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}var Bk=class extends Rk{annotation;previous;onLongPress;cursorSet;moved;snapToSupported;constructor(e,t,n,r){super(),this.annotation=e,this.previous=t,this.onLongPress=r,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,n)}performLongPress(e,t,n){this.onLongPress?this.onLongPress():RA(this.annotation,n)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),zk(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!t||t.axis.pane!==this.annotation.axis.pane)return;let i=this.annotation.axis.toAnnotationPoint(r);if(!M(i)||i.axis!==this.annotation.axis)return;n.drawCrosshair({ap:i,offset:r}),this.cursorSet||=(this.previous.axis.pane.presenter.view.setCursor(te.Move),!0);let a=Lo(i.point,this.previous.point);this.annotation.offset(a),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=i,this.moved=!0}onMouseUp(e){this.cancelLongPress(),yM(this.annotation,this.moved,D.Moved)}},Vk=class{annotation;pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}onMouseMove(e){if(this.alignPointsMode=e.getModifier(E.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),zk(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!t||t.axis.pane!==this.annotation.axis.pane)return;let i=this.annotation.axis.toAnnotationPoint(r);if(n.drawCrosshair({ap:i,offset:r}),N(i)){let e=this.annotation.points[this.pointIndex],t=Lo(i.point,e.point);switch(e.moveDirection){case ne.Both:e.update(i.price,i.time);break;case ne.Horizontal:e.update(e.price,i.time);break;case ne.Vertical:e.update(i.price,e.time)}this.moved=e.moveDirection!==ne.None,this.moved&&this.annotation.wasPointMovedByTool(e,t)}this.annotation.requestRedraw()}onMouseUp(e){yM(this.annotation,this.moved,D.PointMoved)}},Hk=class{anchor;isVertical;axis;constructor(e,t,n){this.anchor=e,this.isVertical=t,this.axis=n}hitTest(e){return N(this.anchor)?this.isVertical?Math.abs(e.x-this.anchor.x)<=z.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=z.HIT_TEST_TOLERANCE:!1}draw(e){let t=z.OUT_OF_SCREEN;this.isVertical?_s(e,this.anchor.x,-t,t):vs(e,this.anchor.y,-t,t)}},Uk=class{id;axis;_price;_time;passive=!1;moveDirection=ne.Both;visible=!0;point;constructor(e,t,n){this.id=xt(),this.axis=e,t!==void 0&&n!==void 0&&(this.price=t,this.time=n,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==ne.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){let e=this.axis.toPoint(this);N(e)&&Qe(e.x)&&Qe(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time=typeof t==`number`?new Date(t):t,this.toPoint()}updateFromPoint(e){let t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){return this.visible?this.distance(e)<=z.HIT_TEST_TOLERANCE:!1}distance(e){let t=e.x-this.point.x,n=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+n*n)-z.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(N(this.point)){let n=z.HALF_ANN_POINT_DIMENSION;N(t)&&t.locked&&(n*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,n,n,0,0,2*Math.PI),e.stroke()}}};function Wk(e){return Yo(e.fill.color).a===0?e.line.color:e.fill.color}function Gk(e,t){return{owner:e.axis.annotationUndoOwner,position:e.axis.findIndex(e),uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function Kk(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}var qk=class{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=xt()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){let n=!this.isSelected||!this.axis.pane.presenter.annotationManipulation;return this.drawPoints(e,t,n),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>e.point!==void 0)}getPriceScaleAdornments(){return z.EMPTY_ARRAY}getTimeScaleAdornments(){return z.EMPTY_ARRAY}extractTraits(e=!0){let t=P(this.traits),n=vc(this.name);return Object.keys(t).forEach(r=>{let i=n.includes(r);(e&&!i||!e&&i)&&delete t[r]}),e||[`line`,`fill`,`zIndex`].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:Ze(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(Ro(t.point,e))})}get traits(){return this._traits||=P(this.defaultTraits),this.adjustFill&&=(this._traits.fill.color=Wk(this._traits),!1),this._traits}set traits(e){e!==void 0&>(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return Ks(this.traits)}get defaultTraits(){return Ws(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return Ks(this.defaultTraits)}get isVisible(){return Ek(this,this.axis.pane.presenter.display)}get adornStyle(){let e=P(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=z.COLOR_TRANSPARENT,Ks(e)}get pointsStyle(){let e=P(this.defaultTraits);return e.line.dashStyle=`Solid`,Ks(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}onFormatterChanged(){}isPointDrawn(e){return e.price!==void 0}drawPoints(e,t,n=!0){this.isVisible&&this.points.forEach(r=>{let i=this.isPointDrawn(r),a=N(e);t&&(i||!a)&&r.toPoint(),n&&a&&i&&(this.isSelected||this.drawn)&&(Gs(e,this.pointsStyle),r.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new Uk(this.axis))}toModel(){let e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:P(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){let t=this.activePoints;t.length===e.length&&t.forEach((t,n)=>{let r=e[n];t.update(r.price,r.time)})}updateFrom(e,t,n,r,i){typeof r==`boolean`&&(this.visible=r),typeof i==`boolean`&&(this.locked=i);let a=N(e)?P(e):{};N(t)&>(a,t),this.traits=a,N(n)&&this.updatePoints(n)}priceMap(e){return this.axis.priceMap(e)}flip(e){let t=this.getFlipAnchorIndices();if(!M(t))return;let n=this.points[t[0]],r=this.points[t[1]];if(e){let e=r.time;r.update(r.price,n.time),n.update(n.price,e)}else{let e=r.price;r.update(n.price,r.time),n.update(e,n.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}};function Jk(e,t,n,r){return function(i,a=!0){let o=new t(i,e,n);return a?i.appendAnnotation(o):o.drawn=!1,N(r)&&(o.traits=r),o}}var Yk=class{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,n,r,i){this.axis=i,N(e,t)&&(this.angle=zo(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=n?this.extendPoint(t,-1):e,this.p2=r?this.extendPoint(e,1):t),this.extended=n||r}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){let n=Math.max(Math.abs(e.x),Math.abs(t.x)),r=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(n*n+r*r)+z.OUT_OF_SCREEN}hitTest(e){return N(this.p1,this.p2)?Bo([this.p1,this.p2],e,z.HIT_TEST_TOLERANCE):!1}draw(e){N(this.p1,this.p2)&&(gs(e,this.p1,this.p2),this.extended)}getAdornOffset(e){let t=us(e),n=cs(e,1);return Po(this.p1,this.p2)<0&&(t.y=n+5),t}},Xk=class{style;axis;rect;constructor(e,t,n,r){this.axis=r,this.rect=new rs(e.x,e.y,t,n)}hitTest(e){return this.rect.contains(e)}draw(e,t){ms(e,this.rect)}},Zk=class extends qk{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.isVisible&&this.prepareDraw(e,t)&&!this.getScreenPoints().some(e=>!N(e))&&!this.drawn){let t=this.getElements();Gs(e,this.style),t.forEach((t,n)=>{Gs(e,this.getStyleForElement(t,n)),t.draw(e)}),Gs(e,this.adornStyle),this.adornElements(t,e);let n=this.getMarkers();Gs(e,this.style),n.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(this.countCache===void 0||this.countCache.time1!==e||this.countCache.time2!==t){let n=this.axis.pane.presenter.view,r=Math.abs(n.toIndex(e)-n.toIndex(t));this.countCache={time1:e,time2:t,barCount:r}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.isVisible){if(this.getScreenPoints().some(e=>!N(e)))return!1;let t=this.getElements(),n=this.getMarkers();return t.some(t=>t.hitTest(e))||n.some(t=>t.hitTest(e))?!0:this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,n)=>this.points[t+n].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return nt(this.traits?.singleStyle,!0)}get showBackground(){return nt(this.traits?.showBackground,!1)}get backgroundOpacity(){return nt(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return Ks({line:{color:z.COLOR_TRANSPARENT,dashStyle:`Solid`,width:0},fill:this.traits[e]})}lineOnlyStyle(e){return Ks({fill:{color:z.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new Yk(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Uo(Ho(e),this.backgroundOpacity)}getTraitsFor(e){let t={fill:{color:z.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground&&(t.fill.color=this.applyBackgroundOpacity(t.line.color)),t}getFlipAnchorIndices(){return this.points.length===2?[0,1]:null}},Qk=class extends Zk{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return z.AT_FACTORS}get factors(){return zs(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[z.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[z.AT_LEVELS_KIND]}get labels(){return this.traits[z.AT_LABELS]}get isExtended(){return this.points.length===3}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,n){let r=this.isBefore(e,t);return n||(r=!r),this.points[r?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[z.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){let n=this.levelsKind===z.AT_LEVELS_PERCENTS,r=``;if(this.showLevels&&(r=n?`${(e*100).toFixed(1)}%`:e.toString()),this.showPrices){let e=this.priceMap(this.axis.toPrice(t));r=(r+` (${Bv(this.axis,e)})`).trim()}return r}getAdornPointAndAlign(e,t){let n=this.labels,r=e instanceof Yk,i=(e,t,n)=>({pt:e,align:t,offset:n});switch(n){case z.AT_LABELS_LEFT:return i(r?e.anchor1:e,w.Right,-t);default:case z.AT_LABELS_RIGHT:return i(r?e.anchor2:e,w.Left,t);case z.AT_LABELS_CENTER:return i(r?No(e.anchor1,e.anchor2):e,w.Center,0)}}getColoredElements(e){let t=this.singleStyle;return this.factors.map(n=>{let r=e(n);return r===null?null:(t||(r.style=Ks(this.getTraitsFor(n))),r._data={factor:n.value},r)}).filter(e=>e!==null)}hitTestAdornments(e,t){let n=this.showLevels,r=this.getTextRef();if(!n||r===null)return!1;let i=this.axis.pane.presenter,a=i.view?.mainContext;if(!a)return!1;let o=null,s=!1;a.save();let{chart:{fontFamily:c},yAxis:{fontSize:l}}=i.display;a.font=`${l??12}px ${c}`;for(let n of e){if(!N(n._data))continue;let{factor:e}=n._data,{ref:i,spacing:c,offsetY:l,text:u}=r(o,n,e),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(i,c);if(ds(a,u,this.getAdornTextPoint(a,l,d,p),f).contains(t)){s=!0;break}o=n}return a.restore(),s}adornElementsForColoredFactors(e,t,n,r){let i=this.singleStyle,a=this.showBackground,o=this.showLevels,s=this.applyBackgroundOpacity(this.traits.line.color),c=r.fillStyle,l=null;e.forEach(e=>{if(!N(e._data))return;let{factor:u}=e._data;if(a){let n=t(l,e);r.fillStyle=i?s:e.style.fillStyle,r.fill(n)}if(o){let{ref:t,spacing:a,offsetY:o,text:s}=n(l,e,u),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(t,a);fs(r,s,this.getAdornTextPoint(r,o,d,p),f,i?c:e.style.strokeStyle)}l=e})}getAdornTextPoint(e,t,n,r){let i=cs(e,.75);return Ro(n,{x:r,y:t===!0?i/2:t})}},$k=class extends Zk{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(z.AT_FILL)}get rect(){let[e,t,,]=this.getScreenPoints(),n=new Xk({x:e.x,y:Math.min(e.y,t.y)},t.x-e.x,Math.abs(e.y-t.y),this.axis);return n.style=this.rectStyle,n}get reverse(){return!1}getLinesDataAtLevels(e,t){let[n,r]=this.points;if(this.reverse&&([n,r]=[r,n]),this.lines==null){let i=(e,t=!1)=>n=>({level:n.value,domain:e(n.value),traits:this.getTraitsFor(n),isPrice:t}),a=r.price-n.price,o=i(e=>n.price+e*a,!0),s=e?.map(o)??[],c=this.axis.pane.presenter.timeline,l=A(c,+n.time,Number,Jv),u=A(c,+r.time,Number,Jv)-l,d=i(e=>+c.at(l+Math.floor(e*u))),f=t?.map(d)||[];this.lines={prices:s,times:f,barsDiff:u,priceDiff:a}}return this.lines}makeColoredLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=Ks(n.traits)),r._data={level:n.level,isPrice:n.isPrice},r}getLineElements(e){let[t,n]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{let r=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:r},{x:n.x,y:r},e)}),timeLines:e.times.map(e=>{let r=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:r,y:t.y},{x:r,y:n.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},eA=class extends Uk{priceRef;timeRef;constructor(e,t,n){super(e),this.priceRef=t,this.timeRef=n,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}},tA=class{points;constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return N(this.points[0].point,this.points[1].point)?new rs(this.left,this.top,this.width,this.height):null}};function nA(e){let t=new Uk(e),n=new Uk(e);return[t,n,new eA(e,t,n),new eA(e,n,t)]}var rA=class extends qk{helper;constructor(e,t){super(e,t),this.points=nA(e),this.helper=new tA(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return!this.isVisible||!this.prepareDraw(e,t)?!1:(Gs(e,this.style),!0)}updatePoints(e){this.allowPricesChangeUI&&e.length===2&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}},iA=class{points;lines;axis;helper;_actualWidth=0;_fontSizeForWidth=0;constructor(e,t,n){this.points=e,this.lines=t,this.axis=n,this.helper=new tA(this.points)}hitTest(e){let t=this.getRect();return M(t)?(t.width=this._actualWidth,t.contains(e)):!1}getRect(){return this.helper.getRect()}get fontSize(){if(this.lines.length===0)return 0;let{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(this.lines.length===0)return;e.save();let{x:t,y:n}=this.getRect(),{chart:{fontFamily:r}}=this.axis.pane.presenter.display,i=this.fontSize;e.textAlign=`left`,e.textBaseline=`top`,e.font=`${i}px ${r}`,this.lines.forEach((r,a)=>{let o=i*a,s=n+o;e.fillText(r,t,s)}),this.computeActualWidth(e),e.restore()}},aA=class extends Zk{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=nA(e),this.adjustFill=!0}get textLines(){return this.traits[z.AT_TEXT_LINES]}set textLines(e){this.traits[z.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!N(this._textAnnElement)&&this.isVisible&&(this._textAnnElement=new iA(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),this._textAnnElement=void 0}getElements(){return this.isVisible?[this.textElement]:[]}},oA=class extends aA{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return this.isVisible?this.textElement.hitTest(e):!1}get prices(){return this.traits.prices}get pricesPoints(){let e=this.points[0].time;return this.prices.map(t=>new Uk(this.axis,t,e))}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),N(e?.textLines)&&(this.textLines=e.textLines)}getElements(){let e=super.getElements(),t=this.pricesPoints.map(e=>new Hk(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();let e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){let{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){let[t,n]=this.defaultFont;e.save(),e.font=`${t}px ${n}`;let r=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:i,y:a}=this.points[0].point;this.points[1].updateFromPoint({x:i+r,y:a+this.textLines.length*t}),e.restore()}},sA=class{annId;annotation;constructor(e){this.annId=e}onKeyDown(e){if(this.annId==null)return;let{key:t,code:n,presenter:r}=e;ze(t,n)&&(N(this.annotation)&&(this.annotation.axis.deleteAnnotation(this.annotation,!1),r.view.redraw()),vM(r,{toolChange:D.Cancelled,annId:this.annId}))}},cA=class extends sA{factory;thirdPoint;dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}updatePoint(e,t){this.annotation.points[t].update(e.price,e.time)}onMouseDown(e){let{point:t,button:n}=e;if(t===void 0)return;let r=M(this.annotation);if(n===T.Left){if(this.alignPointsMode=this.forceAlignPoints||e.getModifier(E.Shift),r){let e=!this.thirdPoint||this.dragged?1:2;this.updatePoint(t,e),this.signalChange();let n=e=>this.annotation.points[e].point;if(!Io(n(e-1),n(e)))return!0;this.dragged=!1,(!this.thirdPoint||e===2)&&this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange()}return!0}onMouseMove(e){let{point:t,view:n,offset:r}=e;return n.drawCrosshair({ap:t,offset:r}),N(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(E.Shift),this.dragged?(this.updatePoint(t,1),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.updatePoint(t,2),this.signalChange())),!0}finish(){yM(this.annotation,!0,D.Created)}isAccidentalMouseUp(e){let{point:t}=e,[n,r]=this.annotation.points,i=n.point,a=t?.point;return!Io(i,r.point)||a!==void 0&&!Io(i,a)}onMouseUp(e){this.annotation===void 0?bM(e):this.dragged&&(this.isAccidentalMouseUp(e)?this.dragged=!0:(this.dragged=!1,this.thirdPoint||this.finish()))}},lA=class extends cA{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}},uA=class extends cA{constructor(e){super(e,!1),this.snapToSupported=!1}updatePoint(e,t){super.updatePoint(e,t);let[n,r]=this.annotation.points,i=Lo(r.point,n.point),a=n.point.y+i.x*Math.sign(i.y)*Math.sign(i.x),o=this.annotation.axis.toPrice(a);r.update(o,e.time)}},dA=class extends sA{factory;existing;isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!N(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew)return{height:100,fontSize:`100%`,color:Wk(Ws(this.anchor.axis.pane.presenter.display,`Text`))};{let e=this.existing.textElement;return{height:e.getRect().height*1.05,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[z.AT_FILL].color}}}onMouseDown(e){let{point:t}=e;if(this.isNew){if(this.clicks===0){if(t===void 0){bM(e);return}t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing()}else this.onEndEditing()}startEditing(){this.textArea=document.createElement(`textarea`);let{x:e,y:t}=this.anchor.point,n=this.anchor.axis.pane.getBounds(),r=n.x+n.width-this.anchor.point.x,{height:i,fontSize:a,color:o}=this.styleProps();oa(this.textArea,{position:`absolute`,top:`${t}px`,left:`${e}px`,border:`none`,outline:`none`,overflow:`hidden`,height:`${i}px`,width:`${r}px`,resize:`none`,backgroundColor:`rgba(255, 255, 255, 0.05)`,zIndex:`5`,fontSize:a,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join(`
|
|
37
|
+
`}function py(e,t,n){let r=typeof n==`string`?ot(n):null,i=r===null?``:` style="color: ${r}"`,a=N(e)?at(e):null;return`${a===null?``:`<span class="field-name">${a}</span>`}<span${i} class="field-value">${at(t)}</span>`}function my(e){return`<a class="delete-plot" data-plot-uid="${ot(e)}" title="Delete plot">${iy(`delete`)}</a>`}function hy(e,t){let n=e>0,r=e<t-1;return[`${n?sy(!0,e):``}`,`${r?sy(!1,e):``}`].join(` `).trim()}function gy(e,t){return e.startsWith(z.FAKE_SYMBOL_PREFIX)&&t.length>0?t:e}function _y(e){if(!e.isStudy)return null;let t=e;return t.getStandalonePaneBasisTitle()?t.getStandalonePaneTitle():null}function vy(e,t,n,r,i,a){let o=yy(e,t);o.offset=n,o.lastBarRefresh=!!r||!1,o.chartId=e.elementId;let s=n=>n.axes.map(e=>e.plots).flat().filter(t=>!i||t===e.mainPlot).map(n=>Cy(e,t,a,o,n)).filter(e=>e!==null);return o.panes=e.panes.map(e=>({bounds:by(e),id:e.id,plots:s(e)})),o}function yy(e,t){let n=e.data.aggregation,r=e.display.xAxis,i=r.isOrdinal,a=M(i)&&i,o=a?r.ordinalName??`Value`:`Date`;return{date:a?Lv(t):Kv(n,t),time:n.isEndOfDay||a?null:qv(n,t,!1),isMultiSymbol:wy(e),isMultiContract:n.isMultiContract,dateFieldName:o}}function by(e){let t=e.getBounds();if(!N(t))return;let{x:n,y:r,width:i,height:a}=t,{leftOffset:o,rightOffset:s}=e.presenter.view;return{top:r,left:n+o,right:s,bottom:r+a,width:i,height:a}}function xy(e,t,n,r=!1){let i=e.plot,a=i.timeSeries.container,o=i.axis.pane.presenter.timeline,s=A(o,+n,Number,Jv),c=o.at(s-e.shift);if(c===null)return[null,0];let l=a.getTimeData(),u=A(l,+c,Number);return[!l[u]||l[u].getTime()!==c.getTime()?null:e.dataAt(t,u,!r),u]}function Sy(e,t,n){N(e.precision)?n.overridePrecision=e.precision:e.isStudy&&N(t.mainPlot?.precision)&&!N(Lc(e.model.study).meta.decimals)&&(n.overridePrecision=t.mainPlot.precision)}function Cy(e,t,n,{isMultiContract:r},i){let a=i.isStudy;if(!i.timeSeries.hasData)return null;let o=i.timeSeries.container;i.type,S.Expression;let s=i.axis.comparison!==x.None,c=i.axis.comparison===x.Percent,l=(e,r)=>i.customPlotValues&&r!==W.DateTime?[i.getValueAt(r,t,n),0]:xy(e,r,t,s),u=i,d=_y(i)??i.title,f=a?`${Lc(u.model.study).meta.title} ${u.fullParams}`:i.metaData.name||``,p={isMain:i.main,type:i.type,typeName:S[i.type],name:gy(d,i.metaData.symbol),description:f,exchange:i.metaData.exchange||``,error:u.errorText,id:i.id,uid:i.uid,visible:i.visible,isHidden:!i.isVisible,seasonalOffset:i.isSeasonal?u.offset??void 0:void 0};if(N(u.yearOffset)&&u.yearOffset!=0){let n=e.data.aggregation;p.unalignedDate=Kv(n,xi(t,u.yearOffset))}let m=i.curves[0],g=i.type===S.Symbol&&Wi(i.title);if(r&&i.type===S.Symbol&&o.hasField(W.Symbol)){let e=t.valueOf()===z.ZERO_DATE.valueOf()?i.timeSeries.container?.getLastDataPoint(W.Symbol):l(m,W.Symbol)[0];N(e)&&e.length>0&&(p.actualSymbol=e,g||(p.name=e))}let _={},v={range:i.axis.yScale.domain(),allDigits:!0};Sy(i,e,v);let y=(e,t)=>{let n=(t===W.Change||t===W.PercentChange)&&e>0?`+`:``;return c?n+Rv(e):n+i.metaData.format(e,t,v)},b=Zv(e),ee=/* @__PURE__ */ new Set;return p.values=i.curves.filter(e=>e.visible).map(e=>(!i.main&&i.isSymbol&&b?g_:e.fields).map(t=>{if(ee.has(t))return null;ee.add(t);let[n,r]=l(e,t),o=i.axis.yScale.priceToY(n);_[t.id]=!0;let s=i.customPlotValues?u.getColorOf(t):e.getColor(r,e.style!==h.HollowCandles,t),c=y(n,t).trim();if(N(n)&&t===W.Change){let[t]=l(e,W.PercentChange);N(t)&&(c+=` (${y(t,W.PercentChange)})`)}return{abbreviation:Ty(t),shortName:t.shortName,id:t.id,name:t.name,longName:`${t.shortName} ${a?u.params:``}`.trim(),color:Ho(s),val:n,y:o,value:c}}).filter(e=>e!==null)).flat(),p.events=i.findEvents(l(m,W.DateTime)).filter(e=>e.field!==W.Custom),p}function wy(e){let t=e.mainPlot.symbol;return e.allPlots.some(e=>e.type===S.Symbol&&e.symbol!==t)}function Ty(e){return e.id===W.Change.id?`Δ`:e.id.substring(0,1)}function Ey(e,t,n){let r=N(t),i=N(n),a,o,s=e.pane.getBounds();if(!r)a=e.priceToY(n),o=new rs(s.x,a,s.width,s.y+s.height-a);else if(!i)a=e.priceToY(t),o=new rs(s.x,s.y,s.width,a-s.y);else{let r=e.priceToY(t),i=e.priceToY(n);a=(r+i)/2,o=new rs(s.x,i,s.width,r-i)}return[a,o]}var Dy=(e,t)=>{let n=qo(.6)(e),r=Jo(.6)(e),i=t===`linLighten`;return[i?r:n,e,i?n:r]};function Oy(e,t,n,r,i=!1,a){let o;e.zones.forEach((s,c)=>{let l=s.value,[u,d]=Ey(e,o,l);t.save(),ns(t,d),i&&(n.range=[null,u]);let f=e.zoneColors[c];if(s.gradient){let e=Dy(f,s.gradient),n=t.createLinearGradient(0,d.y,0,d.y+d.height);n.addColorStop(0,e[0]),n.addColorStop(.5,e[1]),n.addColorStop(1,e[2]),f=n}else N(a)&&(f=a(c,f));r(e,t,n,f),t.restore(),o=l})}function ky(e,t,{bar:n,slice:r},i){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=a+(r[1]-r[0])*n.totalWidth,s=i+n.totalWidth/2;return t.x<a-s||t.x>o+s}function Ay(e,t,n,r=1){let i=e.view.xAxis.xScale.xToIndex(t.x)??n.slice[0];return{from:Math.max(n.slice[0]-1,i-r),to:Math.min(n.slice[1]+1,i+r)}}function jy(e,t,n,r,i,a){let o=Math.min(t,t+r)-a,s=Math.max(t,t+r)+a,c=Math.min(n,n+i)-a,l=Math.max(n,n+i)+a;return e.x>=o&&e.x<=s&&e.y>=c&&e.y<=l}function My(e,t,n,r,i,a){let o=r-t,s=i-n,c=e.x-t,l=e.y-n;if(o===0&&s===0)return Math.abs(c)<=a&&Math.abs(l)<=a;let u=o*o+s*s,d=(c*o+l*s)/u,f=Math.max(0,Math.min(1,d)),p=t+f*o,m=n+f*s,h=e.x-p,g=e.y-m;return h*h+g*g<=a*a}function Ny(e,t,n,r){return e.x>=Math.min(t.x,n.x)-r&&e.x<=Math.max(t.x,n.x)+r}function Py(e,t,n,r){return e.y>=Math.min(t,n)-r&&e.y<=Math.max(t,n)+r}function Fy(e,t,n){let r=n.x-t.x;if(r===0)return n.y;let i=(e-t.x)/r;return t.y+(n.y-t.y)*i}function Iy(e,[t,n],r,i){let a=r,o=e.timeSeries.container.size;for(let r=t;r<=n;r++){for(;e.timeSeriesAt(a)<e.timelineAt(r-e.shift)&&a<o;)++a;if(a===o)break;let t=e.timeSeriesAt(a)>e.timelineAt(r-e.shift);i(a,t)}}var Ly={draw(e,t,n){N(e.zones)?Oy(e,t,n,Wy):e.varyColorPerBar?Jy(e,t,n):Wy(e,t,n)},hitTest:By},Ry={draw(e,t,n){N(e.zones)?Oy(e,t,n,Xy):Xy(e,t,n,e.colors[0])},hitTest:Vy},zy={draw:Yy,hitTest:Hy};function By(e,t,n,r){let i=e.pickMainField(),{from:a,to:o}=Ay(e,t,n,z.CONTINUOUS_LINE_HIT_TEST_RADIUS),s=null;for(let n=a;n<=o;n++){let a=e.pointAtTimelineIndex(n,i);if(a!==null){if(s!==null&&My(t,s.x,s.y,a.x,a.y,r))return!0;s=a}}return!1}function Vy(e,t,n,r){let i=e.pickMainField(),{from:a,to:o}=Ay(e,t,n);for(let n=a;n<=o;n++){let a=e.pointAtTimelineIndex(n-1,i),o=e.pointAtTimelineIndex(n,i);if(a===null||o===null)continue;let s={x:o.x,y:a.y};if(My(t,a.x,a.y,s.x,s.y,r)||My(t,s.x,s.y,o.x,o.y,r))return!0}return!1}function Hy(e,t,n,r){let i=e.pickMainField(),a=Math.max(1,e.lineWidth||z.CURVE_STYLE_DOTS_RADIUS)+r,o=a*a,{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let r=e.pointAtTimelineIndex(n,i);if(r===null)continue;let a=t.x-r.x,s=t.y-r.y;if(a*a+s*s<=o)return!0}return!1}function Uy(e,t,n,r,i=1){let a=z.MARKER_SIZE*i,o=a*1.25;switch(r){case`Circle`:e.moveTo(t+a,n),e.arc(t,n,a,0,Math.PI*2);break;case`Square`:e.rect(t-a,n-a,2*a,2*a);break;case`TriangleUp`:e.moveTo(t-o,n+o),e.lineTo(t+o,n+o),e.lineTo(t,n-o),e.lineTo(t-o,n+o);break;case`TriangleDown`:e.moveTo(t-o,n-o),e.lineTo(t+o,n-o),e.lineTo(t,n+o),e.lineTo(t-o,n-o);break;case`Diamond`:e.moveTo(t,n-o),e.lineTo(t+o,n),e.lineTo(t,n+o),e.lineTo(t-o,n),e.lineTo(t,n-o)}}function Wy(e,t,{bar:n,slice:r,start:i},a=null){let o=a||e.getColor(0),s=M(e.lineMarker);s&&(t.fillStyle=o,t.beginPath());let c=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,l=[],u=e.pickMainField();Iy(e,r,i,(r,i)=>{if(!i){let n=e.dataAt(u,r);if(N(n)){let r=e.priceToY(n);s&&Uy(t,c,r,e.lineMarker),l.push({x:c,y:r})}}c+=n.totalWidth}),s&&t.fill(),t.lineWidth=e.lineWidth,e.dashStyle&&t.setLineDash(Vo(e.dashStyle)),M(e.lineSmoothing)?Gy(t,l,o,e.lineSmoothing):qy(t,l,o)}function Gy(e,t,n,r){if(t.length<2)return;let i=Ky(t,r);e.beginPath(),e.strokeStyle=n,e.moveTo(t[0].x,t[0].y);for(let t of i)e.bezierCurveTo(t.cp1x,t.cp1y,t.cp2x,t.cp2y,t.x,t.y);e.stroke()}function Ky(e,t){let n=[];for(let r=0;r<e.length-1;r++){let i=e[r-1]||e[r],a=e[r],o=e[r+1],s=e[r+2]||o,c=a.x+(o.x-i.x)/t,l=a.y+(o.y-i.y)/t,u=o.x-(s.x-a.x)/t,d=o.y-(s.y-a.y)/t;n.push({cp1x:c,cp1y:l,cp2x:u,cp2y:d,x:o.x,y:o.y})}return n}function qy(e,t,n){if(t.length>1){e.beginPath(),e.strokeStyle=n;let r=t[0];e.moveTo(r.x,r.y);for(let n=1;n<t.length;n++){let r=t[n];e.lineTo(r.x,r.y)}e.stroke()}}function Jy(e,t,{bar:n,slice:r,start:i}){t.lineWidth=e.lineWidth,t.lineCap=`square`,e.dashStyle&&t.setLineDash(Vo(e.dashStyle));let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=null,s=null,c=[];Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let n=e.priceToY(i);s=e.getColor(r),o!==s&&(qy(t,c,o),c.length>0&&(c=[c.pop()]),o=s),c.push({x:a,y:n})}}a+=n.totalWidth}),qy(t,c,s)}function Yy(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2;t.fillStyle=e.getColor(0);let o=Math.max(1,e.lineWidth||z.CURVE_STYLE_DOTS_RADIUS),s=Math.PI*2;t.beginPath(),Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let n=e.priceToY(i);t.moveTo(a+o,n),t.arc(a,n,o,0,s)}}a+=n.totalWidth}),t.fill()}function Xy(e,t,{bar:n,slice:r,start:i},a){let o=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,s=Fs();s.prolog(t),t.strokeStyle=a,t.lineWidth=e.lineWidth,e.dashStyle&&t.setLineDash(Vo(e.dashStyle)),t.beginPath();let c=!1,l=null;Iy(e,r,i,(r,i)=>{if(!i){let n=e.pickMainField(),i=e.dataAt(n,r);if(N(i)){let a=e.priceToY(i);if(c)t.lineTo(o,l),t.lineTo(o,a);else{let i=e.dataAt(n,r-1);if(N(i)){let n=e.priceToY(i);t.moveTo(-1,n),t.lineTo(o,n),t.lineTo(o,a)}else t.moveTo(o,a);c=!0}l=a}}o+=n.totalWidth}),t.stroke(),s.epilog(t)}var Zy={draw(e,t,n){N(e.zones)?Oy(e,t,n,nb,!0):nb(e,t,n,e.colors,!0)},hitTest:tb},Qy={draw:ib,hitTest:tb};function $y(e){let{BaseLevel:t}=ft(e);return{baseLevel:Number.isFinite(t)?St(0,100,t):50}}function eb(e,[t,n]){let{baseLevel:r}=$y(e.plot.inputs);return(t-n)*r/100+n}function tb(e,t,n,r){if(By(e,t,n,r))return!0;let{range:i}=n,a=e.pickMainField(),o=e.isBaseline?eb(e,i):i[1],{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let i=e.pointAtTimelineIndex(n,a),s=e.pointAtTimelineIndex(n+1,a);if(i!==null&&s!==null&&Ny(t,i,s,r)&&Py(t,Fy(t.x,i,s),o,r))return!0}return!1}function nb(e,t,n,r,i=!1){Wy(e,t,n,e.pickAreaStroke(r)),ab(e,t,n,r[0],i)}function rb(e,t,n){let{x:r,width:i}=e.pane.getBoundsWithoutScales();t.save(),t.lineWidth=1,t.strokeStyle=`#888`,t.setLineDash(Vo(`dot`)),vs(t,n,r,r+i),t.restore()}function ib(e,t,n){let[r,i]=n.range,a=eb(e,n.range);e.zones[0].value=e.yToPrice(a),rb(e,t,a),Oy(e,t,n,nb,!0,(e,n)=>{let o=e===1,s=Uo(n,0),c=t.createLinearGradient(0,o?r:i,0,a);return c.addColorStop(0,n),c.addColorStop(1,s),[c,Uo(n,1)]})}function ab(e,t,{bar:n,slice:r,start:i,range:[a,o]},s,c){if(c){let e=t.createLinearGradient(0,a,0,o);e.addColorStop(0,s),e.addColorStop(1,Uo(s,0)),t.fillStyle=e}else t.fillStyle=s;t.beginPath();let l=null,u=e.pickMainField(),d=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,f=!1,p=null;Iy(e,r,i,(r,i)=>{if(!i){let n=e.dataAt(u,r);if(N(n)){let r=e.priceToY(n);f?t.lineTo(d,r):(t.moveTo(l=d,r),f=!0),p=d}}d+=n.totalWidth}),t.lineTo(p,o),t.lineTo(l,o),t.closePath(),t.fill()}var ob={draw(e,t,n){N(e.zones)?Oy(e,t,n,db,!0):db(e,t,{...n,range:[null,null]})},hitTest:cb},sb={draw:ub,hitTest:lb};function cb(e,t,n,r){let{bar:i,slice:a}=n,o=e.view.xAxis.xScale.range()[0],s=e.isMultiColumn,c=s?e.fields.length:1,l=i.width/c,u=s?null:e.pickMainField(),d=e.priceToY(0),{from:f,to:p}=Ay(e,t,n);for(let n=f;n<=p;n++){let f=e.dataIndexAtTimelineIndex(n);if(!N(f))continue;let p=o+i.offset+(n-a[0])*i.totalWidth;for(let n=0;n<c;n++){let i=e.dataAt(s?e.fields[n]:u,f);if(N(i)){let a=e.priceToY(i);if(jy(t,p+n*l,a,l,d-a,r))return!0}}}return!1}function lb(e,t,n,r){let{bar:i,slice:a}=n,o=e.view.xAxis.xScale.range()[0],{from:s,to:c}=Ay(e,t,n);for(let n=s;n<=c;n++){let s=e.dataIndexAtTimelineIndex(n);if(!N(s))continue;let c=o+i.offset+(n-a[0])*i.totalWidth,l=e.priceToY(0),u=0;for(let n=0;n<e.plot.curves.length;n++){let a=e.plot.curves[n];if(!a.visible||!a.isStackedColumn)continue;let o=e.dataAt(a.fields[0],s);if(!N(o))continue;u+=o;let d=e.priceToY(u);if(a===e&&jy(t,c,d,i.width,l-d,r))return!0;l=d}}return!1}function ub(e,t,{bar:n,slice:r,start:i}){if(!e.isFirstVisibleOfStyle())return;let a=e.view.xAxis.xScale.range()[0]+n.offset,o=Fs();o.prolog(t);let s=e.plot.curves.filter(e=>e.isStackedColumn);Iy(e,r,i,(r,i)=>{if(!i){let i=e.priceToY(0),c=0;s.forEach(s=>{if(!s.visible)return;let l=s.fields[0],u=e.dataAt(l,r);if(!N(u))return;c+=u;let d=e.priceToY(c);t.fillStyle=s.getColor(r,!1,l),t.beginPath(),t.rect(o.adjust(a),o.adjust(Math.min(d,i)),o.adjust(n.width),o.adjust(Math.abs(i-d))),t.fill(),i=d})}a+=n.totalWidth}),o.epilog(t)}function db(e,t,{bar:n,slice:r,start:i,range:[a,o]}){let s=e.view.xAxis.xScale.range()[0]+n.offset,c=e.isMultiColumn,l=c?e.fields:[e.pickMainField()],u=n.width/(c?l.length:1),d=Fs();d.prolog(t),Iy(e,r,i,(r,i)=>{i||l.forEach((n,i)=>{let a=e.dataAt(n,r);if(N(a)){N(o)||(o=e.priceToY(0));let c=e.priceToY(a);t.fillStyle=e.getColor(r,!1,n),t.beginPath(),t.rect(d.adjust(s+i*u),d.adjust(Math.min(c,o)),d.adjust(u),d.adjust(Math.abs(o-c))),t.fill()}}),s+=n.totalWidth}),d.epilog(t)}var fb={draw:hb},pb=[W.Open,W.High,W.Low,W.Close],mb=[null,null,null,null];function hb(e,t,{bar:n,slice:r,start:i}){t.lineWidth=Math.max(1,.5*n.width),t.lineJoin=`miter`,t.miterLimit=1.5;let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,o=Fs();o.prolog(t);let s=null,c=null,l=[];Iy(e,r,i,(r,i)=>{if(!i){let i=t=>pb.map(n=>e.dataAt(n,t)),[u,d,f,p]=i(r),[,m,h]=r<0?mb:i(r-1);if(N(u,d,f,p)){let i=o.adjust(a),g=o.adjust(a-n.totalWidth),_=[u,d,f,p].map(e.priceToY,e).map(o.adjust),v=o.adjust(e.priceToY(d>m?m:h));c=e.getColor(r);let y=N(s)&&s!==c,b=u===d?1:2,x=u===d?2:1;l.push({x:g,y:_[0]}),l.push({x:i,y:_[b]}),y&&(l.push({x:i,y:v}),qy(t,l,s),l=[]),y&&l.push({x:i,y:v}),l.push({x:i,y:_[x]}),s=c}}a+=n.totalWidth}),qy(t,l,c),o.epilog(t)}var gb={draw:yb,hitTest:vb},_b=[W.Open,W.High,W.Low,W.Close];function vb(e,t,n,r){let{bar:i}=n,a=i.width/2,{from:o,to:s}=Ay(e,t,n);for(let n=o;n<=s;n++){let o=e.dataIndexAtTimelineIndex(n);if(!N(o))continue;let s=e.dataAt(W.Open,o),c=e.dataAt(W.High,o),l=e.dataAt(W.Low,o),u=e.dataAt(W.Close,o);if(N(s,c,l,u)){let o=e.view.xAxis.xScale.indexToX(n),d=e.priceToY(s),f=e.priceToY(c),p=e.priceToY(l),m=e.priceToY(u);if(e.isCandle){if(jy(t,o-a,d,i.width,m-d,r)||My(t,o,Math.min(m,d),o,f,r)||My(t,o,Math.max(m,d),o,p,r))return!0}else if(My(t,o,p,o,f,r)||!e.isHlcStyle&&My(t,o-a,d,o,d,r)||My(t,o+a,m,o,m,r))return!0}}return!1}function yb(e,t,{bar:n,slice:r,start:i}){let a=e.presenter.display.chart.showMinMaxArc,o=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,s=Fs();s.prolog(t);let c=null,l=null,u=null,d=null,f=n=>{e.isCandle?(e.isHollowCandles?n.outlineColor=e.getColor(n.ix,!1):(e.colors.length>3&&(n.outlineColor=e.colors[3]),e.colors.length>4&&(n.wickColor=e.colors[4])),Sb(t,n,e.lineWidth)):(e.isOhlcStyle||e.isHlcStyle||e.isElderImpulseSystemStyle||e.isRangeStyle)&&xb(t,n,e.lineWidth,!e.isHlcStyle)};Iy(e,r,i,(t,r)=>{if(!r){let r=_b.map(n=>e.dataAt(n,t)),[i,a,p,m]=r;if(N(i,a,p,m)){let h={x:s.adjust(o),adjust:s.adjust,width:n.width,y:[i,a,p,m].map(e.priceToY,e).map(s.adjust),isMin:!1,isMax:!1,ix:t,color:e.getColor(t)},g=Math.min(...r),_=Math.max(...r);(!N(c)||g<c)&&(c=g,u=h),(!N(l)||_>l)&&(l=_,d=h),f(h)}}o+=n.totalWidth}),a&&(N(u)&&(u.isMin=!0,f(u)),N(d)&&(d.isMax=!0,f(d))),s.epilog(t)}function bb(e,t,n,r,i,a,o,s=3){t&&hs(e,{x:r,y:i+s},o,0,Math.PI),n&&hs(e,{x:r,y:a-s},o,0,Math.PI,!0)}function xb(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,isMin:l,isMax:u},d,f){let p=r/2;e.lineWidth=d,e.strokeStyle=c,e.beginPath(),e.moveTo(t,o),e.lineTo(t,a),f&&(e.moveTo(n(t-p),i),e.lineTo(t,i)),e.moveTo(n(t+p),s),e.lineTo(t,s),e.stroke(),bb(e,l,u,t,o,a,p)}function Sb(e,{x:t,adjust:n,width:r,y:[i,a,o,s],color:c,outlineColor:l,wickColor:u,isMin:d,isMax:f},p){let m=r/2;e.lineWidth=p,e.fillStyle=c,e.strokeStyle=l||c,e.beginPath(),e.rect(n(t-m),Math.min(i,s),r,n(Math.abs(s-i))),e.fill(),e.stroke(),e.strokeStyle=u||l||c,e.beginPath(),e.moveTo(t,Math.min(s,i)),e.lineTo(t,a),e.moveTo(t,Math.max(s,i)),e.lineTo(t,o),e.stroke(),e.strokeStyle=Yo(c).a===0?l:c,bb(e,d,f,t,o,a,m)}var Cb={draw:wb};function wb(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0],o=n.totalWidth/2,s=a+n.offset+n.width/2,c=Fs();c.prolog(t);let l=e.plot.timeSeries.builder.boxSize,u=l/2;Iy(e,r,i,(r,i)=>{if(!i){let[n,i]=[W.High,W.Low].map(t=>e.dataAt(t,r)),a=e.colors[0],d=e.colors[1],f=e.dataAt(W.BARKIND,r),p=q_(f),m=f===z.BARKIND_XO,h=f===z.BARKIND_OX;if(N(n,i))for(let r=n;r>=i;r-=l){let l=c.adjust(s),[f,g]=[l-o,l+o],[_,v,y]=[r,r-u,r+u].map(t=>e.priceToY(t)),b=r===n&&m||r===i&&h?!p:p;t.beginPath(),b?(t.strokeStyle=d,t.moveTo(f,v),t.lineTo(g,y),t.moveTo(f,y),t.lineTo(g,v)):(t.strokeStyle=a,t.ellipse(l,_,o,v-_,0,0,Math.PI*2)),t.stroke()}}s+=n.totalWidth}),c.epilog(t)}var Tb={draw:Eb};function Eb(e,t,{bar:n,slice:r,start:i}){let a=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2;Iy(e,r,i,(r,i)=>{if(!i){let[i,o]=[W.Open,W.Close].map(t=>e.dataAt(t,r)).map(e.priceToY,e),s=Math.floor(n.totalWidth/2);t.fillStyle=e.getColor(r),t.beginPath(),t.rect(a-s,Math.min(i,o),n.totalWidth,Math.abs(o-i)),t.fill()}a+=n.totalWidth})}var Db={draw(e,t,n){e.varyColorPerBar?Ab(e,t,n):kb(e,t,n,e.colors[0])},hitTest:Ob};function Ob(e,t,n,r){let[i,a]=e.fields,{from:o,to:s}=Ay(e,t,n);for(let n=o;n<=s;n++){let o=e.pointAtTimelineIndex(n,i),s=e.pointAtTimelineIndex(n+1,i),c=e.pointAtTimelineIndex(n,a),l=e.pointAtTimelineIndex(n+1,a);if(o!==null&&s!==null&&c!==null&&l!==null&&Ny(t,o,s,r)&&Py(t,Fy(t.x,o,s),Fy(t.x,c,l),r))return!0}return!1}function kb(e,t,{bar:n,slice:r,start:i},a){t.fillStyle=a;let[o,s]=e.fields,c=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,l=[];if(Iy(e,r,i,(t,r)=>{if(!r){let n=e.dataAt(o,t),r=e.dataAt(s,t);N(n,r)&&l.push({x:c,upY:e.priceToY(n),downY:e.priceToY(r)})}c+=n.totalWidth}),l.length>0){t.beginPath(),t.moveTo(l[0].x,l[0].upY);for(let e=1;e<l.length;++e)t.lineTo(l[e].x,l[e].upY);let e=l.length-1;t.lineTo(l[e].x,l[e].downY);for(let n=e-1;n>=0;--n)t.lineTo(l[n].x,l[n].downY);t.closePath(),t.fill()}}function Ab(e,t,{bar:n,slice:r,start:i}){let[a,o]=e.fields,s=e.view.xAxis.xScale.range()[0]+n.offset+n.width/2,c=[],l=e=>{if(c.length>1){t.beginPath(),t.fillStyle=e,t.moveTo(c[0].x,c[0].upY);for(let e=1;e<c.length;++e)t.lineTo(c[e].x,c[e].upY);let n=c.length-1;t.lineTo(c[n].x,c[n].downY);for(let e=n-1;e>=0;--e)t.lineTo(c[e].x,c[e].downY);t.closePath(),t.fill()}},u=null,d=null;Iy(e,r,i,(t,r)=>{if(!r){let n=e.dataAt(a,t),r=e.dataAt(o,t);if(N(n,r)){let i=e.priceToY(n),a=e.priceToY(r);d=e.getColor(t),u!==d&&(l(u),c.length>0&&(c=[c.pop()]),u=d),c.push({x:s,upY:i,downY:a})}}s+=n.totalWidth}),l(d)}var jb=class{plot;id;fields=[];colors=[];style=h.Line;attributes=[];zones;_shift=0;lineWidth=1;lineMarker;lineSmoothing;dashStyle=`Solid`;varyColorPerBar=!1;visible=!0;_zoneColors;constructor(){this.id=xt(),this.plot=null}get shift(){return this._shift}set shift(e){this._shift=N(e)?e:0}get isOhlc(){return(this.isOhlcStyle||this.isCandle||this.isHlcStyle||this.isElderImpulseSystemStyle||this.isRangeStyle)&&this.fields.includes(W.Close)}get name(){return this.isOhlc?``:this.fields[0].name}get isHeikinAshiStyle(){return this.style===h.HeikinAshi}get isCandle(){return this.style===h.Candlestick||this.style===h.HollowCandles||this.style===h.HeikinAshi}get isHollowCandles(){return this.style===h.HollowCandles}get isElderImpulseSystemStyle(){return this.style===h.ElderImpulseSystem}get isPercentChangeStyle(){return this.style===h.PercentChange}get isOhlcStyle(){return this.style===h.OHLC}get isHlcStyle(){return this.style===h.HLC}get isRangeStyle(){return this.style===h.Range}get isRenko(){return this.style===h.Renko}get isKagi(){return this.style===h.Kagi}get isPointAndFigure(){return this.style===h.PointAndFigure}get isLineBreak(){return this.style===h.LineBreak}get isBaseline(){return this.style===h.Baseline}get isLineLike(){return[h.Line,h.Area,h.Baseline,h.PercentChange].includes(this.style)}get isColumn(){return this.style===h.Column}get isMultiColumn(){return this.style===h.MultiColumn}get isStackedColumn(){return this.style===h.StackedColumn}isFirstVisibleOfStyle(){return this.plot.curves.find(e=>e.visible&&e.style===this.style)===this}fromModel(e){e.attributes&&(this.attributes=e.attributes.map(e=>m[e])),this.colors=e.colors,this.fields=e.fields.map(e=>W[e]),this.style=h[e.style],this.lineWidth=e.lineWidth,this.dashStyle=e.dashStyle,this.lineMarker=e.lineMarker,this.lineSmoothing=e.lineSmoothing,this.varyColorPerBar=e.varyColorPerBar,this.visible=e.visible??!0,e.zones&&(this.zones=e.zones),this.shift=e.shift}get axis(){return this.plot?.axis}get pane(){return this.axis?.pane}get timeSeries(){return this.plot?.timeSeries}get presenter(){return this.pane?.presenter}get view(){return this.presenter?.view}yToPrice(e){return this.yScale.yToPrice(e)}priceToY(e){return this.yScale.priceToY(e)}dataAt(e,t,n=!0){let r=!this.plot.isComparison(x.None),i=e===W.PercentChange,a=e===W.Change,o=i||(!n||r)&&a,s=this.timeSeries.container.hasField(W.Last)?W.Last:W.Close,c=o?s:e,l=(e,t)=>{let n=this.timeSeries.container.getData(e)[t];return e.type===v.Number?this.plot.priceMapper(n,t,e):n},u=l(c,t);if(!o)return u;if(t<=1)return 0;let d=l(c,t-1),f=u-d;return i?d===0?0:f/d:f}timeSeriesAt(e){let t=this.timeSeries.container.getTimeData(),n=t.length;return e<0||e>n-1?null:t[e]}timelineAt(e){return this.presenter.timeline.at(e)}get shiftedTimeDomain(){let e=this.view.xAxis.xScale;return N(e.extent())?this.shift===0?e.domain():e.extent().map(t=>e.timeline.at(t-this.shift)):null}get yScale(){return this.plot?.yScale??this.axis.yScale}get canHitTest(){return N(Mb(this)?.hitTest)}getCore(){let e=this.timeSeries;if(!e.hasData||!this.visible)return null;let t=this.view.xAxis.xScale.extent();if(!N(t))return null;let n=this.yScale.domain();return N(n)?{ts:e,extent:t,domain:n,range:this.yScale.range()}:null}getDrawInfo(e){let t=e.ts.container.getTimeData(),n=this.shiftedTimeDomain[0];return N(n)?{bar:this.view.xAxis.xScale.bar,domain:e.domain,range:e.range,slice:e.extent,start:A(t,+n,Number)||0}:null}hitTest(e){let t=Mb(this);if(!N(t?.hitTest))return!1;let n=this.getCore();if(n===null)return!1;let r=this.getDrawInfo(n);if(r===null)return!1;let i=z.PLOT_HIT_TEST_TOLERANCE+Math.max(0,this.lineWidth/2);return!ky(this,e,r,i)&&t.hitTest(this,e,r,i)}dataIndexAtTimelineIndex(e){let t=this.timelineAt(e-this.shift);if(!N(t))return null;let n=this.timeSeries.container.getTimeData(),r=A(n,+t,Number),i=n[r];return N(i)&&i.getTime()===t.getTime()?r:null}pointAtTimelineIndex(e,t){let n=this.dataIndexAtTimelineIndex(e);if(!N(n))return null;let r=this.dataAt(t,n);return N(r)?{x:this.view.xAxis.xScale.indexToX(e),y:this.priceToY(r)}:null}drawHover(e,t,n){if(!this.isLineLike||this.getCore()===null)return;let[r,i]=xy(this,this.pickMainField(),t);N(r)&&(e.save(),ns(e,this.plot.axis.pane.getBoundsWithoutScales()),e.fillStyle=Ho(this.getColor(i)),e.beginPath(),Uy(e,n,this.priceToY(r),this.lineMarker??`Circle`,1.3333),e.fill(),e.restore())}draw(e){let t=this.getCore();if(t===null)return;let n=this.getDrawInfo(t);if(n===null)return;e.save(),e.setLineDash([]);let r=Mb(this);N(r)?r.draw(this,e,n):F(`Drawing of the curve style '${this.style}' is not implemented yet`,`error`),e.restore()}pickMainField(){return this.fields.length===1?this.fields[0]:this.fields.includes(W.Last)?W.Last:this.fields.includes(W.Close)?W.Close:this.fields[0]}get zoneColors(){if(!N(this._zoneColors)){let e=this.colors.slice();this._zoneColors=this.zones.map(t=>e.splice(0,t.colors))}return this._zoneColors}getColorsFromZone(e){let t=this.zones.findIndex(t=>e<t.value);return t===-1&&(t=this.zones.length-1),this.zoneColors[t]}pickAreaStroke(e){return e.length<2?Ho(e[0]):e[1]}getComputedColor(e){if(!this.timeSeries.container.hasField(W.BARCOLIX))return null;let t=this.dataAt(W.BARCOLIX,e);return t>=0&&t<this.colors.length?this.colors[t]:null}getColor(e,t=!0,n=null){if(this.varyColorPerBar){let n={};if(this.isOhlc||this.isRenko||this.isLineBreak){let t=this.dataAt(W.Open,e),r=this.dataAt(W.High,e),i=this.dataAt(W.Low,e),a=this.dataAt(W.Close,e),o=this.dataAt(W.Change,e);n.open=t,n.high=r,n.low=i,n.close=a,n.change=o}else if(this.plot.isStudy&&![`VOL`,`MAVOL`].includes(this.plot.model.study)){let t=this.pickMainField(),r=this.dataAt(t,e-1),i=this.dataAt(t,e),a=N(r),o=N(i);n.change=a?o?i-r:-1:+!!o}else{let t=this.plot.axis.pane.presenter.data.aggregation;(!t.isTick||t.spec!==_.None)&&(n.open=this.dataAt(W.Open,e),n.close=this.dataAt(W.Close,e)),n.change=this.dataAt(W.Change,e)}let r,i=Nb(this.style,n,this.colors),a=this.getComputedColor(e);switch(this.style){case h.Candlestick:case h.Renko:case h.LineBreak:case h.Range:case h.HeikinAshi:case h.OHLC:case h.HLC:case h.Column:{if(N(a)){r=a;break}let t=i.useSame?i.isUp:i.isUp||i.isSame,n=i.isSame,o=this.attributes||[],s=this.plot.isStudy&&![`HASMO`,`VOL`,`MAVOL`].includes(this.plot.model.study);(o.includes(m.ChangeBased)||s)&&(t=i.useSame?i.isUpPrev:i.isUpPrev||i.isSamePrev,n=i.isSamePrev),r=this.colors[+!!t],i.useSame&&n&&(r=this.colors[2]),(this.isRenko||this.isLineBreak||this.isRangeStyle)&&this.dataAt(W.Projection,e)===1&&(r=qo(.5,!0)(r));break}case h.ElderImpulseSystem:r=this.colors[this.dataAt(W.BREL,e)];break;case h.HollowCandles:{let e=this.colors[i.isUpPrev||i.isSamePrev?1:0];r=t&&(i.isUp||i.isSame)?z.COLOR_TRANSPARENT:e;break}case h.Line:case h.PercentChange:case h.Ribbon:case h.Kagi:if(N(a)){r=a;break}r=this.colors[0];break;case h.PointAndFigure:{let t=+!!q_(this.dataAt(W.BARKIND,e));r=this.colors[t];break}default:throw Error(`Unexpected style ${h[this.style]} for a curve with varying colors`)}return N(r)||(r=this.colors[0]),r}if(this.zones){let t=this.pickMainField(),n=this.dataAt(t,e),r=this.getColorsFromZone(n);return this.style===h.Area?this.pickAreaStroke(r):r.length>0?r[0]:this.colors[0]}return(this.isMultiColumn||this.isStackedColumn)&&N(n)?this.colors[Ae(this.colors,this.fields.findIndex(e=>e===n))]:this.colors[0]}};function Mb(e){return e.isOhlc?gb:e.isRenko||e.isLineBreak?Tb:e.style===h.Ribbon?Db:e.style===h.Area?Zy:e.isColumn||e.isMultiColumn?ob:e.isStackedColumn?sb:e.isBaseline?Qy:e.style===h.Step?Ry:e.isKagi?fb:e.isPointAndFigure?Cb:e.style===h.Dots?zy:e.style===h.Line||e.isPercentChangeStyle?Ly:null}function Nb(e,{open:t,close:n,change:r},i){let a=i.length>2&&e!==h.HLC,o=N(t,n),s=o&&n>t,c=o&&n===t,l=r>0,u=r===0;return{useSame:a,isUp:s,isSame:c,isUpPrev:l,isSamePrev:u,isDown:!s&&!c,isDownPrev:!l&&!u}}function Pb(e){let t=e.duplicate(),n=e;return`disableStreamingUpdates`in n&&(t.disableStreamingUpdates=n.disableStreamingUpdates),`surrogate`in n&&(t.surrogate=n.surrogate),t}var Fb=class e{symbol;aggregation;range;seriesKind;cacheMe;barsToFetch;offset;chartId;curveStyle;extendedHours;useLastTrade;fields=[];alwaysUseBarsToFetch;inputs=[];splits;padded;constructor(e,t,n=C.Normal,r=[null,null]){this.symbol=e,this.aggregation=t,this.range=r,this.seriesKind=n,this.cacheMe=!1,this.barsToFetch=0,this.offset=0,this.chartId=null,this.curveStyle=null,this.alwaysUseBarsToFetch=!1,this.splits=!0,this.padded=!1}getBuilderKey(){if(this.curveStyle!==null&&Tc(this.inputs,wc(h[this.curveStyle])),!N(this.curveStyle)||!z.SPECIAL_BUILDER_REQUIRED.includes(this.curveStyle))return`Standard`;switch(this.curveStyle){case h.Renko:{let{method:e,period:t,source:n,brickSize:r}=i_(this.inputs);return`Renko;${e===`ATR`?`ATR;${t}`:`${e};${r}`};${n}`}case h.Kagi:{let{method:e,period:t,reversal:n}=z_(this.inputs);return`Kagi;${e===`ATR`?`ATR;${t}`:`User;${n}`}`}case h.PointAndFigure:{let{method:e,period:t,reversal:n,boxSize:r,source:i,oneStepBack:a}=J_(this.inputs);return`PointAndFigure;${e===`ATR`?`ATR;${t}`:`User;${r}`};${i};${n};${a}`}case h.LineBreak:{let{lineBreak:e}=V_(this.inputs);return`LineBreak;${e}`}default:return h[this.curveStyle]}}get usesLastTrade(){let e=this.aggregation;return!e.isEndOfDay||!this.useLastTrade?!1:!(e.backAdjust&&e.isMultiContract)}get needsExtraKey(){return[C.Options,C.BalanceSheet,C.IncomeStatement].includes(this.seriesKind)}getExtraKey(){return this.needsExtraKey&&this.fields.length>0?`${this.fields.map(e=>e.id).join(`;`)}`:``}getHashKey(){let e=this.aggregation.getHashKey(),t=this.getBuilderKey(),n=this.getExtraKey(),r=this.extendedHours??!1,i=this.usesLastTrade;return`${this.symbol}|${i}|${e}|${r}|${this.range}|${this.seriesKind}|${this.offset}|${t}|${this.splits}|${this.padded}|${n}`}duplicate(){let t=new e(this.symbol,this.aggregation.duplicate(),this.seriesKind,this.range);return t.cacheMe=this.cacheMe,t.barsToFetch=this.barsToFetch,t.alwaysUseBarsToFetch=this.alwaysUseBarsToFetch,t.offset=this.offset,t.chartId=this.chartId,t.curveStyle=this.curveStyle,t.useLastTrade=this.useLastTrade,t.extendedHours=this.extendedHours,t.fields=P(this.fields),t.splits=this.splits,t.padded=this.padded,t}},Ib=/* @__PURE__ */ c((/* @__PURE__ */ o(((e,t,n)=>{(function(n,r){var i={};n.PubSub?(i=n.PubSub,console.warn(`PubSub already loaded, using existing version`)):(n.PubSub=i,r(i)),typeof e==`object`?(t!==void 0&&t.exports&&(e=t.exports=i),e.PubSub=i,t.exports=e=i):typeof define==`function`&&define.amd&&define(function(){return i})})(typeof window==`object`&&window||n||global,function(e){var t={},n=-1,r=`*`;function i(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))return!0;return!1}function a(e){return function(){throw e}}function o(e,t,n){try{e(t,n)}catch(e){setTimeout(a(e),0)}}function s(e,t,n){e(t,n)}function c(e,n,r,i){var a=t[n],c=i?s:o,l;if(Object.prototype.hasOwnProperty.call(t,n))for(l in a)Object.prototype.hasOwnProperty.call(a,l)&&c(a[l],e,r)}function l(e,t,n){return function(){var i=String(e),a=i.lastIndexOf(`.`);for(c(e,e,t,n);a!==-1;)i=i.substr(0,a),a=i.lastIndexOf(`.`),c(e,i,t,n);c(e,r,t,n)}}function u(e){var n=String(e);return!!(Object.prototype.hasOwnProperty.call(t,n)&&i(t[n]))}function d(e){for(var t=String(e),n=u(t)||u(r),i=t.lastIndexOf(`.`);!n&&i!==-1;)t=t.substr(0,i),i=t.lastIndexOf(`.`),n=u(t);return n}function f(e,t,n,r){e=typeof e==`symbol`?e.toString():e;var i=l(e,t,r);return d(e)?(n===!0?i():setTimeout(i,0),!0):!1}e.publish=function(t,n){return f(t,n,!1,e.immediateExceptions)},e.publishSync=function(t,n){return f(t,n,!0,e.immediateExceptions)},e.subscribe=function(e,r){if(typeof r!=`function`)return!1;e=typeof e==`symbol`?e.toString():e,Object.prototype.hasOwnProperty.call(t,e)||(t[e]={});var i=`uid_`+String(++n);return t[e][i]=r,i},e.subscribeAll=function(t){return e.subscribe(r,t)},e.subscribeOnce=function(t,n){var r=e.subscribe(t,function(){e.unsubscribe(r),n.apply(this,arguments)});return e},e.clearAllSubscriptions=function(){t={}},e.clearSubscriptions=function(e){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&delete t[n]},e.countSubscriptions=function(e){var n,r,i=0;for(n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0){for(r in t[n])i++;break}return i},e.getSubscriptions=function(e){var n,r=[];for(n in t)Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0&&r.push(n);return r},e.unsubscribe=function(n){var r=typeof n==`string`&&(Object.prototype.hasOwnProperty.call(t,n)||function(e){for(var n in t)if(Object.prototype.hasOwnProperty.call(t,n)&&n.indexOf(e)===0)return!0;return!1}(n)),i=!r&&typeof n==`string`,a=typeof n==`function`,o=!1,s,c,l;if(r)e.clearSubscriptions(n);else{for(s in t)if(Object.prototype.hasOwnProperty.call(t,s)){if(c=t[s],i&&c[n]){delete c[n],o=n;break}if(a)for(l in c)Object.prototype.hasOwnProperty.call(c,l)&&c[l]===n&&(delete c[l],o=!0)}return o}}})})))(),1);function Lb(e,t,n){return new Rb(e,t,n)}var Rb=class{exprModel;innerSeries;calculable=!0;container;innerLookup;policy;exprSymbols;valueSymbols=[];onlyForTimeline;recalcTriggers;crashedComputationReported=!1;isLoading=!1;_sourceFields;_targetFields;basisChangedToken=null;quoteGroupToken=null;seasonalAverageOffset;constructor(e,t,n){this.exprModel=e,this.innerSeries=t,this.container=null,this.innerLookup=t.reduce((e,t)=>(e[n.mapper(t)]=t,e),{}),this.policy=n,this.exprSymbols=of(e),this.valueSymbols=this.exprSymbols.filter(e=>this.innerLookup[e]===void 0),this.onlyForTimeline=k(this.symbols,this.exprSymbols),this.recalcTriggers=new Set(t)}refresh(){this.innerSeries.forEach(e=>e.refresh())}get canLoadMoreData(){return this.policy.loadMoreData&&this.innerSeries.some(e=>e.canLoadMoreData)}async loadMoreData(e=!0){if(this.isLoading)return Promise.resolve();this.isLoading=!0;let t=this.innerSeries.filter(e=>e.canLoadMoreData).map(t=>t.loadMoreData(e));await Promise.all(t),this.isLoading=!1}get isExprInError(){return!N(this.exprModel)}get hasData(){return this.container!==null}get sourceFields(){return this._sourceFields||=Array.from(this.policy.fieldMap.keys()),this._sourceFields}get targetFields(){return this._targetFields||=Array.from(this.policy.fieldMap.values()),this._targetFields}async ready(){return ma.call(this,async()=>{this.basisChangedToken=Ib.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)),this.quoteGroupToken=Ib.default.subscribe(G.RT_QUOTEGROUP,this.onQuoteGroup.bind(this));let e=this.innerSeries.map(e=>e.ready());this.policy.valueProvider!==void 0&&e.push(this.policy.valueProvider.ready());let t=(await Promise.all(e)).every(de);return t&&this.calculate(),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onQuoteGroup(e,t){t.source===this.policy.valueProvider&&this.innerSeries.every(e=>N(e.container))&&this.calculateCommon(G.TS_MANYCHANGED)}onBasisChanged(e,t){if(this.policy.recompute===d.Manual||e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||!this.shouldTriggerOurRecalc(t.series)||this.innerSeries.some(e=>!N(e.container)))return;let n=this.policy.mapper(t.series);if(!(e===G.TS_DATAPOINTCHANGED&&this.onlyForTimeline?.includes(n)))switch(this.policy.recompute===d.Everything?G.TS_MANYCHANGED:e){case G.TS_MANYCHANGED:this.calculate();break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:this.recalculate(e===G.TS_DATAPOINTADDED);break;case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.basisChangedToken&&Ib.default.unsubscribe(this.basisChangedToken),this.quoteGroupToken&&(Ib.default.unsubscribe(this.quoteGroupToken),this.policy.valueProvider?.shutdown())}calculateAt(e){return e.isNull?null:this.sourceFields.map((t,n)=>t===W.Volume?me(this.exprSymbols.map(t=>e.inn[t].values[n]??0)):tf(this.exprModel,t=>e.oneValue[t]??e.inn[t]?.values[n]??null))}pickMainField(){let e=null;for(let t of this.policy.fieldMap.values())if(e==null)e=t;else if(t===W.Close){e=t;break}return e}calculateLastChange(){let e=this.container,t=e.size;if(t<=1)return;let n=this.pickMainField(),r=e.getData(n)[t-2],i=e.getData(n)[t-1];N(r,i)&&e.setLastDataPoint(W.Change,i-r)}calculateDataPoint(e,t){let n=this.calculateAt(e);if(n===null)return;e.atLeastOne=!0;let[r,i]=De(n,0,3);n[1]=i,n[2]=r,this.targetFields.forEach((e,r)=>{let i=n[r];t?this.container.addDataPoint(e,i):this.container.setLastDataPoint(e,i)}),t&&(this.container.addDataPoint(W.Change,null),this.container.addDataPoint(W.DateTime,new Date(e.timeStamp))),this.calculateLastChange()}notify(e){Ke(e,{series:this,index:this.container.size-1})}fieldValueAt(e,t,n){let r=this.innerLookup[e].container.getData(n);return t<0||t>=r.length?null:r[t]}timeStampAt(e,t){return this.fieldValueAt(e,t,W.DateTime)}timeline(e){return e.container.getData(W.DateTime)}getRangeHelper(){switch(this.policy.missing){case u.UseNext:case u.UseNone:return{begin:Math.min,end:Math.min};case u.UseNextFromLatestStart:return{begin:Math.max,end:Math.min};case u.UsePrevious:return{begin:Math.max,end:Math.max};default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}getRange(){let e=this.getRangeHelper();return{begin:new Date(e.begin(...this.symbols.map(e=>we(this.timeline(this.innerLookup[e]))))),end:new Date(e.end(...this.symbols.map(e=>Ce(this.timeline(this.innerLookup[e])))))}}getFirstPos(){return this.getPos(this.getRange().begin)}getLastPos(){return this.getPos(this.getRange().end)}findIndex(e,t){let n=this.timeline(this.innerLookup[e]);switch(this.policy.missing){case u.UseNext:case u.UseNextFromLatestStart:case u.UseNone:return n.findIndex(e=>e.valueOf()>=t.valueOf());case u.UsePrevious:return Te(n,e=>e.valueOf()<=t.valueOf());default:throw Error(`Unknow missing bar policy, likely forgot to implement it.`)}}checkPos(e){let t=Object.keys(e.inn).length;e.isNull=Object.values(e.inn).some(e=>!N(e.timeStamp)&&(!this.policy.stretch(e.symbol)||t===1))}fillPosSymbolAt(e,t,n){e.index=t,e.timeStamp=this.timeStampAt(e.symbol,t);let r=(this.policy.missing===u.UseNone||this.policy.skipLeadingEmpty&&!n.atLeastOne)&&e.timeStamp&&e.timeStamp.valueOf()!==n.timeStamp.valueOf();return e.values=this.sourceFields.map(n=>r?null:this.fieldValueAt(e.symbol,t,n)),e}skippable(e){return this.innerLookup[e].container.isEmpty?this.policy.noDataApproach===f.IgnoreTimelineOnly&&this.onlyForTimeline.includes(e)||this.policy.noDataApproach===f.ModelTransformRequired:!1}get symbols(){let e=Object.keys(this.innerLookup);return N(this.onlyForTimeline)?e.filter(e=>!this.skippable(e)):e}getPos(e){let t={isNull:!0,inn:{},timeStamp:e,atLeastOne:!1,oneValue:{}};return this.symbols.length===0||(this.symbols.forEach(n=>{let r=this.findIndex(n,e),i={symbol:n,index:-1,timeStamp:/* @__PURE__ */ new Date(0),values:[]};t.inn[n]=this.fillPosSymbolAt(i,r,t)}),this.valueSymbols.forEach(e=>{t.oneValue[e]=this.policy.valueProvider?.getValue(e)??null}),this.checkPos(t)),t}getInner(e){return Object.values(e.inn)}moveNext(e){e.isNull||(this.getInner(e).forEach(t=>{for(;N(t.timeStamp)&&t.timeStamp.valueOf()<=e.timeStamp.valueOf();)this.fillPosSymbolAt(t,t.index+1,e)}),this.checkPos(e),e.isNull||(e.timeStamp=new Date(Math.min(...this.getInner(e).filter(e=>e.timeStamp!==null).map(e=>e.timeStamp.valueOf()))),this.policy.missing===u.UsePrevious?this.getInner(e).forEach(t=>{let n=N(t.timeStamp);(n&&t.timeStamp.valueOf()>e.timeStamp.valueOf()||!n&&this.policy.stretch(t.symbol))&&this.fillPosSymbolAt(t,t.index-1,e)}):this.policy.missing===u.UseNone&&this.getInner(e).forEach(t=>this.fillPosSymbolAt(t,t.index,e))))}shouldAdd(e){let t=this.container?.getLastDataPoint(W.DateTime),n=e?.timeStamp;return N(t,n)?t.valueOf()<n.valueOf():!1}calculateCommon(e=null,t=null,n=!0){try{if(t)this.calculateDataPoint(t,n);else if(this.container=this.makeContainer(),!this.isExprInError){let e=this.getFirstPos();for(;!e.isNull;)this.calculateDataPoint(e,!0),this.moveNext(e)}e&&this.notify(e)}catch(e){this.crashedComputationReported||=(F(e,`error`),!0)}}calculate(){let{yes:e,no:t}=O(this.innerSeries,e=>!e.container.isEmpty);if(t.length>0&&this.policy.noDataApproach===f.ModelTransformRequired){let n=e=>e.map(this.policy.mapper),r=this.policy.modelTransform(n(e),n(t));r!==null&&(this.exprModel=r)}this.calculateCommon(G.TS_MANYCHANGED)}recalculate(e){if(this.isExprInError)return;let t=this.getLastPos(),n=this.shouldAdd(t);this.calculateCommon(n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n)}recalculateAt(e,t,n){return this.recalculate(n)}makeContainer(){return new e_([W.DateTime,W.Change].concat(this.targetFields))}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}};function zb(e){if(!(e instanceof Rb)||e.innerSeries.length!==1||e.exprSymbols.length!==1||e.valueSymbols.length!==0)return e;let t=e.innerSeries[0],n=t.query;return!N(n)||!rt(n,`surrogate`)?e:t}function Bb(e){let{query:t}=e;return t!==void 0&&`duplicate`in t&&`getBuilderKey`in t}function Vb(e,t,n){if(!(e instanceof Rb))return n(e);if(e.valueSymbols.length!==0)return new ev;let r=e.innerSeries.map(n);return new Rb(e.exprModel,r,{...e.policy,fieldMap:/* @__PURE__ */ new Map([[t,t]])})}function Hb(e,t){return Vb(e,t,e=>e)}function Ub(e,t){let n=zb(e);if(!Bb(n))return new ev;let r=Pb(n.query);if(r.symbol===z.PLACEHOLDER_SYMBOL_NAME||r.getBuilderKey()!==`Standard`)return new ev(r);{r.barsToFetch!==0&&(r.barsToFetch*=z.SERVER_COMPUTED_STUDY_BAR_MULTIPLIER);let e=t(r);return e.serverComputedSeries=!0,e}}function Wb(e,t,n){return Vb(e,t,e=>Ub(e,n))}function K(e){return new vp(e,v.Number,b.Study,e)}var q=class{calcCtx;container;_source;target;inputs;outFields;studyFields={};innerSeries;calculable=!0;useNotifications=!1;initialNotification=!1;computedServerSide=!1;id;usedAsStyle=!1;recalcTriggers=/* @__PURE__ */ new Set;basisChangedToken=null;_canLoadMoreData=!1;isLoading=!1;query;aggregation;sourceNeedsCompute=!1;allowEmptyValues=!1;constructor(e,...t){this.container=this._source=null,this.inputs=e.inputs,this.setOptions(e),this.innerSeries=t,this.id=xt(),this.addRecalcTrigger(...t)}refresh(){}get canLoadMoreData(){return this._canLoadMoreData}set canLoadMoreData(e){this._canLoadMoreData=e}loadMoreData(e){throw Error(`Should not be called.`)}addInner(...e){this.innerSeries.push(...e),this.addRecalcTrigger(...e)}isCalculable(e){return e.calculable??!1}addRecalcTrigger(...e){for(let t of e)this.isCalculable(t)?t.recalcTriggers.forEach(e=>this.recalcTriggers.add(e)):this.recalcTriggers.add(t)}setOptions(e){dt(this,e),rt(e,`source`)&&(this.source=e.source??null);let t=e.outFields??[e.target];this.studyFields=this.helpers.concat(t).reduce((e,t)=>(e[t.id]=t,e),{})}get helpers(){return z.EMPTY_ARRAY}get hasData(){return this.container!==null}get source(){if(N(this._source))return this._source;let e=N(this.inputs)?this.inputs[z.INPUT_SOURCE]:null;return N(e)?W[e]:null}set source(e){this._source=e}async ready(){return ma.call(this,async()=>{this.basisChangedToken=this.useNotifications?Ib.default.subscribe(G.TS_ALL,this.onBasisChanged.bind(this)):null;let e={tag:xt(),src:null},t=(await Promise.all(this.innerSeries.map(e=>e.ready()))).every(de);return t&&this.calculate(e),t})}shouldTriggerOurRecalc(e){return this.recalcTriggers.has(e)}onBasisChanged(e,t){if(e===G.TS_EVENTSCHANGED||e===G.TS_LOADING||this.innerSeries.some(e=>!e.hasData)||!this.shouldTriggerOurRecalc(t.series)||this.base===null||this===t.series)return;let n={tag:xt(),src:t.series};switch(e){case G.TS_MANYCHANGED:this.calculate(n);break;case G.TS_DATAPOINTCHANGED:case G.TS_DATAPOINTADDED:{let r=this.innerSeries[this.baseIndex].calculable?this.base.size-1:t.index;this.recalculateAt(n,r,e===G.TS_DATAPOINTADDED);break}case G.TS_TIMELINECORRECTION:case G.TS_QUOTEMARKER:break;default:throw Error(`Unknown time series message, likely forgot to handle it`)}}shutdown(){this.useNotifications&&this.basisChangedToken&&Ib.default.unsubscribe(this.basisChangedToken)}get baseIndex(){return 0}get base(){return this.innCont(this.baseIndex)}get period(){return this.inputs?.Period}calculateAt(e){return null}calculateDataPoint(e,t){let n=this.calculateAt(e);n!==null&&Object.keys(n).forEach(e=>{let r=n[e],i=this.studyFields[e];t?this.container.addDataPoint(i,r):this.container.setLastDataPoint(i,r)})}notify(e,t){Ke(e,{series:this,index:t})}calculateCommon(e,t=null,n=-1,r=!0){let i=n===-1,a=i?t=>{(N(e.src)||!N(t.calcCtx))&&t.calculate(e)}:t=>t.recalculateAt(e,n,r);if(!(this.base===null||this.calcCtx&&this.calcCtx.tag===e.tag||this===e.src)){if(this.calcCtx=e,this.innerSeries.filter(e=>this.isCalculable(e)&&!e.usedAsStyle).forEach(e=>a(e)),i&&(this.container=this.makeContainer()),this.calculateAt!==void 0){if(!i)this.calculateDataPoint(n,r);else{let e=this.base.size;for(let t=0;t<e;++t)this.calculateDataPoint(t,!0)}}t&&(N(e.src)||this.initialNotification)&&this.notify(t,n)}}calculate(e){this.calculateCommon(e,G.TS_MANYCHANGED,-1,!0)}recalculateAt(e,t,n){this.computedServerSide||(!n&&M(this.container)&&t>this.container.size-1&&(t=this.container.size-1),this.calculateCommon(e,n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED,t,n))}baseVal(e,t){return this.base.getData(e)[t]}innCont(e){return this.innerSeries[e].container}innVal(e,t,n){let r=this.innCont(e),i=r.size;return n<0||n>i-1?null:r.getData(t)[n]}innHasData(e){let t=this.innCont(e);return N(t)&&t.size>0}wrap(...e){return e.reduce((e,t)=>(e[t.f.id]=t.g,e),{})}wrapBaseFields(...e){return e.map(this.wrapBaseField,this)}wrapInner(e,t){return{f:e,g:()=>this.innCont(t).getData(e)}}wrapBaseField(e){return this.wrapInner(e,this.baseIndex)}get defaultWrappers(){return this.wrapBaseFields(W.DateTime,W.Symbol)}makeContainer(){let e=this.defaultWrappers.concat(this.getWrappers());return new n_(Object.keys(this.studyFields).map(e=>this.studyFields[e],this),this.wrap(...e))}getWrappers(){return[]}atLeast(e,t){return e>=t-1}exactly(e,t){return e==t-1}past(e,t,n,r=this.base){let i=r?.getData(n);return Array.isArray(i)?i.slice(e-t+1,e+1):[]}getCacheableEntities(e){this.innerSeries.forEach(t=>{t.getCacheableEntities(e)})}},Gb=class extends q{constructor(e,...t){super(e,...t),this.usedAsStyle=!0}get actual(){return this.innerSeries[0]}get canLoadMoreData(){return this.actual.canLoadMoreData}async loadMoreData(e=!0){return this.actual.loadMoreData(e)}get record(){return this.actual.record}},Kb=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return null}getWrappers(){return[this.wrapInner(this.target,0)]}},qb=class extends Gb{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let[t,n,r,i]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e),this),a=null,o=null,s=null,c=null,l=he([t,n,r,i]);if(e<1)a=he([t,i]),o=n,s=r,c=0;else{let[t,i]=[W.Open,W.Close].map(t=>this.container.getData(t)[e-1],this);a=he([t,i]),o=Math.max(n,a,l),s=Math.min(r,a,l),c=l-i}return{[W.Open.id]:a,[W.High.id]:o,[W.Low.id]:s,[W.Close.id]:l,[W.Change.id]:c}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Jb=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.inputs.PeriodAverage,i=n(t,r,this.source??W.Close,W.ATREXTAVG),a=AO(t,this.inputs.PeriodATR);this.addInner(i,a)}calculateAt(e){let t=this.innVal(1,W.ATREXTAVG,e),n=this.innVal(2,W.ATR,e),r=t!==null&&n!==null,i=n*this.inputs.Multiplier;return{[W.ATREXTUP.id]:r?t+i:null,[W.ATREXTLOW.id]:r?t-i:null}}getWrappers(){return[this.wrapInner(W.ATREXTAVG,1)]}},Yb=class extends q{constructor(e,t){super(e,t),JO(this)}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)&&r.hasField(this.source)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=he(i.filter(fe)):ge(i)&&(t=he(i))}return{[this.target.id]:t}}getWrappers(){return this.source===W.Volume?this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close):[]}},Xb=class extends q{multiplier;constructor(e,t,n){super(e,t),this.multiplier=n(this.period),JO(this)}calculateAt(e){let t=null,[n,r]=YO(this);if(this.atLeast(e,2)&&r.hasField(this.source)){let i=this.container.getData(this.target)[e-1];if(i!==null)t=(this.innVal(n,this.source,e)-i)*this.multiplier+i;else{let n=this.period;if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=he(i.filter(fe)):ge(i)&&(t=he(i))}}}return{[this.target.id]:t}}},Zb=class extends Xb{constructor(e,t){super(e,t,e=>2/(e+1))}},Qb=class extends Xb{constructor(e,t){super(e,t,e=>1/e)}},$b=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,W.High,W.MAHI),r=J(t,this.inputs.Period2,W.Low,W.MALO);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.MAHI,1),this.wrapInner(W.MALO,2)]}},ex=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=W.OpenInterest;return this.base.hasField(n)&&(t=this.baseVal(n,e)),{[n.id]:t}}},tx=class extends ex{constructor(e,t){super(e,t)}getWrappers(){return this.wrapBaseFields(W.Volume,W.TradeSize,W.Change,W.Open,W.Close)}},nx=class extends ex{constructor(e,t){super(e,Hb(t,W.OpenInterest))}getWrappers(){return this.wrapBaseFields(W.TradeSize,W.Change)}},rx={inField:W.MA,outFields:[W.ENVU,W.ENVD],func:J},ix={inField:W.EMA,outFields:[W.ENVEXPU,W.ENVEXPD],func:Y},ax={inField:W.SMA,outFields:[W.ENVSMOU,W.ENVSMOD],func:xO},ox=class extends q{kind;perc;constructor(e,t,n){super(e,n),this.kind=t,this.perc=this.inputs.Percent/100;let r=t.func(n,this.inputs.Period,e.source);this.addInner(r)}calculateAt(e){let t=null,n=null,r=this.innVal(1,this.kind.inField,e);if(r!==null){let e=r*this.perc;t=r+e,n=r-e}return{[this.kind.outFields[0].id]:t,[this.kind.outFields[1].id]:n}}},sx=class extends ox{constructor(e,t){super(e,rx,t)}},cx=class extends ox{constructor(e,t){super(e,ix,t)}},lx=class extends ox{constructor(e,t){super(e,ax,t)}},ux=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period,this.source),r=J(n,this.inputs.Period,W.MA,W.TMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.TMA,2)]}},dx=class extends q{triangle;constructor(e,t){super(e,t);let n=this.period;this.triangle=n*(n+1)/2,JO(this)}weightedAverage(e){let t=e.length;if(t===0)return null;let n=t===this.period?this.triangle:t*(t+1)/2;return e.reduce((e,t,n)=>e+t*(n+1),0)/n}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);this.allowEmptyValues?t=this.weightedAverage(i.filter(fe)):ge(i)&&(t=this.weightedAverage(i))}return{[this.target.id]:t}}},fx=class extends q{constructor(e,t){super(e,t);let n=J(t,this.inputs.Period1,this.source),r=J(t,this.inputs.Period2,this.source),i=Z(this.target,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},px={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:J,mapFunc:GO,histogramVaryColor:!0},mx={fields:[W.MACD,W.MACDS,W.MACDH],avgFunc:Y,mapFunc:GO,histogramVaryColor:!0},hx={fields:[W.MACD,W.CTLTM,W.CTM],avgFunc:Y,mapFunc:GO,histogramVaryColor:!1},gx={fields:[W.MACD,W.CTLTMF,W.CPMI],avgFunc:Y,mapFunc:GO,histogramVaryColor:!1},_x={fields:[W.PPO,W.PPOS,W.PPOH],avgFunc:Y,mapFunc:KO,histogramVaryColor:!0},vx={fields:[W.PVO,W.PVOS,W.PVOH],avgFunc:Y,mapFunc:KO,histogramVaryColor:!1},yx=class extends q{histogramVaryColor=!1;histogramField;get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=-1;if(this.histogramVaryColor&&e>0){let n=this.container.getData(this.histogramField)[e],r=this.container.getData(this.histogramField)[e-1];if(N(n,r)){let i=n<=0;t=i?1:3,e>0&&(i&&n>r&&(t=0),!i&&n<r&&(t=2))}}return{[W.BARCOLIX.id]:t}}},bx=class extends yx{fields;constructor(e,t,n){super(e,n),this.fields=t.fields,this.histogramVaryColor=t.histogramVaryColor,this.histogramField=this.fields[2];let r=t.avgFunc(n,e.inputs.Period1,e.source,void 0),i=t.avgFunc(n,e.inputs.Period2,e.source,void 0),a=Z(this.fields[0],t.mapFunc,r,i),o=t.avgFunc(a,e.inputs.Period3,a.target,this.fields[1]),s=Z(this.fields[2],GO,a,o);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(this.fields[0],1),this.wrapInner(this.fields[1],2),this.wrapInner(this.fields[2],3)]}},xx=class extends yx{constructor(e,t){super(e,t),this.histogramVaryColor=!0,this.histogramField=W.MACDVH;let n=$O(e,`EMA`,`Average`),r=n(t,e.inputs.Period1,e.source,void 0),i=n(t,e.inputs.Period2,e.source,void 0),a=AO(t,e.inputs.Period2,e.inputs.Average),o=Z(W.MACDV,(e,t,n,r)=>(t-n)/r*100,r,i,a),s=n(o,e.inputs.Period3,o.target,W.MACDVS),c=Z(W.MACDVH,GO,o,s);this.addInner(o,s,c)}getWrappers(){return[this.wrapInner(W.MACDV,1),this.wrapInner(W.MACDVS,2),this.wrapInner(W.MACDVH,3)]}},Sx=class extends bx{constructor(e,t){super(e,px,t)}},Cx=class extends bx{constructor(e,t){super(e,mx,t)}},wx=class extends bx{constructor(e,t){e.inputs={Period1:5,Period2:21,Period3:34},super(e,hx,t)}},Tx=class extends bx{constructor(e,t){e.inputs={Period1:3,Period2:5,Period3:8},super(e,gx,t)}},Ex=class extends bx{constructor(e,t){super(e,_x,t)}},Dx=class extends bx{constructor(e,t){super(e,vx,t)}},Ox=K(`_AVG_GAIN`),kx=K(`_AVG_LOSS`),Ax=class extends q{isModified;constructor(e,t){super(e,t);let n=e.inputs.Modified;this.isModified=n}get helpers(){return[Ox,kx]}gain(e,t){return t[e]>t[e-1]?t[e]-t[e-1]:0}loss(e,t){return t[e]<t[e-1]?t[e-1]-t[e]:0}calculateAt(e){let t=null,n=null,r=null,i=this.period;if(this.atLeast(e,i+1)){if(this.container.getData(this.target)[e-1]!==null&&!this.isModified){let t=this.container.getData(Ox)[e-1],a=this.container.getData(kx)[e-1],o=this.past(e,2,this.source),s=this.gain(1,o),c=this.loss(1,o);n=(t*(i-1)+s)/i,r=(a*(i-1)+c)/i}else{let t=this.past(e,i+1,this.source);if(ge(t)){let e=_e(1,i),a=e.map(e=>this.gain(e,t)),o=e.map(e=>this.loss(e,t));n=he(a),r=he(o)}}n!==null&&r!==null&&(t=100-100/(1+n/r))}return{[Ox.id]:n,[kx.id]:r,[this.target.id]:t}}},jx=class extends q{constructor(e,t,n){super(e,n);let r=FO(n,this.inputs.Period,this.source,W.RSI,t),i=$O(e,`MA`,`Average`)(r,this.inputs.PeriodAvg,W.RSI,W.RSIAVG);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.RSI,1),this.wrapInner(W.RSIAVG,2)]}},Mx=class extends jx{constructor(e,t){super(e,!1,t)}},Nx=class extends jx{constructor(e,t){super(e,!0,t)}},Px=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period,this.source),r=this.inputs.Range,i=X(W.STORSI,function(e){let t=null;if(this.atLeast(e,r)){let n=this.past(e,r,W.RSI,this.base),i=De(n),a=i[0],o=i[1];t=(Ce(n)-a)/(o-a)}return{[W.STORSI.id]:t}},n),a=$O(e,`MA`,`Average`),o=this.inputs.PeriodAvg,s=a(i,o,W.STORSI,W.STORSIAVG);this.addInner(i,s)}getWrappers(){return[this.wrapInner(W.STORSI,1),this.wrapInner(W.STORSIAVG,2)]}},Fx=class extends q{constructor(e,t){super(e,t);let n=TO(t,this.inputs.Period1,W.High,W.HH,!0),r=TO(t,this.inputs.Period2,W.Low,W.LL,!1);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.HH,1),this.wrapInner(W.LL,2)]}},Ix=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,[n,r,i]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e));return t=(2*n+r+i)/4,{[this.target.id]:t}}},Lx=class extends q{highest;index;constructor(e,t,n,r){super(e,r),this.highest=t,this.index=n}calculateAt(e){let t=null,n=this.inputs.Period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);ge(r)&&(t=this.highest?Math.max(...r):Math.min(...r),this.index&&(t=n-r.indexOf(t)-1))}return{[this.target.id]:t}}},Rx=class extends q{toHighest;field;highField;lowField;constructor(e,t,n){super(e,n),this.toHighest=t;let r=N(e.source),i=e.source,a=r?i:W.Close;this.field=a;let o=r?i:W.High;this.highField=o;let s=r?i:W.Low;this.lowField=s;let c=TO(n,e.inputs.Period,this.highField,W.HH,!0),l=TO(n,e.inputs.Period,this.lowField,W.LL,!1);this.addInner(c,l)}calculateAt(e){let t=null,n=this.baseVal(this.field,e),r=this.innVal(1,W.HH,e),i=this.innVal(2,W.LL,e);if(ge([n,r,i])){let e=this.toHighest?r:i,a=r-i;a!==0&&(t=(n-e)/a*100)}return{[this.target.id]:t}}},zx=class extends Rx{constructor(e,t){super(e,!0,t)}},Bx=K(`RawPercK`),Vx=class extends q{kField;constructor(e,t,n,r){super(e,r);let i=EO(r,this.inputs.Period1,t?Bx:n,!1),a=$O(e,`MA`),o=a(i,this.inputs.Period2,i.target,t?n:W.PercD),s=t?a(o,this.inputs.Period3,o.target,W.PercD):o;this.kField=n,t?this.addInner(o,s):this.addInner(i,o)}getWrappers(){return[this.wrapInner(this.kField,1),this.wrapInner(W.PercD,2)]}},Hx=class extends Vx{constructor(e,t){super(e,!1,W.PercK,t)}},Ux=class extends Vx{constructor(e,t){super(e,!0,W.PercK,t)}},Wx=class extends Vx{constructor(e,t){e.inputs={Period1:5,Period2:3,Period3:3},super(e,!0,W.CTPI,t)}};function Gx(e,t,n,r,i){if(i===null)return null;let a=e*i,o=r+a,s=r-a;switch(t){case W.BOLLBU:return o;case W.BOLLBL:return s;case W.BOLLBW:return(o-s)/r*100;default:return null}}var Kx=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t,JO(this);let r=this.inputs.Period,i=this.source,a=J(n,r,i,W.BOLLBM),o=t===`Modified`,s=LO(o?DO(n,i):n,r,o?W.PCTCHG:i),c=this.inputs.Width,l=e=>le(Gx,c,e),u=Z(W.BOLLBU,l(W.BOLLBU),a,s),d=Z(W.BOLLBL,l(W.BOLLBL),a,s),f=Z(W.BOLLBW,l(W.BOLLBW),a,s),p=$O(e,`MA`,`Average`),m=this.inputs.PeriodAvg,h=p(f,m,W.BOLLBW,W.BOLLBWA);this.addInner(a,s,u,d,f,h)}calculateAt(e){let t=+!!this.sourceNeedsCompute,n=this.innVal(3+t,W.BOLLBU,e),r=this.innVal(4+t,W.BOLLBL,e),i=this.innVal(1+t,W.BOLLBM,e),a=this.innVal(5+t,W.BOLLBW,e),o=this.innVal(6+t,W.BOLLBWA,e),s=null;switch(this.kind){case`Regular`:return{[W.BOLLBU.id]:n,[W.BOLLBL.id]:r,[W.BOLLBM.id]:i};case`Width`:return{[W.BOLLW.id]:n-r};case`Percent`:if(N(n,r)){let[t]=YO(this),i=this.innVal(t,this.source,e);N(i)&&(s=(i-r)/(n-r))}return{[W.BOLLP.id]:s};case`BandWidth`:return{[W.BOLLBW.id]:a,[W.BOLLBWA.id]:o};case`Modified`:{let n=null,r=null,a=null,o=null,s=this.innVal(2+t,W.MSD,e);if(N(s)){let e=this.inputs.MultInside,t=this.inputs.MultOutside;n=i+e*s,a=i-e*s,r=i+t*s,o=i-t*s}return{[W.MBBUI.id]:n,[W.MBBLI.id]:a,[W.MBBUO.id]:r,[W.MBBLO.id]:o,[W.MBBM.id]:i}}default:return null}}},qx=class extends Kx{constructor(e,t){super(e,`Regular`,t)}},Jx=class extends Kx{constructor(e,t){super(e,`Width`,t)}},Yx=class extends Kx{constructor(e,t){super(e,`Percent`,t)}},Xx=class extends Kx{constructor(e,t){super(e,`BandWidth`,t)}},Zx=class extends Kx{constructor(e,t){super(e,`Modified`,t)}},Qx=class extends q{constructor(e,t){super(e,t);let n=X(W.OBVOL,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];N(a)||(a=0),t=n>i?a+r:n<i?a-r:a}return{[this.target.id]:t}},t),r=$O(e,`MA`,`Average`),i=this.period,a=r(n,i,W.OBVOL,W.OBVOLAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.OBVOL,1),this.wrapInner(W.OBVOLAVG,2)]}},$x=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);if(e>0){let i=this.baseVal(W.Close,e-1);t=Math.max(n-r,Math.abs(n-i),Math.abs(r-i))}else t=n-r;return{[this.target.id]:t}}},eS=K(`_ABS_CHG`),tS=K(`_MA_ABS_CHG`),nS=K(`_CHG`),rS=class extends q{constructor(e,t){super(e,t);let n=kO(t,W.TR),r=$O(e,`SMA`)(n,this.inputs.Period,W.TR,this.target),i=J(r,this.inputs.Period2,W.ATR,W.ATRMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.target,1),this.wrapInner(W.ATRMA,2)]}},iS=class extends q{constructor(e,t){super(e,t);let n=X(eS,ce((e,t)=>{let n=0;return t>0&&(n=this.baseVal(e,t)-this.baseVal(e,t-1)),{[eS.id]:Math.abs(n)}},this.source),t),r=$O(e,`MA`)(n,this.inputs.Period,eS,tS),i=Z(W.ADJATR,(e,t)=>2*t,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.ADJATR,1)]}},aS=class extends q{constructor(e,t){super(e,t);let n=X(nS,e=>{let t=0;return e>0&&(t=this.baseVal(W.Close,e)-this.baseVal(W.Close,e-1)),{[nS.id]:t}},t),r=tk(e),i=this.inputs.Period,a=this.inputs.Smoothing,o=r(t,i,a),s=Z(this.target,(e,t,n)=>!N(t)||!N(n)?null:t/n,n,o);this.addInner(s)}getWrappers(){return[this.wrapInner(this.target,1)]}},oS=K(`_PDM`),sS=K(`_MDM`),cS=K(`_TRS`),lS=K(`_PDS`),uS=K(`_MDS`),dS=K(`_DX`),fS=class extends q{useEma;adxField;multiplier;constructor(e,t,n,r){super(e,r),this.useEma=t,this.adxField=n,this.multiplier=2/(this.inputs.AdxSmoothing+1);let i=kO(r,W.TR);this.addInner(i)}get helpers(){return[oS,sS,cS,lS,uS,dS]}sum(e,t,n,r){let i=null;if(this.atLeast(e-1,r-1)){let a=this.past(e-1,r-1,t,this.container);a.push(n),ge(a)&&(i=a.reduce((e,t,n)=>e+t,0))}return i}smooth1(e,t,n,r){let i=null,a=this.inputs.DiLength,o=this.container.getData(n)[e-1];return i=o===null?this.sum(e,t,r,a):o-o/a+r,i}smooth2(e,t,n,r){let i=this.container.getData(n)[e-1],a=this.inputs.AdxSmoothing;if(i!==null)return this.useEma?(r-i)*this.multiplier+i:(i*(a-1)+r)/a;{let n=this.sum(e,t,r,a);if(n!==null)return n/a}return null}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null,l=null;if(e>0){let u=this.past(e,2,W.High),d=this.past(e,2,W.Low),f=Math.max(u[1]-u[0],0),p=Math.max(d[0]-d[1],0);t=f>p?f:0,n=p>f?p:0;let m=this.container.getData(W.TR)[e];i=this.smooth1(e,oS,lS,t),a=this.smooth1(e,sS,uS,n),r=this.smooth1(e,W.TR,cS,m),(i>0||a>0)&&r!==0&&(o=i/r*100,s=a/r*100,c=100*Math.abs(o-s)/(o+s),l=this.smooth2(e,dS,this.adxField,c))}return{[oS.id]:t,[sS.id]:n,[cS.id]:r,[lS.id]:i,[uS.id]:a,[W.PDI.id]:o,[W.MDI.id]:s,[dS.id]:c,[this.adxField.id]:l}}getWrappers(){return[this.wrapInner(W.TR,1)]}},pS=class extends fS{constructor(e,t){super(e,!1,W.ADX,t)}},mS=class extends fS{constructor(e,t){super(e,!0,W.ADXM,t)}},hS=class extends q{constructor(e,t){super(e,t);let n=IO(t);this.addInner(n)}calculateAt(e){let t=null;return t=(e>0?this.container.getData(this.target)[e-1]:0)+this.innVal(1,W.MFMUL,e),{[this.target.id]:t}}},gS=class extends q{constructor(e,t){super(e,t);let n=X(W.ADWM,function(e){let t=null,n=null;if(e>0){let r=this.baseVal(W.Close,e-1),i=Math.max(r,this.baseVal(W.High,e)),a=Math.min(r,this.baseVal(W.Low,e)),o=this.baseVal(W.Close,e);t=o>r?o-a:o<r?o-i:0,e>1&&(n=(e>2?this.container.getData(W.ADWM)[e-1]:0)+t)}return{[W.ADWM.id]:n}},t),r=J(n,this.inputs.Period,W.ADWM,W.ADWMMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.ADWM,1),this.wrapInner(W.ADWMMA,2)]}},_S=class extends q{constructor(e,t){super(e,t);let n=W.ADL,r=MO(t,n),i=Y(r,3,n),a=Y(r,10,n),o=Z(e.target,(e,t,n)=>t-n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},vS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;return t=he([W.Close,W.High,W.Low].map(t=>this.baseVal(t,e))),{[this.target.id]:t}}},yS=class extends q{calculateAtFunc;constructor(e,t,...n){super(e,...n),this.calculateAtFunc=t}calculateAt(e){let t=this.innerSeries.map((t,n)=>{let r=t,i=r.target;return N(i)||(i=r.container.hasField(W.Close)?W.Close:r.container.fields[0]),this.innVal(n,i,e)}),n=null;return ge(t)&&(n=this.calculateAtFunc(e,...t)),{[this.target.id]:n}}};function bS(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:(n+r)/2}}function xS(e,t){let n=this.baseVal(W.High,t),r=this.baseVal(W.Low,t);return{[e.id]:n-r}}var SS=class extends q{calculateAtFunc;constructor(e,t,n){super(e,n),this.calculateAtFunc=t}calculateAt(e){return this.calculateAtFunc.call(this,e)}},CS=K(`_RANGE`),wS=K(`_MOV_RANGE`),TS={fields:[W.KCUP,W.KCLOW,W.KCMID],midSeries:e=>NO(e,W.TP),midTarget:W.TP,rangeSeries:e=>X(CS,ce(xS,CS),e),rangeTarget:CS,func:`MA`,useMultiplier:!1},ES={fields:[W.KBUP,W.KBLOW,W.KBMID],midSeries:e=>e,midTarget:W.Close,rangeSeries:e=>kO(e,W.TR),rangeTarget:W.TR,func:`EMA`,useMultiplier:!0},DS=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=t.midSeries(n),i=$O(e,t.func,`Average`),a=i(r,this.inputs.Period,t.midTarget,t.fields[2]),o=i(t.rangeSeries(n),this.inputs.Period,t.rangeTarget,wS);this.addInner(a,o)}calculateAt(e){let t=this.innVal(1,this.kind.fields[2],e),n=this.innVal(2,wS,e),r=t!==null&&n!==null,i=this.kind.useMultiplier?this.inputs.Multiplier:1;return{[this.kind.fields[0].id]:r?t+n*i:null,[this.kind.fields[1].id]:r?t-n*i:null}}getWrappers(){return[this.wrapInner(this.kind.fields[2],1)]}},OS=class extends DS{constructor(e,t){super(e,TS,t)}},kS=class extends DS{constructor(e,t){super(e,ES,t)}},AS=class extends q{isWidth;constructor(e,t,n){super(e,n),this.isWidth=t;let r=TO(n,this.inputs.Period,W.High,W.DONUP,!0),i=TO(n,this.inputs.Period,W.Low,W.DONLOW,!1);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.DONUP,e),n=this.innVal(2,W.DONLOW,e),r=t===null&&n===null;return this.isWidth?{[W.DONW.id]:r?null:t-n}:{[W.DONMID.id]:r?null:(t+n)/2}}getWrappers(){return[this.wrapInner(W.DONUP,1),this.wrapInner(W.DONLOW,2)]}},jS=class extends AS{constructor(e,t){super(e,!1,t)}},MS=class extends AS{constructor(e,t){super(e,!0,t)}},NS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e),i=this.baseVal(W.Close,e-1),a=this.container.getData(this.target)[e-1];N(a)||(a=0);let o=(n-i)/i*r;t=a+o}return{[this.target.id]:t}}},PS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=PO(i,1,i.target,this.target);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},FS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Z(W.DEMA,(e,t,n)=>2*t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.DEMA,1)]}},IS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period1,this.source),r=Y(t,this.inputs.Period2,this.source),i=Z(W.EOSC,(e,t,n)=>t-n,n,r);this.addInner(i)}getWrappers(){return[this.wrapInner(W.EOSC,1)]}},LS=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,this.source),r=Y(n,this.inputs.Period,n.target),i=Y(r,this.inputs.Period,r.target),a=Z(W.TEMA,(e,t,n,r)=>3*(t-n)+r,n,r,i);this.addInner(a)}getWrappers(){return[this.wrapInner(W.TEMA,1)]}},RS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.baseVal(this.source,e-n);r!==null&&r!==0&&(t=(this.baseVal(this.source,e)-r)/r*100)}return{[this.target.id]:t}}},zS=class extends q{constructor(e,t){super(e,t);let n=NO(t,W.PVPT);this.addInner(n)}calculateAt(e){let t=this.innVal(1,W.PVPT,e),n=this.baseVal(W.High,e),r=this.baseVal(W.Low,e);return{[W.PVPTR.id]:t+n-r,[W.PVPTS.id]:t-n+r}}getWrappers(){return[this.wrapInner(W.PVPT,1)]}},BS=K(`_HIND`),VS=K(`_LIND`),HS=class extends q{justWidth;constructor(e,t,n){super(e,n),this.justWidth=t,this.justWidth=t;let r=this.inputs.Period,i=TO(n,r,W.High,BS,!0,!0),a=TO(n,r,W.Low,VS,!1,!0);this.addInner(i,a)}calculateAt(e){let t=null,n=null,r=null,i=this.innVal(1,BS,e),a=this.innVal(2,VS,e);if(i!==null&&a!==null){let e=this.period;t=(e-i)/e*100,n=(e-a)/e*100,r=t-n}return this.justWidth?{[W.ARNOSC.id]:r}:{[W.ARNUP.id]:t,[W.ARNLOW.id]:n}}},US=class extends HS{constructor(e,t){super(e,!1,t)}},WS=class extends HS{constructor(e,t){super(e,!0,t)}},GS=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Range===`Close`,r=rk(t);if(!n&&r){let e=X(W.TCHNUP,(e,t)=>null,t),n=X(W.TCHNLOW,(e,t)=>null,t);this.addInner(e,n)}else{let r=TO(t,e.inputs.PeriodUpper,n?W.Close:W.High,W.TCHNUP,!0),i=TO(t,e.inputs.PeriodLower,n?W.Close:W.Low,W.TCHNLOW,!1);this.addInner(r,i)}}getWrappers(){return[this.wrapInner(W.TCHNUP,1),this.wrapInner(W.TCHNLOW,2)]}},KS=class extends q{constructor(e,t){super(e,t);let n=BO(t,e.inputs.Period,e.inputs.Range);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.TCHNUP,e),r=this.innVal(1,W.TCHNLOW,e),i=this.inputs.Adjustment,a=this.inputs.Retracement;return a===`Long`?t=N(n)?n-i:null:a===`Short`&&(t=N(r)?r+i:null),{[this.target.id]:t}}},qS=K(`_MIDPOINT`),JS=class extends q{constructor(e,t){super(e,t);let n=X(qS,ce(bS,qS),t),r=xO(n,e.inputs.Period1,qS,W.ALJAW),i=xO(n,e.inputs.Period2,qS,W.ALTEETH),a=xO(n,e.inputs.Period3,qS,W.ALLIPS);this.addInner(r,i,a)}calculateAt(e){return{[W.ALJAW.id]:this.innVal(1,W.ALJAW,e),[W.ALTEETH.id]:this.innVal(2,W.ALTEETH,e),[W.ALLIPS.id]:this.innVal(3,W.ALLIPS,e)}}},YS=class extends q{constructor(e,t){super(e,t)}calculateAt(e){return{[W.PLTLN.id]:this.inputs.Position}}},XS=K(`_MIDPOINT`),ZS=class extends q{constructor(e,t){super(e,t);let n=X(XS,ce(bS,XS),t),r=J(n,this.inputs.Period1,XS),i=J(n,this.inputs.Period2,XS),a=Z(W.AWOS,(e,t,n)=>t-n,r,i),o=J(a,this.inputs.Period3,a.target,W.AWOSMA);this.addInner(a,o)}getWrappers(){return[this.wrapInner(W.AWOS,1),this.wrapInner(W.AWOSMA,2)]}},QS=class extends q{multiplyVol;constructor(e,t,n){super(e,n),this.multiplyVol=t}calculateAt(e){let[t,n,r,i]=[W.High,W.Low,W.Close,W.Volume].map(t=>this.baseVal(t,e)),a=t===n?0:(r-n-(t-r))/(t-n);return this.multiplyVol&&(a*=i),{[this.target.id]:a}}},$S=class extends QS{constructor(e,t){super(e,!1,t)}},eC=class extends QS{constructor(e,t){super(e,!0,t)}},tC=class extends q{constructor(e,t){super(e,t);let n=IO(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Volume),i=this.past(e,n,W.MFMUL,this.innCont(1));if(ge(r)&&ge(i)){let e=me(r);e!==0&&(t=me(i)/e)}}return{[this.target.id]:t}}},nC=K(`_RANGE`),rC=class extends q{constructor(e,t){super(e,t);let n=PO(Y(X(nC,ce(xS,nC),t),this.inputs.Period1,nC),this.inputs.Period2,W.EMA,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},iC=class extends q{shift;constructor(e,t){super(e,t);let n=this.inputs.Period;this.shift=Math.floor(n/2)+1;let r=J(t,n,e.source);this.addInner(r)}calculateAt(e){let t=null,n=this.shift,r=this.innVal(1,W.MA,e-n);return r!==null&&(t=this.baseVal(this.source,e)-r),{[this.target.id]:t}}},aC=K(`_MATP`),oC=class extends q{constructor(e,t){super(e,t);let n=NO(t),r=J(n,this.inputs.Period,n.target,aC);this.addInner(n,r)}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1));if(ge(r)){let n=this.innVal(2,aC,e);if(n!==null){let i=r.reduce((e,t,r)=>e+Math.abs(n-t),0)/this.period;t=(this.innVal(1,W.TP,e)-n)/(.015*i)}}}return{[this.target.id]:t}}},sC=class extends q{constructor(e,t){super(e,t);let n=X(W.EMV,function(e){let t=null;if(e>0){let[n,r,i]=[W.High,W.Low,W.Volume].map(t=>this.baseVal(t,e)),[a,o]=[W.High,W.Low].map(t=>this.baseVal(t,e-1));t=((n+r)/2-(a+o)/2)/(i/1e6/(n-r))}return{[this.target.id]:t}},t),r=J(n,this.inputs.Period,W.EMV,W.EMVMA);this.addInner(n,r)}getWrappers(){return[this.wrapInner(W.EMV,1),this.wrapInner(W.EMVMA,2)]}},cC=class extends q{isBull;constructor(e,t,n){super(e,n),this.isBull=t;let r=Y(n,this.inputs.Period,this.source);this.addInner(r)}calculateAt(e){let t=null,n=this.innVal(1,W.EMA,e);return n!==null&&(t=this.isBull?this.baseVal(W.High,e)-n:this.baseVal(W.Low,e)-n),{[this.isBull?W.ERBLPOW.id:W.ERBRPOW.id]:t}}},lC=class extends cC{constructor(e,t){super(e,!0,t)}},uC=class extends cC{constructor(e,t){super(e,!1,t)}},dC=K(`_FORCE`),fC=class extends q{constructor(e,t){super(e,t);let n=Y(X(dC,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Volume,e);t=(n-this.baseVal(W.Close,e-1))*r}return{[this.target.id]:t}},t),this.inputs.Period,dC,W.FI);this.addInner(n)}getWrappers(){return[this.wrapInner(W.FI,1)]}},pC=K(`_RANGE`),mC=K(`_EMA1`),hC=K(`_EMA2`),gC=K(`_RATIO`),_C=class extends q{constructor(e,t){super(e,t);let n=Y(X(pC,ce(xS,pC),t),9,pC,mC),r=Z(gC,(e,t,n)=>t/n,n,Y(n,9,mC,hC));this.addInner(r)}calculateAt(e){let t=null;if(this.atLeast(e,25)){let n=this.past(e,25,gC,this.innCont(1));ge(n)&&(t=me(n))}return{[this.target.id]:t}}},vC=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=X(W.MOM,le(ZO,n,this.source),t),i=J(r,this.inputs.Movement,W.MOM,W.MOMMA);this.addInner(r,i)}getWrappers(){return[this.wrapInner(W.MOM,1),this.wrapInner(W.MOMMA,2)]}},yC=class extends q{constructor(e,t){super(e,t);let n=NO(t);this.addInner(n)}calculateAt(e){let t=null,n=this.period+1;if(this.atLeast(e,n)){let r=this.past(e,n,W.TP,this.innCont(1)),i=this.past(e,n,W.Volume).map(e=>e??0);if(ge(r)&&ge(i)){let e=0,a=0;for(let t=1;t<n;++t){let n=r[t]*i[t];r[t]>r[t-1]?e+=n:a+=n}t=100-100/(1+e/a)}}return{[this.target.id]:t}}},bC=class extends q{constructor(e,t){super(e,t),JO(this);let n=J(t,this.inputs.Period,this.source);this.addInner(n)}calculateAt(e){let t=null,[n,r]=YO(this),i=this.innVal(n+1,W.MA,e);if(i!==null){let n=this.inputs.Period,a=this.past(e,n,this.source,r);a=a.map(e=>(e-i)*(e-i)),t=Math.sqrt(he(a))}return{[this.target.id]:t}}getWrappers(){let[e]=YO(this);return[this.wrapInner(W.MA,e+1)]}},xC={isNegative:!1,fields:[W.PVI,W.PVIEMA]},SC={isNegative:!0,fields:[W.NVI,W.NVIEMA]},CC=class extends q{kind;constructor(e,t,n){super(e,n),this.kind=t;let r=X(this.kind.fields[0],ce(function(e,t){let n=1e3;if(t>0){let r=[W.Close,W.Volume],[i,a]=r.map(e=>this.baseVal(e,t)),[o,s]=r.map(e=>this.baseVal(e,t-1)),c=this.container.getData(this.target)[t-1];n=(e?a<s:a>s)?c*((i-o)/o+1):c}return{[this.target.id]:n}},this.kind.isNegative),n),i=Y(r,this.inputs.Period,this.kind.fields[0],this.kind.fields[1]);this.addInner(r,i)}getWrappers(){return[this.wrapInner(this.kind.fields[0],1),this.wrapInner(this.kind.fields[1],2)]}},wC=class extends CC{constructor(e,t){super(e,SC,t)}},TC=class extends CC{constructor(e,t){super(e,xC,t)}},EC=K(`_PRICE_CHANGE`),DC=class extends q{constructor(e,t){super(e,t);let n=this.source??W.Close,r=Math.sqrt(nk(e.aggregation)),i=e.inputs.Calculation===`Absolute`;if(r===0){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let a=function(e,t){let n=null;if(t>0){let r=this.baseVal(e,t),a=this.baseVal(e,t-1);r!==null&&a!==null&&(n=i?r-a:Math.log(r/a))}return{[EC.id]:n}},o=function(e,t){let n=null,r=this.baseVal(W.MSD,t);return r!==null&&(n=(i?1:100)*r*e),{[W.HV.id]:n}},s=LO(X(EC,ce(a,n),t),e.inputs.Period,EC,W.MSD),c=X(W.HV,ce(o,r),s);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},OC=class extends q{noOp;constructor(e,t){super(e,t);let n=this.inputs.Anchor===`VisibleStart`;this.noOp=n}calculateAt(e){let t=null,n=this.baseVal(this.source,0),r=this.baseVal(this.source,e);return this.noOp?t=r:n!==null&&r!==null&&(t=(r-n)/n*100),{[this.target.id]:t}}},kC=K(`_SWING_INDEX`),AC=class extends q{constructor(e,t){super(e,t)}get helpers(){return[kC]}ohlcVals(e){return[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}obtainR(e,t,n,r){let i=Math.abs(e-r),a=Math.abs(t-r),o=Math.abs(e-t),s=Math.max(i,a,o),c=.25*Math.abs(r-n);return s===i?i-.5*a+c:s===a?a-.5*i+c:o+c}calculateAt(e){let t=null,n=null;if(e>0){let r=this.container.getData(kC)[e-1];N(r)||(r=0);let[i,a,o,s]=this.ohlcVals(e),[c,l,u,d]=this.ohlcVals(e-1);if(ge([i,a,o,s,c,d])){let e=Math.max(Math.abs(a-d),Math.abs(o-d)),l=this.inputs.Limit,u=this.obtainR(a,o,c,d);t=50*((s-d+.5*(s-i)+.25*(d-c))/u)*(e/l),n=r+t}}return{[kC.id]:t,[this.target.id]:n}}},jC=K(`_MIN_CLOSE`),MC=K(`_MAX_CLOSE`),NC=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[MC,jC]}calculateAt(e){let t=null,n=null,r=null,i=null,a=this.innVal(1,W.ATR,e);if(a!==null){let o=this.baseVal(W.Close,e),s=this.baseVal(W.Close,e-1),c=this.period;r=Math.max(...this.past(e,c,W.Close)),i=Math.min(...this.past(e,c,W.Close));let l=a*this.inputs.Constant;if(this.innVal(1,W.ATR,e-1)===null)o>s?t=r-l:n=i+l;else{let[a,s,c,u]=[W.WWVSARU,W.WWVSARD,MC,jC].map(t=>this.container.getData(t)[e-1]);r=c,i=u,a===null?o>s?(r=o,t=o-l):(i=Math.min(o,i),n=i+l):o<a?(i=o,n=o+l):(r=Math.max(o,r),t=r-l)}}return{[MC.id]:r,[jC.id]:i,[W.WWVSARU.id]:t,[W.WWVSARD.id]:n}}},PC=K(`_EP`),FC=K(`_AF`),IC=K(`_POS`),LC=1,RC=-1,zC=class extends q{constructor(e,t){super(e,t)}get helpers(){return[PC,FC,IC]}hlcVals(e){return[W.High,W.Low,W.Close].map(t=>this.baseVal(t,e))}me(e,t){return this.container.getData(e)[t]}reciprocal(e){return 1/e}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(e>0){let[s,c,l]=this.hlcVals(e),[u,d,f]=this.hlcVals(e-1),p=this.reciprocal(this.inputs.Acceleration),m=this.reciprocal(this.inputs.Limit);if(e===1){a=l>f?LC:RC;let e=a===LC;o=e?d:u,r=e?Math.max(s,u):Math.min(c,d),i=p,e?t=o:n=o}else{let[l,f,h,g,_]=[IC,W.PARSARS,W.PARSARL,PC,FC].map(t=>this.me(t,e-1)),v=l===LC,y=v?h:f,b=_*Math.abs(g-y);a=v?y+b>c?RC:LC:y-b<s?LC:RC;let x=l===a;o=x?v?Math.min(y+b,d,this.baseVal(W.Low,e-2)):Math.max(y-b,u,this.baseVal(W.High,e-2)):g,r=x?v?Math.max(s,g):Math.min(c,g):a===LC?s:c,i=_,x?(v?r>g:r<g)&&_<m&&(i=_+p):i=p,a===LC?t=o:n=o}}return{[PC.id]:r,[FC.id]:i,[IC.id]:a,[W.PARSARS.id]:n,[W.PARSARL.id]:t}}},BC=class extends q{xSum;xSum2;x2Sum;constructor(e,t){super(e,t);let n=this.period;this.xSum=n*(n+1)/2,this.xSum2=this.xSum*this.xSum,this.x2Sum=n*(n+1)*(2*n+1)/6}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,this.source);if(ge(r)){let e=me(r),i=(n*me(r.map((e,t)=>e*(t+1)))-this.xSum*e)/(n*this.x2Sum-this.xSum2);t=(e-i*this.xSum)/n+i*n}}return{[this.target.id]:t}}},VC=K(`_IDY`),HC=[0,0,0,1,1,1,5,5,2,1,1,0,50,50,0,1,1,1,5,0,0],UC=e=>Array(e).fill(0);function WC(e,t){return YC(e,t,10)}function GC(e,t){return YC(e,t,13)}function KC(e,t){return YC(e,t,16)}function qC(e,t){return YC(e,t,4)}function JC(e,t){return YC(e,t,7)}function YC(e,t,n){let r=e[n-1];return t===0&&(r=e[n]),t<0&&(r=e[n+1]),r}function XC(e,t,n,r,i){let a=i[18],o=r+1,s=0;for(let n=0;n<a;++n){let n=0,r=0;for(let i=1;i<6;++i){if(o--,e[o]==null)continue;let a=e[o]-t[o];i==1&&(n=r=a),a>n&&(n=a),a<r&&(r=a)}s=s+n-r}return s=s/a*qC(i,n[r]),s}function ZC(e,t,n,r,i){let a=r,o=JC(i,n[r]),s=0;do a--,e[a]!=null&&s++;while(s<o&&a>0);return t[r]-t[a]}function QC(e,t,n,r,i,a){let o=n;do o--;while(e[o]==null);return t[n]=t[o],e[n]>i&&t[o]<=0&&(t[n]=t[o]+1),e[n]<r&&t[o]>=0&&(t[n]=t[o]-1),a++,t[n]!==t[o]&&(a=1),a}function $C(e,t,n,r,i,a,o,s,c,l){let u=WC(i,n[r]),d=GC(i,n[r]),f=KC(i,n[r]),p=c+l+t[r]-e[r],m=100;i[20]>0&&(m=i[20]);let h=u*s/m;s>d&&(h=u*d/m);let g=l*2,_=e[r]+(p-g)-(p-g)*h,v=e[r]+(p-p*h),y=[a,o];return(s===1||f!==1||_>a)&&(y[0]=_),(s===1||f!==1||v<o)&&(y[1]=v),y}function ew(e,t,n){let r=0,i=-1,a=0,o=1;for(let s=0;s<n;++s){if(t[s]=0,e[s]==null||(r++,r==21&&(o=2),r==31&&(o=3),a+=e[s]*o,r<40))continue;t[s]=a/70;let c=0,l=i+1;for(let t=l;t<n&&!(e[t]!=null&&(c++,c==1&&(i=t),(c==1||c==21||c==31)&&(a-=e[t]),c==31));++t);}}var tw=class extends q{haveEnoughData=!1;firstUsefulIndex=0;s3;itr;constructor(e,t){super(e,t),this.s3=this.itr=[];let n=[`VelocityUpTrend`,`VelocitySideTrend`,`VelocityDownTrend`].map(t=>e.inputs[t]||`3`).map(Number);HC.splice(6,3,...n)}get helpers(){return[VC]}prepareComputation(){let e=this.base.getData(W.Close),t=0,n=0,r=e.length;for(;n<72&&t<r;)e[t]!=null&&n++,t++;this.haveEnoughData=t<r,this.firstUsefulIndex=t,this.s3=UC(r),this.itr=UC(r),this.haveEnoughData&&ew(e,this.s3,r)}us(e,t){return this.container.getData(e)[t]}recalculateAt(e,t,n){let r=this.base.getData(W.Close),i=r.length;this.haveEnoughData&&ew(r,this.s3,i),super.recalculateAt(e,t,n)}calculateAt(e){let t=null,n=null,r=null,i=t=>this.us(t,e-1);if(e===0)this.prepareComputation();else if(this.haveEnoughData&&e>=this.firstUsefulIndex&&this.baseVal(W.Close,e)!==null){let a=i(W.TRSP1),o=i(W.TRSP2);r=i(VC),a===null&&o===null&&(a=o=this.baseVal(W.Close,this.firstUsefulIndex)),r===null&&(r=1);let s=this.base.getData(W.Close);r=QC(s,this.itr,e,a,o,r);let c=ZC(s,this.s3,this.itr,e,HC),l=XC(s,this.s3,this.itr,e,HC);[a,o]=$C(s,this.s3,this.itr,e,HC,a,o,r,c,l),this.itr[e]>=0&&(t=a),this.itr[e]<=0&&(n=o)}return{[VC.id]:r,[W.TRSP1.id]:t,[W.TRSP2.id]:n}}},nw=class extends q{constructor(e,t){super(e,t),this.addInner(NO(t))}get helpers(){return[W.BARCOLIX]}getTarget(e){let t=this.baseVal(W.Close,e),n=this.innVal(1,W.TP,e);if(!N(t,n)||!this.atLeast(e,4))return null;let r=this.innVal(1,W.TP,e-3);return r===null?null:t+(n-r)/3}calculateAt(e){let t=null,n=this.getTarget(e);if(n!==null&&e>0){let r=this.container.getData(W.TARGP)?.[e-1];r!==null&&(t=n===r?this.container.getData(W.BARCOLIX)?.[e-1]??1:+(n>r))}return{[W.TARGP.id]:n,[W.BARCOLIX.id]:t}}},rw=1,iw=2,aw=3,ow={[rw]:{param:`cot`,func:`parseCotLineChart`,fields:[W.DateTime,W.COTLCCMSP,W.COTLCLGSP,W.COTLCSMSP]},[iw]:{param:`cotadv`,func:`parseDisaggregated`,fields:[W.DateTime,W.COTDAGPRO,W.COTDAGSPD,W.COTDAGMNM,W.COTDAGOTH]},[aw]:{param:`cotfin`,func:`parseFinancialTradersReport`,fields:[W.DateTime,W.COTFTRDLI,W.COTFTRASM,W.COTFTRLVF,W.COTFTROTH]}},sw=class extends q{wrappers;constructor(e,t,n){super(e,Ub(n,e=>new cw(t,e))),this.computedServerSide=!0,this.initialNotification=!0,this.wrappers=ow[t].fields.slice(1).map(e=>this.wrapInner(e,0))}getWrappers(){return this.wrappers}},cw=class extends Q_{kind;constructor(e,t){super(t),this.kind=e}getRetriever(){return new lw(this.kind)}onStreamingUpdates(e){}},lw=class extends C_{kind;constructor(e){super(),this.kind=e}addExtraParams(e){e[ow[this.kind].param]=`y`}getParser(e){return new uw(e.symbol,e.aggregation,e.offset,this.kind)}},uw=class extends v_{kind;constructor(e,t,n,r){super(e,t,n),this.kind=r}makeContainer(){return new e_(ow[this.kind].fields)}getParseFunc(){return this.aggregation.isEndOfDay?this[ow[this.kind].func]:null}parseCotLineChart(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTLCCMSP,parseInt(e[2])),this.container.addDataPoint(W.COTLCLGSP,parseInt(e[3])),this.container.addDataPoint(W.COTLCSMSP,parseInt(e[4]))}parseDisaggregated(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTDAGPRO,parseInt(e[2])),this.container.addDataPoint(W.COTDAGSPD,parseInt(e[3])),this.container.addDataPoint(W.COTDAGMNM,parseInt(e[4])),this.container.addDataPoint(W.COTDAGOTH,parseInt(e[5]))}parseFinancialTradersReport(e){this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.COTFTRDLI,parseInt(e[2])),this.container.addDataPoint(W.COTFTRASM,parseInt(e[3])),this.container.addDataPoint(W.COTFTRLVF,parseInt(e[4])),this.container.addDataPoint(W.COTFTROTH,parseInt(e[5]))}},dw=class extends sw{constructor(e,t){super(e,rw,t)}},fw=class extends sw{constructor(e,t){super(e,iw,t)}},pw=class extends sw{constructor(e,t){super(e,aw,t)}},mw=[`Day`,`Week`,`Month`,`Year`];function hw(e){return mw.some(t=>t===e)}function gw(e,t){if(hw(e))return e;switch(t?.unit){case g.Tick:return`Day`;case g.Intraday:return t.size<=15?`Day`:`Week`;case g.Day:return`Month`;default:return`Year`}}function _w(e,t){switch(t){case`Day`:return Sn(e);case`Week`:return bn(e,{weekStartsOn:1});case`Month`:return ir(e);case`Year`:return or(e)}}var vw={Day:[W.PreviousHigh,W.PreviousLow,W.PreviousClose],Week:[W.WeekPreviousHigh,W.WeekPreviousLow,W.WeekPreviousClose],Month:[W.MonthPreviousHigh,W.MonthPreviousLow,W.MonthPreviousClose]};function yw(e){return e.length===3&&e.every(e=>typeof e==`number`&&Number.isFinite(e))}var bw=class extends q{disabled;record;streamingSubscription;constructor(e,t,n){if(super(e,n),this.disabled=!t||!N(n.query)||!N(n.query.symbol),!this.disabled){let e=n.query.symbol;e.endsWith(`.BZ`)&&(e=e.slice(0,-3)),this.record=$().getRecordSource().getRecord(e),this.record.addFields(...t),this.streamingSubscription=this.getStreamingSubscription()}this.initialNotification=!0}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>{let t=zp(G.RT_QUOTE,this.record.symbol);return e.filter(t)}),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}async ready(){return ma.call(this,async()=>N(this.record)?await this.record.ready()&&await super.ready():await super.ready(),`asyncReadyWork2`)}onStreamingUpdates(e){if(this.record){let e={tag:xt(),src:null};this.calculate(e)}}shutdown(){super.shutdown(),this.disabled||this.streamingSubscription.unsubscribe()}getValues(e){return vw[e].map(e=>this.record.getValue(e))}},xw=class extends bw{referencePeriod;dynamic;periods=[];constructor(e,t){super(e,e.inputs.Dynamic===`No`?vw[e.inputs.Previous]:void 0,t),this.referencePeriod=gw(e.inputs.Previous,e.aggregation??t.query?.aggregation),this.dynamic=e.inputs.Dynamic!==`No`,this.dynamic&&this.addInner(Ub(t,e=>{let t=new Fb(e.symbol,e.aggregation);return t.aggregation.unit=g[this.referencePeriod],t.aggregation.size=1,t.aggregation.isMultiContract||(t.aggregation.spec=_.None),t.useLastTrade=e.useLastTrade,t.splits=e.splits??!0,t.offset=e.offset,new Q_(t)}))}getPeriods(){return this.base?.size?this.periods:[]}hasHistoryFor(e){if(!this.dynamic)return!0;let t=this.innCont(1)?.getTimeData()[0];return t!==void 0&&+_w(t,this.referencePeriod)<e}loadMoreData(){let e=this.innerSeries[1];return e?.canLoadMoreData&&!e.isLoading?e.loadMoreData():Promise.resolve()}recalculateAt(e,t,n){n&&this.calculate(e)}shutdown(){super.shutdown(),this.innerSeries[1]?.shutdown()}historicalValues(e){let t=this.innCont(1),n=t.getTimeData();if(!n.length)return[];let r=e=>+_w(e,this.referencePeriod),i=A(n,e,r);return r(n[i])>=e&&i--,i<0?[]:[W.High,W.Low,W.Close].map(e=>t.getData(e)?.[i]??null)}calculateAt(e){let t=(t,n=e)=>({key:t,startIndex:e,endIndex:n,levels:this.calculateLevels(t)});if(e===0&&(this.periods=[]),!this.dynamic)return e===0&&this.periods.push(t(0,this.base.size-1)),{};let n=+_w(this.base.getTimeData()[e],this.referencePeriod),r=this.periods.at(-1);return r?.key===n?r.endIndex=e:this.periods.push(t(n)),{}}calculateLevels(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null;if(this.dynamic||!this.disabled){let c=this.dynamic?this.historicalValues(e):this.getValues(this.inputs.Previous);if(yw(c)){let[e,l,u]=c;t=(e+l+u)/3;let d=2*t;n=d-l,r=d-e;let f=e-l;i=t+f,a=t-f,o=e+2*(t-l),s=l-2*(e-t)}}return{[W.PPTPIV.id]:t,[W.PPTR1.id]:n,[W.PPTR2.id]:i,[W.PPTR3.id]:o,[W.PPTS1.id]:r,[W.PPTS2.id]:a,[W.PPTS3.id]:s}}},Sw=class extends bw{constructor(e,t){super(e,vw.Day,t)}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=null,c=null;if(!this.disabled){let e=this.getValues(`Day`);if(ge(e)){let[l,u,d]=e,f=l-u,[p,m,h,g]=[2,4,6,12].map(e=>1.1/e*f);s=d+p,a=d+m,r=d+h,t=d+g,n=d-g,i=d-h,o=d-m,c=d-p}}return{[W.CPPH4.id]:s,[W.CPPH3.id]:a,[W.CPPH2.id]:r,[W.CPPH1.id]:t,[W.CPPL1.id]:n,[W.CPPL2.id]:i,[W.CPPL3.id]:o,[W.CPPL4.id]:c}}},Cw=class extends q{constructor(e,t){super(e,Wb(t,W.IMPVOL,e=>new ww(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.IMPVOL,0)]}},ww=class extends Q_{constructor(e){super(e)}getRetriever(){return Oi(this.query.symbol)?new Ow:new Tw}onStreamingUpdates(e){}},Tw=class extends C_{addExtraParams(e){e.impl=`y`}getParser(e){return new Dw(e.symbol,e.aggregation,e.offset)}};function Ew(){return new e_([W.DateTime,W.IMPVOL])}var Dw=class extends v_{constructor(e,t,n=0){super(e,t,n)}makeContainer(){return Ew()}getParseFunc(){return this.parseImpVol}parseImpVol(e){!this.aggregation.isEndOfDay||e.length<9||(this.container.addDataPoint(W.DateTime,this.parseDate(e[1])),this.container.addDataPoint(W.IMPVOL,parseFloat(e[8])))}},Ow=class extends T_{emptyContainer(e,t){return Ew()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date.substring(0,10)));let r=M(e.impliedVolatility);n.addDataPoint(W.IMPVOL,r?e.impliedVolatility*100:null)}},kw=K(`_ABS_CHG`),Aw=K(`_DS1_EMA1`),jw=K(`_DS1_EMA2`),Mw=K(`_DS2_EMA1`),Nw=K(`_DS2_EMA2`),Pw=class extends q{constructor(e,t){super(e,t);let n=(e,t,n,r,i,a)=>Y(Y(e,t,n,r),i,r,a),r=X(kw,ce((e,t)=>({[e.id]:Math.abs(this.baseVal(W.Change,t))}),kw),t),i=n(t,e.inputs.Period1,W.Change,Aw,e.inputs.Period2,jw),a=n(r,e.inputs.Period1,kw,Mw,e.inputs.Period2,Nw),o=Z(W.TSI,(e,t,n)=>100*t/n,i,a),s=Y(o,e.inputs.Period3,W.TSI,W.TSISIG);this.addInner(o,s)}getWrappers(){return[this.wrapInner(W.TSI,1),this.wrapInner(W.TSISIG,2)]}},Fw=class extends q{constructor(e,t){super(e,t);for(let n=1;n<=12;++n){let r=ik(e.inputs,n);this.addInner(Y(t,r,W.Close,e.outFields[n-1]))}}getWrappers(){return _e(1,12).map(e=>this.wrapInner(this.outFields[e-1],e))}},Iw=class extends q{constructor(e,t){super(e,t);let n=Y(t,this.inputs.Period,W.Close);this.addInner(n)}calculateAt(e){let t=null,n=e>0?this.container.getData(this.target)[e-1]:null,r=this.innVal(1,W.EMA,e);if(!M(n))t=r;else{let i=this.baseVal(this.source,e),a=(i/n)**4;t=n+(i-n)/(.6*this.period*a);let o=e=>Math.log10(Math.abs(e-t))>1,s=o(n)||o(r);(!Number.isFinite(t)||s)&&(t=null)}return{[this.target.id]:t}}},Lw=K(`_DIFF`),Rw=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=Math.floor(n/2),i=this.allowEmptyValues,a=SO(Z(Lw,(e,t,n)=>2*t-n,SO(t,r,this.source,W.WMA,i),SO(t,n,this.source,W.WMA,i)),Math.floor(Math.sqrt(n)),Lw,this.target,i);this.addInner(a)}getWrappers(){return[this.wrapInner(this.target,1)]}},zw=K(`_SUM`),Bw=class extends q{constructor(e,t){super(e,t);let n=SO(Z(zw,(e,t,n)=>t+n,PO(t,this.inputs.PeriodRocLong),PO(t,this.inputs.PeriodRocShort)),this.inputs.PeriodWma,zw,this.target);this.addInner(n)}getWrappers(){return[this.wrapInner(this.target,1)]}},Vw=K(`_ABS_CHG`),Hw=K(`_HH_LL`),Uw=K(`_MULMA`),Ww=class extends q{constructor(e,t){super(e,t);let n=e.inputs.TurtleChnField===`Close`,r=e.inputs.Direction===`Long`,i=rk(t);if(!n&&i){let e=X(this.target,(e,t)=>null,t);this.addInner(e)}else{let e=J(X(Vw,ce((e,t)=>({[Vw.id]:t>0?e*Math.abs(this.baseVal(W.Change,t)):null}),this.inputs.FactorATR),t),this.inputs.PeriodAdjATR,Vw,W.MA),i=r?W.High:W.Low,a=TO(t,this.inputs.PeriodTurtleChn,n?W.Close:i,Hw,r),o=Z(Uw,(e,t)=>this.inputs.FactorAdjATR*t,e),s=r?-1:1,c=Z(this.target,(e,t,n)=>t+s*n,a,o);this.addInner(c)}}getWrappers(){return[this.wrapInner(this.target,1)]}},Gw=class extends q{state;constructor(e,t){super(e,t),this.resetState()}resetState(){let e=this.inputs.ExtendLines??`None`;this.state={startIndex:null,endIndex:null,slope:null,intercept:null,stdDevWidth:null,extendLeft:e===`Left`||e===`Both`,extendRight:e===`Right`||e===`Both`}}calculateAt(e){let t=this.inputs.Period,n=this.inputs.Width,r=this.source;if(e===this.base.size-1&&this.base.size>=t){this.resetState();let e=t*(t+1)/2,i=e*e,a=t*(t+1)*(2*t+1)/6,o=0,s=0,c=1,l=this.base.size-t;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Qe(t))return{};o+=t,s+=c*t,c+=1}let u=(t*s-e*o)/(t*a-i),d=o/t-u*e/t;if(!Qe(u)||!Qe(d))return{};let f=0;for(let e=0;e<t;++e){let t=this.baseVal(r,l+e);if(!Qe(t))return{};let n=t-(d+u*(e+1));f+=n*n}let p=Math.sqrt(f/t);if(!Qe(p))return{};this.state.startIndex=l,this.state.endIndex=this.base.size-1,this.state.slope=u,this.state.intercept=d,this.state.stdDevWidth=n*p}return{}}getCurrentState(){return this.state}},Kw=class extends q{computeDone;constructor(e,t){super(e,t,Ub(t,e=>{let t=P(e);return t.symbol=Fi(e.symbol),N(t.symbol)?new Q_(t):new ev(t,!0)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignCashTimelineWithUnderlying(){let e=this.innCont(0);if(!N(e)||e.size===0)return;let t=this.innCont(1),n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.Close),a=Array(n.length).fill(null);if(!(this.innerSeries[1]instanceof ev)){let o=0,s=e.size,c=t.size;for(let e=0;e<s;++e){for(;o<c&&r[o].getTime()<n[e].getTime();)o++;o<c&&r[o].getTime()===n[e].getTime()&&(a[e]=i[o])}}this.container.setData(this.target,a)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignCashTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},qw=class extends q{constructor(e,t){let n=zO(t);super(e,t,n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e===this.innerSeries[1]&&this.innHasData(0)&&this.innHasData(1)}calculateAt(e){let t=(t,n)=>N(this.innCont(t))?this.innVal(t,n,e):null,n=t(0,W.Close),r=t(1,W.CSHO);return{[this.target.id]:N(r)&&N(n)?r-n:null}}},Jw=class extends q{computeDone;constructor(e,t){super(e,t,Ub(t,e=>{let t=new Fb(e.symbol,new yd(e.aggregation.unit===g.Year?g.Year:g.Quarter,1),C.BalanceSheet);return t.fields=[W.SharesOutstanding],t.cacheMe=!0,new rv(t)})),this.computedServerSide=!0,this.initialNotification=!0,this.computeDone=!1}alignFundamentalTimelineWithUnderlying(){let e=this.innCont(0);if(!N(e)||e.size===0)return;let t=this.innCont(1);if(!N(t)||t.size===0)return;let n=e.getTimeData(),r=t.getTimeData(),i=t.getData(W.SharesOutstanding),a=e.getData(W.Close),o=Array(n.length),s=0,c=e.size,l=t.size;for(let e=0;e<c;++e){let t=n[e].getTime();for(;s<l-1&&r[s+1].getTime()<=t;)s++;if(s<l&&r[s].getTime()<=t){let t=i[s],n=a[e];o[e]=N(t,n)?t*n:null}}this.container.setData(this.target,o)}calculate(e){this.computeDone||(this.container=this.makeContainer(),this.alignFundamentalTimelineWithUnderlying(),this.computeDone=!0,this.notify(G.TS_MANYCHANGED,-1))}},Yw=class extends q{constructor(e,t){super(e,t),JO(this)}calculateAt(e){let t=null,[n]=YO(this);if(e>0){let r=this.innVal(n,this.source,e-1);r!==null&&(t=100*(this.innVal(n,this.source,e)-r)/r)}return{[this.target.id]:t}}},Xw=class extends Gb{constructor(e,t){super(e,t),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=[null,null,null,null,null];if(e>0){let n=(e,t)=>this.baseVal(e,t),r=[W.Open,W.High,W.Low,W.Close],i=r.map(t=>n(t,e));if(ge(i)){let a=r.map(t=>n(t,e-1));if(ge(a)){t=i.map((e,t)=>100*(e-a[t])/a[t]);let[n,r]=De(t);if(t[1]=r,t[2]=n,e>1){let n=this.container.getData(W.Close)[e-1];t[4]=t[3]-n}}}}return{[W.Open.id]:t[0],[W.High.id]:t[1],[W.Low.id]:t[2],[W.Close.id]:t[3],[W.Change.id]:t[4]}}getWrappers(){return this.wrapBaseFields(W.Volume,W.OpenInterest,W.TradingDay)}},Zw=K(`_DIST`),Qw=K(`_EMA_DIST1`),$w=K(`_EMA_DIST2`),eT=K(`_DIFF`),tT=K(`_EMA_DIFF1`),nT=K(`_EMA_DIFF2`),rT=class extends q{constructor(e,t){super(e,t);let n=TO(t,e.inputs.Period1,W.High,W.HH,!0),r=TO(t,e.inputs.Period1,W.Low,W.LL,!1),i=Y(Y(Z(Zw,(e,t,n)=>this.baseVal(W.Close,e)-(t+n)/2,n,r),e.inputs.Period2,Zw,Qw),e.inputs.Period2,Qw,$w),a=Y(Y(Z(eT,(e,t,n)=>t-n,n,r),e.inputs.Period2,eT,tT),e.inputs.Period2,tT,nT),o=Z(W.STOMOMIX,(e,t,n)=>100*t/n,i,a);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},iT=K(`_CHG`),aT=K(`_M1`),oT=K(`_M2`),sT=class extends q{constructor(e,t){super(e,t);let n=X(iT,function(e){let t=W.Close,n=e>0?this.baseVal(t,e)-this.baseVal(t,e-1):0;return{[iT.id]:n}},t),r=(e,t)=>t>=0?t:0,i=(e,t)=>t>=0?0:-t,a=Z(aT,r,n),o=Z(oT,i,n);this.addInner(a,o)}perc(e,t){return 100*e/t}calculateAt(e){let t=null,n=this.period;if(this.atLeast(e,n+1)){let r=this.past(e,n,aT,this.innCont(1)),i=this.past(e,n,oT,this.innCont(2));if(ge(r)&&ge(i)){let e=me(r),n=me(i);t=this.perc(e-n,e+n)}}return{[W.CHDMOMOSC.id]:t}}},cT=class extends q{constructor(e,t){super(e,t);let n=new sT(e,t),r=$O(e,`MA`,`Average`),i=this.inputs.PeriodAvg,a=r(n,i,W.CHDMOMOSC,W.CHDMOMOSCAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.CHDMOMOSC,1),this.wrapInner(W.CHDMOMOSCAVG,2)]}},lT=K(`_MAX`),uT=K(`_MIN`),dT=K(`_ISUPTREND`),fT=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[lT,uT,dT]}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null,s=1,c=this.baseVal(W.Close,e),l=(e,t)=>N(e)?e:t,u=e=>l(e,0),d=(e,t)=>this.container.getData(e)[t];e>0&&(r=Math.max(u(d(lT,e-1)),c),a=Math.min(u(d(uT,e-1)),c),s=d(dT,e-1));let f=this.inputs.Multiplier,p=this.innVal(1,W.ATR,e);if(N(p)){let l=s===1,u=l?r-f*p:a+f*p,m=d(l?W.VSTOPUP:W.VSTOPLOW,e-1);N(m)||(m=0);let h=l?Math.max(m,u):Math.min(m,u);o=+(c-h>=0);let g=o!=s;n=g?c:r,i=g?c:a,t=g?o===1?n-f*p:i+f*p:h}return{[W.VSTOPUP.id]:o===1?t:null,[W.VSTOPLOW.id]:o===1?null:t,[lT.id]:n,[uT.id]:i,[dT.id]:o}}},pT=K(`_TRENDUP`),mT=K(`_TRENDDOWN`),hT=K(`_TREND`),gT=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period);this.addInner(n)}get helpers(){return[pT,mT,hT,W.BARCOLIX]}calculateAt(e){let t=0,n=0,r=0,i=null,a=0,o=this.innVal(1,W.ATR,e);if(N(o)){let s=(e,t)=>N(e)?e:t,[c,l,u]=[W.Close,W.High,W.Low].map(t=>this.baseVal(t,e)),d=(l+u)/2,f=this.baseVal(W.Close,e-1),p=this.inputs.Multiplier,m=d-p*o,h=d+p*o,[g,_,v]=[pT,mT,hT].map(t=>this.container.getData(t)[e-1]);t=f>g?Math.max(m,g):m,n=f<_?Math.min(h,_):h,r=c>_?1:c<g?-1:s(v,1);let y=r===1;i=y?t:n,a=+!!y}return{[pT.id]:t,[mT.id]:n,[hT.id]:r,[W.SUPTR.id]:i,[W.BARCOLIX.id]:a}}},_T=class extends q{constructor(e,t){super(e,t);let n=e=>TO(t,e,W.Low,W.LL,!1),r=e=>TO(t,e,W.High,W.HH,!0),i=(e,t,n)=>Z(n,(e,t,n)=>(t+n)/2,e,t),a=(e,t)=>i(n(e),r(e),t),o=a(e.inputs.PeriodConversionLine,W.CONVLN),s=a(e.inputs.PeriodBaseLine,W.BASELN),c=i(o,s,W.LEADSP1),l=a(e.inputs.PeriodLaggingSpan2,W.LEADSP2);this.addInner(o,s,c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(3,W.LEADSP1,e)>this.innVal(4,W.LEADSP2,e));return{[W.LAGGSP.id]:this.baseVal(W.Close,e),[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.CONVLN,1),this.wrapInner(W.BASELN,2),this.wrapInner(W.LEADSP1,3),this.wrapInner(W.LEADSP2,4)]}},vT=K(`_CUM_PRICE`),yT=K(`_CUM_VOL`),bT=K(`_PER_CHG`),xT=e=>e===void 0||e===`Date`;function ST(e){return typeof e==`number`&&Number.isFinite(e)&&e>0}function CT(e){switch(e){case g.Tick:case g.Intraday:return`Session`;case g.Day:return`Week`;case g.Week:return`Month`;case g.Month:return`Quarter`;default:return`Year`}}var wT=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,ce(XO,n),t);this.addInner(r)}get helpers(){return[vT,yT,bT]}get vwapField(){return W.VWAP}get hasBands(){return!0}get anchorPeriod(){return this.inputs.AnchorPeriod}valueAt(e,t){return this.container.getData(e)[t]}dateAt(e){return this.container.getTimeData()[e]}isSame(e,t){switch(this.anchorPeriod){case`Session`:default:return Ln(e,t);case`Week`:return pi(e,t);case`Month`:return hi(e,t);case`Quarter`:return gi(e,t);case`Year`:return _i(e,t);case`Decade`:return Ug(e,t);case`Century`:return Wg(e,t)}}startsPeriod(e){if(e===0)return!0;if(this.anchorPeriod===`Session`&&this.aggregation&&!this.aggregation.isEndOfDay){let t=this.base.getData(W.TradingDay),n=t?.[e-1],r=t?.[e];if(ST(n)&&ST(r))return n!==r}return!this.isSame(this.dateAt(e-1),this.dateAt(e))}findPrevPeriodChange(e){for(let t=e;t>0;t--)if(this.valueAt(bT,t)===1)return t;return 0}calculateAt(e){let t=!this.startsPeriod(e),n=t?this.valueAt(vT,e-1):0,r=t?this.valueAt(yT,e-1):0,i=this.innVal(0,W.Volume,e),a=n+this.innVal(1,this.source,e)*i,o=r+i,s=a/o;return{[vT.id]:a,[yT.id]:o,[bT.id]:+!t,[this.vwapField.id]:s,...this.hasBands?this.bandsAt(e,s,t):{}}}bandsAt(e,t,n){let r=t,i=t,a=t,o=t;if(n){let n=this.findPrevPeriodChange(e-1),s=this.container.getData(this.vwapField).slice(n,e);s.push(t);let c=he(s),l=s.map(e=>(e-c)*(e-c)),u=Math.sqrt(he(l)),d=this.inputs.Stdev1stMultiplier*u;r=t+d,i=t-d;let f=this.inputs.Stdev2ndMultiplier*u;a=t+f,o=t-f}return{[W.VWAPSD1U.id]:r,[W.VWAPSD1L.id]:i,[W.VWAPSD2U.id]:a,[W.VWAPSD2L.id]:o}}};function TT(e){let t=xT(e.find(e=>e.name===`AnchorPeriod`)?.value);return e.filter(e=>t||e.name!==`Anchor`).map(e=>e.name===`Anchor`?new Date(e.value).toLocaleString():e.value)}var ET=class extends wT{periodStart=0;constructor(e,t){super(e,t)}get vwapField(){return W.AVWAP}get hasBands(){return!1}get anchorPeriod(){let e=super.anchorPeriod;return e===`Auto`?CT(this.aggregation.unit):e}isSameOhlcBar(e,t){let{unit:n,size:r}=this.aggregation;switch(n){case g.Tick:return+e===t;case g.Intraday:return li(t,En(e,r));case g.Day:return li(t,mn(e,r));case g.Week:return pi(e,t);case g.Month:return hi(e,t);case g.Quarter:return gi(e,t);case g.Year:return _i(e,t);default:throw Error(`Unexpected aggregation unit ${g[n]}`)}}findPeriodStart(){let e=this.base.size;if(xT(this.inputs.AnchorPeriod)){let t=this.inputs.Anchor,n=this.base.getTimeData().findIndex(e=>li(t,e)||this.isSameOhlcBar(e,t));return n===-1?e:n}let t=e-1;for(;t>0&&!super.startsPeriod(t);)t--;return Math.max(t,0)}startsPeriod(e){return e===this.periodStart}recalculateAt(e,t,n){n?this.calculate(e):super.recalculateAt(e,t,n)}calculateAt(e){return e===0&&(this.periodStart=this.findPeriodStart()),e>=this.periodStart?super.calculateAt(e):{[vT.id]:null,[yT.id]:null,[bT.id]:null,[W.AVWAP.id]:null}}},DT=K(`_DIFF`),OT=[DT,W.BARCOLIX],kT=[...OT,W.Buy,W.Sell];function AT(e){return e.ShowSignals!==`No`}function jT(e,t,n,r,i){let a=null,o=null,s=null,c=null;N(n,r)&&(s=n-r);let l=t>0?e.getData(DT)[t-1]:null,u=t>0?e.getData(W.BARCOLIX)[t-1]:null;i&&N(s,l)&&(a=s>0&&l<=0?1:null,o=s<0&&l>=0?-1:null),N(s)&&(c=s>0?1:s<0?0:u);let d={[DT.id]:s,[W.BARCOLIX.id]:c};return i&&(d[W.Buy.id]=a,d[W.Sell.id]=o),d}var MT=class extends q{_showSignals;constructor(e,t){super(e,t),this._showSignals=AT(e.inputs)}get helpers(){return this._showSignals??AT(this.inputs)?kT:OT}calculateDiff(e,t,n,r){return jT(e,t,n,r,this._showSignals)}},NT=class extends MT{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MAS),i=n(t,e.inputs.Period2,this.source,W.MAL);this.addInner(r,i)}calculateAt(e){let t=this.innVal(1,W.MAS,e),n=this.innVal(2,W.MAL,e);return this.calculateDiff(this.container,e,t,n)}getWrappers(){return[this.wrapInner(W.MAS,1),this.wrapInner(W.MAL,2)]}},PT=class extends MT{_maIndex;_maTarget;constructor(e,t){super(e,t),JO(this);let n=$O(e,`MA`,`Average`)(t,e.inputs.Period,this.source);this.addInner(n);let[r]=YO(this);this._maIndex=r+1,this._maTarget=n.target}calculateAt(e){let t=this.innVal(this._maIndex,this._maTarget,e),[,n]=YO(this),r=n.getData(this.source)[e],i=this.calculateDiff(this.container,e,r,t);return i[this.target.id]=t,i}},FT=K(`_PVM`),IT=K(`_NVM`),LT=class extends q{constructor(e,t){super(e,t);let n=function(e){return{[FT.id]:e>0?Math.abs(this.baseVal(W.High,e)-this.baseVal(W.Low,e-1)):null}},r=function(e){return{[IT.id]:e>0?Math.abs(this.baseVal(W.Low,e)-this.baseVal(W.High,e-1)):null}},i=X(FT,n,t),a=X(IT,r,t),o=kO(t,W.TR);this.addInner(i,a,o)}calculateAt(e){let t=null,n=null,r=this.period;if(this.atLeast(e,r)){let i=this.past(e,r,FT,this.innCont(1)),a=this.past(e,r,IT,this.innCont(2)),o=this.past(e,r,W.TR,this.innCont(3));if(ge(i)&&ge(a)&&ge(o)){let e=me(i),r=me(a),s=me(o);t=e/s,n=r/s}}return{[W.PLVI.id]:t,[W.MNVI.id]:n}}},RT=K(`_AVG`),zT=class extends q{isPercent;constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.period,i=n(t,r,this.source,RT);this.isPercent=e.inputs.Distance===`Percentage`,this.addInner(i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=this.innVal(1,RT,e),i=this.baseVal(this.source,e);if(r!=null&&r!==0){t=i-r,this.isPercent&&(t=100*t/r);let a=t<=0;if(n=a?1:3,e>0){let r=this.container.getData(this.target)[e-1];r!==null&&(a&&t>r&&(n=0),!a&&t<r&&(n=2))}}return{[this.target.id]:t,[W.BARCOLIX.id]:n}}},BT=class extends q{constructor(e,t){super(e,t);let n=Y(Y(FO(t,this.inputs.PeriodRsi,this.source,W.RSI),this.inputs.PeriodEma1,W.RSI,W.EMA),this.inputs.PeriodEma2,W.EMA,W.EMA),r=J(n,this.inputs.PeriodMa,W.EMA,W.MA),i=Z(W.DOSCH,(e,t,n)=>t-n,n,r),a=J(i,this.inputs.PeriodSig,W.DOSCH,W.DOSCS);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.DOSCH,1),this.wrapInner(W.DOSCS,2)]}},VT=class extends q{constructor(e,t){super(e,t);let n=this.inputs.Period,r=this.inputs.Increment,i=Math.min(Math.max(0,this.inputs.Count),10);for(let e=0;e<i;++e){let i=J(t,n+e*r,this.source,this.outFields[e]);this.addInner(i)}}getWrappers(){let e=this.outFields,t=this.inputs.Count;return[this.wrapInner(e[0],1),this.wrapInner(e[1],2),this.wrapInner(e[2],3),this.wrapInner(e[3],4),this.wrapInner(e[4],5),this.wrapInner(e[5],6),this.wrapInner(e[6],7),this.wrapInner(e[7],8),this.wrapInner(e[8],9),this.wrapInner(e[9],10)].slice(0,t)}},HT=K(`_HAO`),UT=K(`_HAH`),WT=K(`_HAL`),GT=K(`_HAC`),KT=class extends q{constructor(e,t){super(e,t);let n=$O(e,`EMA`,`Smoothing1`),r=e.inputs.Period1,i=n(t,r,W.Open),a=n(t,r,W.High),o=n(t,r,W.Low),s=n(t,r,W.Close),c=Z(GT,(e,t,n,r,i)=>(t+n+r+i)/4,i,a,o,s);function l(e,t,n,r){let i=null;if(e>0){let r=this.container.getData(HT)[e-1],a=this.innVal(2,GT,e-1);N(r,a)?i=(r+a)/2:N(t,n)&&(i=(t+n)/2)}return i}let u=Z(HT,l,i,s,c),d=Z(UT,(e,t,n,r)=>N(t,n,r)?Math.max(t,Math.max(n,r)):null,a,u,c),f=Z(WT,(e,t,n,r)=>N(t,n,r)?Math.min(t,Math.min(n,r)):null,o,u,c),p=$O(e,`EMA`,`Smoothing2`),m=e.inputs.Period2,h=p(u,m,HT,W.Open),g=p(d,m,UT,W.High),_=p(f,m,WT,W.Low),v=p(c,m,GT,W.Close),y=X(W.Change,function(e){let t=null;if(e>0){let n=this.baseVal(W.Close,e),r=this.baseVal(W.Close,e-1);N(n,r)?t=n-r:N(n)&&!N(r)&&(t=0)}return{[W.Change.id]:t}},v);this.addInner(h,g,_,v,y)}getWrappers(){return[this.wrapInner(W.Open,1),this.wrapInner(W.High,2),this.wrapInner(W.Low,3),this.wrapInner(W.Close,4),this.wrapInner(W.Change,5)]}},qT=K(`_DELTA`),JT=class extends q{constructor(e,t){super(e,t);let n=e.inputs,r=Y(t,n.PeriodEmaKeltner,W.Close),i=AO(t,n.PeriodAtrKeltner);function a(e,t,n,r){return N(n,r)?n+e*r:null}let o=n.MultiplierKeltner,s=Z(W.KCUP,ce(a,o),r,i),c=Z(W.KCLOW,ce(a,-o),r,i),l=VO(t,n.PeriodBollinger,n.WidthBollinger),u=HO(t,n.PeriodMomentum),d=J(t,n.PeriodMomentum,W.Close);function f(e,t,n,r){let i=null,a=this.innVal(1,W.DONMID,e);return N(a,r)&&(i=t-(a+r)/2),i}let p=UO(Z(qT,f,t,u,d),n.PeriodMomentum,qT,W.TTMSQZOSC);this.addInner(s,c,l,p)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=null,r=-1,i=this.innVal(1,W.KCUP,e),a=this.innVal(2,W.KCLOW,e),[o,s]=[W.BOLLBU,W.BOLLBL].map(t=>this.innVal(3,t,e));o<i&&s>a?t=0:n=0;let c=this.innVal(4,W.TTMSQZOSC,e),l=e>0?this.innVal(4,W.TTMSQZOSC,e-1):null;if(N(c)){if(!N(l))r=2;else{let e=c>=0,t=l<c;r=e?t?3:2:+!!t}}return{[W.TTMSQZON.id]:t,[W.TTMSQZOFF.id]:n,[W.BARCOLIX.id]:r}}getWrappers(){return[this.wrapInner(W.TTMSQZOSC,4)]}},YT=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNextFromLatestStart:u.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */ new Map([[W.Close,W.CRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},XT=class extends q{constructor(e,t){if(super(e,t),ak(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.inputs.Symbol.toUpperCase();let i=n.getTimeSeries(r),a=e=>e.query?.symbol,{model:o}=ef(((e,t)=>`{${a(e)}} / {${a(t)}}`)(t,i),!1),s=YT(e.aggregation),c=new Rb(o,[t,i],s),l=$O(e,`MA`,`Average`)(c,this.period,W.CRS,W.CRSAVG);this.addInner(i,c,l),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.CRS,(e,t)=>null,t),r=X(W.CRSAVG,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.CRS,2),this.wrapInner(W.CRSAVG,3)]}},ZT=K(`_DIFF`),QT=K(`_RANK`),$T=K(`_CHG`),eE=K(`_AVG`),tE=K(`_HBRAKE_CHG`),nE=K(`_HEIGHT_DELTA`),rE=K(`_ACTION`),iE=K(`_REVERSAL`),aE=200,oE=10,sE=e=>[e>0,e<0],cE=[null,null,null],lE={None:0,Hold:1,Take:2};function uE([e,t],n){let r=null;if(n>0){let t=this.baseVal(e,n-1);N(t)&&(r=this.baseVal(e,n)-t)}return{[t.id]:r}}var dE=class extends q{useHandbrake;constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,St(1,999,this.inputs.FastPeriod),W.Close),i=St(0,999,this.inputs.SlowPeriod),a=i>0,o=a?n(t,i,W.Close):t,s=Z(ZT,a?(e,t,n)=>t-n:(e,t,n)=>n-t,r,o),c=X($T,ce(uE,[W.Close,$T]),t),l=X(QT,function(e){let t=Math.abs(this.baseVal(ZT,e)),n=null,r=0,i=0;for(let n=e-1;n>=0&&r<aE;--n){let e=Math.abs(this.baseVal(ZT,n));r++,e<t&&i++}return r>0&&(n=Math.floor(i/r*oE)),n===oE&&n--,{[QT.id]:n}},s),u=St(0,999,this.inputs.HandbrakePeriod);this.useHandbrake=u>0;let d=n(t,u,W.Close,eE),f=X(tE,ce(uE,[eE,tE]),d);this.addInner(c,s,l,f)}get helpers(){return[nE,W.BARCOLIX,rE,iE]}getStateAt(e){let t=this.innVal(2,ZT,e);return N(t)?sE(t):cE}findPreviousKnownState(e){for(let t=e-1;t>0;t--){let e=this.getStateAt(t);if(e===cE)return cE;let[n,r]=e;if(n||r)return e}return cE}getBuySell(e){let t=this.getStateAt(e);if(t===cE)return cE;let[n,r]=t,i=this.findPreviousKnownState(e),[a,o]=i;if(!n&&!r)return i===cE?cE:[a,o,!1];let s=n!==a||r!==o;return s?[a,o,s]:[n,r,s]}getPrev(e,t){return t>0?this.container.getData(e)[t-1]:null}calculateAt(e){let t=null,n=null,r=0,i=-1,a=lE.None,[o,s,c]=this.getBuySell(e),[l,u]=[iE,rE].map(t=>this.getPrev(t,e)),[d,f]=[0,-1].map(t=>this.innVal(4,tE,e+t));if(i=c?oE:this.innVal(3,QT,e),this.useHandbrake&&N(d,f)){let t=o&&f>0||s&&f<0,n=!o&&d>0||!s&&d<0;c?(i=n?oE:12,a=u):(l===!0||u===lE.Hold)&&(t?(i=this.innVal(3,QT,e),a=lE.Take):(i=n?11:13,a=lE.Hold))}if(N(this.innVal(2,ZT,e))){let t=this.innVal(1,$T,e),[n,i]=sE(t),a=Math.abs(t);(o&&n||s&&i)&&(r=a),(o&&i||s&&n)&&(r=-a)}return o?t=1:s&&(n=1),{[W.JPIB.id]:t,[W.JPIS.id]:n,[W.BARCOLIX.id]:i,[nE.id]:r,[rE.id]:a,[iE.id]:c}}},fE=class extends dE{constructor(e,t){e.inputs=ft(B(`JPI`).defaults.inputs.filter(e=>e.name!==`HandbrakePeriod`)),super(e,t)}},pE={FastPeriod:8,SlowPeriod:21,HandbrakePeriod:13,Average:`EMA`,Height:`Fixed`},mE=class extends dE{constructor(e,t){e.inputs=structuredClone(pE),super(e,t)}},hE=e=>{let t=e.unit===g.Month;return{mapper:e=>e.query.symbol,loadMoreData:!1,recompute:d.Manual,missing:t?u.UseNextFromLatestStart:u.UsePrevious,stretch:e=>!1,fieldMap:/* @__PURE__ */ new Map([[W.Close,W.DRS]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1}},gE=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){if(super(e,t),ak(t)){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=this.indexSymbol;let i=n.getTimeSeries(r),{model:a}=ef(`{${t.query.symbol}} / {${i.query.symbol}} * 100`,!1),o=hE(e.aggregation),s=new Rb(a,[t,i],o);this.addInner(i,s),this.canLoadMoreData=!0,this.initialNotification=!0}else{let e=X(W.Close,(e,t)=>null,t),n=X(W.DRS,(e,t)=>null,t);this.addInner(e,n),this.canLoadMoreData=!1}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(W.DateTime,2),this.wrapInner(W.DRS,2)]}},_E=class extends q{get indexSymbol(){return this.inputs[z.INPUT_SYMBOL]}constructor(e,t){super(e,t);let n=RO(t,this.indexSymbol,e.aggregation),r=J(n,this.period,W.DRS);this.addInner(n,r),this.canLoadMoreData=!0,this.initialNotification=!0}calculateAt(e){let t=this.innVal(1,W.DRS,e),n=this.innVal(2,W.MA,e),r=null;return N(t,n)&&n!==0&&(r=(t/n-1)*100),{[W.MRS.id]:r}}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[0].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},vE=K(`_SMTH_ROC`),yE=K(`_TEN_SMTH_ROC`);function bE(e,t,n,r,i){return new Xb({source:r,target:i,outFields:[i],aggregation:n,inputs:fO(t)},e,e=>2/e)}var xE=class extends q{constructor(e,t){super(e,t);let n=PO(t,1),r=e.aggregation,i=this.inputs.Period1,a=Z(yE,(e,t)=>10*t,bE(n,i,r,W.ROC,vE)),o=this.inputs.Period2,s=bE(a,o,r,yE,W.PMO),c=Y(s,this.inputs.Period3,W.PMO,W.PMOS);this.addInner(s,c)}getWrappers(){return[this.wrapInner(W.PMO,1),this.wrapInner(W.PMOS,2)]}},SE=K(`_VOL_AVG`),CE=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`)(t,this.period,W.Volume,SE,!0);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(0,W.Volume,e),r=this.innVal(1,SE,e);return N(n,r)&&r!==0&&(t=n/r),{[this.target.id]:t}}},wE=e=>Ze(.5**(1/e),6),TE=52,EE=53,DE=27,OE=5,kE=131,AE=(()=>{let e=wE(51),t=Oe(TE,t=>e**+t),n=TE/me(t);return t.map(e=>e*n)})(),jE=[`Renko`,`Kagi`,`PointAndFigure`,`LineBreak`],ME=class extends q{isDaily;isFeasible=!0;constructor(e,t){super(e,t);let n=zb(t),r=n.query?.curveStyle;this.isFeasible=!(n instanceof ev)&&(!N(r)||!jE.includes(h[r])),this.isDaily=e.aggregation.unit===g.Day}acceptable(e,t,n,r){return this.isDaily?r===0||!pi(this.baseVal(W.DateTime,t),this.baseVal(W.DateTime,n)):e>0&&n-t>=OE}pluckValues(e){let t=0,n=[],r=e+OE;for(let i=0;t<EE&&e-i>0;i++){let a=e-i,o=this.baseVal(this.source,a);this.acceptable(o,a,r,t)&&(n.push(o),r=a,t++)}return n}calculateAt(e){let t=null;if(this.isFeasible&&e>=kE){let n=1,r=this.pluckValues(e),i=r.length;if(i>=DE)for(let e=0;e<i-1;e++){let t=r[e]/r[e+1]-1;t<0?t=Math.max(t,-.2):t>=0&&(t=Math.min(t,.2)),t=t*AE[e]+1,n*=t}t=100*(n-1)}return{[this.target.id]:t}}},NE=20;function PE(e,t){switch(e){case g.Intraday:return t>=240?3:t>=120?2:1;case g.Day:default:return 5;case g.Week:return 15;case g.Month:return 60;case g.Quarter:case g.Year:return 240}}function FE(e){return e===_.Continue||e===_.Nearest}var IE=class extends q{additionalChunksCounter=1;noData=!1;isPeriodic=!1;constructor(e,t,n){super(e,n,Ub(n,e=>{let t=re[$()?.config.mode??`Unspecified`];if(!Vc(t))return n;let r=e.duplicate(),i=e.aggregation;if(i.hasSpec)return FE(i.spec)?n:new ev(r,!0);let a=i.unit===g.Intraday&&i.size<=5,o=PE(i.unit,i.size);r.aggregation=a?new yd(g.Tick,i.size,_.PerSeconds):new yd(g.Intraday,o);let s=a?1:3;return r.barsToFetch=Math.min(z.MAX_INTRADAY_BARS,s*e.barsToFetch),new Q_(r)})),this.isPeriodic=t,this.noData=this.innerSeries[1]instanceof ev,this.computedServerSide=!0,this.initialNotification=!0}get canLoadMoreData(){return!1}loadMoreData(){let e=this.innerSeries[1];return!this.noData&&this.additionalChunksCounter<NE&&e.canLoadMoreData&&!e.isLoading?(this.additionalChunksCounter+=1,e.loadMoreData()):Promise.resolve()}recalculateAt(e,t,n){if(e.src!==this.innerSeries[0])return;let r=n?G.TS_DATAPOINTADDED:G.TS_DATAPOINTCHANGED;this.notify(r,this.innerSeries[0].container.size-1)}getWrappers(){return[this.wrapInner(W.Change,1),this.wrapInner(W.Open,1),this.wrapInner(W.Close,1)]}},LE=class extends IE{constructor(e,t){super(e,!1,t)}},RE=class extends IE{constructor(e,t){super(e,!0,t)}},zE=class extends q{constructor(e,t){super(e,t);let n=AO(t,e.inputs.Period,e.inputs.Smoothing);this.addInner(n)}calculateAt(e){let t=null,n=this.innVal(1,W.ATR,e),r=this.baseVal(W.Close,e);return N(n,r)&&r>0&&(t=n/r*100),{[W.ATRP.id]:t}}},BE=K(`_DR`),VE=class extends q{constructor(e,t,n){super(e,n);let r=X(BE,e=>{let t=this.baseVal(W.High,e),n=this.baseVal(W.Low,e);return{[BE.id]:N(t,n)?t-n:null}},n),i=$O(e,`MA`)(r,this.inputs.Period,BE,W.ADR);if(t){let e=Z(this.target,(e,t,n)=>!N(t,n)||n===0?null:t/n*100,i,n);this.addInner(e)}else this.addInner(i)}getWrappers(){return[this.wrapInner(this.target,1)]}},HE=class extends VE{constructor(e,t){super(e,!1,t)}},UE=class extends VE{constructor(e,t){super(e,!0,t)}},WE=class extends q{constructor(e,t){super(e,t);let n=this.source,r=X(n,ce(XO,n),t),i=PO(r,this.inputs.PeriodRoc1,n),a=PO(r,this.inputs.PeriodRoc2,n),o=PO(r,this.inputs.PeriodRoc3,n),s=PO(r,this.inputs.PeriodRoc4,n),c=J(i,this.inputs.PeriodMa1,W.ROC,W.MA1),l=J(a,this.inputs.PeriodMa2,W.ROC,W.MA2),u=J(o,this.inputs.PeriodMa3,W.ROC,W.MA3),d=J(s,this.inputs.PeriodMa4,W.ROC,W.MA4),f=Z(W.KST,(e,t,n,r,i)=>t+2*n+3*r+4*i,c,l,u,d),p=J(f,this.inputs.PeriodSig,W.KST,W.KSTSIG);this.addInner(f,p)}getWrappers(){return[this.wrapInner(W.KST,1),this.wrapInner(W.KSTSIG,2)]}},GE=K(`_EMA1`),KE=K(`_EMA2`),qE=K(`_MACD`),JE=K(`_PCTK`),YE=K(`_PCTD`),XE=K(`_PCTK2`),ZE=class extends q{constructor(e,t){super(e,t);let n=Z(qE,(e,t,n)=>t-n,Y(t,this.inputs.PeriodShort,W.Close,GE),Y(t,this.inputs.PeriodLong,W.Close,KE)),r=this.inputs.PeriodStoch1,i=this.inputs.PeriodStoch2,a=$O(e,`EMA`),o=a(EO(a(EO(n,r,JE,!1,qE),i,JE,YE),r,XE,!1,YE),i,XE,this.target);this.addInner(o)}getWrappers(){return[this.wrapInner(this.target,1)]}},QE=K(`_EMA1`),$E=K(`_EMA2`),eD=K(`_CORE`),tD=class extends q{isEmpty=!1;constructor(e,t){if(super(e,t),ak(t)&&e.aggregation?.isEndOfDay){let n=[`$ADVT`,`$DECT`];switch(this.inputs.Source){case`TotalStocks`:default:break;case`NYSEStocks`:n=[`$ADVN`,`$DECN`];break;case`NasdaqStocks`:n=[`$AVDQ`,`$DECQ`]}let r=this.getSeries(t.query,n[0]),i=this.getSeries(t.query,n[1]),a=this.getTargetSeries(e,r,i);this.addInner(r,i,a),this.canLoadMoreData=!0,this.initialNotification=!0}else{this.isEmpty=!0;let e=X(W.Close,(e,t)=>null,t),n=X(W.Close,(e,t)=>null,t),r=X(this.target,(e,t)=>null,t);this.addInner(e,n,r),this.canLoadMoreData=!1}}get baseIndex(){return+!this.isEmpty}getSeries(e,t){let n=e.duplicate();return n.symbol=t,$().getTimeSeriesDataSource().getTimeSeries(n)}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e!==this.innerSeries[0]&&(e===this.innerSeries[1]||e===this.innerSeries[2])&&this.innHasData(1)&&this.innHasData(2)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData||!this.innerSeries[2].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),await this.innerSeries[2].loadMoreData(e),this.isLoading=!1}getWrappers(){return[this.wrapInner(this.target,3)]}},nD=class extends tD{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=(e,t,n)=>t-n,i=Z(eD,this.inputs.RatioAdjusted===`Yes`?(e,t,n)=>(t-n)/(t+n)*1e3:r,t,n),a=Y(i,this.inputs.Period1,eD,QE),o=Y(i,this.inputs.Period2,eD,$E);return Z(this.target,r,a,o)}},rD=K(`_INN_HL_ACC_IX`),iD=new yd;function aD(e,t,n){return new oD({aggregation:iD,source:null,target:n,outFields:[n],inputs:{...t}},e)}var oD=class extends q{isWeekly=!1;constructor(e,t){if(super(e,t),t instanceof ev)this.canLoadMoreData=!1;else{let n=this.inputs.Source===`PriceIndex`?`$MADX`:`$FADX`,r=this.getSeries(t.query,n);if(this.addInner(r),this.isWeekly=e.aggregation.unit===g.Week,this.isWeekly){let e=aD(this.getSeries(t.query,n,iD),this.inputs,rD);this.addInner(e)}this.canLoadMoreData=!0,this.initialNotification=!0}}getSeries(e,t,n){let r=e.duplicate();return r.symbol=t,n&&(r.aggregation=n,r.barsToFetch=z.US_TRADING_DAYS_PER_YEAR*15),$().getTimeSeriesDataSource().getTimeSeries(r)}get baseIndex(){return 1}calculateAt(e){if(this.isWeekly)return this.calculateAtWeekly(e);let t=null,n=this.period;if(this.atLeast(e,n)){let r=this.past(e,n,W.Close);ge(r)&&(t=me(r))}return{[this.target.id]:t}}calculateAtWeekly(e){let t=this.container?.size??-1,n=null,r=this.innCont(2);if(t>0&&e===t-1)n=r.getLastDataPoint(rD);else{let t=this.container.getTimeData()[e],i=r.getTimeData(),a=A(i,t),o=i[a],s=null;for(;a<r.size&&pi(t,o);)s=a,a+=1,o=i[a];s!==null&&(n=r.getData(rD)[s])}return{[this.target.id]:n}}shouldTriggerOurRecalc(e){return super.shouldTriggerOurRecalc(e)?!0:e!==this.innerSeries[0]&&e===this.innerSeries[1]&&this.innHasData(1)}async loadMoreData(e=!0){if(this.isLoading||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},sD=K(`_RSI1`),cD=K(`_RSI1_MOM`),lD=K(`_RSI2`),uD=K(`_RSI2_MA`),dD=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period1Rsi,W.Close,sD),r=X(cD,le(ZO,this.inputs.Period1Mom,sD),n),i=J(FO(t,this.inputs.Period2Rsi,W.Close,lD),this.inputs.Period2Ma,lD,uD),a=Z(W.CMBCI,(e,t,n)=>t+n,r,i),o=J(a,this.inputs.PeriodFastMa,W.CMBCI,W.CMBCIF),s=J(a,this.inputs.PeriodSlowMa,W.CMBCI,W.CMBCIS);this.addInner(a,o,s)}getWrappers(){return[this.wrapInner(W.CMBCI,1),this.wrapInner(W.CMBCIF,2),this.wrapInner(W.CMBCIS,3)]}};function fD(e){return new dw({source:W.Close,inputs:{},outFields:yO(`COTLC`)},e)}var pD=class extends q{constructor(e,t){super(e,fD(t));let n=Number.parseInt(this.inputs.History),r=n===6?26:52*n,i=EO(this.innerSeries[0],r,W.COTI,!1,W.COTLCCMSP);this.initialNotification=!0,this.computedServerSide=!0,this.addInner(i)}getWrappers(){return[this.wrapInner(W.COTI,1)]}},mD=K(`_MUL_ATR`),hD=class extends q{isLong;constructor(e,t){super(e,t),this.isLong=this.inputs.Direction===`Long`;let n=this.period,r=AO(t,n),i=this.inputs.Multiplier,a=Z(mD,(e,t)=>t===null?null:i*t,r),o=TO(t,n,W.High,W.HH,!0),s=TO(t,n,W.Low,W.LL,!1);this.addInner(a,o,s)}calculateAt(e){let t=null,n=null,r=this.innVal(1,mD,e);return r!==null&&(this.isLong?t=this.innVal(2,W.HH,e)-r:n=this.innVal(3,W.LL,e)+r),{[W.CHEXL.id]:t,[W.CHEXS.id]:n}}},gD=class extends q{constructor(e,t){let n=e.outFields??[],r=e=>{let t=$().getTimeSeriesDataSource();return e.seriesKind=C.Options,e.fields=n,t.getTimeSeries(e)},i=n.length===1?n[0]:void 0,a=i?Wb(t,i,r):Ub(t,r);super(e,a),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return this.outFields.map(e=>this.wrapInner(e,0))}},_D=class extends gD{},vD=class extends gD{},yD=class extends gD{},bD=class extends gD{},xD=class extends gD{},SD=class extends gD{},CD=class extends gD{},wD=class extends q{constructor(e,t){super(e,t);let n=AO(t,1),r=this.inputs.Period,i=TO(t,r,W.High,W.HH,!0),a=TO(t,r,W.Low,W.LL,!1);this.addInner(n,i,a)}calculateAt(e){let t=null,n=this.period;if(e>n){let r=this.past(e,n,W.ATR,this.innCont(1));if(ge(r)){let i=me(r)/(this.innVal(2,W.HH,e)-this.innVal(3,W.LL,e));t=100*Math.log10(i)/Math.log10(n)}}return{[this.target.id]:t}}},TD=class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=n(t,e.inputs.Period1,this.source,W.MACLD1),i=n(t,e.inputs.Period2,this.source,W.MACLD2);this.addInner(r,i)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=+(this.innVal(1,W.MACLD1,e)>this.innVal(2,W.MACLD2,e));return{[W.BARCOLIX.id]:t}}getWrappers(){return[this.wrapInner(W.MACLD1,1),this.wrapInner(W.MACLD2,2)]}},ED=K(`_CORE`),DD=class extends tD{constructor(e,t){super(e,t)}getTargetSeries(e,t,n){let r=Z(ED,(e,t,n)=>t/(t+n),t,n);return $O(e,`MA`,`Average`)(r,this.inputs.Period,ED,this.target)}},OD=class extends q{stdDevs;periodForecast;unitsPerYear;constructor(e,t){super(e,t),this.unitsPerYear=nk(e.aggregation),this.stdDevs=this.toInt(`StandardDeviations`),this.periodForecast=this.inputs.PeriodForecast;let n=this.getHistVolPeriod();if(n!==null){let r=WO(t,n,e.aggregation);this.addInner(r)}}getHistVolPeriod(){return this.isCustomVolatility?null:Number.parseInt(this.volatilityParam.substring(2))}toInt(e){return Number.parseInt(this.inputs[e])}get volatilityParam(){return this.inputs.Volatility}get isCustomVolatility(){return this.volatilityParam===`Custom`}get haveVolatility(){return this.isCustomVolatility||this.innHasData(1)}getVolatilityPercent(){return(this.isCustomVolatility?this.inputs.VolatilityPercent:this.innCont(1).getLastDataPoint(W.HV))/100}calculateAt(e){let t=null,n=null,r=null,i=null,a=null,o=null;if(this.haveVolatility){let s=this.base.size-this.periodForecast;if(e>=s){let c=this.base.getLastDataPoint(W.Close),l=this.getVolatilityPercent(),u=e-s+1,d=c*l*Math.sqrt(u/this.unitsPerYear);if(t=c+d,n=c-d,this.stdDevs>1){let e=2*d;if(r=c+e,i=c-e,this.stdDevs>2){let e=3*d;a=c+e,o=c-e}}}}return{[W.PCUP1.id]:t,[W.PCDN1.id]:n,[W.PCUP2.id]:r,[W.PCDN2.id]:i,[W.PCUP3.id]:a,[W.PCDN3.id]:o}}recalculateAt(e,t,n){let r={tag:xt(),src:this.innerSeries[0]};n&&this.calculate(r)}},kD=class extends q{constructor(e,t){super(e,Ub(t,e=>new AD(e))),this.computedServerSide=!0,this.initialNotification=!0}getWrappers(){return[this.wrapInner(W.Delta,0),this.wrapInner(W.Gamma,0),this.wrapInner(W.Theta,0),this.wrapInner(W.Vega,0)]}},AD=class extends Q_{constructor(e){super(e)}getRetriever(){return Oi(this.query.symbol)?new ND:Pi(this.query.symbol)?new PD:new MD}};function jD(){return new e_([W.DateTime,W.Delta,W.Gamma,W.Theta,W.Vega])}var MD=class{supportsChunks;constructor(){this.supportsChunks=!1}async retrieve(e){return jD()}},ND=class extends T_{emptyContainer(e,t){return jD()}get iterateForward(){return!1}getPageName(){return`getFuturesOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date.substring(0,10))),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},PD=class extends T_{emptyContainer(e,t){return jD()}addExtraParams(e){e.fields=`delta,gamma,theta,vega`}get iterateForward(){return!0}getPageName(){return`getEquityOptionsHistory`}processRow(e,t,n){n.addDataPoint(W.DateTime,qg(e.date)),n.addDataPoint(W.Delta,e.delta),n.addDataPoint(W.Gamma,e.gamma),n.addDataPoint(W.Theta,e.theta),n.addDataPoint(W.Vega,e.vega)}},FD=K(`_RSI1`),ID=K(`_RSI2`),LD=class extends q{constructor(e,t){super(e,t);let n=FO(t,this.inputs.Period1,this.source,FD),r=FO(t,this.inputs.Period2,this.source,ID),i=Z(W.RSA,(e,t,n)=>(t+n)/2,n,r),a=$O(e,`MA`,`Average`)(i,this.inputs.PeriodAvg,W.RSA,W.RSAAVG);this.addInner(i,a)}getWrappers(){return[this.wrapInner(W.RSA,1),this.wrapInner(W.RSAAVG,2)]}},RD=class extends q{constructor(e,t){super(e,t),JO(this);let n=e.inputs.PeriodRSI,r=e.inputs.PeriodTradeSignal,i=e.inputs.PeriodMarketBase,a=e.inputs.PeriodBB,[o]=YO(this),s=this.innerSeries[o],c=FO(s,n,this.source,W.TDIPRC),l=J(c,r,W.TDIPRC,W.TDITSL),u=J(c,i,W.TDIPRC,W.TDIMBL),d=LO(c,a,W.TDIPRC,W.MSD);this.addInner(c,l,u,d)}calculateAt(e){let t=this.inputs.MultiplierBB,n=+!!this.sourceNeedsCompute,r=this.innVal(1+n,W.TDIPRC,e),i=this.innVal(2+n,W.TDITSL,e),a=this.innVal(3+n,W.TDIMBL,e),o=this.innVal(4+n,W.MSD,e),s=null,c=null;if(N(a,o)){let e=t*o;s=a+e,c=a-e}return{[W.TDIPRC.id]:r,[W.TDITSL.id]:i,[W.TDIMBL.id]:a,[W.TDIUPR.id]:s,[W.TDILWR.id]:c}}},zD=K(`_ANCHR`),BD=class extends q{isLong;isPercent;constructor(e,t){super(e,t);let n=e.inputs.Period,r=e.inputs.Range,i=e.inputs.Direction;this.isLong=i===`Long`,this.isPercent=e.inputs.Type===`Percent`;let a=r===`Close`,o=W.Close;a||(o=this.isLong?W.High:W.Low);let s=TO(t,n,o,zD,this.isLong);this.addInner(s)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=null,n=this.innVal(1,zD,e),r=this.inputs.StopValue;if(n!==null){let e=this.isPercent?n*r/100:r;t=this.isLong?n-e:n+e}let i=+!!this.isLong;return{[W.PPS.id]:t,[W.BARCOLIX.id]:i}}},VD=K(`_HH_N`),HD=K(`_LL_N`),UD=K(`_HH_H1`),WD=K(`_LL_H1`),GD=K(`_HH_H2`),KD=K(`_LL_H2`),qD=class extends q{constructor(e,t){super(e,t),JO(this);let n=e.inputs.Period,r=Math.floor(n/2),i=TO(t,n,W.High,VD,!0),a=TO(t,n,W.Low,HD,!1),o=TO(t,r,W.High,UD,!0),s=TO(t,r,W.Low,WD,!1),c=TO(t,r,W.High,GD,!0),l=TO(t,r,W.Low,KD,!1);this.addInner(i,a,o,s,c,l)}calculateAt(e){let t=this.period,n=Math.floor(t/2),[,r]=YO(this),i=r.getData(this.source)[e];if(!this.atLeast(e,t))return{[this.target.id]:i};let a=+!!this.sourceNeedsCompute,o=this.innVal(1+a,VD,e),s=this.innVal(2+a,HD,e),c=this.innVal(3+a,UD,e),l=this.innVal(4+a,WD,e),u=this.innVal(5+a,GD,e-n),d=this.innVal(6+a,KD,e-n);if(!N(o,s,c,l,u,d))return{[this.target.id]:i};let f=(o-s)/t,p=(c-l)/n,m=(u-d)/n,h=0;p>0&&m>0&&f>0&&(h=(Math.log(p+m)-Math.log(f))/Math.log(2));let g=Math.exp(-4.6*(h-1));g=Math.max(.01,Math.min(1,g));let _=e>0?this.container.getData(this.target)[e-1]:i,v=_===null?i:g*i+(1-g)*_;return{[this.target.id]:v}}},JD=K(`_MIDPOINT`),YD=K(`_VALUE`),XD=class extends q{constructor(e,t){super(e,t);let n=e.inputs.Period,r=X(JD,ce(bS,JD),t),i=TO(r,n,JD,W.HH,!0),a=TO(r,n,JD,W.LL,!1);this.addInner(r,i,a)}get helpers(){return[YD]}calculateAt(e){let t=this.innVal(1,JD,e),n=this.innVal(2,W.HH,e),r=this.innVal(3,W.LL,e);if(!N(n,r,t))return{[W.FISHER.id]:null,[W.FISHTRG.id]:null,[YD.id]:null};let i=n-r,a=i===0?.5:(t-r)/i,o=t=>this.container.getData(t)[e-1],s=e>0?o(YD):null,c=.66*(a-.5)+.67*(s??0);c>.99?c=.999:c<-.99&&(c=-.999);let l=e>0?o(W.FISHER):null,u=.5*Math.log((1+c)/(1-c))+.5*(l??0);return{[W.FISHER.id]:u,[W.FISHTRG.id]:l,[YD.id]:c}}},ZD=class extends q{constructor(e,t){super(e,t),JO(this)}computeMidranks(e){let t=e.length,n=e.map((e,t)=>({v:e,i:t}));n.sort((e,t)=>e.v-t.v);let r=Array(t),i=0;for(;i<t;){let e=i,a=n[i].v;for(;e+1<t&&n[e+1].v===a;)e++;let o=(i+1+(e+1))/2;for(let t=i;t<=e;t++)r[n[t].i]=o;i=e+1}return r}pearsonCorrelation(e){let t=e.length;if(t<2)return null;let n=(t+1)/2,r=0;for(let n=0;n<t;n++)r+=e[n];let i=r/t,a=0,o=0,s=0;for(let r=0;r<t;r++){let t=r+1-n,c=e[r]-i;a+=t*c,o+=t*t,s+=c*c}let c=Math.sqrt(o*s);return c===0?null:a/c}calculateAt(e){let t=null,n=this.period,[,r]=YO(this);if(this.atLeast(e,n)){let i=this.past(e,n,this.source,r);if(i.every(e=>e!==null)){let e=this.computeMidranks(i),n=this.pearsonCorrelation(e);n!==null&&(t=100*n)}}return{[W.RCI.id]:t}}},QD=class extends q{constructor(e,t){super(e,t);let n=this.source,r=new ZD({source:n,target:W.RCI,inputs:{Period:e.inputs.Period}},t),i=e.inputs.PeriodSignal,a=$O(e,`MA`,`Smoothing`)(r,i,W.RCI,W.RCISIG);this.addInner(r,a)}getWrappers(){return[this.wrapInner(W.RCI,1),this.wrapInner(W.RCISIG,2)]}},$D=K(`_ATR`),eO=class extends q{state;useHighLow;isAtrMode;atrMult;percent;constructor(e,t){if(super(e,t),this.useHighLow=e.inputs.Method===`High/Low`,this.isAtrMode=e.inputs.PercentMode===`ATR`,this.percent=e.inputs.Percent,this.atrMult=e.inputs.MultiplierAtr,this.useHighLow||JO(this),this.isAtrMode){let t=e.inputs.PeriodAtr,[n]=this.useHighLow?[0]:YO(this),r=this.innerSeries[n],i=AO(r,t,`SMA`,$D);this.addInner(i)}this.resetState()}getHigh(e){if(this.useHighLow)return this.baseVal(W.High,e);let[,t]=YO(this);return t.getData(this.source)[e]}getLow(e){if(this.useHighLow)return this.baseVal(W.Low,e);let[,t]=YO(this);return t.getData(this.source)[e]}getAtrDenom(e){if(this.useHighLow)return this.baseVal(W.Close,e);let[,t]=YO(this);return t.getData(this.source)[e]}setPivot(e,t){this.state.pivotPrice=e,this.state.pivotIndex=t}setCandidate(e,t){this.state.candPrice=e,this.state.candIndex=t}getDevPct(e){if(this.isAtrMode){let t=!this.useHighLow&&this.sourceNeedsCompute?1:0,n=this.innVal(1+t,$D,e),r=this.getAtrDenom(e);if(n===null||r===null||r===0)return 0;let i=n/r*100;return this.atrMult*i}return this.percent}pct(e,t){return e===0?0:(t-e)/e*100}resetState(){this.state={mode:0,pivotPrice:null,pivotIndex:null,candPrice:null,candIndex:null,confirmedPivots:/* @__PURE__ */ new Map}}calculateAt(e){let t=this.getHigh(e),n=this.getLow(e),r=this.getDevPct(e);if(t===null||n===null)return{};if(e===0){this.resetState();let n=this.useHighLow?this.baseVal(W.Close,e):t;return this.setPivot(n,e),this.setCandidate(n,e),{}}if(this.state.mode===0)this.pct(this.state.pivotPrice,t)>=r?(this.state.mode=1,this.setCandidate(t,e)):-this.pct(this.state.pivotPrice,n)>=r&&(this.state.mode=-1,this.setCandidate(n,e));else if(this.state.mode===1){let i=t>=this.state.candPrice;i&&this.setCandidate(t,e);let a=(this.state.candPrice-n)/this.state.candPrice*100;if(!i&&a>=r){let t=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(t,r),this.setPivot(r,t),this.setCandidate(n,e),this.state.mode=-1}}else if(this.state.mode===-1){let i=n<=this.state.candPrice;i&&this.setCandidate(n,e);let a=(t-this.state.candPrice)/this.state.candPrice*100;if(!i&&a>=r){let n=this.state.candIndex,r=this.state.candPrice;this.state.confirmedPivots.set(n,r),this.setPivot(r,n),this.setCandidate(t,e),this.state.mode=1}}return{}}getCurrentState(){return this.state}},tO=class extends q{constructor(e,t){super(e,t);let n=X(W.BOP,function(e){let t=null,[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(t=>this.baseVal(t,e));if(N(n,r,i,a)){let e=r-i;t=e===0?0:(a-n)/e}return{[this.target.id]:t}},t),r=$O(e,`MA`,`Average`),i=this.period,a=r(n,i,W.BOP,W.BOPAVG);this.addInner(n,a)}getWrappers(){return[this.wrapInner(W.BOP,1),this.wrapInner(W.BOPAVG,2)]}};function nO(e,t){let n=e.length;if(n<2||t.length!==n)return null;let r=0,i=0,a=0,o=0,s=0;for(let c=0;c<n;c++){let n=e[c],l=t[c];r+=n,i+=l,a+=n*n,o+=l*l,s+=n*l}let c=n*s-r*i,l=Math.sqrt((n*a-r*r)*(n*o-i*i));if(l===0||!Number.isFinite(l))return null;let u=c/l;return Number.isFinite(u)?Math.max(-1,Math.min(1,u)):null}var rO=class extends q{constructor(e,t){if(super(e,t),ak(t)){let e=this.inputs.Symbol?.toUpperCase();if(e){let n=$().getTimeSeriesDataSource(),r=t.query.duplicate();r.symbol=e;let i=n.getTimeSeries(r);this.addInner(i),this.canLoadMoreData=!0,this.initialNotification=!0}}}compareCloseAt(e){let t=this.innCont(1);if(!t||t.isEmpty)return null;let n=this.baseVal(W.DateTime,e);if(n===null)return null;let r=t.getData(W.DateTime),i=t.getData(W.Close);if(r.length===0)return null;let a=n.valueOf(),o=A(r,a,Number),s=r[o];if(!N(s))return null;let c=s.valueOf()<=a?o:o-1;if(c<0)return null;let l=i[c];return N(l)?l:null}calculateCorrelation(e){let t=this.period;if(!this.atLeast(e,t)||!this.innHasData(1))return null;let n=[],r=[];for(let i=e-t+1;i<=e;i++){let e=this.baseVal(W.Close,i),t=this.compareCloseAt(i);if(!N(e,t))return null;n.push(e),r.push(t)}return nO(n,r)}calculateAt(e){return{[this.target.id]:this.calculateCorrelation(e)}}async loadMoreData(e=!0){if(this.isLoading||this.innerSeries.length<2||!this.innerSeries[1].canLoadMoreData)return Promise.resolve();this.isLoading=!0,await this.innerSeries[1].loadMoreData(e),this.isLoading=!1}},iO=4,aO=4,oO=K(`_RVI_NUM`),sO=K(`_RVI_DEN`),cO=K(`_RVI_NUMAVG`),lO=K(`_RVI_DENAVG`);function uO(e){if(e.length<aO||!ge(e))return null;let[t,n,r,i]=e;return(t+2*n+2*r+i)/6}var dO={_TR:$x,_RSI:Ax,MA:Yb,MAEXP:Zb,MAHLC:$b,VOL:tx,MAENV:sx,MAENVEXP:cx,MAENVSMO:lx,MATRI:ux,MAWEI:dx,MAVOL:Yb,MASMO:Qb,MACD:Sx,MACDEXP:Cx,MACDV:xx,GMMA:Fw,OSCI:fx,OSCIVOL:fx,RSI:Mx,RSIMOD:Nx,RSISTO:Px,RSA:LD,WPERCR:zx,HHLL:Fx,WGCL:Ix,STOCHF:Hx,STOCHS:Ux,BBANDS:qx,BWIDTH:Jx,BPERC:Yx,OBVOL:Qx,ATR:rS,ADR:HE,ATRP:zE,ADRP:UE,ADX:pS,ADXMOD:mS,ADL:hS,ADWM:gS,CHAOSC:_S,TP:vS,KELCHN:OS,KELBND:kS,DONCHN:jS,DONWIDTH:MS,PVT:NS,ROC:RS,TRIX:PS,PPMOV:zS,PIVPTS:xw,CPP:Sw,ARNUPDW:US,ARNOSC:WS,TCHN:GS,TCHRE:KS,ALLG:JS,PLTLN:YS,AWEOSC:ZS,MFV:eC,CLV:$S,CHAMF:tC,CHAVOL:rC,DPO:iC,CCI:oC,EMV:sC,ERBRPOW:uC,ERBLPOW:lC,FI:fC,MI:_C,MOM:vC,MFI:yC,MSD:bC,NVI:wC,PVI:TC,PPO:Ex,PVO:Dx,HV:DC,PERF:OC,WASI:AC,WWVOL:NC,PARTP:zC,MOVLR:BC,TRSP:tw,TARGP:nw,COTLC:dw,COTDAG:fw,COTFTR:pw,IMPVOL:Cw,CTM:wx,CPMI:Tx,DEMA:FS,EOSC:IS,TEMA:LS,TSI:Pw,ADJATR:iS,COTR:aS,MCGD:Iw,HMA:Rw,COPP:Bw,REATRS:Ww,LINRCHN:Gw,CSHO:Kw,CSHB:qw,MKTCAP:Jw,CTPI:Wx,PCTCHG:Yw,OPINT:nx,STOMOMIX:rT,CHDMOMOSC:cT,VSTOP:fT,ATREXT:Jb,SUPTR:gT,ICHCLD:_T,VWAP:wT,MACROSS:NT,PACROSS:PT,VOIN:LT,DIFA:zT,DOSC:BT,BBANDW:Xx,MARIB:VT,HASMO:KT,TTMSQZ:JT,CRS:XT,JPI:dE,CTTP:fE,CTTI:mE,DRS:gE,MRS:_E,PMO:xE,RVOL:CE,WGALPH:ME,VOLAP:LE,AVWAP:ET,KST:WE,STC:ZE,MCCLO:nD,NHLAI:oD,CMBCI:dD,COTI:pD,CHEXI:hD,MBBANDS:Zx,OPTIV:_D,IVRANK:vD,IVPCTL:yD,OPTVOLPC:bD,OPTOIPC:xD,OPTVOL:SD,OPTOI:CD,CHOP:wD,MACLD:TD,BTI:DD,FRAMA:qD,FISHER:XD,PC:OD,GREEKS:kD,PVACP:RE,TDI:RD,PPS:BD,RCI:QD,BOP:tO,CORR:rO,RVI:class extends q{constructor(e,t){super(e,t);let n=(e,t)=>function(n){let r=this.past(n,aO,e),i=this.past(n,aO,t),a=null;if(ge(r)&&ge(i)){let e=r,t=i;a=uO(e.map((e,n)=>e-t[n]))}return{[this.target.id]:a}},r=X(oO,n(W.Close,W.Open),t),i=X(sO,n(W.High,W.Low),t),a=this.period,o=J(r,a,oO,cO),s=J(i,a,sO,lO),c=Z(W.RVI,(e,t,n)=>n===0?null:t/n,o,s),l=X(W.RVISIG,function(e){return{[this.target.id]:uO(this.past(e,iO,W.RVI))}},c);this.addInner(c,l)}getWrappers(){return[this.wrapInner(W.RVI,1),this.wrapInner(W.RVISIG,2)]}},ZIGZAG:eO,DIDI:class extends q{constructor(e,t){super(e,t);let n=$O(e,`MA`,`Average`),r=this.source??W.Close,i=n(t,this.inputs.PeriodShort,r),a=n(t,this.inputs.PeriodMedium,r),o=n(t,this.inputs.PeriodLong,r),s=(e,t,n)=>n===0?null:t/n,c=Z(W.DIDIS,s,i,a),l=Z(W.DIDIL,s,o,a);this.addInner(c,l)}get helpers(){return[W.BARCOLIX]}calculateAt(e){let t=this.innVal(1,W.DIDIS,e),n=this.innVal(2,W.DIDIL,e),r=this.innVal(1,W.DIDIS,e-1),i=this.innVal(2,W.DIDIL,e-1),a=t===null||n===null?-1:+(t>n),o=null,s=null;if(t!==null&&n!==null&&r!==null&&i!==null){let e=(n+i)/2;t>n&&r<=i&&(o=e),n>t&&i<=r&&(s=e)}return{[W.DIDIUP.id]:o,[W.DIDIDN.id]:s,[W.BARCOLIX.id]:a}}getWrappers(){return[this.wrapInner(W.DIDIS,1),this.wrapInner(W.DIDIL,2)]}}};function fO(e){return{[z.INPUT_PERIOD]:e}}function pO(e){return{[z.INPUT_SYMBOL]:e}}function mO(e){return{target:e,source:null,inputs:OO}}function hO(e){return e instanceof Rb&&typeof e.seasonalAverageOffset==`number`&&e.seasonalAverageOffset<0}function gO(e,t){if(!N(e))return e;for(let[n,r]of t.policy.fieldMap.entries())if(r===e)return n;return e}function _O(e,t,n){if(!z.CLIENT_SIDE_SEASONAL_AVERAGE_DISTRIBUTED_STUDIES.has(e)||!hO(n))return null;let r=gO(t.source,n),i=t.target??t.outFields?.[0];if(!M(i))return null;let a=n.innerSeries.map(n=>{let a=vO(e,{...t,source:r??null,target:i,outFields:[i],inputs:P(t.inputs??{})},n);return a.query=n.query,a}),o=new Rb(n.exprModel,a,{...n.policy,fieldMap:/* @__PURE__ */ new Map([[i,i]])});return new Kb({...t,source:r??null,target:i,outFields:[i]},o)}function vO(e,t,n){let r=_O(e,t,n);if(r)return r;if(rt(dO,e))return new dO[e](t,n);let i=$()?.config.extensions?.studyProvider;if(i){let r=i.factory(e,t,n);if(r)return r}throw Error(`Study ${e} has not been implemented yet.`)}function yO(e){return B(e).defaults.curves.reduce((e,t)=>e.concat(t.fields.filter(t=>!e.includes(t))),[]).map(e=>W[e])}function bO(e,t,n,r){return{source:t,target:n,inputs:fO(e),allowEmptyValues:r}}function J(e,t,n,r=W.MA,i=!1){return vO(`MA`,bO(t,n,r,i),e)}function Y(e,t,n,r=W.EMA,i=!1){return vO(`MAEXP`,bO(t,n,r,i),e)}function xO(e,t,n,r=W.SMA,i=!1){return vO(`MASMO`,bO(t,n,r,i),e)}function SO(e,t,n,r=W.WMA,i=!1){return vO(`MAWEI`,bO(t,n,r,i),e)}function CO(e,t,n,r=W.HMA,i=!1){return vO(`HMA`,bO(t,n,r,i),e)}function wO(e,t,n,r,i=W.Close){return vO(`MACDEXP`,{source:i,inputs:{Period1:t,Period2:n,Period3:r},outFields:[W.MACD,W.MACDS,W.MACDH]},e)}function TO(e,t,n,r,i,a=!1){return new Lx({source:n,target:r,inputs:fO(t)},i,a,e)}function EO(e,t,n,r,i=null){return new Rx({source:i,target:n,inputs:fO(t)},r,e)}function DO(e,t,n=W.PCTCHG){return vO(`PCTCHG`,{source:t,target:n,inputs:OO},e)}var OO={};function kO(e,t=W.TR){return vO(`_TR`,mO(t),e)}function AO(e,t,n=`SMA`,r=W.ATR){return vO(`ATR`,{target:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n},source:null},e)}function jO(e,t,n=`MA`,r=W.Close,i=W.ADJATR){return vO(`ADJATR`,{source:r,target:i,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_SMOOTHING]:n}},e)}function MO(e,t=W.ADL){return vO(`ADL`,mO(t),e)}function NO(e,t=W.TP){return vO(`TP`,mO(t),e)}function PO(e,t,n=W.Close,r=W.ROC){return vO(`ROC`,{source:n,target:r,inputs:fO(t)},e)}function FO(e,t,n,r=W.RSI,i=!1){return vO(`_RSI`,{source:n,target:r,inputs:{...fO(t),Modified:i}},e)}function IO(e,t=W.MFMUL){return vO(`MFV`,mO(t),e)}function LO(e,t,n,r=W.MSD){return vO(`MSD`,{source:n,target:r,inputs:fO(t)},e)}function RO(e,t,n,r=W.DRS){return vO(`DRS`,{target:r,inputs:pO(t),aggregation:n,source:null},e)}function zO(e,t=W.CSHO){return vO(`CSHO`,mO(t),e)}function BO(e,t,n){let r=`TCHN`;return vO(r,{inputs:{PeriodUpper:t,PeriodLower:t,Range:n},outFields:yO(r),source:null},e)}function VO(e,t,n,r=W.Close){let i=`BBANDS`,a=yO(i);return vO(i,{source:r,inputs:{[z.INPUT_PERIOD]:t,[z.INPUT_WIDTH]:n},outFields:a},e)}function HO(e,t){let n=`DONCHN`,r=yO(n);return vO(n,{inputs:fO(t),outFields:r,source:null},e)}function UO(e,t,n,r=W.MOVLR){return vO(`MOVLR`,{source:n,inputs:fO(t),target:r},e)}function WO(e,t,n,r=W.Close,i=W.HV){return vO(`HV`,{source:r,target:i,aggregation:n,inputs:fO(t)},e)}function X(e,t,n){return new SS(mO(e),t,n)}function Z(e,t,...n){return new yS(mO(e),t,...n)}function GO(e,t,n){return t-n}function KO(e,t,n){return(t-n)/n*100}function qO(e){switch(e.id){case`HL/2`:case`OC/2`:case`HLC/3`:case`OHLC/4`:case`HLCC/4`:return!0;default:return!1}}function JO(e){let t=e.source;if(e.sourceNeedsCompute=qO(t),e.sourceNeedsCompute){let n=X(t,ce(XO,t),e.innerSeries[0]);e.addInner(n)}}function YO(e){let t=+!!e.sourceNeedsCompute;return[t,e.innCont(t)]}var XO=function(e,t){let[n,r,i,a]=[W.Open,W.High,W.Low,W.Close].map(e=>this.baseVal(e,t)),o=null,s=e.id;switch(s){case`Open`:o=n;break;case`High`:o=r;break;case`Low`:o=i;break;case`Close`:o=a;break;case`HL/2`:o=(r+i)/2;break;case`OC/2`:o=(n+a)/2;break;case`HLC/3`:o=(r+i+a)/3;break;case`OHLC/4`:o=(n+r+i+a)/4;break;case`HLCC/4`:o=(r+i+a+a)/4}return{[s]:o}},ZO=function(e,t,n){let r=null;if(this.atLeast(n,e+1)){let i=this.baseVal(t,n-e);i!==null&&(r=this.baseVal(t,n)-i)}return{[this.target.id]:r}},QO={sma:xO,ma:J,ema:Y,wma:SO,hma:CO};function $O(e,t,n=`Smoothing`){return QO[(e.inputs[n]??t).toLowerCase()]}var ek={atr:AO,adjatr:jO};function tk(e){return ek[e.inputs.TypeOfATR.toLowerCase()]}function nk(e){switch(e.unit){case g.Day:return 252;case g.Week:return 52;case g.Month:return 12;default:return 0}}function rk(e){let t=[W.High,W.Low];return e instanceof Rb&&Se(e.targetFields,t).length!==2}function ik(e,t){return e[`Period${t}`]}function ak(e){return!(e instanceof ev)&&e.query instanceof Fb}var ok=class extends Gb{constructor(e,t){let n=Y(t,13,W.Close),r=wO(t,12,26,9,W.Close);super(e,t,n,r),this.query=t.query,this.useNotifications=!0}calculateAt(e){let t=p.Same,n=this.innVal(1,W.EMA,e),r=this.innVal(1,W.EMA,e-1),i=this.innVal(2,W.MACDH,e),a=this.innVal(2,W.MACDH,e-1);return N(n,r,i,a)&&(n>r&&i>a?t=p.Up:n<r&&i<a&&(t=p.Down)),{[W.BREL.id]:t}}getWrappers(){return this.wrapBaseFields(W.Open,W.High,W.Low,W.Close,W.Change,W.Volume,W.OpenInterest,W.TradingDay)}};function sk(e,t){return N(t)?(this[e]=t,null):this[e]}var ck=class{_domain;_range;_extent;_padding;constructor(){this._domain=this._range=this._extent=null,this._padding=[0,0]}domain(e){return sk.call(this,`_domain`,e)}range(e){return sk.call(this,`_range`,e)}padding(e){return sk.call(this,`_padding`,e)}get ready(){return N(this._domain,this._range)}},lk=1/Math.log2(10),uk=(e,t)=>n=>e*(1-n)+t*n,dk=(e,t)=>(t-=e,t>0?n=>(n-e)/t:e=>de(isNaN(t)?NaN:.5));function fk(e,t){let n=dk(e[0],e[1]),r=uk(t[0],t[1]);return e=>r(n(e))}function pk(e){return Math.sign(e)*Math.log10(1+Math.abs(e/lk))}function mk(e){return Math.sign(e)*lk*(-1+10**Math.abs(e))}var hk=[[0,1],[1,10],[10,100],[100,1e3],[1e3,1e4],[1e4,1e5]],gk=class extends ck{scaleType;axis;constructor(e,t){super(),this.scaleType=e,this.axis=t}domain(e){return this.axis&&e&&!ve(e,this._domain)&&this.axis.pane.presenter.onScaleDomainChanged(this.axis),super.domain(e)}yToPrice(e){return this.mapValue(e)}rangeWithPadding(){return[this._range[0]+this._padding[0],this._range[1]-this._padding[1]]}mapValue(e,t=!0){if(!this.ready)return null;let n=de,r=de;switch(this.scaleType){case ee.Linear:break;case ee.Logarithmic:n=pk,r=mk;break;default:throw Error(`Unexpected scale type (neither linear nor log)`)}let i=this._domain.map(n),a=this.rangeWithPadding(),o=t?fk(a,i):fk(i,a),s=e=>a[1]-e+a[0];return(t?r:s)(o((t?s:n)(e)))}priceToY(e){return this.mapValue(e,!1)}getTicks(e){if(!this.ready)return[];let[t,n]=this._range.map(e=>this.mapValue(e,!0));if(t===n&&e>0)return[t];let[r,i]=this._domain;if(this.scaleType===ee.Linear||r<0||i>1e5)return _k(t,n,e);let a=this.findLogBand(r),o=this.findLogBand(i),s=e*2;return o-a===0?_k(t,n,s):this.getLogTicks(a,o,s,n<t)}findLogBand(e){return hk.findIndex(([t,n])=>e>=t&&e<n)}getLogTicks(e,t,n,r){let i=[...this._domain],a=[];try{for(let o=e;o<=t;o++){let[s,c]=hk[o];o===e?s=i[0]:o===t&&(c=i[1]),this.domain([s,c]);let[l,u]=this._range.map(e=>this.mapValue(e,!0)),d=_k(l,u,n);a=r?d.concat(a):a.concat(d)}}finally{this.domain(i)}return Me(a,r?(e,t)=>e>t:(e,t)=>e<t),a}checkTicks(){return this.scaleType===ee.Logarithmic}};function _k(e,t,n){let r,i=-1,a,o,s;if(t=+t,e=+e,n=+n,e===t&&n>0)return[e];if((r=t<e)&&(a=e,e=t,t=a),(s=vk(e,t,n))===0||!isFinite(s))return[];if(s>0)for(e=Math.ceil(e/s),t=Math.floor(t/s),o=Array(a=Math.ceil(t-e+1));++i<a;)o[i]=(e+i)*s;else for(e=Math.floor(e*s),t=Math.ceil(t*s),o=Array(a=Math.ceil(e-t+1));++i<a;)o[i]=(e-i)/s;return r&&o.reverse(),o}function vk(e,t,n){let r=Math.sqrt(50),i=Math.sqrt(10),a=Math.sqrt(2),o=(t-e)/Math.max(0,n),s=Math.floor(Math.log(o)/Math.LN10),c=o/10**s;return s>=0?(c>=r?10:c>=i?5:c>=a?2:1)*10**s:-(10**-s)/(c>=r?10:c>=i?5:c>=a?2:1)}var yk=[`None`,`Annotations`,`Studies`,`All`],bk=yk[0];function xk(e){return e?.hiddenItems??bk}function Sk(e){let t=xk(e);return t===`Annotations`||t===`All`}function Ck(e){let t=xk(e);return t===`Studies`||t===`All`}function wk(e,t){return e.type===S.Study&&Ck(t)}function Tk(e,t){return e.visible!==!1&&!wk(e,t)}function Ek(e,t){return e.visible!==!1&&!Sk(t)}var Dk={color:z.COLOR_TRANSPARENT},Ok={color:z.COLOR_TRANSPARENT,width:0,dashStyle:`Solid`},kk=[W.Open,W.High,W.Low,W.Close],Ak=new Set(kk.map(e=>e.id)),jk=e=>Ak.has(e.id),Mk=e=>e.visible,Nk=e=>e.visible&&e.canHitTest,Pk=new rs(0,0,0,0),Fk=class{axis;id;uid;record;metaData;timeSeries;notifyAboutPriceDomains=!1;customPlotValues=!1;_priceMapFirstIndex;priceMapper;_firstVisibleDate=null;_lastVisibleDate=null;main=!1;curves=[];type=S.Symbol;isShutDown=!1;targetFields=[];detachedScale;yScale=null;levels;bands;annotations;visFromIndex;visToIndex;_eventsData;precision;visible=!0;constructor(){this.axis=null,this.id=xt(),this.uid=this.id,this.record=new Dp(``),this.metaData=new So,this.timeSeries=new ev,this.priceMapper=this._priceMapper.bind(this),this._priceMapFirstIndex=/* @__PURE__ */ new Map}get title(){return``}get showPrevious(){return!1}getPreviousValue(){return null}get mainCurve(){return this.curves[0]}get hasEvents(){return!1}findEvents([e,t]){return[]}get eventsSeries(){return null}get hasEventsData(){return this.hasEvents&&N(this.eventsSeries)&&this.eventsSeries.hasData&&this.eventsSeries.container.size>0}getEventFor(e){return null}get isSymbol(){return this.is(S.Symbol)}get isExpression(){return this.is(S.Expression)}get isStudy(){return this.is(S.Study)}get isForward(){return this.is(S.Forward)}get isSeasonal(){return this.is(S.Seasonal)}get isVisible(){return Tk(this,this.presenter?.display)}getValueAt(e,t,n){return null}wrapIfAdvancedStyle(e){let t=e,n=e=>({outFields:e,inputs:{},source:null});return this.mainCurve.isHeikinAshiStyle?t=new qb(n(g_.slice()),e):this.mainCurve.isElderImpulseSystemStyle?t=new ok(n(g_.slice().concat(W.BREL)),e):this.mainCurve.isPercentChangeStyle&&(t=new Xw(n(g_.slice()),e)),t}is(e){return this.type===e}getCacheableEntities(e){this.metaData.getCacheableEntities(e.metaData),this.timeSeries.getCacheableEntities(e.timeSeries)}fromModel(e){this.type=S[e.type];let t=e;this.uid=t.uid,this.main=t.main,t.levels&&(this.levels=t.levels),t.bands&&(this.bands=t.bands),N(t.precision)&&(this.precision=t.precision),this.curves=e.curves.map(e=>{let t=new jb;return t.plot=this,t.fromModel(e),t}),t.detachedScale&&(this.detachedScale=t.detachedScale,this.yScale=new gk(ee.Linear,null)),this.visible=t.visible??!0}initialize(){}shutdown(){N(this.timeSeries)&&N(this.timeSeries.shutdown)&&!this.timeSeries.isCached&&this.timeSeries.shutdown(),this.isShutDown=!0}makeQuery(){let e=this.axis.pane.presenter,t=new Fb(null,e.data.aggregation,C.Normal,[mt(it(e.data,null,`range`,`from`)),mt(it(e.data,null,`range`,`to`))]);return t.barsToFetch=e.data.maxDataPoints||z.DEFAULT_MAX_RECORDS,t.aggregation.backAdjust&&(t.barsToFetch=4*t.barsToFetch),t.chartId=e.elementId,t.curveStyle=this.curves[0].style,t.visibleRange=it(e.display,null,`xAxis`,`visibleRange`),t.useLastTrade=e.data.useLastTrade,t.extendedHours=e.data.extendedHours,t}priceToY(e){return(this.hasDetachedScale?this.yScale:this.axis.yScale).priceToY(e)}get hasDetachedScale(){return N(this.detachedScale,this.yScale)&&this.detachedScale}hasCurveThat(e){return this.curves.some(e)}get hasVisibleCurves(){return this.hasCurveThat(Mk)}get hasHitTestableCurves(){return this.hasCurveThat(Nk)}getDetachedScaleMargins(){return z.DEFAULT_DETACHED_SCALE_MARGINS}setViewBox(e){if(!this.hasDetachedScale)return;let{y:t,height:n}=e,{top:r,bottom:i}=this.getDetachedScaleMargins();this.yScale.range([Math.floor(t+r*n),Math.floor(t+n-i*n)])}drawLevels(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.levels.filter(e=>e.visible)){let r=this.priceToY(n.value);Gs(e,Ks({line:n.line,fill:Dk})),gs(e,{x:-1,y:r},{x:t,y:r})}e.restore()}drawBands(e){e.save();let t=z.OUT_OF_SCREEN;for(let n of this.bands){let r=this.priceToY(n.range.to),i=this.priceToY(n.range.from);Gs(e,Ks({fill:n.fill,line:Ok})),ms(e,new rs(-1,r,t,i-r),!1)}e.restore()}drawAnnotations(e){e.save(),this.annotations.forEach(t=>t.draw(e,!0)),e.restore()}getEventFields(){return!this.hasEvents||!this.hasEventsData?[]:this.eventsSeries.container.fields.filter(e=>e!==W.DateTime)}getEventsAt(e){let t=this.eventsSeries.container,n=n=>t.getData(n)[e];return this.getEventFields().map(t=>{let r=n(t);if(!N(r))return null;let i=this.getEventFor(t);if(!N(i))return null;let a={field:t,value:r,date:n(W.DateTime),text:i.title,color:i.color};if(t===W.Custom&&r===z.FAKE_CUSTOM_EVENT){let t=e%2==0;return{...a,value:t?`___news`:`___video`,text:t?`N`:`V`}}return a}).filter(e=>e!=null)}getRefEventField(e,t,n,r){let i=r?.container,a=e.fields[0];t&&(a=e.isOhlc?W.High:n.isTick?W.Last:W.Close);let o=[a,e.fields[0]].filter(M);return M(i)?o.find(e=>i.hasField(e))??a:a}getRefPlot(e){return this.axis.pane.isMain?e.mainPlot:this}drawEvents(e,t){let n=this.axis.pane.presenter,r=n.view.xAxis.xScale,i=r.domain();if(!N(i)||!N(i[0],i[1]))return;let a=(e,t=W.DateTime)=>e.container.getData(t),o=a(this.eventsSeries),s=this.getRefPlot(n),c=s.timeSeries,l=a(c),u=n.data.aggregation,d=s===n.mainPlot,f=a(c,this.getRefEventField(s.mainCurve,d,u,c));if(!Array.isArray(f))return;let{chart:{fontFamily:p}}=this.axis.pane.presenter.display,m=e=>e.valueOf()>=i[0].valueOf()&&e.valueOf()<=i[1].valueOf(),h=o.flatMap((e,i)=>m(e)?this.getEventsAt(i).map(e=>{let i=Lg(u,e.date),a=A(l,+i,Number);if(a<0||a>=f.length)return null;let o=f[a];if(!Qe(o))return null;t.has(a)||t.set(a,-1);let s=t.get(a);t.set(a,++s);let c=r.timeToX(i),d=n.view.getEventRadius(),p=this.axis.yScale.priceToY(o)-s*(d+d+d);return{visible:!0,...e,x:c,y:p,r:d,rect:Pk}}).filter(M):[]);e.save();let g=!0;h.forEach(t=>{t.rect=ys(e,t,p),this.customEventPopup?.visible&&t.date===this.customEventPopup.date&&(this.showCustomEventPopup(t),g=!1)}),e.restore(),this._eventsData=h,this.customEventPopup?.visible&&g&&this.hideCustomEventPopup()}get customEventPopup(){return this.axis.pane.presenter.view.customEventPopup}hideCustomEventPopup(){this.customEventPopup?.hide()}showCustomEventPopup(e){let{x:t,y:n,r,date:i,value:a}=e;this.customEventPopup?.show({x:t+2*r,y:n-2*r},i,a)}getCustomEventDataAt(e){if(!this.isVisible||!this._eventsData)return null;let t=this._eventsData.find(t=>t.rect.contains(e));return t?.field===W.Custom?t:null}hitTestCustomEvent(e){return this.getCustomEventDataAt(e)!==null}hitTest(e){if(!this.isVisible)return!1;for(let t=0;t<this.curves.length;t++){let n=this.curves[t];if(n.visible&&n.hitTest(e))return!0}return!1}tryHandleCustomEventClick(e){let t=this.getCustomEventDataAt(e);return N(t)?(this.showCustomEventPopup(t),!0):!1}startHoverDim(e){let t=this.presenter?.shouldDimPlot(this)??!1;return t&&(e.save(),e.globalAlpha*=z.PLOT_HOVER_DIM_ALPHA),t}finishHoverDim(e,t){t&&e.restore()}isEmpty(){let e=this.timeSeries;return N(e)&&e.hasData&&e.container.isEmpty}draw(e){if(!this.isVisible)return;let t=this.startHoverDim(e);N(this.levels)&&this.drawLevels(e),N(this.bands)&&this.drawBands(e);for(let t of this.curves)t.draw(e);this.finishHoverDim(e,t)}drawEventsTopmost(e,t){if(!this.isVisible||!this.hasEventsData)return;let n=this.startHoverDim(e);this.drawEvents(e,t),this.finishHoverDim(e,n)}isComparison(e){return this.axis.comparison===e}invalidatePriceMappingCache(){this._firstVisibleDate=null}_priceMapper(e,t,n,r){if(!N(e)||!this.timeSeries.hasData||!this.shouldPriceMap(n,r))return e;let[i,a]=this.axis.pane.presenter.view.xAxis.xScale.domain()||[];if(!N(i)||!zn(i))return e;if(this._firstVisibleDate!==i){this._firstVisibleDate=i;let e=this.timeSeries.container.getTimeData(),t=t=>A(e,+t,Number);this.visFromIndex=t(i),this.visToIndex=t(a),this._priceMapFirstIndex.clear()}return this._priceMapFirstIndex.has(n)||this.canPriceMap(t,n),this.priceMap(e,t,n,!1,r)}isOhlcMapping(e){return this.mainCurve.isOhlc&&jk(e)}getRefPriceMapField(e){return this.isOhlcMapping(e)||e===W.PreviousClose?W.Close:e}dataOf(e){return this.timeSeries.container.getData(e)}canPriceMap(e,t){let n=this.getRefPriceMapField(t),r=this.dataOf(n),i=null,a=this.visFromIndex;for(;i===null&&a<=this.visToIndex;)i=r[a++];this._priceMapFirstIndex.set(n,i===null?NaN:a-1)}priceMap(e,t,n,r=!1,i=x.None){let a=this.getRefPriceMapField(n),o=this._priceMapFirstIndex.get(a);if(!Number.isFinite(o))return e;let s=this.dataOf(a)[o];return this.isComparison(x.Percent)||i===x.Percent?r?s+s*e/100:(e>=s?1:-1)*(Math.abs(e-s)*100)/Math.abs(s):r?s+e:e-s}shouldPriceMap(e,t){return N(t)?t!==x.None:this.isComparison(x.Percent)||this.isComparison(x.Value)}onPriceDomainsUpdated(){}get presenter(){return this.axis?.pane?.presenter}},Ik=class extends Fk{_symbol;_showPrevious;yearOffset;resolved=null;events;inputs=[];_eventsSeries;compare;tracePlot(e,t={}){yg(e,{chartId:this.axis?.pane?.presenter?.elementId,symbol:this.symbol,...t})}get symbol(){return this._symbol}get title(){return this.symbol}get showPrevious(){return this._showPrevious}getPreviousValue(){if(!N(this.timeSeries)||!N(this.timeSeries.record))return null;let e=this.axis.pane.presenter.display.chart.previous.field;return this.timeSeries.record.getValue(W[e])}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=this.makeQuery();switch(t.symbol=this.symbol,this.mainCurve.style){case h.Renko:case h.Kagi:case h.PointAndFigure:t.barsToFetch=10100,t.inputs=this.inputs;break;case h.Range:t.barsToFetch=4e3;break;case h.LineBreak:t.inputs=this.inputs}let n=this.axis.pane;if(N(n.alignedToYear)){let e=Yi(this.resolved??t.symbol);e!==null&&(this.yearOffset=n.alignedToYear-e.getFullYear(),t.offset=this.yearOffset)}let r=e.getTimeSeries(t);this.timeSeries=this.wrapIfAdvancedStyle(r),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:ie.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e),this.getEvents()}})}getMetaData(){let e=$().getMetaDataSource();this.metaData=e.getMetaData(this.resolved),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}getEvents(){if(!this.hasEvents)return;let e=$().getTimeSeriesDataSource(),t={symbol:this.symbol,seriesKind:C.Events,getHashKey:function(){return Object.values(this).filter(e=>typeof e!=`function`).join(`|`)}};z.EVENTS.forEach(e=>{t[e]=it(this.events,!1,e,`show`)}),this._eventsSeries=e.getTimeSeries(t),this._eventsSeries.ready().then(e=>{e&&this.presenter?.notifyHost(G.TS_EVENTSCHANGED,{series:this.eventsSeries})})}get eventsSeries(){return this._eventsSeries??null}get hasEvents(){return N(this.events)?z.EVENTS.some(e=>it(this.events,!1,e,`show`)):!1}findEvents(e){if(!this.hasEventsData||e[0]===null||e[1]===null)return[];let t=e[0],n=e[1];if(n>0&&this.axis?.pane?.presenter?.data?.aggregation?.isIntraday){let e=this.timeSeries.container.getTimeData()[n-1];if(this.compare(e,t))return[]}return this.eventsSeries.container.getTimeData().map((e,n)=>this.compare(e,t)?this.getEventsAt(n):[]).flat()}fromModel(e){super.fromModel(e);let t=e;this._showPrevious=t.showPrevious,this.events=t.events,this.inputs=t.inputs||[],this.compare=pd(this.axis.pane.presenter.data.aggregation),this._symbol=t.symbol}getEventFor(e){let t=this.events[e.id.toLowerCase()];return!N(t)||!t.show?null:t}async initialize(){return ma.call(this,async()=>(this.tracePlot(`plot:init:start`),this.resolved=await Di(this.symbol),this.isShutDown?(this.tracePlot(`plot:init:aborted`,{resolved:this.resolved}),!1):(this.getMetaData(),this.getTimeSeries(),this.tracePlot(`plot:init:ready`,{resolved:this.resolved}),!0)))}},Lk=class extends Ik{seriesKind;fundamental;constructor(e){super(),this.seriesKind=e}get showPrevious(){return!1}get title(){return`${this.curves[0].fields[0].name}(${g[this.fundamental].substring(0,1)})`}fromModel(e){this.fundamental=g[e.fundamental],super.fromModel(e)}makeQuery(){let e=new Fb(this.symbol,new yd(this.fundamental),this.seriesKind);return e.fields=this.curves[0].fields,e}},Rk=class{longPressTimeout;constructor(){this.longPressTimeout=null}getTouchCrosshairDelayMillis(){let e=$().config.touchCrosshairDelayMillis;return N(e)&&Number.isFinite(e)?e:z.LONG_PRESS_DELAY_MILLIS}startLongPress(e,t,n){Le()&&(this.longPressTimeout=setTimeout(()=>this.longPressTriggered(e,t,n),this.getTouchCrosshairDelayMillis()))}longPressTriggered(e,t,n){this.cancelLongPress(),this.performLongPress(e,t,n)}cancelLongPress(){Le()&&N(this.longPressTimeout)&&(clearTimeout(this.longPressTimeout),this.longPressTimeout=null)}performLongPress(e,t,n){}};function zk(e){return e.locked||e.axis.pane.presenter.display.allAnnotationsLocked}var Bk=class extends Rk{annotation;previous;onLongPress;cursorSet;moved;snapToSupported;constructor(e,t,n,r){super(),this.annotation=e,this.previous=t,this.onLongPress=r,this.cursorSet=!1,this.moved=!1,this.snapToSupported=!1,this.startLongPress(null,t,n)}performLongPress(e,t,n){this.onLongPress?this.onLongPress():RA(this.annotation,n)}onMouseMove(e){if(this.cancelLongPress(),this.annotation.axis.pane.presenter.enableTooltip(!1),zk(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!t||t.axis.pane!==this.annotation.axis.pane)return;let i=this.annotation.axis.toAnnotationPoint(r);if(!M(i)||i.axis!==this.annotation.axis)return;n.drawCrosshair({ap:i,offset:r}),this.cursorSet||=(this.previous.axis.pane.presenter.view.setCursor(te.Move),!0);let a=Lo(i.point,this.previous.point);this.annotation.offset(a),this.annotation.wasModifiedByTool(),this.annotation.requestRedraw(),this.previous=i,this.moved=!0}onMouseUp(e){this.cancelLongPress(),yM(this.annotation,this.moved,D.Moved)}},Vk=class{annotation;pointIndex;snapToSupported=!0;moved=!1;alignPointsMode=!1;constructor(e,t){this.annotation=e,this.pointIndex=e.points.indexOf(t)}onMouseMove(e){if(this.alignPointsMode=e.getModifier(E.Shift),this.annotation.axis.pane.presenter.enableTooltip(!1),zk(this.annotation))return;let{point:t,view:n,offset:r}=e;if(!t||t.axis.pane!==this.annotation.axis.pane)return;let i=this.annotation.axis.toAnnotationPoint(r);if(n.drawCrosshair({ap:i,offset:r}),N(i)){let e=this.annotation.points[this.pointIndex],t=Lo(i.point,e.point);switch(e.moveDirection){case ne.Both:e.update(i.price,i.time);break;case ne.Horizontal:e.update(e.price,i.time);break;case ne.Vertical:e.update(i.price,e.time)}this.moved=e.moveDirection!==ne.None,this.moved&&this.annotation.wasPointMovedByTool(e,t)}this.annotation.requestRedraw()}onMouseUp(e){yM(this.annotation,this.moved,D.PointMoved)}},Hk=class{anchor;isVertical;axis;constructor(e,t,n){this.anchor=e,this.isVertical=t,this.axis=n}hitTest(e){return N(this.anchor)?this.isVertical?Math.abs(e.x-this.anchor.x)<=z.HIT_TEST_TOLERANCE:Math.abs(e.y-this.anchor.y)<=z.HIT_TEST_TOLERANCE:!1}draw(e){let t=z.OUT_OF_SCREEN;this.isVertical?_s(e,this.anchor.x,-t,t):vs(e,this.anchor.y,-t,t)}},Uk=class{id;axis;_price;_time;passive=!1;moveDirection=ne.Both;visible=!0;point;constructor(e,t,n){this.id=xt(),this.axis=e,t!==void 0&&n!==void 0&&(this.price=t,this.time=n,this.toPoint())}get price(){return this._price}set price(e){this._price=e}get time(){return this._time}set time(e){this._time=e}get movable(){return this.moveDirection!==ne.None}get presenter(){return this.pane.presenter}get pane(){return this.axis.pane}toPoint(){let e=this.axis.toPoint(this);N(e)&&Qe(e.x)&&Qe(e.y)&&(this.point=e)}update(e,t){this.price=e,this.time=typeof t==`number`?new Date(t):t,this.toPoint()}updateFromPoint(e){let t=this.axis.toAnnotationPoint(e);this.price=t.price,this.time=t.time,this.point=e}hitTest(e){return this.visible?this.distance(e)<=z.HIT_TEST_TOLERANCE:!1}distance(e){let t=e.x-this.point.x,n=e.y-this.point.y;return Math.abs(Math.sqrt(t*t+n*n)-z.HALF_ANN_POINT_DIMENSION)}draw(e,t){if(N(this.point)){let n=z.HALF_ANN_POINT_DIMENSION;N(t)&&t.locked&&(n*=.6),e.beginPath(),e.ellipse(this.point.x,this.point.y,n,n,0,0,2*Math.PI),e.stroke()}}};function Wk(e){return Yo(e.fill.color).a===0?e.line.color:e.fill.color}function Gk(e,t){return{owner:e.axis.annotationUndoOwner,position:e.axis.findIndex(e),uid:e.uid,id:e.name,traits:{...e.extractTraits(!0),...e.extractTraits(!1)},extras:{},points:e.extractPoints(),visible:e.visible,locked:e.locked,isUndoRedo:!0,toolChange:t}}function Kk(e){return{uid:e.uid,id:e.name,traits:e.extractTraits(!0),extras:e.extractTraits(!1),points:e.extractPoints(),visible:e.visible,locked:e.locked,chart:e.axis.pane.presenter.accessor}}var qk=class{points=[];isSelected=!1;drawn=!0;axis;name;uid;alignPointsSupported=!1;visible=!0;locked=!1;computed=!1;_traits;adjustFill;constructor(e,t){this.axis=e,this.name=t,this.uid=xt()}requestRedraw(){this.axis.pane.presenter.view?.redraw()}prepareDraw(e,t){let n=!this.isSelected||!this.axis.pane.presenter.annotationManipulation;return this.drawPoints(e,t,n),this.readyToDraw()}readyToDraw(){return this.activePoints.every(e=>e.point!==void 0)}getPriceScaleAdornments(){return z.EMPTY_ARRAY}getTimeScaleAdornments(){return z.EMPTY_ARRAY}extractTraits(e=!0){let t=P(this.traits),n=vc(this.name);return Object.keys(t).forEach(r=>{let i=n.includes(r);(e&&!i||!e&&i)&&delete t[r]}),e||[`line`,`fill`,`zIndex`].forEach(e=>delete t[e]),t}extractPoints(){return this.activePoints.map(e=>({price:e.price,time:Ze(+e.time,4)}))}offset(e){this.points.filter(e=>e.movable).forEach(t=>{t.updateFromPoint(Ro(t.point,e))})}get traits(){return this._traits||=P(this.defaultTraits),this.adjustFill&&=(this._traits.fill.color=Wk(this._traits),!1),this._traits}set traits(e){e!==void 0&>(this.traits,e)}get activePoints(){return this.points.filter(e=>!e.passive)}get style(){return Ks(this.traits)}get defaultTraits(){return Ws(this.axis.pane.presenter.display,this.name)}get defaultStyle(){return Ks(this.defaultTraits)}get isVisible(){return Ek(this,this.axis.pane.presenter.display)}get adornStyle(){let e=P(this.defaultTraits);return e.fill.color=this.traits.line.color,e.line.width=0,e.line.color=z.COLOR_TRANSPARENT,Ks(e)}get pointsStyle(){let e=P(this.defaultTraits);return e.line.dashStyle=`Solid`,Ks(e)}get allowPricesChangeUI(){return this.traits?.allowPricesChangeUI}wasModifiedByTool(){}wasPointMovedByTool(e,t){}onFormatterChanged(){}isPointDrawn(e){return e.price!==void 0}drawPoints(e,t,n=!0){this.isVisible&&this.points.forEach(r=>{let i=this.isPointDrawn(r),a=N(e);t&&(i||!a)&&r.toPoint(),n&&a&&i&&(this.isSelected||this.drawn)&&(Gs(e,this.pointsStyle),r.draw(e,this))})}addPoints(e){for(let t=0;t<e;t++)this.points.push(new Uk(this.axis))}toModel(){let e=this.extractPoints();return{id:this.name,uid:this.uid,visible:this.visible,locked:this.locked,points:e,traits:P(this.traits)}}canMove(e){return!0}updatePoints(e){}updateActivePoints(e){let t=this.activePoints;t.length===e.length&&t.forEach((t,n)=>{let r=e[n];t.update(r.price,r.time)})}updateFrom(e,t,n,r,i){typeof r==`boolean`&&(this.visible=r),typeof i==`boolean`&&(this.locked=i);let a=N(e)?P(e):{};N(t)&>(a,t),this.traits=a,N(n)&&this.updatePoints(n)}priceMap(e){return this.axis.priceMap(e)}flip(e){let t=this.getFlipAnchorIndices();if(!M(t))return;let n=this.points[t[0]],r=this.points[t[1]];if(e){let e=r.time;r.update(r.price,n.time),n.update(n.price,e)}else{let e=r.price;r.update(n.price,r.time),n.update(e,n.time)}this.wasModifiedByTool()}getFlipAnchorIndices(){return null}};function Jk(e,t,n,r){return function(i,a=!0){let o=new t(i,e,n);return a?i.appendAnnotation(o):o.drawn=!1,N(r)&&(o.traits=r),o}}var Yk=class{axis;angle;extent;anchor1;anchor2;p1;p2;style;extended;_data;isTrend;constructor(e,t,n,r,i){this.axis=i,N(e,t)&&(this.angle=zo(e,t),this.extent=this.getExtent(e,t),this.anchor1=e,this.anchor2=t,this.p1=n?this.extendPoint(t,-1):e,this.p2=r?this.extendPoint(e,1):t),this.extended=n||r}extendPoint(e,t){return{x:e.x+t*this.extent*Math.cos(this.angle),y:e.y+t*this.extent*Math.sin(this.angle)}}getExtent(e,t){let n=Math.max(Math.abs(e.x),Math.abs(t.x)),r=Math.max(Math.abs(e.y),Math.abs(t.y));return Math.sqrt(n*n+r*r)+z.OUT_OF_SCREEN}hitTest(e){return N(this.p1,this.p2)?Bo([this.p1,this.p2],e,z.HIT_TEST_TOLERANCE):!1}draw(e){N(this.p1,this.p2)&&(gs(e,this.p1,this.p2),this.extended)}getAdornOffset(e){let t=us(e),n=cs(e,1);return Po(this.p1,this.p2)<0&&(t.y=n+5),t}},Xk=class{style;axis;rect;constructor(e,t,n,r){this.axis=r,this.rect=new rs(e.x,e.y,t,n)}hitTest(e){return this.rect.contains(e)}draw(e,t){ms(e,this.rect)}},Zk=class extends qk{countCache;constructor(e,t){super(e,t)}draw(e,t){if(this.isVisible&&this.prepareDraw(e,t)&&!this.getScreenPoints().some(e=>!N(e))&&!this.drawn){let t=this.getElements();Gs(e,this.style),t.forEach((t,n)=>{Gs(e,this.getStyleForElement(t,n)),t.draw(e)}),Gs(e,this.adornStyle),this.adornElements(t,e);let n=this.getMarkers();Gs(e,this.style),n.forEach(t=>{t.draw(e)})}}getBarCount(e,t){if(this.countCache===void 0||this.countCache.time1!==e||this.countCache.time2!==t){let n=this.axis.pane.presenter.view,r=Math.abs(n.toIndex(e)-n.toIndex(t));this.countCache={time1:e,time2:t,barCount:r}}return this.countCache.barCount}getElements(){return[]}get presenter(){return this.axis.pane.presenter}get formatter(){return this.presenter.mainPlot.metaData}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}getScreenPoints(){return this.points.map(e=>e.point)}getStyleForElement(e,t){return this.style}adornElements(e,t){}hitTestAdornments(e,t){return!1}getTextRef(){return null}hitTest(e){if(!this.drawn&&this.isVisible){if(this.getScreenPoints().some(e=>!N(e)))return!1;let t=this.getElements(),n=this.getMarkers();return t.some(t=>t.hitTest(e))||n.some(t=>t.hitTest(e))?!0:this.hitTestAdornments(t,e)}return!1}updatePointsFrom(e,t=0){e.forEach((e,n)=>this.points[t+n].update(e.price,e.time))}updatePoints(e){this.allowPricesChangeUI&&this.updatePointsFrom(e)}getMarkers(){return[]}get marker(){return this.traits?.marker}get showPrices(){return this.traits?.showPrices}get singleStyle(){return nt(this.traits?.singleStyle,!0)}get showBackground(){return nt(this.traits?.showBackground,!1)}get backgroundOpacity(){return nt(this.traits?.backgroundOpacity,0)}fillOnlyStyle(e){return Ks({line:{color:z.COLOR_TRANSPARENT,dashStyle:`Solid`,width:0},fill:this.traits[e]})}lineOnlyStyle(e){return Ks({fill:{color:z.COLOR_TRANSPARENT},line:this.traits[e]})}makeLine(e,t){return new Yk(e,t,!1,!1,this.axis)}applyBackgroundOpacity(e){return Uo(Ho(e),this.backgroundOpacity)}getTraitsFor(e){let t={fill:{color:z.COLOR_TRANSPARENT},line:{...e.line}};return this.showBackground&&(t.fill.color=this.applyBackgroundOpacity(t.line.color)),t}getFlipAnchorIndices(){return this.points.length===2?[0,1]:null}},Qk=class extends Zk{_factors;constructor(e,t){super(e,t)}get factorsPropName(){return z.AT_FACTORS}get factors(){return zs(this._factors??this.traits[this.factorsPropName])}getStyleForElement(e,t){return e.style??super.getStyleForElement(e,t)}get showLevels(){return this.traits[z.AT_SHOW_LEVELS]}get levelsKind(){return this.traits[z.AT_LEVELS_KIND]}get labels(){return this.traits[z.AT_LABELS]}get isExtended(){return this.points.length===3}isBefore(e,t){return this.points[e].time<this.points[t].time}comparePoints(e,t,n){let r=this.isBefore(e,t);return n||(r=!r),this.points[r?e:t].point}getPoint(e){return this.isExtended?this.comparePoints(1,2,e):this.comparePoints(0,1,e)}get leftPoint(){return this.getPoint(!0)}get rightPoint(){return this.getPoint(!1)}get pricesOnScale(){return this.traits[z.AT_PRICES_ON_SCALE]}formatLevelPrice(e,t){let n=this.levelsKind===z.AT_LEVELS_PERCENTS,r=``;if(this.showLevels&&(r=n?`${(e*100).toFixed(1)}%`:e.toString()),this.showPrices){let e=this.priceMap(this.axis.toPrice(t));r=(r+` (${Bv(this.axis,e)})`).trim()}return r}getAdornPointAndAlign(e,t){let n=this.labels,r=e instanceof Yk,i=(e,t,n)=>({pt:e,align:t,offset:n});switch(n){case z.AT_LABELS_LEFT:return i(r?e.anchor1:e,w.Right,-t);default:case z.AT_LABELS_RIGHT:return i(r?e.anchor2:e,w.Left,t);case z.AT_LABELS_CENTER:return i(r?No(e.anchor1,e.anchor2):e,w.Center,0)}}getColoredElements(e){let t=this.singleStyle;return this.factors.map(n=>{let r=e(n);return r===null?null:(t||(r.style=Ks(this.getTraitsFor(n))),r._data={factor:n.value},r)}).filter(e=>e!==null)}hitTestAdornments(e,t){let n=this.showLevels,r=this.getTextRef();if(!n||r===null)return!1;let i=this.axis.pane.presenter,a=i.view?.mainContext;if(!a)return!1;let o=null,s=!1;a.save();let{chart:{fontFamily:c},yAxis:{fontSize:l}}=i.display;a.font=`${l??12}px ${c}`;for(let n of e){if(!N(n._data))continue;let{factor:e}=n._data,{ref:i,spacing:c,offsetY:l,text:u}=r(o,n,e),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(i,c);if(ds(a,u,this.getAdornTextPoint(a,l,d,p),f).contains(t)){s=!0;break}o=n}return a.restore(),s}adornElementsForColoredFactors(e,t,n,r){let i=this.singleStyle,a=this.showBackground,o=this.showLevels,s=this.applyBackgroundOpacity(this.traits.line.color),c=r.fillStyle,l=null;e.forEach(e=>{if(!N(e._data))return;let{factor:u}=e._data;if(a){let n=t(l,e);r.fillStyle=i?s:e.style.fillStyle,r.fill(n)}if(o){let{ref:t,spacing:a,offsetY:o,text:s}=n(l,e,u),{pt:d,align:f,offset:p}=this.getAdornPointAndAlign(t,a);fs(r,s,this.getAdornTextPoint(r,o,d,p),f,i?c:e.style.strokeStyle)}l=e})}getAdornTextPoint(e,t,n,r){let i=cs(e,.75);return Ro(n,{x:r,y:t===!0?i/2:t})}},$k=class extends Zk{lines;constructor(e,t){super(e,t),this.resetComputedState()}get rectStyle(){return this.fillOnlyStyle(z.AT_FILL)}get rect(){let[e,t,,]=this.getScreenPoints(),n=new Xk({x:e.x,y:Math.min(e.y,t.y)},t.x-e.x,Math.abs(e.y-t.y),this.axis);return n.style=this.rectStyle,n}get reverse(){return!1}getLinesDataAtLevels(e,t){let[n,r]=this.points;if(this.reverse&&([n,r]=[r,n]),this.lines==null){let i=(e,t=!1)=>n=>({level:n.value,domain:e(n.value),traits:this.getTraitsFor(n),isPrice:t}),a=r.price-n.price,o=i(e=>n.price+e*a,!0),s=e?.map(o)??[],c=this.axis.pane.presenter.timeline,l=A(c,+n.time,Number,Jv),u=A(c,+r.time,Number,Jv)-l,d=i(e=>+c.at(l+Math.floor(e*u))),f=t?.map(d)||[];this.lines={prices:s,times:f,barsDiff:u,priceDiff:a}}return this.lines}makeColoredLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=Ks(n.traits)),r._data={level:n.level,isPrice:n.isPrice},r}getLineElements(e){let[t,n]=this.getScreenPoints();return{priceLines:e.prices.map(e=>{let r=this.axis.toY(e.domain);return this.makeColoredLine({x:t.x,y:r},{x:n.x,y:r},e)}),timeLines:e.times.map(e=>{let r=this.presenter.view.toX(e.domain);return this.makeColoredLine({x:r,y:t.y},{x:r,y:n.y},e)})}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}resetComputedState(){}wasModifiedByTool(){this.resetComputedState()}wasPointMovedByTool(e,t){this.wasModifiedByTool()}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},eA=class extends Uk{priceRef;timeRef;constructor(e,t,n){super(e),this.priceRef=t,this.timeRef=n,this.passive=!0}get price(){return this.priceRef.price}get time(){return this.timeRef.time}set price(e){this.priceRef.price=e}set time(e){this.timeRef.time=e}},tA=class{points;constructor(e){this.points=e}get left(){return Math.min(this.points[0].point.x,this.points[1].point.x)}get top(){return Math.min(this.points[0].point.y,this.points[1].point.y)}get width(){return Math.abs(this.points[1].point.x-this.points[0].point.x)}get height(){return Math.abs(this.points[1].point.y-this.points[0].point.y)}getRect(){return N(this.points[0].point,this.points[1].point)?new rs(this.left,this.top,this.width,this.height):null}};function nA(e){let t=new Uk(e),n=new Uk(e);return[t,n,new eA(e,t,n),new eA(e,n,t)]}var rA=class extends qk{helper;constructor(e,t){super(e,t),this.points=nA(e),this.helper=new tA(this.points)}get left(){return this.helper.left}get top(){return this.helper.top}get width(){return this.helper.width}get height(){return this.helper.height}getRect(){return this.helper.getRect()}draw(e,t){return!this.isVisible||!this.prepareDraw(e,t)?!1:(Gs(e,this.style),!0)}updatePoints(e){this.allowPricesChangeUI&&e.length===2&&e.forEach((e,t)=>this.points[t].update(e.price,e.time))}},iA=class{points;lines;axis;helper;_actualWidth=0;_fontSizeForWidth=0;constructor(e,t,n){this.points=e,this.lines=t,this.axis=n,this.helper=new tA(this.points)}hitTest(e){let t=this.getRect();return M(t)?(t.width=this._actualWidth,t.contains(e)):!1}getRect(){return this.helper.getRect()}get fontSize(){if(this.lines.length===0)return 0;let{height:e}=this.getRect();return Math.floor(e/this.lines.length)}computeActualWidth(e){(this._actualWidth<=0||this._fontSizeForWidth!==this.fontSize)&&(this._actualWidth=Math.max(...this.lines.map(t=>e.measureText(t).width)),this._fontSizeForWidth=this.fontSize)}draw(e){if(this.lines.length===0)return;e.save();let{x:t,y:n}=this.getRect(),{chart:{fontFamily:r}}=this.axis.pane.presenter.display,i=this.fontSize;e.textAlign=`left`,e.textBaseline=`top`,e.font=`${i}px ${r}`,this.lines.forEach((r,a)=>{let o=i*a,s=n+o;e.fillText(r,t,s)}),this.computeActualWidth(e),e.restore()}},aA=class extends Zk{textEditable;_textAnnElement;constructor(e,t){super(e,t),this.textEditable=!0,this.points=nA(e),this.adjustFill=!0}get textLines(){return this.traits[z.AT_TEXT_LINES]}set textLines(e){this.traits[z.AT_TEXT_LINES]=e,this._textAnnElement=void 0}get textElement(){return!N(this._textAnnElement)&&this.isVisible&&(this._textAnnElement=new iA(this.points,this.textLines,this.axis)),this._textAnnElement}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),this._textAnnElement=void 0}getElements(){return this.isVisible?[this.textElement]:[]}},oA=class extends aA{constructor(e,t){super(e,t),this.textEditable=!1}canMove(e){return this.isVisible?this.textElement.hitTest(e):!1}get prices(){return this.traits.prices}get pricesPoints(){let e=this.points[0].time;return this.prices.map(t=>new Uk(this.axis,t,e))}updateFrom(e,t,n,r,i){super.updateFrom(e,t,n,r,i),N(e?.textLines)&&(this.textLines=e.textLines)}getElements(){let e=super.getElements(),t=this.pricesPoints.map(e=>new Hk(e.point,!1,this.axis));return e.concat(t)}getPriceScaleAdornments(){if(!this.showPrices)return super.getPriceScaleAdornments();let e=this.traits.line;return this.prices.map(t=>({price:t,color:e.color}))}get defaultFont(){let{chart:{fontSize:e,fontFamily:t}}=this.axis.pane.presenter.display;return[e??13,t]}updateOtherPoints(e){let[t,n]=this.defaultFont;e.save(),e.font=`${t}px ${n}`;let r=Math.max(...this.textLines.map(t=>e.measureText(t).width)),{x:i,y:a}=this.points[0].point;this.points[1].updateFromPoint({x:i+r,y:a+this.textLines.length*t}),e.restore()}},sA=class{annId;annotation;constructor(e){this.annId=e}onKeyDown(e){if(this.annId==null)return;let{key:t,code:n,presenter:r}=e;ze(t,n)&&(N(this.annotation)&&(this.annotation.axis.deleteAnnotation(this.annotation,!1),r.view.redraw()),vM(r,{toolChange:D.Cancelled,annId:this.annId}))}},cA=class extends sA{factory;thirdPoint;dragged=!1;snapToSupported=!0;isDrawingAnnotation=!0;forceAlignPoints=!1;indices;alignPointsMode=!1;constructor(e,t=!1){super(e.annName),this.factory=e,this.thirdPoint=t,this.indices=t?[0,1,2]:[0,1]}signalChange(){this.annotation.wasModifiedByTool(),this.annotation.requestRedraw()}updatePoint(e,t){this.annotation.points[t].update(e.price,e.time)}onMouseDown(e){let{point:t,button:n}=e;if(t===void 0)return;let r=M(this.annotation);if(n===T.Left){if(this.alignPointsMode=this.forceAlignPoints||e.getModifier(E.Shift),r){let e=!this.thirdPoint||this.dragged?1:2;this.updatePoint(t,e),this.signalChange();let n=e=>this.annotation.points[e].point;if(!Io(n(e-1),n(e)))return!0;this.dragged=!1,(!this.thirdPoint||e===2)&&this.finish()}else this.dragged=!0,t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis),this.annotation.drawn=!1,this.indices.forEach(e=>this.annotation.points[e].update(t.price,t.time)),this.signalChange()}return!0}onMouseMove(e){let{point:t,view:n,offset:r}=e;return n.drawCrosshair({ap:t,offset:r}),N(this.annotation,t)&&(this.alignPointsMode=this.forceAlignPoints||e.getModifier(E.Shift),this.dragged?(this.updatePoint(t,1),this.signalChange()):this.thirdPoint&&!this.dragged&&(this.updatePoint(t,2),this.signalChange())),!0}finish(){yM(this.annotation,!0,D.Created)}isAccidentalMouseUp(e){let{point:t}=e,[n,r]=this.annotation.points,i=n.point,a=t?.point;return!Io(i,r.point)||a!==void 0&&!Io(i,a)}onMouseUp(e){this.annotation===void 0?bM(e):this.dragged&&(this.isAccidentalMouseUp(e)?this.dragged=!0:(this.dragged=!1,this.thirdPoint||this.finish()))}},lA=class extends cA{constructor(e,t=!1){super(e,t),this.forceAlignPoints=!0}},uA=class extends cA{constructor(e){super(e,!1),this.snapToSupported=!1}updatePoint(e,t){super.updatePoint(e,t);let[n,r]=this.annotation.points,i=Lo(r.point,n.point),a=n.point.y+i.x*Math.sign(i.y)*Math.sign(i.x),o=this.annotation.axis.toPrice(a);r.update(o,e.time)}},dA=class extends sA{factory;existing;isNew;anchor;clicks=0;snapToSupported=!1;isDrawingAnnotation;textArea;constructor(e,t){super(e?e.annName:null),this.factory=e,this.existing=t,this.isNew=!N(t),this.isNew||(this.anchor=this.existing.points[0]),this.isDrawingAnnotation=this.isNew}getChartParent(){return this.anchor.axis.pane.presenter.view.canvasContainer}styleProps(){if(this.isNew)return{height:100,fontSize:`100%`,color:Wk(Ws(this.anchor.axis.pane.presenter.display,`Text`))};{let e=this.existing.textElement;return{height:e.getRect().height*1.05,fontSize:`${Math.round(e.fontSize)}px`,color:this.existing.traits[z.AT_FILL].color}}}onMouseDown(e){let{point:t}=e;if(this.isNew){if(this.clicks===0){if(t===void 0){bM(e);return}t.axis.pane.presenter.clearSelection(),this.anchor=t,this.clicks++,this.startEditing()}else this.onEndEditing()}else this.onEndEditing()}startEditing(){this.textArea=document.createElement(`textarea`);let{x:e,y:t}=this.anchor.point,n=this.anchor.axis.pane.getBounds(),r=n.x+n.width-this.anchor.point.x,{height:i,fontSize:a,color:o}=this.styleProps();oa(this.textArea,{position:`absolute`,top:`${t}px`,left:`${e}px`,border:`none`,outline:`none`,overflow:`hidden`,height:`${i}px`,width:`${r}px`,resize:`none`,backgroundColor:`rgba(255, 255, 255, 0.05)`,zIndex:`5`,fontSize:a,color:o}),this.getChartParent().appendChild(this.textArea),this.textArea.onblur=this.onEndEditing.bind(this),this.textArea.onkeydown=e=>e.stopImmediatePropagation(),this.isNew||(this.textArea.value=this.existing.textLines.join(`
|
|
38
38
|
`),this.existing.textLines=[``],this.existing.requestRedraw()),setTimeout(()=>this.textArea.focus(),100)}onEndEditing(){let e=this.anchor,t=this.isNew?this.factory(e.axis):this.existing,n=this.textArea.value.split(`
|
|
39
39
|
`);if(this.isNew){let{actualWidth:r,actualHeight:i}=this.getTextDimensions(n);t.points[0].update(e.price,e.time);let{x:a,y:o}=t.points[0].point;t.points[1].updateFromPoint({x:a+r,y:o+i}),t.drawn=!1}t.textLines=n,this.textArea.onblur=null,this.getChartParent().removeChild(this.textArea),t.requestRedraw(),this.isNew||t.requestRedraw(),yM(t,!0,this.isNew?D.Created:D.TextChanged)}getTextDimensions(e){let t=globalThis.getComputedStyle(this.textArea).getPropertyValue(`font-size`),n=parseFloat(t)*e.length,r=0,i=this.anchor.axis.pane.presenter,a=i.view.mainContext;a.save();let{chart:{fontFamily:o}}=i.display;a.font=`${t} ${o}`;for(let t=0;t<e.length;t++){let n=a.measureText(e[t]).width;n>r&&(r=n)}return a.restore(),{actualWidth:r,actualHeight:n}}};function fA(e){return $().config.tooltipMovement===e}function pA(){return fA(`Draggable`)}function mA(){return fA(`Auto`)}var hA=z.TOOLTIP_STD_LEGACY_CLASS,gA=z.TOOLTIP_STD_CLASS,_A=z.TOOLTIP_BUBBLE_CLASS;function vA(e,t){let n=e.filter(e=>!e.isHidden),r=e=>M(e.val)&&Number.isFinite(e.y),i=n.find(e=>e.isMain)||n[0],a=i?.values.find(e=>[`Close`,`Last`].includes(e.id)&&r(e))?.y??i?.values.find(r)?.y??t,o=n.map(e=>e.values.filter(e=>e.id!==`Change`&&e.y>0&&r(e)).map(e=>e.y)).flat(),[s,c]=o.length>0?[Math.min(...o),Math.max(...o)]:[a,a];return{plots:n,y:a,yMin:s,yMax:c,hasData:n.some(e=>e.values.some(r))}}var yA=class{view;tooltipElem;leftSide;mode;isDrag=!1;layoutTop=0;canDrag;isToggling;constructor(e){this.view=e,this.tooltipElem=ua(e.el,`div`),sa(this.tooltipElem,{id:`${e.presenter.elementId}-global-tooltip`,class:`${gA} ${hA}`}),this.leftSide=!0,oa(this.tooltipElem,{visibility:`hidden`,position:`absolute`,cursor:pA()?`move`:`default`,zIndex:20,top:`${z.TOOLTIP_Y_OFFSET}px`,left:`${z.TOOLTIP_X_OFFSET}px`}),this.setMode(e.presenter.display.tooltip.mode),this.handleMouseMove=this.handleMouseMove.bind(this),this.startDrag=this.startDrag.bind(this),this.stopDrag=this.stopDrag.bind(this),this.view.el.addEventListener(`mousemove`,this.handleMouseMove),this.view.el.addEventListener(`mouseleave`,this.stopDrag),this.tooltipElem.addEventListener(`mousedown`,this.startDrag),this.tooltipElem.addEventListener(`mouseup`,this.stopDrag)}startDrag(){this.isDrag=!0}stopDrag(){this.isDrag=!1}setMode(e){if(this.mode!==e){if(this.mode=e,e===z.TOOLTIP_BUBBLE)this.canDrag=!1,this.tooltipElem.style.transition=`none`,this.tooltipElem.classList.remove(gA,hA),this.tooltipElem.classList.add(_A),oa(this.tooltipElem,{pointerEvents:`none`});else if(e===z.TOOLTIP_STD){this.canDrag=pA(),this.tooltipElem.classList.remove(_A),this.tooltipElem.classList.add(gA,hA);let e=z.TOOLTIP_TOGGLE_SIDE_ANIM_MS;this.layoutTop=this.view.xAxis?.contentBounds?.y??0,oa(this.tooltipElem,{pointerEvents:`all`,top:`${this.layoutTop+z.TOOLTIP_Y_OFFSET}px`,left:`${z.TOOLTIP_X_OFFSET}px`,transition:mA()?`left ${e}ms ease-out`:null})}}}show(e,t){let n=this.tooltipElem;if(t){let{width:e,height:r,leftOffset:i,rightOffset:a}=this.view,o=n.getBoundingClientRect(),s=o.width/2,c=n.style,l=r*z.TOOLTIP_BUBBLE_OFFSET,u=t.yMin-o.height-l,d=t.x-s,f=t.yMax+l,p=f+o.height,m=this.view.xAxis?.contentBounds,h=m?.y??0,g=m?m.y+m.height:r,_=u<h?p<g?f:h:u,v=d,y=e-a;v<i?v=i:v+o.width>y&&(v=y-o.width),c.top=`${_}px`,c.left=`${v}px`}n.style.visibility===`hidden`&&(n.style.visibility=`visible`),fa(n,e)}hide(){this.tooltipElem.style.visibility=`hidden`}remove(){this.view.el.removeEventListener(`mousemove`,this.handleMouseMove),this.view.el.removeEventListener(`mouseleave`,this.stopDrag),this.tooltipElem.removeEventListener(`mousedown`,this.startDrag),this.tooltipElem.removeEventListener(`mouseup`,this.stopDrag),ia(this.tooltipElem)}reposition(e,t){oa(this.tooltipElem,{left:`${e}px`,top:`${t}px`})}isAutoMove(){return this.mode===z.TOOLTIP_STD&&mA()}handleMouseMove(e){if(this.isDrag&&this.canDrag){let{movementX:t,movementY:n}=e,{top:r,left:i}=this.tooltipElem.style,a=parseInt(r)+n,o=parseInt(i)+t;this.reposition(o,a)}else if(this.isAutoMove()){let t=this.tooltipElem.getBoundingClientRect(),n=this.view.el.getBoundingClientRect(),r=e.pageX,i=z.TOOLTIP_TOGGLE_DISTANCE_TOLERANCE,a=n.width>t.width*2,o=r>t.x&&r<=t.right+i,s=r<t.x&&r>=t.x-i;a&&(o||s)&&this.toggleSide()}}repositionForLayout(){let e=this.view.xAxis?.contentBounds?.y??0;if(this.mode===z.TOOLTIP_STD&&e!==this.layoutTop){let t=parseFloat(this.tooltipElem.style.top),n=Number.isFinite(t)?t:z.TOOLTIP_Y_OFFSET;this.tooltipElem.style.top=`${n+e-this.layoutTop}px`}this.layoutTop=e}repositionAuto(){if(this.isAutoMove()){let e=this.view.presenter.mainPane.getBoundsWithoutScales(),t=parseFloat(this.tooltipElem.style.top),n=e.x+(this.leftSide?z.TOOLTIP_X_OFFSET:e.width-this.tooltipElem.offsetWidth-z.TOOLTIP_X_OFFSET);this.reposition(n,t)}}toggleSide(){this.isToggling||(this.isToggling=!0,setTimeout(()=>this.isToggling=!1,z.TOOLTIP_TOGGLE_SIDE_ANIM_MS),this.leftSide=!this.leftSide,this.repositionAuto())}};function bA(e){e.showTooltip&&xA(e,{time:z.ZERO_DATE,offset:z.OFFSCREEN_OFFSET,price:0,lastBarRefresh:void 0,justMain:void 0})}function xA(e,{time:t,lastBarRefresh:n,justMain:r,offset:i,price:a}){let o=vy(e,t,i,n,r,a),{mode:s,showMainPlot:c,hideSymbols:l,revealingClose:u}=e.display.tooltip,{includeTimestamp:d,showMainPlot:f,showPlotActions:p}=$().config.tooltipHeaders||{},m=N(f)?f:c,h=N(d)?d:!1,g=N(l)?l:!1,_=N(u)?u:!1,v=N(p)?p:!1,y=t.valueOf()===z.ZERO_DATE.valueOf();switch(s){case z.TOOLTIP_CARDS:r||CA(e,o,m,!y,h&&!y,!1,g,_,v,e.hasLegend?e.view?.legend?.getLegendElem().clientHeight:0);break;case z.TOOLTIP_BUBBLE:if(!y){let t=vA(o.panes.find(e=>{let{top:t,left:n,width:r,height:a}=e.bounds;return new rs(n,t,r,a).contains(i)}).plots,i.y);if(t.hasData){let n=`<div class="bubble-box">${ey({...o,hideSymbols:g,revealingClose:_,plots:t.plots})}</div>`;e.view.tooltip.show(n,{x:i.x,y:t.y,yMin:t.yMin,yMax:t.yMax})}else e.view.tooltip.hide()}CA(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_STD:if(!y){let t=ey({...o,hideSymbols:g,revealingClose:_,plots:o.panes.map(e=>e.plots).flat()});e.view.tooltip.show(t)}CA(e,o,m,!1,!1,e.hasLegend,g,_,v);break;case z.TOOLTIP_EXTERNAL:e.notifyHost(G.CH_TOOLTIPCHANGED,o);break;default:F(`Unknown tooltip mode requested: ${s}`,`warn`)}}function SA(e,t,n,r,i,a){oa(e,{position:`absolute`,display:`flex`,"flex-direction":t,"flex-wrap":`wrap`,left:`${n+z.CARDS_X_OFFSET}px`,top:`${i+z.CARDS_Y_OFFSET}px`,maxWidth:`${a-r-z.CARDS_X_OFFSET*2}px`})}function CA(e,t,n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=0){let u=e.view.el,d=ty(e,t,n,r,i,o,s,c);d.some(e=>!N(e.bounds))||d.forEach(({id:t,isMainPane:n,content:r,moveContent:i,bounds:{left:o,right:s,top:c,width:d}},f)=>{if(r!==``&&(!a||!n)){let i=ca(t,u,`div`);SA(i,n&&Zv(e)?`column`:`row`,o,s,c+l,d),la(i,{"bcharts-card":!0,"bcharts-card-main":n,"bcharts-card-first":f===0}),i.innerHTML=r}let p=aa(`#right-${t}`,u);N(p)||(p=document.createElement(`div`),p.id=`right-${t}`,u.appendChild(p),la(p,`bcharts-card bcharts-card-move`)),oa(p,{position:`absolute`,display:`block`,right:`${s+z.CARDS_X_OFFSET}px`,top:`${c+l+z.CARDS_Y_OFFSET}px`}),p.innerHTML=i})}var wA=null;function TA(){return wA===null&&(wA=$().config.hostingModel===oe[oe.Application]),wA}var EA=class extends Rk{ap;onLongPress;presenter;panY;snapToSupported=!1;warmUp=!0;preventDefault=!1;lastOffset;lastPanningExtremes;constructor(e,t){super(),this.ap=e,this.onLongPress=t,this.presenter=e.presenter,this.panY=e.axis.isCustomDomain}activated(){}deactivated(){this.cancelLongPress()}startPan(e){this.startLongPress(this.presenter,this.ap,e),this.lastOffset=e,this.lastPanningExtremes=this.ap.axis.yScale.domain();let t=this.ap.presenter;t.enableTooltip(!1),t.view.tooltip.hide(),t.view.drawCrosshair({ap:void 0})}onMouseMove(e){if(e.pinchZoom){this.presenter.resetActiveTool();return}let{point:t,view:n,offset:r}=e;if(t&&t.axis!==this.ap.axis)return;let{x:i,y:a}=r,o=i-this.lastOffset.x,s=Math.abs(o),c=this.lastOffset.y,l=a-c,u=Math.abs(l);s>=1&&this.cancelLongPress();let d=TA();if(Le()&&!d&&this.warmUp)return(s>7||u>7)&&(this.warmUp=!1,this.preventDefault=s>u),!1;if(this.preventDefault||!Le()||d){if(n.xAxis.pan(o),this.panY&&t&&t.axis){u>=1&&this.cancelLongPress();let e=DA(t.axis,c,a,this.lastPanningExtremes);this.lastPanningExtremes=e,t.axis.yScale.domain(e)}this.lastOffset=r,n.redraw(),t&&t.presenter.view.setCursor(te.Grabbing)}return d||this.preventDefault}finished(){vM(this.presenter)}onMouseLeave(){this.finished()}onMouseUp(){this.finished()}onMouseDblClick({presenter:e,offset:t,originalEvent:n}){Le()&&zA(e,t,n)}performLongPress(e,t,n){e.enableTooltip(!0),e.resetActiveTool(),this.onLongPress?this.onLongPress():e.activeTool.startTouchCrosshairMode(e,t,n)}};function DA(e,t,n,r){let i=(n-t)/e.viewBox.height,[a,o]=r,s=i*(o-a);return[a+s,o+s]}var OA=null;function kA(e,t){let n=new DOMParser().parseFromString(e,`image/svg+xml`),r=n.querySelector(`svg`)?.getAttribute(`viewBox`),i=n.querySelector(`path`)?.getAttribute(`d`);if(M(r)&&M(i)){let e=r.split(` `).map(Number);e.length===4&&e.every(Number.isFinite)&&(OA={path:new Path2D(i),width:e[2],height:e[3],rect:new rs(0,0,0,0),logoClickable:t})}}var AA=5,jA=50;function MA(e,{x:t,y:n,height:r,width:i}){if(!M(OA))return;let{path:a,width:o,height:s,rect:c}=OA,l=i/8,u=Math.min(Math.max(jA,l),o)/o;c.width=o*u,c.height=s*u,c.x=t+AA,c.y=n+r-c.height-AA,e.save();let d=getComputedStyle(e.canvas).getPropertyValue(`--widget-logo-fill-color`);e.fillStyle=d.length===0?`rgba(127, 127, 127, 0.6)`:d,e.translate(c.x,c.y),e.scale(u,u),e.fill(a),e.restore()}function NA(){return M(OA)&&OA.logoClickable?OA.rect:null}var PA=class extends rA{constructor(e,t){super(e,t)}hitTest(e){if(!this.isVisible)return!1;let t=this.getRect();return t!==null&&t.contains(e)}draw(e,t){return super.draw(e,t)?(ms(e,this.getRect()),!0):!1}};function FA(e,t){return e<t?[e,t]:[t,e]}var IA={line:{width:1,color:`rgba(127, 127, 127, 0.3)`,dashStyle:`LongDash`},fill:{color:`rgba(127, 127, 127, 0.1)`}},LA=class extends cA{snapToSupported=!1;preventDefault=!1;axis;presenter;constructor(){super(Jk(`Rectangle`,PA,null,IA),!1)}activated(){}deactivated(){N(this.axis,this.annotation)&&this.axis.deleteAnnotation(this.annotation,!1)}onMouseDown(e){let t=super.onMouseDown(e);if(t===!0){let{point:t}=e;this.axis=t.axis,this.presenter=t.presenter}return t}finish(){if(N(this.axis,this.presenter)){vM(this.presenter,{toolChange:D.Executed,annId:`ZoomIn`});let e=this.annotation.points,t=FA(e[0].price,e[1].price),n=FA(e[0].time,e[1].time),r=(e,t)=>Math.abs(t(e[0])-t(e[1])),i=r(n,e=>this.axis.toX(e)),a=r(t,e=>this.axis.toY(e)),o=this.presenter.view,s=z.MINIMUM_ZOOM_DIMENSION;if(i>s&&a>s){let e=o.xAxis.xScale;this.axis.isCustomDomain=!0,this.axis.yScale.domain(t),e.wasZoomed=!0,e.scaleBarToFitRange(n,!1),e.domain(n)}o.redraw()}}};function RA(e,t,n=e.isSelected){let r=Kk(e);r.offset={x:t.x,y:t.y},r.wasSelected=n,r.canFlip=e.getFlipAnchorIndices()!==null;let i=e.axis.pane.presenter;r.candidates=i.defaultTool.findAnnotationHits(e.axis.toAnnotationPoint(t)).reverse().map(e=>({...Kk(e),paneIndex:i.panes.indexOf(e.axis.pane),axisIndex:e.axis.pane.axes.indexOf(e.axis),position:e.axis.findIndex(e),canFlip:e.getFlipAnchorIndices()!==null})),i.annotationManipulation||i.clearSelection(),i.notifyHost(G.CH_ANNNEEDSCONTEXTMENU,r)}function zA(e,t,n){let r={offset:{x:t.x,y:t.y},chart:e.accessor,originalEvent:n};e.notifyHost(G.CH_CHTNEEDSCONTEXTMENU,r)}function BA(e,t,n,r=1,i=-1){let a=(n.y-t.y)/10,o=e.yScale.rangeWithPadding().reverse();return[o[0]+a*r,o[1]+a*i].map(t=>e.yScale.yToPrice(t))}function VA(e,t){return t.x===e.x||t.x===e.x+e.width||t.y===e.y||t.y===e.y+e.height}function HA(){let e=$().config.touchCrosshairTimeoutMillis;return N(e)&&Number.isFinite(e)?e:z.LONG_PRESS_TIMEOUT_MILLIS}var UA=class{resizingPanes=!1;snapToSupported=!1;touchCrosshairMode=!1;notifyZoomChanged;previousTouchTimestamp=null;resizingScale=!1;resizingScaleId=null;lastScaleResizingOffset=null;touchCrosshairTimeout=null;lastResizingOffset=null;splitter;prevZoomingOffset;prevPinchDistance=null;constructor(){this.stopResizingScale(),this.notifyZoomChanged=qe(G.CH_ZOOMCHANGED,1e3)}startTouchCrosshairMode(e,t,n){this.touchCrosshairMode=!0,this.showCrosshairAndTooltips(e.view,t,n)}activated(){}deactivated(){}findAnnotationHits(e){let t=e.point;if(!t)return[];let n=e.presenter.selectedAnnotation,r=e=>e.hitTest(t)||e===n&&e.points.some(e=>e.hitTest(t));return e.axis.pane.axes.flatMap(e=>e.annotations.filter(e=>!e.computed&&e.isVisible&&r(e)))}findHit(e){if(!e.point)return[];if(e.axis.pane.axes.some(t=>t.plots.some(t=>t.hitTestCustomEvent(e.point))))return z.EVENT_PIN_HIT;let t=e.presenter.selectedAnnotation;if(t?.isVisible&&!t.computed&&t.axis.pane===e.axis.pane){let n=t.points.find(t=>t.hitTest(e.point));if(n)return[t,n];if(e.presenter.annotationManipulation&&t.hitTest(e.point))return[t,void 0]}return[Ce(e.presenter.annotationManipulation?this.findAnnotationHits(e):e.axis.annotations.filter(t=>!t.computed&&t.isVisible&&t.hitTest(e.point))),void 0]}restoreSelection(e,t){e.clearSelection();let n=e.allAnnotations.find(e=>e.uid===t);n?.isVisible&&e.setSelection(n)}findPlotHits(e,t){let n=e.axes.map(e=>e.plots).flat().filter(e=>e.isVisible);if(n.length===1){let[t]=n;if(t.isStudy&&e.presenter.isHoverHighlightable(t))return[t]}let r=[];for(let n=e.axes.length-1;n>=0;n--){let i=e.axes[n].plots;for(let n=i.length-1;n>=0;n--){let a=i[n];e.presenter.isHoverHighlightable(a)&&a.isVisible&&a.hasHitTestableCurves&&a.hitTest(t)&&r.push(a)}}return r}stopResizingScale(){this.resizingScale=!1,this.resizingScaleId=null,this.lastScaleResizingOffset=null}resetVerticalAxis(e,t=!0){this.stopResizingScale(),e.isCustomDomain=!1,t&&e.setDomain()}resetHorizontalAxis(e,t=!0){e.view.xAxis.resetZoom(),t&&e.view.setPriceAxesDomains(),this.fireZoomChanged(e)}canVerticalZoom(e){return $e(e.display.chart.zooming)[0]}canHorizontalZoom(e){return $e(e.display.chart.zooming)[1]}canRectangleZoom(e){return this.canVerticalZoom(e)&&this.canHorizontalZoom(e)}fireZoomChanged(e){this.notifyZoomChanged({chart:e.accessor})}onMouseDblClick({priceAxis:e,offset:t,presenter:n,view:r}){let i=r.xAxis.contains(t),a=!1;if(N(e))this.resetVerticalAxis(e),a=!0;else if(i)this.resetHorizontalAxis(n),a=!0;else if(Le()){let e=n.selectedAnnotation;e==null?zA(n,t):RA(e,t)}a&&r.redraw()}onMouseEnter(){this.previousTouchTimestamp=null}computePreviousTouchStartDuration(){if(!Le())return null;let e=(/* @__PURE__ */ new Date()).getTime(),t=N(this.previousTouchTimestamp)?e-this.previousTouchTimestamp:null;return this.previousTouchTimestamp=e,t}onMouseDown(e){let{point:t,button:n,splitter:r,offset:i,priceAxis:a,presenter:o,originalEvent:s}=e,c=window.navigator.platform.toLowerCase().startsWith(`mac`),l=c?E.Meta:E.Control,u=n===T.Right||c&&n===T.Left&&e.getModifier(E.Control);this.touchCrosshairMode&&N(this.touchCrosshairTimeout)&&(clearTimeout(this.touchCrosshairTimeout),this.touchCrosshairTimeout=null);let d=this.computePreviousTouchStartDuration();if(N(d)&&d<z.DOUBLE_CLICK_DURATION_MILLIS)return this.onMouseDblClick(e),!0;if(!u&&this.isLogoLink(i)&&o.notifyHost(G.CH_LOGOCLICKED,{chart:o.accessor}),N(t)&&o.allPlots.some(e=>e.tryHandleCustomEventClick(t.point)))return!0;if(N(r))return this.resizingPanes=!0,this.lastResizingOffset=i,this.splitter=r,o.enableTooltip(!1),!0;if(N(a))return this.canVerticalZoom(o)&&this.startAxisScaling(a,i),!0;if(t!=null){if(e.getModifier(l)&&this.canRectangleZoom(o))return o.activeTool=new LA,o.activeTool.onMouseDown(e),!0;let[n,r]=this.findHit(t),a=o.annotationManipulation,c=o.selectedAnnotation?.uid,d=n!=null&&c===n.uid,f=()=>this.findAnnotationHits(t).length>1,p;if(a&&n!=null&&(p=()=>{!d&&f()&&this.restoreSelection(o,c),RA(n,i,d)}),a&&u&&n!=null&&!d&&f())return RA(n,i,!1),Le();if(o.clearSelection(),n!=null&&o.setSelection(n),n==null||n?.locked)return u?(this.hideCrosshairAndTooltips(o.view),n==null?zA(o,i,s):n?.locked&&RA(n,i,d),!0):this.touchCrosshairMode?!0:(o.activeTool=new EA(t,p),o.activeTool.startPan(i),TA());let m=r!=null;if(u)return RA(n,i,d),Le();{if(m&&!r.movable||!m&&!n.canMove(t.point))return!1;let e=m&&n.points.indexOf(r)!==-1,a=n.axis.toAnnotationPoint(i);return o.activeTool=e?new Vk(n,r):new Bk(n,a,i,p),Le()}}return this.canHorizontalZoom(o)&&(this.prevZoomingOffset=i),!1}onContextMenu(e){return!0}isLogoLink(e){let t=NA();return N(t)&&t.contains(e)}onMouseMove(e){let{point:t,splitter:n,priceAxis:r,view:i,presenter:a,offset:o}=e;if(N(e.pinchZoom)&&e.pinchZoom&&N(e.pinchDistance))return N(this.prevPinchDistance)&&(e.delta=this.prevPinchDistance-e.pinchDistance,this.onWheel(e)),this.prevPinchDistance=e.pinchDistance,Le();if(n!=null||this.resizingPanes)i.setCursor(te.ResizeVertical),this.resizingPanes&&this.resizePanes(i,o);else if(N(t)){let[e,n]=this.findHit(t),r=!N(e)&&!N(n)?this.findPlotHits(t.pane,o):[],i=a.setHoverHighlight(r);N(n)?t.presenter.view.setCursor(te.Crosshair):N(e)?e.isSelected?t.presenter.view.setCursor(te.Move):t.presenter.view.setCursor(te.Hand):i?t.presenter.view.setCursor(te.Crosshair):t.presenter.view.setCursor(te.Arrow)}else if(N(r))this.canVerticalZoom(a)&&(i.setCursor(te.ResizeVertical),this.performAxisScaling(i,r,o));else{let e=this.canHorizontalZoom(a);if(!e&&this.prevZoomingOffset&&delete this.prevZoomingOffset,this.prevZoomingOffset&&e){let{x:e}=this.prevZoomingOffset,{x:t}=o,n=e-t;this.applyZoom(i.presenter,-n),this.prevZoomingOffset=o}i.setCursor(e?te.ResizeHorizontal:te.Arrow)}return!t||this.resizingPanes?(this.hideCrosshairAndTooltips(i),Le()):(this.isLogoLink(o)&&i.setCursor(te.Hand),this.showCrosshairAndTooltips(i,t,o),Le())}showCrosshairAndTooltips(e,t,n){t.time&&(!Le()||this.touchCrosshairMode)&&e.drawCrosshair({ap:t,offset:n})&&e.presenter.showTooltip&&xA(e.presenter,{time:t.time,offset:n,price:t.price,lastBarRefresh:void 0,justMain:void 0})}hideCrosshairAndTooltips(e,t=!1){e.presenter.setHoverHighlight([]),e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(t),t&&e.tooltip.mode===`cards`&&!e.presenter?.hasLegend&&bA(e.presenter)}onMouseLeave(e){let{view:t,offset:n}=e;t.presenter.accessor.getPaneBounds()?.every(e=>!e||!e.contains(n)||VA(e,n))&&(this.hideCrosshairAndTooltips(t,!0),this.stopResizeZoom(t.presenter)),t.setCursor(te.Arrow),this.touchCrosshairMode=!1}stopResizeZoom(e){this.resizingPanes&&(this.resizingPanes=!1,e.enableTooltip(!0),e.onPaneHeightsUpdated()),this.resizingScale&&this.stopResizingScale(),this.prevZoomingOffset&&delete this.prevZoomingOffset}onMouseUp({presenter:e}){if(this.stopResizeZoom(e),Le()){let t=HA();this.touchCrosshairTimeout=window.setTimeout(()=>{this.hideCrosshairAndTooltips(e.view,!0),this.touchCrosshairMode=!1},t)}}applyZoom(e,t,n=!0){if(!this.canHorizontalZoom(e))return;let r=Math.sign(t)*(Le()?2:10),i=e.view;i.xAxis.zoom(r)&&(i.setPriceAxesDomains(),i.redraw(),n&&this.fireZoomChanged(e))}onWheel({view:e,presenter:t,getModifier:n,delta:r}){let{scrollBehavior:i}=t.display;return!(Le()?i!==`none`:i===`wheel`||i===`wheel+shift`&&n(E.Shift))||r===0?!1:(e.drawCrosshair({ap:void 0}),e.tooltip.hide(),e.presenter.hideCards(),this.applyZoom(t,r),!0)}get useKeyboardShortcuts(){return $().config.hostingModel!==oe[oe.Application]}onKeyDown(e){let{key:t,code:n,presenter:r}=e;if(N(r.selectedAnnotation)&&Re(t,n)&&r.deleteAnnotationWithUndo(r.selectedAnnotation),N(r.selectedAnnotation)&&(ze(t,n)?r.clearSelection():Be(t,n)&&r.selectedAnnotation instanceof aA&&r.selectedAnnotation.textEditable&&(r.activeTool=new dA(null,r.selectedAnnotation),r.activeTool.startEditing())),Ve(t,n)||He(t,n)){let e=Ve(t,n)?1:-1,i=r.view;i.xAxis.pan(e*i.xAxis.xScale.bar.totalWidth),this.hideCrosshairAndTooltips(i),i.redraw()}let i=window.navigator.platform.toLowerCase().startsWith(`mac`)?E.Meta:E.Control;if(e.getModifier(i)&&this.useKeyboardShortcuts){let e=Ue(t,n),i=Ge(t,n);return e&&r.undoRedoManager.undo(),i&&r.undoRedoManager.redo(),e||i}We(t,n)&&e.getModifier(E.Alt)&&this.resetView(r)}resetView(e){e.allAxes.forEach(e=>this.resetVerticalAxis(e,!1)),this.resetHorizontalAxis(e,!1),e.view.xAxis.goToLatest(!0)}resizePanes(e,t){let n=t.y-this.lastResizingOffset.y;if(n===0)return;let r=e.presenter.panes,[i,a]=this.splitter,o=r.map((e,t)=>{let r=e.getBounds().height;return t===i?r+n:t===a?r-n:r});if(o.some(e=>e<z.MINIMUM_PANE_HEIGHT))return;let s=(e,t)=>e+t,c=o.reduce(s,0),l=r.map(e=>e.height).reduce(s,0),u=e=>Ze(e,4);r.forEach((e,t)=>e.height=u(o[t]/c*l)),this.lastResizingOffset=t,e.recalculateLayout(),e.redraw()}startAxisScaling(e,t){this.resizingScale=!0,this.resizingScaleId=e.id,this.lastScaleResizingOffset=t}performAxisScaling(e,t,n){if(this.resizingScale&&this.resizingScaleId===t.id){let r=Le()?4:5,i=BA(t,this.lastScaleResizingOffset,n,r,-r);this.lastScaleResizingOffset=n,t.isCustomDomain=!0,t.yScale.domain(i),e.redraw()}}},WA=class extends sA{factory;maxClicks;clicks=0;snapToSupported=!0;isDrawingAnnotation=!0;constructor(e,t){super(e.annName),this.factory=e,this.maxClicks=t}onMouseMove(e){let{point:t,view:n,offset:r}=e;n.drawCrosshair({ap:t,offset:r})}onMouseDown(e){let{point:t,view:n}=e;if(t===void 0)return this.clicks===0&&bM(e),!1;this.clicks===0&&(t.axis.pane.presenter.clearSelection(),this.annotation=this.factory(t.axis)),this.applyToPoints(t);let r=e=>this.annotation.points[e].point;this.clicks>0&&!Io(r(this.clicks-1),r(this.clicks))?this.annotation.requestRedraw():(this.clicks++,this.clicks===this.maxClicks&&this.annotation!==void 0?(this.annotation.drawn=!1,this.annotation.requestRedraw(),typeof this.annotation.updateOtherPoints==`function`&&this.annotation.updateOtherPoints(n.mainContext),yM(this.annotation,!0,D.Created)):this.annotation.requestRedraw())}applyToPoints(e){this.annotation.points[this.clicks].update(e.price,e.time)}},GA=class{snapToSupported=!1;constructor(e,t){setTimeout(()=>this.finalize(e,t),10)}finalize(e,t){let n=e(t);t.pane.presenter.clearSelection(),n.drawn=!1,n.requestRedraw(),yM(n,!0,D.None)}},KA=z.MARKER_ARROW_ANGLE*Math.PI/180/2;function qA(e,t){return JA(e.map(e=>e.point),t)}function JA(e,t,n=z.MARKER_ARROW_LENGTH){return new YA(e,t,n)}var YA=class{vertex;arrowLen;p1;p2;constructor(e,t,n=z.MARKER_ARROW_LENGTH){this.vertex=t,this.arrowLen=n,this.p1=e[0],this.p2=e[1]}hitTest(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();return Bo([t,n],e,z.HIT_TEST_TOLERANCE)||Bo([t,r],e,z.HIT_TEST_TOLERANCE)}draw(e){let{anchor:t,p1:n,p2:r}=this.getArrowPoints();gs(e,t,n),gs(e,t,r)}getArrowPoints(){let e=zo(this.p1,this.p2),t=this.vertex===`start`?0:Math.PI,n=e-KA+t,r=e+KA+t,i=this.vertex===`start`?this.p1:this.p2,a=this.arrowLen*Math.cos(n)+i.x,o=this.arrowLen*Math.sin(n)+i.y,s=this.arrowLen*Math.cos(r)+i.x,c=this.arrowLen*Math.sin(r)+i.y;return{anchor:i,p1:{x:a,y:o},p2:{x:s,y:c}}}},XA=class{hitTest(){return!1}draw(){}},ZA=class extends Zk{constructor(e,t){super(e,t),this.addPoints(2),this.alignPointsSupported=!0}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}get showPercentDiff(){return this.traits[z.AT_SHOW_PERCENTDIFF]}get showBarCount(){return this.traits[z.AT_SHOW_BARCOUNT]}get showRatio(){return this.traits[z.AT_RATIO]}getElements(){let e=this.points[0].point,t=this.points[1].point,n=new Yk(e,t,this.extend1,this.extend2,this.axis),r=[];return this.extend1&&r.push(new Yk(n.p1,e,!0,!1,this.axis)),r.push(new Yk(e,t,!1,!1,this.axis)),this.extend2&&r.push(new Yk(t,n.p2,!1,!0,this.axis)),r}formatRatio(e,t){return` (${Ze(e/t,3)})`}formatPercDiff(e,t){let n=(t-e)/e*100;return` (${n>0?`+`:``}${Ze(n,2)}%)`}formatPrice(e){return Bv(this.axis,this.priceMap(e))}adornElements(e,t){if(!this.showBarCount&&!this.showPrices&&!this.showPercentDiff&&!this.showRatio)return;let[n,r]=this.points,i=e[+!!this.extend1].getAdornOffset(t);if(this.showBarCount){let e=Ro(No(n.point,r.point),i);fs(t,this.getBarCount(n.time,r.time).toFixed(0),e,w.Right)}let a=this.showRatio?this.formatRatio(n.price,r.price):``,o=`${this.showPrices?this.formatPrice(n.price):``}${a}`.trim();o!==``&&fs(t,o,Ro(n.point,i),w.Right);let s=this.showPercentDiff?this.formatPercDiff(n.price,r.price):``,c=`${this.showPrices?this.formatPrice(r.price):``}${s}`.trim();c!==``&&fs(t,c,Ro(r.point,i),w.Right)}getMarkers(){let e=this.marker;if(!e||e.vertex===`none`)return[];let{vertex:t,kind:n}=e;return(t===`both`?[`start`,`end`]:[t]).map(e=>n===`arrow`?qA(this.points,e):(F(`There is no marker of ${n} kind`,`warn`),new XA))}},QA=class extends Zk{constructor(e,t){super(e,t),this.addPoints(1)}get showTimestamps(){return this.traits[z.AT_SHOW_TIMESTAMPS]}getElements(){return[new Hk(this.points[0].point,!0,this.axis)]}getTimeScaleAdornments(){return this.showTimestamps?[{time:this.points[0].time,color:this.traits.line.color}]:super.getTimeScaleAdornments()}},$A=class extends Zk{constructor(e,t){super(e,t),this.addPoints(1)}getElements(){return[new Hk(this.points[0].point,!1,this.axis)]}getPriceScaleAdornments(){return this.showPrices?[{price:this.points[0].price,color:this.traits.line.color}]:super.getPriceScaleAdornments()}},ej=class extends Zk{constructor(e,t,n){super(e,t),this.addPoints(2),N(n)&&N(n.points)&&n.points.forEach((e,t)=>this.points[t].update(e.price,e.time))}allPoints(){let[e,t]=this.points;return N(e,e.point,t,t.point)?[e,this.axis.toAnnotationPoint(No(e.point,t.point)),t]:z.EMPTY_ARRAY}line2(){return this.traits[z.AT_LINE_2]}use52WeekPrices(){return this.traits[z.AT_USE_52WEEK_PRICES]}getElements(){let e=this.allPoints();return e===z.EMPTY_ARRAY?z.EMPTY_ARRAY:e.map(e=>new Yk({x:-z.OUT_OF_SCREEN,y:e.point.y},{x:z.OUT_OF_SCREEN,y:e.point.y},!1,!1,this.axis))}wasPointMovedByTool(e,t){N(this.use52WeekPrices())&&(this.traits[z.AT_USE_52WEEK_PRICES]=!1)}getStyleForElement(e,t){let n=this.line2();if(t!==1||!N(n))return super.getStyleForElement(e,t);let r=P(this.traits);return r.line=n,Ks(r)}getPriceScaleAdornments(){let e=this.allPoints();if(!this.showPrices||e===z.EMPTY_ARRAY)return super.getPriceScaleAdornments();let t=this.traits.line,n=e.map(e=>({price:e.price,color:t.color})),r=this.line2();return N(r)&&(n[1].color=r.color),n}getFlipAnchorIndices(){return null}},tj=5,nj=class extends Qk{helper;constructor(e,t,n){super(e,t),this.addPoints(n),this.helper=new Uk(e)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get hasAllPoints(){return N(...this.points.map(e=>e.point))}get line2(){return this.traits[z.AT_LINE_2]}get extendLeft(){return this.traits[z.AT_EXTEND_LEFT]}get extendRight(){return this.traits[z.AT_EXTEND_RIGHT]}get reverse(){return this.traits[z.AT_REVERSE]}get levelsRespectLogScale(){return this.traits[z.AT_LEVELS_RESPECT_LOG_SCALE]}getStyleForElement(e,t){if(e.isTrend){let e=P(this.traits);return e.line=this.line2,Ks(e)}return super.getStyleForElement(e,t)}getKeyPoints(){let e=e=>e.map(e=>this.points[e]);return this.isExtended?e(this.reverse?[1,0,2]:[0,1,2]):e(this.reverse?[0,1,0]:[1,0,1])}getElements(){if(!this.hasAllPoints)return[];let[e,t,n]=this.getKeyPoints(),r=t.price-e.price,i=t.price/e.price,a=this.extendLeft,o=this.extendRight,s=this.leftPoint,c=this.rightPoint,l=(e,t,n=!1)=>{let r=new Yk(e,t,!n&&a,!n&&o,this.axis);return r.isTrend=n,r},u=this.levelsRespectLogScale&&this.axis.scale===ee.Logarithmic,d=this.getColoredElements(({value:e})=>{let t=n.price+r*e,a=n.price*i**+e,o=u?a:t;this.helper.update(o,n.time);let d=this.helper.point.y;return l({x:s.x,y:d},{x:c.x,y:d})});return this.showTrendLine&&(d.push(l(e.point,t.point,!0)),this.isExtended&&d.push(l((this.reverse?e:t).point,n.point,!0))),d}getAdornPointAndAlign(e,t){let n=this.labels,r=(e,t,n)=>({pt:e,align:t,offset:n}),i=this.axis.pane.getBoundsWithoutScales();switch(n){case z.AT_LABELS_LEFT:return this.extendLeft?r({x:i.x,y:e.anchor1.y},w.Left,t):super.getAdornPointAndAlign(e,t);default:case z.AT_LABELS_RIGHT:return this.extendRight?r({x:i.x+i.width,y:e.anchor2.y},w.Right,-t):super.getAdornPointAndAlign(e,t);case z.AT_LABELS_CENTER:return super.getAdornPointAndAlign(e,t)}}getTextRef(){return(e,t,n)=>({ref:t,spacing:tj,offsetY:-5,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,(e,t)=>{let n=new Path2D;return e===null||(as(n,e.p1),n.lineTo(t.p2.x,e.p1.y),os(n,t.p2),n.lineTo(e.p1.x,t.p2.y)),n},this.getTextRef(),t)}getPriceScaleAdornments(){if(!this.pricesOnScale)return super.getPriceScaleAdornments();let e=this.getElements();if(e.length===0)return super.getPriceScaleAdornments();let t=this.traits.line.color;return this.factors.map((n,r)=>{let i=e[r++].p1,a=this.singleStyle?t:n.line.color;return{price:this.axis.toPrice(i.y),color:a}})}},rj=class extends nj{constructor(e,t){super(e,t,2)}},ij=class extends nj{constructor(e,t){super(e,t,3)}},aj=5,oj=(e,t)=>{let n=new Path2D;return e===null||(as(n,e.p1),os(n,e.p2),os(n,t.p2)),n},sj=class extends Qk{constructor(e,t){super(e,t),this.addPoints(2)}get reverse(){return this.traits[z.AT_REVERSE]}getElements(){let[e,t]=this.getScreenPoints(),n=t.y-e.y;return this.getColoredElements(({value:r})=>{let i=this.reverse?e.y+r*n:t.y-r*n;return new Yk(e,{x:t.x,y:i},!1,!0,this.axis)})}getTextRef(){let[e,t]=this.getScreenPoints(),n=t.y-e.y,[r,i]=[this.leftPoint,this.rightPoint];return(a,o,s)=>{let c=this.reverse?e.y+s*n:t.y-s*n;return{ref:new Yk({x:r.x,y:c},{x:i.x,y:c},!1,!1,this.axis),spacing:aj,offsetY:!0,text:s.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,oj,this.getTextRef(),t)}},cj=class extends sj{constructor(e,t){super(e,t)}};function lj(e,t,n){return new dj(e,t,Fo(e,t),0,Math.PI,null,n)}function uj(e,t,n,r,i,a){return new dj(e,null,t,n,r,i,a)}var dj=class{center;rim;radius;startAngle;endAngle;antiClockwise;axis;left=null;right=null;scale=null;clip=null;style;constructor(e,t,n,r,i,a,o){this.center=e,this.rim=t,this.radius=n,this.startAngle=r,this.endAngle=i,this.antiClockwise=a,this.axis=o,t!==null&&(this.left={x:this.center.x-this.radius,y:this.center.y},this.right={x:this.center.x+this.radius,y:this.center.y})}get hasScale(){return this.scale!==null}get hasClip(){return this.clip!==null}get hasRim(){return this.rim!==null}applyScale(e){e.translate(this.center.x,this.center.y),e.scale(this.scale.x,this.scale.y),e.translate(-this.center.x,-this.center.y)}inverseScale(e){let t=new DOMPointReadOnly(e.x,e.y),n=this.axis.pane.presenter.view.mouseContext;n.save(),n.resetTransform(),this.applyScale(n);let r=n.getTransform().inverse();return n.restore(),r.transformPoint(t)}hitTest(e){let t=999;if(this.hasRim&&(this.center.y<this.rim.y&&e.y<=this.center.y||this.center.y>=this.rim.y&&e.y>=this.center.y))t=Math.min(Fo(this.left,e),Fo(this.right,e));else{let{x:n,y:r}=Lo(this.hasScale?this.inverseScale(e):e,this.center);if(!this.hasRim){let{startAngle:e,endAngle:t,antiClockwise:i}=this,a=Math.PI/2;if(e===0&&t===a&&!i&&(n<0||r<0)||e===a&&t===Math.PI&&!i&&(n>0||r<0)||e===-a&&t===Math.PI&&i&&(n>0||r>0)||e===0&&t===-a&&i&&(n<0||r>0))return!1}t=Math.abs(Math.sqrt(n*n+r*r)-this.radius)}return t<=z.HIT_TEST_TOLERANCE}get isAntiClockwise(){return this.hasRim?this.rim.y<=this.center.y:this.antiClockwise}draw(e){e.save(),this.hasClip&&e.clip(this.clip),this.hasScale&&this.applyScale(e),hs(e,this.center,this.radius,this.startAngle,this.endAngle,this.isAntiClockwise??!1),e.restore()}},fj=(e,t)=>{let n=new Path2D,{center:r}=t;if(as(n,r),n.arc(r.x,r.y,t.radius,t.startAngle,t.endAngle,t.isAntiClockwise??!1),e===null)return n;let i=new Path2D,{center:a}=e;return as(i,a),i.arc(a.x,a.y,e.radius,e.endAngle,e.startAngle,!e.isAntiClockwise),n.addPath(i),n},pj=class extends Qk{constructor(e,t){super(e,t),this.addPoints(2)}getElements(){let[e,t]=this.getScreenPoints();if(!N(e,t))return[];let n=Fo(e,t),r=Lo(t,e),i=r.y/n,a=r.x/n,o=this.getColoredElements(({value:t})=>{let r=n*t,o=i*r,s=a*r,c={x:e.x+s,y:e.y+o};return lj(e,c,this.axis)});if(this.showTrendLine){let n=new Yk(e,t,!1,!1,this.axis);n.isTrend=!0,o.unshift(n)}return o}get showTrendLine(){return!0}getTextRef(){return(e,t,n)=>{let{center:r}=t,i=t.isAntiClockwise?-1:1;return{ref:{x:r.x,y:r.y+i*t.radius},spacing:0,offsetY:!0,text:n.toString()}}}adornElements(e,t){this.adornElementsForColoredFactors(e,fj,this.getTextRef(),t)}},mj=class extends pj{constructor(e,t){super(e,t)}getStyleForElement(e,t){if(e.isTrend){let e=P(this.traits);return e.line=this.line2,Ks(e)}return super.getStyleForElement(e,t)}get showTrendLine(){return this.traits[z.AT_SHOW_TRENDLINE]}get line2(){return this.traits[z.AT_LINE_2]}},hj=class extends Qk{constructor(e,t){super(e,t),this.addPoints(2)}get factorsPropName(){return z.AT_ANGLES}getElements(){let[e,t]=this.getScreenPoints(),{x:n,y:r}=Lo(t,e);return this.getColoredElements(({value:i})=>{let a=(t,n)=>new Yk(e,{x:t,y:n},!1,!0,this.axis),o=i.charAt(0)!==`1`,s=Number(o?i.charAt(0):i.charAt(2));return o?a(t.x,e.y+r/s):a(e.x+n/s,t.y)})}getTextRef(){return(e,t,n)=>({ref:t.anchor2,spacing:0,offsetY:!0,text:n.toString()})}adornElements(e,t){this.adornElementsForColoredFactors(e,oj,this.getTextRef(),t)}},gj=class extends sj{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}getElements(){let[e,t]=this.getScreenPoints();return[new Yk(e,t,!1,!1,this.axis)].concat(super.getElements())}},_j=class extends pj{constructor(e,t){super(e,t),this._factors=[{shown:!0,value:1/3},{shown:!0,value:2/3}]}},vj=class extends Zk{constructor(e,t){super(e,t),this.addPoints(3)}getElements(){let e=this.points[0].point,t=this.points[1].point,n=this.points[2].point,r=(t.x+n.x)/2-e.x,i=(t.y+n.y)/2-e.y,a=[];return a.push(new Yk(t,{x:t.x+r,y:t.y+i},!1,!0,this.axis)),a.push(new Yk(e,{x:e.x+r,y:e.y+i},!1,!0,this.axis)),a.push(new Yk(n,{x:n.x+r,y:n.y+i},!1,!0,this.axis)),a.push(new Yk(t,n,!1,!1,this.axis)),a}},yj=class extends rA{constructor(e,t){super(e,t)}getEllipse(){let e=this.getRect();return e===null?null:new is(e.centerX,e.centerY,e.width/2,e.height/2)}hitTest(e){if(!this.isVisible)return!1;let t=this.getEllipse();return t!==null&&t.contains(e)}draw(e,t){return super.draw(e,t)?(ps(e,this.getEllipse()),!0):!1}},bj=class extends Zk{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getLastPoint(){let[e,t,n]=this.points;var r=Fo(e.point,t.point),i=zo(e.point,t.point);return{x:n.point.x+r*Math.cos(i),y:n.point.y+r*Math.sin(i)}}getElements(){let[e,t,n]=this.points;var r=[];if(r.push(new Yk(e.point,t.point,this.extend1,this.extend2,this.axis)),N(n?.price)){var i=this.getLastPoint();r.push(new Yk(n.point,i,this.extend1,this.extend2,this.axis))}return r}},xj=class extends rA{kind;constructor(e,t,n){super(e,t),this.kind=n,this.adjustFill=!0}hitTest(e){if(!this.isVisible)return!1;let t=this.getRect();return t!==null&&t.contains(e)}get dimension(){let e=this.kind===`fish_hook`?2:1;return z.DEFAULT_SYMBOL_WIDTH_HEIGHT*e}updateOtherPoints(){this.points[1].price||this.setBottomRight()}setBottomRight(){let e=this.dimension,t=this.axis.pane.presenter.timeline,{price:n,time:r}=this.points[0],i=A(t,r,Number,Jv);if(i!==-1){let r=this.axis.pane.presenter.view.xAxis.xScale.bar.totalWidth,a=1;for(;(2*a+1)*r<e;)a++;this.points[0].update(n,t.at(i-a)),this.points[1].update(n,t.at(i+a));let o=Ro(this.points[0].point,{x:0,y:-e/2}),s=Ro(this.points[1].point,{x:0,y:e/2});this.points[0].updateFromPoint(o),this.points[1].updateFromPoint(s)}}draw(e,t){if(!super.draw(e,t))return!1;let n=this.getRect();return n.width===0&&(n.width=this.dimension),bs(e,this.kind,n),!0}},Sj=class extends Qk{helper;constructor(e,t){super(e,t),this.addPoints(2),this.helper=new Uk(e)}getElements(){let e=this.axis.pane.presenter.timeline,{price:t,time:n}=this.points[0],r=A(e,n,Number,Jv),i=A(e,this.points[1].time,Number,Jv),a=i-r;return r===-1||i===-1?[]:this.getColoredElements(({value:n})=>{let i=e.at(r+n*a);return i===null?null:(this.helper.update(t,i),new Hk(this.helper.point,!0,this.axis))})}getTextRef(){return(e,t,n)=>({ref:t.anchor,spacing:3,offsetY:!0,text:n.toString()})}adornElements(e,t){let n=this.axis.pane.getBoundsWithoutScales();this.adornElementsForColoredFactors(e,(e,t)=>{let r=new Path2D;if(e===null)return r;let i=t.anchor.x-e.anchor.x;return r.rect(e.anchor.x,n.y,i,n.height),r},this.getTextRef(),t)}getTimeScaleAdornments(){let e=e=>({time:this.points[e].time,color:this.traits.line.color});return[e(0),e(1)]}},Cj=class{snapToSupported=!0;isDrawingAnnotation=!0;constructor(){}onMouseMove(e){let{point:t,view:n,offset:r}=e;n.drawCrosshair({ap:t,offset:r})}onMouseDown(e){if(Le()&&e.originalEvent instanceof TouchEvent)return;let{point:t}=e;if(!t?.axis?.pane?.presenter||!t.time)return;let n=t.axis.pane.presenter,r={chart:n.accessor,axis:t.axis,point:{time:t.time.getTime(),price:t.price}};n.notifyHost(G.CH_ANNPOINTPICKED,r),vM(n,void 0)}};function wj(e){if(!Tt(e)||e.length!==1)return 0;let t=no.parse(e);return t===null?0:t.baseCode}function Tj(e){let t=e?.minMovement;if(!Number.isFinite(t)||t<=0)return z.MIN_POSITION_PRICE_PRECISION;let[n,r=`0`]=t.toString().toLowerCase().split(`e`),i=(n.includes(`.`)?n.split(`.`)[1].length:0)+Math.max(0,-Number.parseInt(r,10));return Math.max(z.MIN_POSITION_PRICE_PRECISION,i)}function Ej(e){if(e?.symbolType===`Forex`)return 10**wj(e.unitCode);let t=e?.pointValue;return Number.isFinite(t)?t:1}function Dj(e,t,n){return Ze(n?e/100*t:e,2)}function Oj({entryPrice:e,upperPrice:t,lowerPrice:n,isLong:r},i){let a=r?e-n:t-e;return!Number.isFinite(a)||a<=0?NaN:Math.floor(i/a)}function kj(e,t,n){let r=n?e:t,i=n?t:e;return!Number.isFinite(i)||i===0?NaN:Ze(r/i,2)}function Aj(e,t,n,r){return Ze((r===`upper`?1:-1)*(n?1:-1)*e*t,2)}function jj(e,t,n,r,i){return Ze(e+(i===`upper`?1:-1)*(r?1:-1)*t*n,2)}function Mj(e,t){return Number.isFinite(e)?t?e>0:e<=0:!0}var Nj={Open:`Open`,Closed:`Closed`},Pj=class extends Zk{isLong;twoDecMeta;_dataWindow;_metaData;isHit=!1;constructor(e,t,n){super(e,t),this.isLong=n,this.addPoints(4);let r=(e,t)=>this.points[e].moveDirection=t;r(1,ne.Vertical),r(2,ne.Vertical),r(3,ne.Horizontal),this.twoDecMeta=new xo(2)}data(e){return this.presenter.mainPlot.timeSeries.container.getData(e)}get presenter(){return this.axis.pane.presenter}get metaData(){return this._metaData||=this.presenter.mainPlot.metaData,this._metaData}getDataWindow(e,t,n=!0,r=!0){let i=this.data(W.DateTime),a=A(i,+e,Number),o=A(i,+t,Number),s={refIndex:-1,highestIndex:-1,lowestIndex:-1,highest:null,lowest:null,data:[]},[c,l,u]=[W.High,W.Low,W.Close].map(e=>this.data(e)),d=e=>e-a;for(let e=a;e<=o;e++)n&&s.refIndex===-1&&N(this.entryPrice)&&this.entryPrice>=l[e]&&this.entryPrice<=c[e]&&(s.refIndex=d(e)),(!n||s.refIndex>=0&&d(e)>=s.refIndex)&&((!N(s.highest)||c[e]>s.highest)&&(s.highest=c[e]),(!N(s.lowest)||l[e]<s.lowest)&&(s.lowest=l[e])),n&&s.refIndex!==-1&&(s.highestIndex===-1&&c[e]>this.upperPrice&&(s.highestIndex=d(e)),s.lowestIndex===-1&&l[e]<this.lowerPrice&&(s.lowestIndex=d(e))),r&&s.data.push({high:c[e],low:l[e],close:u[e],time:i[e]});if(r&&s.data&&s.data.length>0){s.state=N(s.highest,s.lowest)&&(this.upperPrice<s.highest||this.lowerPrice>s.lowest)?Nj.Closed:Nj.Open,s.special=s.highestIndex===-1&&s.lowestIndex===-1||s.highestIndex===s.lowestIndex;let e=Ce(s.data);if(s.toPrice=e.close,s.toTime=e.time,s.state===Nj.Closed){if(s.special)s.refIndex!==-1&&(s.toTime=s.data[s.refIndex].time,s.toPrice=(this.isLong?this.lowerPrice<s.lowest:this.upperPrice<s.highest)?this.upperPrice:this.lowerPrice);else{let e=s.highestIndex!==-1&&s.lowestIndex!==-1;e&&s.highestIndex<s.lowestIndex||s.lowestIndex===-1?(s.toPrice=this.upperPrice,s.toTime=s.data[s.highestIndex].time):(e&&s.lowestIndex<s.highestIndex||s.highestIndex===-1)&&(s.toPrice=this.lowerPrice,s.toTime=s.data[s.lowestIndex].time)}}let t=this.isLong?s.toPrice-this.entryPrice:this.entryPrice-s.toPrice;s.pAndL=this.roundPriceDelta(t)}return s}get dataWindow(){return N(this._dataWindow)||(this._dataWindow=this.getDataWindow(this.entryAnchor.time,this.exitAnchor.time)),this._dataWindow}getVisiblePriceRange(){let e=this.axis.yScale.domain();return e[1]-e[0]}getFutureTimestamp(){let e=this.axis.pane.presenter.timeline,t=A(e,+this.points[0].time,Number,Jv);if(!Number.isFinite(t)||t<0)return Date.now();let n=Math.min(e.length-1,t+50),r=e.at(n);return N(r)?r.getTime():Date.now()}get entryPrice(){return this.entryAnchor.price}get entryAnchor(){return this.points[0]}get upperPrice(){return this.upperAnchor.price}get upperAnchor(){return this.points[1]}get lowerPrice(){return this.lowerAnchor.price}get lowerAnchor(){return this.points[2]}get exitAnchor(){return this.points[3]}get accountSize(){return this.traits[z.AT_ACCOUNT_SIZE]}get risk(){return Dj(this.traits[z.AT_RISK],this.accountSize,this.traits[z.AT_RISK_IS_PERCENT])}get positionInputs(){return{entryPrice:this.entryPrice,upperPrice:this.upperPrice,lowerPrice:this.lowerPrice,isLong:this.isLong}}get pricePrecision(){return Tj(this.metaData)}get pointValue(){return Ej(this.metaData)}roundPriceDelta(e){return Ze(e,this.pricePrecision)}formatDollarValue(e){return Number.isFinite(e)?`${e<0?`-`:``}$${this.twoDecMeta.format(Math.abs(e))}`:z.NOT_APPLICABLE}formatRatioValue(e){return Number.isFinite(e)?e.toFixed(2):z.NOT_APPLICABLE}formatQuantityValue(e){return Number.isFinite(e)?`${e}`:z.NOT_APPLICABLE}formatPercentChange(e){return Number.isFinite(e)?`(${Ze(e,2).toFixed(2)}%)`:`(${z.NOT_APPLICABLE})`}get qty(){return Oj(this.positionInputs,this.risk)}get upperDiff(){return this.roundPriceDelta(this.upperPrice-this.entryPrice)}get upperAmount(){return jj(this.accountSize,this.qty,this.upperDiff,this.isLong,`upper`)}get upperPandL(){return Aj(this.upperDiff,this.pointValue,this.isLong,`upper`)}get isCompact(){return this.traits[z.AT_COMPACT]}get upper(){let e=Bv(this.axis,this.priceMap(this.upperPrice)),t=this.formatPercentChange(this.upperDiff/this.entryPrice*100);return this.isCompact,`${e} ${t}`}get upperText(){let e=`${this.formatDollarValue(this.upperPandL)}`,t=`${this.formatDollarValue(this.upperAmount)}`,n=this.isLong?`Target`:`Stop`;return this.isCompact?`${this.upper} ${e}`:`${n}: ${this.upper}, P&L: ${e}, Amount: ${t}`}get lowerDiff(){return this.roundPriceDelta(this.entryPrice-this.lowerPrice)}get lowerAmount(){return jj(this.accountSize,this.qty,this.lowerDiff,this.isLong,`lower`)}get lowerPandL(){return Aj(this.lowerDiff,this.pointValue,this.isLong,`lower`)}get lower(){let e=Bv(this.axis,this.priceMap(this.lowerPrice)),t=this.formatPercentChange(this.lowerDiff/this.entryPrice*100);return this.isCompact,`${e} ${t}`}get lowerText(){let e=`${this.formatDollarValue(this.lowerPandL)}`,t=`${this.formatDollarValue(this.lowerAmount)}`,n=this.isLong?`Stop`:`Target`;return this.isCompact?`${this.lower} ${e}`:`${n}: ${this.lower}, P&L: ${e}, Amount: ${t}`}get riskReward(){return kj(this.upperDiff,this.lowerDiff,this.isLong)}get state(){return this.dataWindow.state}get pAndL(){return this.dataWindow.pAndL}get pAndLValue(){return this.pAndL*this.pointValue}positionPoints(){let e=this.getVisiblePriceRange()/5,t=this.getFutureTimestamp();this.upperAnchor.update(this.entryPrice+e,this.entryAnchor.time),this.lowerAnchor.update(this.entryPrice-e,this.entryAnchor.time),this.exitAnchor.update(this.entryPrice,t)}get lowerStyle(){return this.fillOnlyStyle(z.AT_FILL2)}get upperStyle(){return this.fillOnlyStyle(z.AT_FILL)}get textStyle(){return this.fillOnlyStyle(z.AT_FILL_TEXT)}get secondaryLineStyle(){return Ks({line:{color:this.traits.line.color,dashStyle:`ShortDash`},fill:{color:z.COLOR_TRANSPARENT}})}wasModifiedByTool(){N(this.points[2].price)||this.positionPoints(),this._dataWindow=void 0}wasPointMovedByTool(e,t){let n=this.getVisiblePriceRange()/5e3;if(this.points.indexOf(e)<3){let t=t=>e.update(t,e.time);this.entryAnchor.price>this.upperAnchor.price&&(e===this.entryAnchor?t(this.upperAnchor.price-n):t(this.entryAnchor.price+n)),this.entryAnchor.price<this.lowerAnchor.price&&(e===this.entryAnchor?t(this.lowerAnchor.price+n):t(this.entryAnchor.price-n))}if(e===this.entryAnchor){let t=(t,n,r)=>t.update(n?e.price:t.price,r?e.time:t.time);t(this.exitAnchor,!0,!1),t(this.upperAnchor,!1,!0),t(this.lowerAnchor,!1,!0)}this.wasModifiedByTool()}get isUpperPerPAndL(){return Mj(this.dataWindow.pAndL,this.isLong)}getStyleForElement(e,t){return e.style||this.defaultStyle}getElements(){let e=new Yk(this.entryAnchor.point,this.exitAnchor.point,!1,!1,this.axis),t=this.exitAnchor.point.x<this.entryAnchor.point.x,n=Math.abs(this.exitAnchor.point.x-this.entryAnchor.point.x),r=(e,t)=>({x:e.x+t,y:e.y}),i=new Xk(r(this.upperAnchor.point,t?-n:0),n,Math.abs(this.upperAnchor.point.y-this.entryAnchor.point.y),this.axis);i.style=this.upperStyle;let a=new Xk(r(this.entryAnchor.point,t?-n:0),n,Math.abs(this.entryAnchor.point.y-this.lowerAnchor.point.y),this.axis);a.style=this.lowerStyle;let o=[e,i,a],s=this.dataWindow;if(s.refIndex!==-1){let e=s.data[s.refIndex],t=new Uk(this.axis,this.entryPrice,e.time),n=new Uk(this.axis,s.toPrice,s.toTime),r=new Yk(t.point,n.point,!1,!1,this.axis);if(r.style=this.secondaryLineStyle,o.push(r),t.time!==n.time){let e=this.entryPrice<s.toPrice,r=new Xk({x:t.point.x,y:Math.min(t.point.y,n.point.y)},n.point.x-t.point.x,Math.abs(n.point.y-t.point.y),this.axis);r.style=e?this.upperStyle:this.lowerStyle,o.push(r)}}return o}hitTest(e){if(!this.isVisible)return!1;let t=this.isHit||!1;return this.isHit=super.hitTest(e),this.isHit!==t&&this.requestRedraw(),this.isHit}get showTextAdornments(){return this.isHit||this.isSelected}getPriceScaleAdornments(){let e=e=>Ho(this.traits[e].color);return[{price:this.upperPrice,color:e(z.AT_FILL)},{price:this.entryPrice,color:e(z.AT_LINE)},{price:this.lowerPrice,color:e(z.AT_FILL2)}]}adornElements(e,t){let[n,r,i]=e;if(this.showTextAdornments){let[e,a]=[!0,!1].map(e=>ls(t,e)),{x:o,y:s,width:c}=r.rect,l={x:o+c/2,y:s+e},u=this.textStyle.fillStyle;fs(t,this.upperText,l,w.Center,u,Ho(this.upperStyle.fillStyle));let{x:d,y:f,width:p,height:m}=i.rect,h={x:d+p/2,y:f+m+Math.abs(a)};fs(t,this.lowerText,h,w.Center,u,Ho(this.lowerStyle.fillStyle));let{p1:g,p2:_}=n,{x:v,y}=g,{x:b}=_,x=this.state||z.NOT_APPLICABLE,ee=this.isCompact?`${this.formatDollarValue(this.pAndLValue)}`:`${x} P&L: ${this.formatDollarValue(this.pAndLValue)}, Qty: ${this.formatQuantityValue(this.qty)}`,S=this.isCompact?`${this.formatRatioValue(this.riskReward)}`:`Risk/Reward Ratio: ${this.formatRatioValue(this.riskReward)}`,C=e=>t.measureText(e).width,te=Math.max(C(ee),C(S)),T=Math.abs(b-v)<te*1.25?y+Math.abs(a)+5:y+e+10,E={x:v+(b-v)/2,y:T},ne=Ho(this.isUpperPerPAndL?this.upperStyle.fillStyle:this.lowerStyle.fillStyle);fs(t,[ee,S],E,w.Center,u,ne)}}updatePoints(e){super.updatePoints(e),this.wasModifiedByTool()}},Fj=class extends $k{markers;display=null;constructor(e,t){super(e,t),this.points=nA(e),this.points[2].visible=!1,this.points[3].visible=!1,this.markers=[new XA]}isPointDrawn(e){return super.isPointDrawn(e)?e.visible:!1}makeLineArrow(e,t,n,r){let i=[No(e,t),No(n,r)];return[this.makeLine(i[0],i[1]),JA(i,`end`,10)]}get rectColor(){return this.traits[z.AT_FILL].color}get textColor(){return this.traits[z.AT_FILL_TEXT].color}getMarkers(){return this.markers}getScreenPoints(){return this.points.slice(2).forEach(e=>e.toPoint()),super.getScreenPoints()}formatDateDifference(e,t){return this.presenter.data.aggregation.isEndOfDay?`${Un(t,e)}d`:ni(si({start:e,end:t}),{format:[`days`,`hours`,`minutes`,`seconds`]}).replaceAll(/(days?)|(hours?)|(minutes?)|(seconds?)/g,e=>e[0])}computeState(){}get text(){return this.display===null&&this.computeState(),this.display}getTextCoord(e,t){let n=this.points[0].price<this.points[1].price,r=ls(t,n,this.text.length),{x:i,y:a,width:o,height:s}=e.rect;return{x:i+o/2,y:a+(n?0:s)+(n?r:Math.abs(r))}}adornElements(e,t){fs(t,this.text,this.getTextCoord(e[0],t),w.Center,this.textColor,Ho(this.rectColor))}getDateDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.time);if(!e||!t)return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let n=Math.min(+e,+t),r=Math.max(+e,+t),i=this.data(W.DateTime);if(!i||i.length===0)return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let a=A(i,+n,Number),o=A(i,+r,Number),s=this.data(W.Volume);if(!Array.isArray(s))return[`0 bars, `,`Vol ${this.formatter.format(0,W.Volume)}`];let c=me(s.slice(a,o+1)),l=this.formatter.format(c,W.Volume),u=o-a,d=u===0?``:this.formatDateDifference(n,r),f=e<t?``:`-`;return[`${f}${u} bars, ${f}${d}`,`Vol ${l}`]}getPriceDifference(){let[e,t]=this.points.slice(0,2).map(e=>e.price),n=t-e,r=n/e;return[`${this.formatter.format(n,W.Close)} (${this.formatter.format(r,W.PercentChange)})`]}resetComputedState(){this.display=null}onFormatterChanged(){this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}},Ij=class extends Fj{getElements(){let[e,t,n,r]=this.getScreenPoints(),i=this.makeLine(e,r),a=this.makeLine(t,n),[o,s]=this.makeLineArrow(e,r,t,n);return this.markers[0]=s,[this.rect,i,a,o]}computeState(){this.display=this.getDateDifference()}},Lj=class extends Fj{getElements(){let[e,t,n,r]=this.getScreenPoints(),i=this.makeLine(e,n),a=this.makeLine(t,r),[o,s]=this.makeLineArrow(e,n,t,r);return this.markers[0]=s,[this.rect,i,a,o]}computeState(){this.display=this.getPriceDifference()}},Rj=class extends Fj{get drawBorder(){return this.traits[z.AT_DRAW_BORDER]}getBorderElements(){if(!this.drawBorder)return[];let[e,t,n,r]=this.getScreenPoints();return[this.makeLine(e,r),this.makeLine(t,n),this.makeLine(e,n),this.makeLine(t,r)]}getElements(){let[e,t,n,r]=this.getScreenPoints(),[i,a]=this.makeLineArrow(e,r,t,n),[o,s]=this.makeLineArrow(e,n,t,r);this.markers=[a,s];let c=this.getBorderElements();return[this.rect,i,o].concat(c)}computeState(){this.display=this.getPriceDifference().concat(this.getDateDifference())}},zj=class extends $k{constructor(e,t){super(e,t),this.points=nA(e)}get priceLevels(){return zs(this.traits[z.AT_PRICE_LEVELS])}get timeLevels(){return zs(this.traits[z.AT_TIME_LEVELS])}get showAngles(){return this.traits[z.AT_SHOW_ANGLES]}get reverse(){return this.traits[z.AT_REVERSE]}get showLeftLabels(){return this.traits[z.AT_SHOW_LEFT_LABELS]}get showRightLabels(){return this.traits[z.AT_SHOW_RIGHT_LABELS]}get showTopLabels(){return this.traits[z.AT_SHOW_TOP_LABELS]}get showBottomLabels(){return this.traits[z.AT_SHOW_BOTTOM_LABELS]}getAngles(e,t){let n=this.getScreenPoints(),r=this.lineOnlyStyle(z.AT_LINE_2),i=(e,t)=>e.x===t.x&&e.y===t.y,a=(e,t)=>e.x===t.x||e.y===t.y,o=[];e.concat(t).flatMap(e=>[e.p1,e.p2]).map(e=>{o.some(t=>i(e,t))||o.push(e)});let s=n.map(e=>o.filter(t=>!a(t,e)).map(t=>this.makeLine(e,t))).flat();return s.forEach(e=>e.style=r),s}getElements(){let e=this.getLinesDataAtLevels(this.priceLevels,this.timeLevels),{priceLines:t,timeLines:n}=this.getLineElements(e),r=this.showAngles?this.getAngles(t,n):[];return[...t,...n,...r]}adornElements(e,t){let n=this.singleStyle,r=this.showBackground,i=t.fillStyle,a=cs(t,1)/2,o=e=>Number(e.toFixed(4)).toString(),{x:s,y:c}=z.DEFAULT_ADORN_OFFSET,l=(e,n,r,i,a)=>{let s=Ro(e,n);fs(t,o(r),s,i,a)},u=(e,n)=>{let r=new Path2D;ss(r,e.p1,n.p2),t.fillStyle=n.style.fillStyle,t.fill(r)},d=null;if(e.forEach(e=>{if(!e._data)return;let{level:t,isPrice:o}=e._data,f=n?i:e.style.strokeStyle,p=d&&r&&!n;o?(this.showLeftLabels&&l(e.p1,{x:s,y:a},t,w.Right,f),this.showRightLabels&&l(e.p2,{x:-s,y:a},t,w.Left,f),p&&u(d,e)):(this.showTopLabels&&l(e.p1,{x:0,y:c},t,w.Center,f),this.showBottomLabels&&l(e.p2,{x:0,y:-c*2},t,w.Center,f),p&&u(d,e)),d=e}),n&&r){let e=this.applyBackgroundOpacity(this.traits.line.color),n=new Path2D,[r,i]=this.getScreenPoints();ss(n,r,i),t.fillStyle=e,t.fill(n)}}resetComputedState(){this.lines=void 0}updateFrom(e,t,n,r,i){let a=e.reverse!==this.reverse;super.updateFrom(e,t,n,r,i),a&&this.resetComputedState()}getFlipAnchorIndices(){return[0,1]}},Bj=e=>e.map(e=>({...e,dimensions:e.value.split(`x`).map(Number)})),Vj=5,Hj=(e,t)=>Math.abs(e-t)<1e-7,Uj=class extends $k{_parsedFans=null;_parsedArcs=null;constructor(e,t){super(e,t),this.points=nA(e),this._parsedFans=this._parsedArcs=null}get levels(){return zs(this.traits[z.AT_LEVELS])}setComputedAndTraits(e,t){let n={...e,computed:t,traits:this.getTraitsFor(e)};return delete n.line,n}get computedLevels(){return this.levels.map(e=>this.setComputedAndTraits(e,e.value/Vj))}get showRangesRatio(){return this.traits[z.AT_SHOW_RANGES_RATIO]}get arcs(){return zs(this.traits[z.AT_ARCS])}get fans(){return zs(this.traits[z.AT_FANS])}get reverse(){return this.traits[z.AT_REVERSE]}get parsedFans(){return this._parsedFans===null&&(this._parsedFans=Bj(this.fans)),this._parsedFans}get computedFans(){let[,,e,t]=this.getReversedScreenPoints(),{dx:n,dy:r}=this.unit,{signX:i,signY:a}=this.getOrientation();return this.parsedFans.map(o=>{let[s,c]=o.dimensions;return this.setComputedAndTraits(o,s>=c?{x:e.x,y:e.y+c/s*a*Vj*r}:{x:t.x+s/c*Vj*i*n,y:t.y})})}get parsedArcs(){return this._parsedArcs===null&&(this._parsedArcs=Bj(this.arcs)),this._parsedArcs}get computedArcs(){let{dx:e}=this.unit;return this.parsedArcs.map(t=>{let[n,r]=t.dimensions;return this.setComputedAndTraits(t,Math.sqrt(e**2*(n**2+r**2)))})}getReversedScreenPoints(){let[e,t,n,r]=this.getScreenPoints();return this.reverse?[t,e,r,n]:[e,t,n,r]}get unit(){let[e,t]=this.getReversedScreenPoints();return e.x!==t.x&&e.y!==t.y?{dx:Math.abs(t.x-e.x)/Vj,dy:Math.abs(t.y-e.y)/Vj}:null}get priceBarRatio(){return this.traits[z.AT_PRICE_BAR_RATIO]}set priceBarRatio(e){this.traits[z.AT_PRICE_BAR_RATIO]=e}makeStyledLine(e,t,n){let r=this.makeLine(e,t);return this.singleStyle||(r.style=Ks(n)),r}getGridLines(e,t){let n=t.x-e.x,r=t.y-e.y;return this.computedLevels.map(({computed:i,traits:a})=>{let o=e.x+i*n,s=e.y+i*r;return[this.makeStyledLine({x:o,y:e.y},{x:o,y:t.y},a),this.makeStyledLine({x:e.x,y:s},{x:t.x,y:s},a)]}).flat()}getArcs(e){let{flipX:t,flipY:n,signY:r}=this.getOrientation(),{dx:i,dy:a}=this.unit,o=Hj(i,a)?null:{x:1,y:a/i},s=this.getClipPath();return this.computedArcs.map(({computed:i,traits:a})=>{let c=uj(e,i,t?r*Math.PI/2:0,t?Math.PI:r*Math.PI/2,n,this.axis);return o!==null&&(c.scale=o),c.clip=s,this.singleStyle||(c.style=Ks(a)),c})}getFans(e){return this.computedFans.map(({computed:t,traits:n})=>this.makeStyledLine(e,t,n))}getElements(){if(this.unit===null)return[];let[e,t]=this.getReversedScreenPoints(),n=this.getGridLines(e,t),r=this.getArcs(e),i=this.getFans(e);return[...n,...r,...i]}getOrientation(){let[e,t]=this.getReversedScreenPoints(),n=t.x<e.x,r=t.y<e.y;return{flipX:n,signX:n?-1:1,flipY:r,signY:r?-1:1}}getClipPath(){let[e,t]=this.getReversedScreenPoints(),n=new Path2D;return ss(n,e,t),n}adornElements(e,t){if(e.length===0)return;let n=(e,n,r)=>{t.fillStyle=r;let i=n.hasScale;i&&(t.save(),n.applyScale(t)),t.fill(e),i&&t.restore()};if(this.showBackground){let r=e.filter(e=>e.radius),i=this.getClipPath();if(t.save(),t.clip(i),this.singleStyle){let e=Ce(r);n(fj(null,e),e,this.applyBackgroundOpacity(this.traits.line.color))}else{let e=null;r.forEach(t=>{let r=fj(e,t),i=t.style.fillStyle;n(r,t,i),e=t})}t.restore()}if(this.showRangesRatio&&this.unit!==null){let e=Ce(this.computedLevels),n=(this.singleStyle?this:e).traits.line.color,[,r,i,a]=this.getReversedScreenPoints(),{x:o,y:s}=z.DEFAULT_ADORN_OFFSET,{flipX:c,signX:l,signY:u}=this.getOrientation(),d=Ro(i,{x:-o*l,y:s*u}),{priceDiff:f,barsDiff:p}=this.getLinesDataAtLevels(null,null),m=c?w.Right:w.Left;fs(t,p.toFixed(0),d,m,n);let h=Ro(a,{x:o*2*l,y:-s*u}),g=c?w.Left:w.Right;fs(t,this.formatter.format(f,W.Close),h,g,n);let _=Ro(r,{x:-o*l,y:-s*u});fs(t,this.priceBarRatio.toFixed(6),_,m,n)}}resetComputedState(){if(this.lines=void 0,this.points.length===4&&this.unit!==null){let{priceDiff:e,barsDiff:t}=this.getLinesDataAtLevels(null,null);this.priceBarRatio=Math.abs(e/t)}}updateFrom(e,t,n,r,i){if(super.updateFrom(e,t,n,r,i),this._parsedFans=this._parsedArcs=null,!Hj(e.priceBarRatio,this.priceBarRatio)){let[t,n,,]=this.points;this.reverse&&([t,n]=[n,t]);let{priceDiff:r,barsDiff:i}=this.getLinesDataAtLevels(null,null);n.update(t.price+Math.sign(r)*e.priceBarRatio*i,n.time),this.resetComputedState()}}getFlipAnchorIndices(){return[0,1]}},Wj=5,Gj=(e,t)=>{let n=new Path2D;return e===null||(as(n,e.p1),os(n,e.p2),os(n,t.p2),os(n,t.p1)),n},Kj=class extends Qk{constructor(e,t){super(e,t),this.addPoints(3)}get extend1(){return this.traits[z.AT_EXTEND_PT_1]}get extend2(){return this.traits[z.AT_EXTEND_PT_2]}getElements(){let[e,t,n]=this.getScreenPoints(),{x:r,y:i}=Lo(n,e),a=n=>{let[r,i]=[e,t].map(e=>Ro(e,n));return new Yk(r,i,this.extend1,this.extend2,this.axis)};return this.getColoredElements(({value:e})=>a({x:r*e,y:i*e}))}getTextRef(){return(e,t,n)=>({ref:t,spacing:Wj,offsetY:!0,text:this.formatLevelPrice(n,t.anchor1.y)})}adornElements(e,t){this.adornElementsForColoredFactors(e,Gj,this.getTextRef(),t)}};function qj(e,t,n){let r;switch(e.BarColoring){case`OpenToClose`:r=!1;break;case`CloseToClose`:r=!0;break;default:r=t()}return{levelMode:e.LevelMode,levelSize:St(1,1e3,e.LevelSize),useChange:r,valueRangePercent:e.ValueRangePercent/100,minMovement:n}}function Jj(e,t,n){if(!N(e)||e.length===0)return null;let r=t=>A(e,+t,Number),i=r(t),a=r(n);if(a<0||a>=e.length||i<0||i>=e.length)return null;let o=e[a];return!N(o)||(o.getTime()>n.getTime()&&--a,a<0)||i>a?null:[i,a]}function Yj(e,t,n=!1){if(e.bars.length===0||e.zone===0)return-1;let r=Math.floor((t-e.min)/e.zone);return n?Math.min(e.bars.length-1,r):r}function Xj(e,t){return{min:Number.MAX_VALUE,max:Number.MIN_VALUE,zone:0,bars:[],maxVolumeIndex:-1,firstDate:e,lastDate:t}}function Zj(e,t,n,r,i,a){let o=M(i)&&M(a);for(let s=t;s<=n;s++)if(o){let t=i[s];t>e.max&&(e.max=t);let n=a[s];n<e.min&&(e.min=n)}else{let t=r[s];t<e.min&&(e.min=t),t>e.max&&(e.max=t)}}function Qj(e,t){if(e.maxVolumeIndex===-1||e.bars.length===0)return;e.bars[e.maxVolumeIndex].isValue=!0;let n=me(e.bars.map(e=>e.totalVolume))*t,r=e.bars[e.maxVolumeIndex].totalVolume,i=e.maxVolumeIndex,a=e.maxVolumeIndex;for(;r<n;){let t=[{dir:`lower`,count:2,startIdx:i-2,endIdx:i-1},{dir:`lower`,count:1,startIdx:i-1,endIdx:i-1},{dir:`upper`,count:2,startIdx:a+1,endIdx:a+2},{dir:`upper`,count:1,startIdx:a+1,endIdx:a+1}].filter(t=>t.startIdx>=0&&t.endIdx<e.bars.length).map(t=>{let n=me(e.bars.slice(t.startIdx,t.endIdx+1).map(e=>e.totalVolume));return{...t,volume:n,newTotal:r+n}});if(t.length===0)break;let o=(e,t)=>t.newTotal<e.newTotal?t:e,s=(e,t)=>t.volume>e.volume?t:e,c=t.filter(e=>e.newTotal>=n),l=c.length>0?c.reduce(o):t.reduce(s);for(let t=l.startIdx;t<=l.endIdx;t++)e.bars[t].isValue=!0;if(l.dir===`lower`?i=l.startIdx:a=l.endIdx,r=l.newTotal,r>=n)break}}function $j(e,t,n,r,i,a,o,s){let c=Number.MIN_VALUE,l=!1;for(let u=t;u<=n;u++){let t=i[u],n=Yj(e,t,!0);if(n===-1){l=!0;break}let d=o[u],f=s.useChange?a[u]>=0:r[u]<=i[u],p=e.bars[n];f?p.upVolume+=d:p.downVolume+=d,p.totalVolume=p.downVolume+p.upVolume,p.totalVolume>c&&(c=p.totalVolume,e.maxVolumeIndex=n)}l||Qj(e,s.valueRangePercent)}function eM(e,t,n,r,i,a){let o=Xj(r,i),s=t=>e.getData(t),[c,l,u,d,f,p]=[`Open`,`High`,`Low`,`Close`,`Change`,`Volume`].map(e=>s(W[e]));Zj(o,t,n,d,l,u);let m=o.max-o.min,h=e=>({upVolume:0,downVolume:0,isValue:!1,totalVolume:0});if(a.levelMode===`Count`)o.zone=m/a.levelSize,o.bars=Oe(a.levelSize,h);else{let e=a.minMovement*a.levelSize,t=Math.max(1,Math.ceil(m/e));o.zone=m/t,o.bars=Oe(t,h)}return $j(o,t,n,c,d,f,p,a),o}function tM(e,t,n,r){let i=e.getTimeData(),a=Jj(i,t,n);if(!a)return null;let[o,s]=a,c=eM(e,o,s,t,n,r),l=c.bars.map((e,t)=>({priceLow:c.min+t*c.zone,priceHigh:c.min+(t+1)*c.zone,upVolume:e.upVolume,downVolume:e.downVolume,totalVolume:e.totalVolume,inValueArea:e.isValue})),u=l.filter(e=>e.inValueArea);return{from:i[o],to:i[s],barCount:s-o+1,priceLow:c.min,priceHigh:c.max,levelHeight:c.zone,totalVolume:me(l.map(e=>e.totalVolume)),pointOfControl:c.maxVolumeIndex===-1?null:l[c.maxVolumeIndex],valueArea:u.length===0?null:{priceLow:u[0].priceLow,priceHigh:u[u.length-1].priceHigh,totalVolume:me(u.map(e=>e.totalVolume))},levels:l}}var nM=class extends Zk{levelSize=0;alignLeft=!0;totalVolume=!1;widthPercent=30;useChange=!1;studyPlotId;gotData;boxes=[];periodType=`VisibleScreen`;period=0;valueRangePercent=.7;levelMode=`Count`;usesFinerGrainedAgg=!0;constructor(e,t,n){super(e,t),this.computed=!0,this.studyPlotId=n,this.gotData=!1}setOptions(e){let t=qj(e,()=>(this.presenter.mainPlot?.mainCurve?.attributes)?.includes(m.ChangeBased)??!1,1);this.levelMode=t.levelMode,this.levelSize=t.levelSize,this.useChange=t.useChange,this.valueRangePercent=t.valueRangePercent,this.alignLeft=e.Position===`Left`,this.totalVolume=e.Volume===`Total`,this.widthPercent=St(5,100,e.WidthPercent)/100,M(e.PeriodType)&&(this.periodType=e.PeriodType),this.period=e.Period;let n=re[$()?.config.mode??`Unspecified`];this.usesFinerGrainedAgg=Vc(n)}get settings(){return{levelMode:this.levelMode,levelSize:this.levelSize,useChange:this.useChange,valueRangePercent:this.valueRangePercent,minMovement:this.presenter.mainPlot?.metaData.minMovement??0}}get isCountMode(){return this.levelMode===`Count`}get canComputeProfile(){if(this.isCountMode)return!0;let{minMovement:e}=this.settings;return Number.isFinite(e)&&e>0}onFormatterChanged(){this.boxes=[],this.gotData=!1}updateLastBox(){if(this.boxes.length>0){let e=this.boxes.pop(),t=this.getDataForRange(e.firstDate,e.lastDate);t&&this.boxes.push(t)}}invalidate(e){switch(this.periodType){case`VisibleScreen`:this.gotData=!1,this.boxes=[];break;case`Bars`:case`Days`:switch(e){case`DataPointAdded`:{let e=this.studySeries.innCont(0)?.getTimeData();if(!N(e))return;let t=e[e.length-1],n=this.boxes.length>0?this.boxes[this.boxes.length-1]:null;if(M(n)&&t.valueOf()<n.lastDate.valueOf())this.updateLastBox();else{let e=this.getDataForRange(t,this.getBoxEndFromStart(t));e&&this.boxes.push(e)}break}case`DataPointChanged`:this.updateLastBox();break;case`NewChunkArrived`:this.gotData=!1}}}getBoxRect(e){switch(this.periodType){case`VisibleScreen`:return this.axis.pane.getBoundsWithoutScales();case`Bars`:case`Days`:{let t=this.axis.pane.presenter.view.xAxis.xScale.bar,n=this.axis.toY(e.min),r=this.axis.toY(e.max),i=this.axis.pane.presenter.view.toX(e.firstDate)-t.width/2,a=0;if(this.periodType===`Days`){let n=e.lastDate,r=this.axis.pane.presenter.view.xAxis.xScale.timeline,o=r.at(r.lastSeriesIndex),s=o.valueOf()<n.valueOf(),c=s?o:n,l=(s?1:-2)*t.width/2;a=this.axis.pane.presenter.view.toX(c)+l-i}else a=this.period*t.width+(this.period-1)*t.spacing;return new rs(i,r,a,n-r)}default:throw Error(`Unexpected period type for Volume At Price annotation`)}}getElementsForBox(e){let t=this.getBoxRect(e),n=[];if(this.isPeriodic){let e=new Xk({x:t.x,y:t.y},t.width,t.height,this.axis);e.style=this.backgroundStyle,n.push(e)}let{x:r,width:i}=t,a=i*this.widthPercent,o=e.bars[e.maxVolumeIndex];return e.bars.forEach((t,s)=>{let{upVolume:c,downVolume:l,totalVolume:u,isValue:d}=t;if(c===0&&l===0)return null;let f=this.axis.toY(e.min+s*e.zone),p=this.axis.toY(e.min+(s+1)*e.zone),m=Math.abs(f-p),h=(e,t,n=0)=>{let a=new Xk({x:this.alignLeft?r+n:r+i-e-n,y:p},e,m,this.axis);return a.style=t,a},g=(e,t,n)=>e/t.totalVolume*n,_=this.studyPlot.curves[2].visible,v=_&&d?this.upValueStyle:this.upStyle,y=_&&d?this.downValueStyle:this.downStyle,b=_&&d?this.totalValueStyle:this.totalStyle;if(this.totalVolume){let e=g(u,o,a);n.push(h(e,b))}else{let e=g(l,o,a),t=g(c,o,a);n.push(h(t,v),h(e,y,t))}if(this.studyPlot.curves[1].visible&&s===e.maxVolumeIndex){let e=n[n.length-1].rect,t=this.alignLeft?e.x+e.width:r,a=(p+f)/2,o=this.alignLeft?r+i:e.x;n.push(new Yk({x:t,y:a},{x:o,y:a},!1,!1,this.axis))}}),n}get isVisible(){return super.isVisible&&this.studyPlot.isVisible&&this.studyPlot.mainCurve.visible}getElements(){if(this.gotData||this.getData(),!this.gotData||!this.isVisible||this.boxes.length===0)return[];switch(this.periodType){case`VisibleScreen`:{let e=this.boxes[0];return!e||e.bars.length===0?[]:this.getElementsForBox(e)}case`Bars`:case`Days`:{let[e,t]=this.presenter.view.xAxis.xScale.domain()||[];if(!zn(e)||!zn(t))return[];let n=this.boxes.findIndex(t=>t.firstDate.getTime()<=e.getTime()&&t.lastDate.getTime()>=e.getTime());n===-1&&(n=0,this.studySeries.loadMoreData());let r=this.boxes.findIndex(e=>e.firstDate.getTime()<=t.getTime()&&e.lastDate.getTime()>=t.getTime());r===-1&&n!==-1&&(r=this.boxes.length-1);let i=[];for(let e=n;e<=r;e++)i.push(...this.getElementsForBox(this.boxes[e]));return i}default:throw Error(`Unexpected period type for Volume At Price annotation`)}}getStyleForElement(e,t){return e.style||super.getStyleForElement(e,t)}get presenter(){return this.axis.pane.presenter}get downStyle(){return this.fillOnlyStyle(z.AT_FILL)}get upStyle(){return this.fillOnlyStyle(z.AT_FILL2)}get totalStyle(){return this.fillOnlyStyle(z.AT_FILL3)}get downValueStyle(){return this.fillOnlyStyle(z.AT_FILL4)}get upValueStyle(){return this.fillOnlyStyle(z.AT_FILL5)}get totalValueStyle(){return this.fillOnlyStyle(z.AT_FILL6)}get backgroundStyle(){return this.fillOnlyStyle(z.AT_FILL7)}get lineStyle(){return this.lineOnlyStyle(z.AT_LINE)}getBoxEndFromStart(e){switch(this.periodType){case`VisibleScreen`:default:return null;case`Days`:return sr(Rg(g.Day,this.period)(e),1);case`Bars`:{let t=this.axis.pane.presenter.data.aggregation;return sr(Rg(t.unit,t.size*this.period)(e),1)}}}getData(){if(!this.canComputeProfile)return;let e=this.axis.pane.presenter.data.aggregation;if(e.isTick||e.hasSpec&&!FE(e.spec))return;let[t,n]=this.presenter.view.xAxis.xScale.domain()||[];if(!zn(t)||!zn(n))return;let r=Rg(e.unit,e.size);switch(this.periodType){case`VisibleScreen`:{let e=this.boxes[0];if(!e||e.firstDate!==t||e.lastDate!==n){let e=this.getDataForRange(t,n);e&&(this.boxes[0]=e)}else this.gotData=!0;break}case`Bars`:{let[e,t]=[0,1].map(e=>this.studySeries.innCont(e));if((e?.size??0)<1||(t?.size??0)<1)return;let n=e.getTimeData(),i=0;for(this.boxes=[];i<n.length;){let e=n[i],t=i+this.period,a=sr(t<n.length?n[t]:r(n[n.length-1]),1),o=this.getDataForRange(e,a);o&&this.boxes.push(o),i+=this.period}this.gotData=!0;break}case`Days`:{if(e.isEndOfDay){this.boxes=[],this.gotData=!0;return}let[t,n]=[0,1].map(e=>this.studySeries.innCont(e));if((t?.size??0)<1||(n?.size??0)<1)return;let i=t.getTimeData(),a=t.getData(W.TradingDay),o=e=>{let t=0,n=i[e],r=a[e];for(let o=e;o<i.length;o++)if(wn(i[o],n)>0&&a[o]!==r&&(t+=1,n=i[o],r=a[o],t===this.period))return o;return-1},s=0,c=i[s],l=o(s)-1;for(;(l<0||l===s)&&s<i.length;)s+=1,l=o(s)-1;for(this.boxes=[];s<i.length&&l<i.length&&s<l;){let e=sr(r(i[l]),1),t=this.getDataForRange(c,e);t&&this.boxes.push(t),s=l+1,c=i[s],l=o(s)-1}if(l<0&&s<i.length-1){let e=sr(r(i[i.length-1]),1),t=this.getDataForRange(i[s],e);t&&this.boxes.push(t)}this.gotData=!0;break}}}getBoxAt(e){if(this.boxes.length===0)return null;switch(this.periodType){case`VisibleScreen`:{let t=this.boxes[0];return t.firstDate>e||t.lastDate<e?null:t}case`Bars`:case`Days`:{let t=e.getTime();return this.boxes.find(e=>e.firstDate.getTime()<=t&&e.lastDate.getTime()>=t)||null}}}getValueAt(e,t,n){if(!this.isVisible)return null;let r=this.getBoxAt(t);if(!r)return null;let i=Yj(r,n);if(i<0||i>=r.bars.length)return null;let a=r.bars[i];switch(e){case W.UPVOL:return this.totalVolume?null:a.upVolume;case W.DNVOL:return this.totalVolume?null:a.downVolume;case W.TOTVOL:return this.totalVolume?a.totalVolume:null;case W.POC:case W.VAREA:case W.BARBACK:return null;default:throw Error(`Unexpected Volume At Price field`)}}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}get isPeriodic(){return this.periodType===`Bars`||this.periodType===`Days`}get isVisibleScreen(){return this.periodType===`VisibleScreen`}getDataForRange(e,t){if(!this.canComputeProfile)return null;let n=this.studySeries.innCont(1),r=n?.getTimeData(),i=Jj(r,e,t);if(!i)return null;let[a,o]=i;if(this.axis.pane.presenter.data.aggregation.unit===g.Day&&this.periodType===`Bars`){let e=n.getData(W.TradingDay),t=e[a];for(;t===e[a]&&a>0;)--a;a+=1;let i=0;for(o=a;o<r.length&&i<this.period;)e[o]!==t&&(i+=1,t=e[o]),o+=1;o-=2}this.isVisibleScreen&&this.usesFinerGrainedAgg&&a<1e3&&this.studySeries.loadMoreData();let s=eM(n,a,o,e,t,this.settings);return this.gotData=!0,s}},rM=[`None`,`Absolute`,`Percent`],iM=`#16A34A`,aM=`#DC2626`;function oM(e){return typeof e==`string`&&rM.includes(e)}var sM=class extends Zk{studyPlotId;displayMode=`None`;visibleLabelSegments=[];constructor(e,t,n){super(e,t),this.studyPlotId=n}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}setOptions(e){let t=e.ReversalChange;this.displayMode=oM(t)?t:`None`}formatSegmentValue(e,t){return this.displayMode===`Absolute`?this.formatter.format(t-e,W.Close):this.displayMode===`Percent`?e===0?``:this.formatter.format((t-e)/e,W.PercentChange):``}getElements(){if(this.visibleLabelSegments=[],!this.studyPlot.isVisible||!this.studyPlot.mainCurve.visible)return[];let e=this.studySeries.getCurrentState();if(!e)return[];let t=e.confirmedPivots,n=Array.from(t.keys()).sort((e,t)=>e-t);if(n.length===0)return[];let r=this.presenter.mainPlot?.timeSeries?.container;if(!r||r.size<2)return[];let i=r.getTimeData();if(!i)return[];let a=this.presenter.view,[o,s]=a.xAxis.xScale.domain()||[];if(!o||!s)return[];let c=o.getTime(),l=s.getTime(),u=-1,d=-1;for(let e=0;e<n.length;e++){let t=i[n[e]].getTime();if(u===-1&&t>=c&&(u=Math.max(0,e-1)),t<=l)d=e;else if(u!==-1)break}if(u===-1){if(n.length>0&&i[n[0]].getTime()>l)return[];u=n.length-1,d=n.length-1}else d===-1&&(d=u);d=Math.min(n.length-1,d+1);let f=[];for(let e=u;e<d;e++){let r=n[e],o=n[e+1],s=t.get(r),u=t.get(o),d=a.toX(i[r]),p=this.axis.toY(s),m=a.toX(i[o]),h=this.axis.toY(u);f.push(this.makeLine({x:d,y:p},{x:m,y:h}));let g=i[o].getTime();g>=c&&g<=l&&this.visibleLabelSegments.push({fromPrice:s,toPrice:u,toPoint:{x:m,y:h}})}if(N(e.pivotPrice)&&N(e.candPrice)){let t=i[e.pivotIndex].getTime();if(i[e.candIndex].getTime()>=c&&t<=l){let t=a.toX(i[e.pivotIndex]),n=this.axis.toY(e.pivotPrice),r=a.toX(i[e.candIndex]),o=this.axis.toY(e.candPrice);f.push(this.makeLine({x:t,y:n},{x:r,y:o}))}}return f}adornElements(e,t){if(this.displayMode===`None`||this.visibleLabelSegments.length===0)return;let n=Math.abs(ls(t,!0));this.visibleLabelSegments.forEach(e=>{let r=this.formatSegmentValue(e.fromPrice,e.toPrice);if(r===``)return;let i=e.toPrice>=e.fromPrice;fs(t,r,{x:e.toPoint.x,y:e.toPoint.y+(i?-n:n)},w.Right,i?iM:aM)})}},cM=[z.AT_LINE,z.AT_LINE_2,z.AT_LINE_3],lM=class extends Zk{studyPlotId;constructor(e,t,n){super(e,t),this.studyPlotId=n}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get studySeries(){return this.studyPlot.timeSeries}isCurveVisible(e){return this.studyPlot.curves[e]?.visible??!1}getChannelPrices(){let e=this.studySeries.getCurrentState();if(!e)return null;let{startIndex:t,endIndex:n,slope:r,intercept:i,stdDevWidth:a}=e;if(!M(t)||!M(n)||!M(r)||!M(i)||!M(a)||!Qe(r)||!Qe(i)||!Qe(a))return null;let o=n-t+1;if(o<1)return null;let s=e=>i+r*(e+1),c=s(0),l=s(o-1);return{start:[c+a,c,c-a],end:[l+a,l,l-a]}}makeLines(){if(!this.studyPlot?.isVisible)return null;let e=this.studySeries.getCurrentState(),t=this.getChannelPrices();if(!e||!t)return null;let{startIndex:n,endIndex:r,extendLeft:i,extendRight:a}=e;if(!M(n)||!M(r))return null;let o=this.studyPlot.basePlot?.timeSeries?.container??this.presenter.mainPlot?.timeSeries?.container;if(!o||o.size<2)return null;let s=o.getTimeData();if(!s||s.length<=r)return null;let c=this.presenter.view,[[l,u,d],[f,p,m]]=[t.start,t.end],h=c.toX(s[n]),g=c.toX(s[r]),_=(e,t,n)=>{let r=this.axis.toY(e),o=this.axis.toY(t),s=new Yk({x:h,y:r},{x:g,y:o},i,a,this.axis);return s._data={lineIndex:n},s};return[_(l,f,0),_(u,p,1),_(d,m,2)]}getStyleForElement(e,t){let n=cM[e._data?.lineIndex??t],r=this.traits[n];return r?Ks({line:r,fill:{color:z.COLOR_TRANSPARENT}}):super.getStyleForElement(e,t)}getElements(){let e=this.makeLines();return e?e.filter((e,t)=>this.isCurveVisible(t)):[]}getPriceScaleAdornments(){let e=this.getChannelPrices();if(!e)return[];let t=[this.traits?.[z.AT_LINE]?.color,this.traits?.[z.AT_LINE_2]?.color,this.traits?.[z.AT_LINE_3]?.color];return e.end.map((e,n)=>({price:e,color:t[n]??this.traits?.line?.color??`#000`}))}getDomainPrices(){let e=this.getChannelPrices();return e?[...e.start,...e.end]:[]}adornElements(e,t){let n=this.makeLines();if(!n||!n.every(e=>N(e.p1,e.p2)))return;let[r,i,a]=n,o=(e,n,r)=>{t.fillStyle=r,t.fill(Gj(e,n))};this.isCurveVisible(3)&&o(r,i,this.traits?.[z.AT_FILL]?.color),this.isCurveVisible(4)&&o(i,a,this.traits?.[z.AT_FILL2]?.color)}},uM=class extends Zk{studyPlotId;constructor(e,t,n){super(e,t),this.studyPlotId=n,this.computed=!0}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get isVisible(){return this.visible&&(this.studyPlot?.isVisible??!1)}getValueAt(e,t){let n=this.studyPlot;if(!this.visible||!n?.isVisible)return null;let r=n.timeSeries,i=n.curves.find(t=>t.fields.includes(e));if(i.shift!==0){let e=this.presenter.timeline,n=A(e,+t,Number,Jv),r=e.at(n-i.shift);if(!r)return null;t=r}let a=r.base.getTimeData(),o=r.getPeriods(),s=o[A(o,+t,e=>+a[e.endIndex])];return!s||t<a[s.startIndex]||t>a[s.endIndex]?null:s.levels[e.id]??null}getDomainPrices(){let e=this.studyPlot,t=e?.timeSeries;if(!e||!this.isVisible||!t?.hasData)return[];let n=t.base.getTimeData();return t.getPeriods().flatMap(t=>e.curves.flatMap(e=>{if(!e.visible)return[];let r=this.presenter.view?.xAxis?e.shiftedTimeDomain:null;if(r&&(n[t.endIndex]<r[0]||n[t.startIndex]>r[1]))return[];let i=e.fields[0],a=t.levels[i.id];if(a==null||!Number.isFinite(a))return[];let o=this.axis.priceMap(a);return o!=null&&Number.isFinite(o)?[o]:[]}))}getElements(){let e=this.studyPlot,t=e?.timeSeries,n=this.presenter.view?.xAxis?.xScale;if(!this.isVisible||!e||!t?.hasData||!n?.range())return[];let r=t.base.getTimeData(),[i,a]=n.range(),o=n.bar.totalWidth/2,s=[],c=!1;for(let l of t.getPeriods()){let u=n.timeToIndex(r[l.startIndex]),d=n.timeToIndex(r[l.endIndex]);u!=null&&d!=null&&e.curves.forEach((e,r)=>{if(!e.visible)return;let f=n.indexToX(u+e.shift)-o,p=n.indexToX(d+e.shift)+o;if(p<i||f>a)return;t.hasHistoryFor(l.key)||(c=!0);let m=e.fields[0],h=l.levels[m.id];if(h==null||!Number.isFinite(h))return;let g=this.axis.priceMap(h);if(g==null||!Number.isFinite(g))return;let _=e.priceToY(g),v=new Yk({x:f,y:_},{x:p,y:_},!1,!1,this.axis);v._data={curveIndex:r,startIndex:l.startIndex,price:h},s.push(v)})}return c&&t.loadMoreData(),s}getStyleForElement(e){let t=this.studyPlot.curves[e._data.curveIndex];return Ks({line:{color:t.getColor(e._data.startIndex),width:t.lineWidth,dashStyle:t.dashStyle??`Solid`},fill:{color:z.COLOR_TRANSPARENT}})}adornElements(e,t){if(!this.showPrices)return;let n=this.studyPlot,[r,i]=this.presenter.view.xAxis.xScale.range(),a=Math.abs(ls(t,!0)),o={};Sy(n,this.presenter,o);for(let s of e){let e=s,{curveIndex:c,startIndex:l,price:u}=s._data,d=n.curves[c],f=n.metaData.format(u,d.fields[0],o),p=Math.max(r,e.p1.x),m=Math.min(i,e.p2.x);t.measureText(f).width+8>m-p||fs(t,f,{x:p+4,y:e.p1.y-a},w.Left,d.getColor(l))}}};function dM(e){let t=e<0?-1:1,n=Math.abs(e)/Math.SQRT2,r=1/(1+.3275911*n);return .5*(1+t*(1-((((1.061405429*r+-1.453152027)*r+1.421413741)*r+-.284496736)*r+.254829592)*r*Math.exp(-n*n)))}var fM=class extends Zk{studyPlotId;periodTarget=0;targetPrice1=0;targetPrice2=0;pricesCount=0;targetDate;computed=!1;anchorPrice=0;sigmaAnnualized=0;unitsPerYear=0;probabilityAbove=0;probabilityBelow=0;probabilityBetween=0;styles=[];constructor(e,t,n){super(e,t),this.studyPlotId=n}makeStyles(){let e=this.lineOnlyStyle(z.AT_LINE),t=this.lineOnlyStyle(z.AT_LINE_2);this.styles=[e,t,t]}containerOf(e){return e?.timeSeries.container}get mainCont(){return this.containerOf(this.presenter.mainPlot)}get studyCont(){return this.containerOf(this.studyPlot)}get studyPlot(){return this.presenter.allPlots.find(e=>e.id===this.studyPlotId)}get targetPrice(){return this.targetPrice1===0?this.targetPrice2:this.targetPrice1}setOptions(e){if(this.periodTarget=e.PeriodTarget,this.targetPrice1=e.TargetPrice1,this.targetPrice2=e.TargetPrice2,this.pricesCount=(this.targetPrice1===0?0:1)+(this.targetPrice2===0?0:1),this.pricesCount>1&&this.targetPrice1<this.targetPrice2){let e=this.targetPrice1;this.targetPrice1=this.targetPrice2,this.targetPrice2=e}}get haveInput(){return this.periodTarget!==0&&(this.targetPrice1!==0||this.targetPrice2!==0)}get haveData(){return M(this.mainCont)&&!this.mainCont.isEmpty&&this.studySeries.haveVolatility}get studySeries(){return this.studyPlot.timeSeries}getData(){let e=this.presenter.timeline;this.targetDate=e.at(e.lastSeriesIndex+this.periodTarget),this.points=[new Uk(this.axis,this.targetPrice,this.targetDate)],this.pricesCount>1&&this.points.push(new Uk(this.axis,this.targetPrice2,this.targetDate)),this.unitsPerYear=nk(this.presenter.data.aggregation),this.anchorPrice=this.mainCont.getLastDataPoint(W.Close),this.sigmaAnnualized=this.studySeries.getVolatilityPercent()}computeProbabilities(){let e=this.sigmaAnnualized*Math.sqrt(this.periodTarget/this.unitsPerYear),t=t=>(t-this.anchorPrice)/(this.anchorPrice*e),n=dM(t(this.targetPrice));if(this.pricesCount>1){let e=dM(t(this.targetPrice2));this.probabilityAbove=1-n,this.probabilityBelow=e,this.probabilityBetween=n-e}else this.probabilityBelow=n,this.probabilityAbove=1-this.probabilityBelow;this.computed=!0}compute(){this.haveInput&&this.haveData&&(this.getData(),this.computeProbabilities())}getElements(){if(this.computed||this.compute(),!this.computed||!this.studyPlot.isVisible||!this.studyPlot.mainCurve.visible)return[];let e=[];return e.push(new Hk(this.points[0].point,!0,this.axis)),e.push(new Hk(this.points[0].point,!1,this.axis)),this.pricesCount>1&&e.push(new Hk(this.points[1].point,!1,this.axis)),e}getStyleForElement(e,t){return this.styles.length||this.makeStyles(),this.styles[t]}get hasPoint(){return this.points.length>0}getTimeScaleAdornments(){return this.hasPoint?[{time:this.points[0].time,color:this.traits.line.color}]:[]}getPriceScaleAdornments(){if(!this.hasPoint)return[];let e=[];return e.push({price:this.points[0].price,color:this.traits.line2.color}),this.pricesCount>1&&e.push({price:this.points[1].price,color:this.traits.line2.color}),e}adornElements(e,t){if(this.computed){let[e,n]=[!0,!1].map(e=>Math.abs(ls(t,e))),r=this.pricesCount>1,i=this.points[0].point,a=r?this.points[1].point:i,o=this.traits.line2.color,s=Qo(o),c=cs(t),l=[`Above`,`Below`,`Between`],u=(e,t)=>`${Ze(e*100,2).toFixed(2)}% Probability ${l[t]}`,d=(e,n)=>fs(t,e,n,w.Right,s,o);if(d(u(this.probabilityAbove,0),{x:i.x-10,y:i.y-e}),r){let e=i.y+(a.y-i.y+c)/2;d(u(this.probabilityBetween,2),{x:i.x-10,y:e})}d(u(this.probabilityBelow,1),{x:a.x-10,y:a.y+n})}}},pM=new UA,mM=e=>Q(WA,xj,1,e),hM=e=>Q(WA,oA,1,e),gM={Default:()=>function(){return pM},Line:()=>Q(cA,ZA,!1),DateRange:()=>Q(cA,Ij,!1),PriceRange:()=>Q(cA,Lj,!1),DatePriceRange:()=>Q(cA,Rj,!1),GannBox:()=>Q(cA,zj,!1),GannSquare:()=>Q(uA,Uj),Ray:()=>Q(cA,ZA,!1),GannLine:()=>Q(lA,ZA,!1),VerticalLine:()=>Q(WA,QA,1),HorizontalLine:()=>Q(WA,$A,1),LongPosition:()=>Q(WA,Pj,1,!0),ShortPosition:()=>Q(WA,Pj,1,!1),FiftyPercentLine:function(e,t){return N(e)?Q(GA,ej,e.axis||t.mainAxis,e):Q(WA,ej,2)},FibonacciRetracement:()=>Q(cA,rj,!1),TrendBasedFibExtension:()=>Q(cA,ij,!0),FibonacciFan:()=>Q(cA,cj,!1),FibonacciArcs:()=>Q(cA,mj,!1),FibonacciChannel:()=>Q(cA,Kj,!0),GannFan:()=>Q(cA,hj,!1),SpeedResistanceFan:()=>Q(cA,gj,!1),SpeedResistanceArcs:()=>Q(cA,_j,!1),AndrewsPitchfork:()=>Q(WA,vj,3),Rectangle:()=>Q(cA,PA,!1),Ellipse:()=>Q(cA,yj,!1),TrendChannel:()=>Q(cA,bj,!0),SymbolArrowUp:()=>mM(`arrow_up`),SymbolArrowDown:()=>mM(`arrow_down`),SymbolArrowRight:()=>mM(`arrow_right`),SymbolArrowLeft:()=>mM(`arrow_left`),SymbolArrowHorizontal:()=>mM(`arrow_horizontal`),SymbolArrowVertical:()=>mM(`arrow_vertical`),SymbolArcDown:()=>mM(`arc_down`),SymbolArcUp:()=>mM(`arc_up`),SymbolThumbsUp:()=>mM(`thumbs_up`),SymbolThumbsDown:()=>mM(`thumbs_down`),SymbolZero:()=>mM(`zero`),SymbolOne:()=>mM(`one`),SymbolTwo:()=>mM(`two`),SymbolThree:()=>mM(`three`),SymbolFour:()=>mM(`four`),SymbolFive:()=>mM(`five`),SymbolSix:()=>mM(`six`),SymbolSeven:()=>mM(`seven`),SymbolEight:()=>mM(`eight`),SymbolNine:()=>mM(`nine`),SymbolQuestion:()=>mM(`question`),SymbolFishHook:()=>mM(`fish_hook`),SymbolLetterB:()=>mM(`letter_b`),SymbolLetterS:()=>mM(`letter_s`),SymbolLetterA:()=>mM(`letter_a`),SymbolLetterC:()=>mM(`letter_c`),SymbolLetterD:()=>mM(`letter_d`),SymbolLetterE:()=>mM(`letter_e`),FibonacciTimeZones:()=>Q(cA,Sj,!1),Text:()=>Q(dA,aA,null),PickPoint:()=>function(){return new Cj},ZoomIn:()=>function(){return new LA},ProfitLoss:hM,RewardRisk:hM,VolumeAtPrice:function(e){return Q(WA,nM,2,e)},ZigZag:function(e){return Q(GA,sM,null,e)},ProbabilityCones:function(e){return Q(WA,fM,2,e)},LinearRegressionChannel:function(e){return Q(GA,lM,null,e)},PivotPoints:function(e){return Q(GA,uM,null,e)}};function _M(e,t=!1,n=null,r=null,i=null){let a=gM[e];return a=a(r,i),a(e,t,n)}function vM(e,t={}){e.enableTooltip(!0),e.resetActiveTool();let{axis:n,annotation:r,toolChange:i,annId:a}=t;N(n)&&e.onAnnotationsUpdated(n),N(r)&&e.onAnnotationModifiedByTool(r,i),[D.Cancelled,D.Executed,D.TextChanged].includes(i)&&e.onAnnotationDone(a,i)}function yM(e,t=!0,n=D.None){e.wasModifiedByTool();let r=e.axis,i={axis:r,annotation:e,toolChange:n};vM(r.pane.presenter,t?i:void 0)}function Q(e,t,n,r){return function(i,a,o){let s=Jk(i,t,r,o);return s.annName=i,a?s:new e(s,n)}}function bM(e){e.button===T.Right&&vM(e.presenter)}function xM(e,t,n){let r={};r.inputs=ft(e.inputs);let i=r.inputs[z.INPUT_SOURCE],a=M(i)?W[i]:void 0;r.source=W[e.source]??a;let o=e.target!==void 0,s=N(n)?n:e.curves;return r.outFields=ke(o?[W[e.target]]:s.map(e=>e.fields).flat()),r.target=o?W[e.target]:r.outFields[0],r.aggregation=t,r}function SM(e){return Array.isArray(e.innerSeries)}function CM(e){return e.query?.symbol===z.PLACEHOLDER_SYMBOL_NAME?!0:SM(e)?e.innerSeries.some(e=>CM(e)):!1}var wM=class extends Fk{model;basePlot;_hasEvents;_params;_shiftFmt;_title;range;shouldMaybePriceMap;_canPriceMap;#e(e=3){let t=this.model.inputs||[],n=this.model.study===`AVWAP`?TT(t):t.map(e=>e.value);if(n.length===0)return``;let r=``;return n.length>e&&(n=n.slice(0,e),r=`, ...`),`(${n.join(`, `)}${r})`}get params(){return N(this._params)||(this._params=this.#e()),this._params}get fullParams(){return this.#e(Number.MAX_VALUE)}get shiftFmt(){if([`PC`,`TARGP`].includes(this.model.study))return``;if(!N(this._shiftFmt)){let e=this.curves.map(e=>Number(e.shift)).filter(e=>e!==0);this._shiftFmt=e.length===0?``:`[${e.join(`, `)}]`}return this._shiftFmt}get title(){if(!N(this._title)){let e=this.params,t=this.shiftFmt;this._title=`${this.model.study} ${e} ${t}`.trim()}return this._title}getStandalonePaneTitle(){let e=this.getStandalonePaneBasisTitle();return e?`${this.title} on ${e}`:this.title}getStandalonePaneBasisTitle(){if(this.model?.basis?.kind!==`seasonal`)return null;let e=this.basePlot;if(!e?.isSeasonal)return null;let t=e;if(t.isFutures&&!t.hasComputation){let t=e.metaData?.symbol;if(typeof t==`string`&&t.length>0)return t}return e.title||null}fromModel(e){this.model=e,super.fromModel(this.model)}getMetaData(e){let t=e.meta.decimals;this.metaData=t===void 0?this.basePlot.metaData:new xo(t),N(e.meta.range)&&(this.range=e.meta.range)}setStudyAnnotation(e){this.annotations=[e]}getDetachedScaleMargins(){return this.model?.study===`VOL`&&this.axis?.pane.isMain?z.VOLUME_DETACHED_SCALE_MARGINS:super.getDetachedScaleMargins()}applySpecifics(e){let t=this.model.study,n=B(t);n.meta.shiftable===!0&&this.curves.forEach(t=>{Number.isFinite(e.inputs.Offset)&&(t.shift=e.inputs.Offset)});let r=(e,t,n)=>this.curves[e].zones[t].value=this.model.levels[n].value;switch(t){case`PIVPTS`:{this.customPlotValues=!0;let t=_M(`PivotPoints`,!0,{[z.AT_SHOW_PRICES]:e.inputs.ShowPrices!==`No`},this.id);this.setStudyAnnotation(t(this.axis,!1));break}case`ICHCLD`:{let t=e.inputs.Displacement;this.curves[2].shift=-t,this.curves[3].shift=t,this.curves[4].shift=t,this.curves[5].shift=t;break}case`MARIB`:{let t=Math.min(Math.max(0,e.inputs.Count),10);this.curves.forEach((e,n)=>e.visible=e.visible&&n<t);break}case`CRS`:{let t=e.inputs.Display===`PercentChange`;this.axis.comparison=t?x.Percent:x.None;break}case`PERF`:{let t=e.inputs.Anchor===`VisibleStart`;this.axis.comparison=t?x.Percent:x.None;break}case`HV`:e.inputs.Calculation===`Absolute`&&delete n.meta.decimals;break;case`JPI`:case`CTTP`:case`CTTI`:{let t=Oe(10,e=>(e+1)*.025),n=e=>t.map(t=>Jo(t)(e)),r=([e,t])=>[...n(e).reverse(),t,`#6a4a3a`,`#a000c8`,`#ffffff`];this.curves[0].colors=r(this.curves[0].colors),this.curves[1].colors=r(this.curves[1].colors);let i=this.curves[0].colors.length;this.curves[0].colors[i-1]=this.curves[1].colors[t.length],this.curves[1].colors[i-1]=this.curves[0].colors[t.length],this.shouldMaybePriceMap=e.inputs.Height===`Performance`;break}case`RSI`:case`RSIMOD`:case`RSISTO`:case`CCI`:r(0,0,0),r(0,1,2);break;case`STC`:r(0,0,0),r(0,1,1);break;case`RVOL`:case`DPO`:case`COPP`:r(0,0,0);break;case`VOL`:this.setCurveAttributes(0,e.inputs.BarColoring);break;case`MAVOL`:this.setCurveAttributes(1,e.inputs.BarColoring);break;case`VOLAP`:{this.notifyAboutPriceDomains=!0,this.customPlotValues=!0;let t=this.curves[1],n=this.curves[2],r=_M(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.AT_FILL6]:{color:n.colors[2]}},this.id)(this.axis,!1);r.setOptions(e.inputs),this.setStudyAnnotation(r);break}case`PVACP`:{this.customPlotValues=!0;let t=this.curves[1],n=this.curves[2],r=this.curves[3],i=_M(`VolumeAtPrice`,!0,{[z.AT_LINE]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle},[z.AT_FILL]:{color:this.curves[0].colors[0]},[z.AT_FILL2]:{color:this.curves[0].colors[1]},[z.AT_FILL3]:{color:this.curves[0].colors[2]},[z.AT_FILL4]:{color:n.colors[0]},[z.AT_FILL5]:{color:n.colors[1]},[z.AT_FILL6]:{color:n.colors[2]},[z.AT_FILL7]:{color:r.colors[0]}},this.id)(this.axis,!1);i.setOptions(e.inputs),this.setStudyAnnotation(i);break}case`ZIGZAG`:{this.customPlotValues=!0;let t=_M(`ZigZag`,!0,{[z.AT_LINE]:{color:this.curves[0].colors[0],width:this.curves[0].lineWidth,dashStyle:this.curves[0].dashStyle??`Solid`}},this.id)(this.axis,!1);t.setOptions(e.inputs),this.setStudyAnnotation(t);break}case`LINRCHN`:{this.customPlotValues=!0;let e=this.curves[0],t=this.curves[1],n=this.curves[2],r=this.curves[3],i=this.curves[4],a=_M(`LinearRegressionChannel`,!0,{[z.AT_LINE]:{color:e.colors[0],width:e.lineWidth,dashStyle:e.dashStyle??`Solid`},[z.AT_LINE_2]:{color:t.colors[0],width:t.lineWidth,dashStyle:t.dashStyle??`Solid`},[z.AT_LINE_3]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle??`Solid`},[z.AT_FILL]:{color:r.colors[0]},[z.AT_FILL2]:{color:i.colors[0]}},this.id)(this.axis,!1);this.setStudyAnnotation(a);break}case`IVRANK`:{let t=W.ImplVolRank1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolRank5D;break;case`1-Month`:t=W.ImplVolRank1M;break;case`3-Month`:t=W.ImplVolRank3M;break;case`6-Month`:t=W.ImplVolRank6M;break;case`YTD`:t=W.ImplVolRankYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`IVPCTL`:{let t=W.ImplVolPerc1Y;switch(e.inputs.TimeFrame){case`1-Year`:default:break;case`5-Day`:t=W.ImplVolPerc5D;break;case`1-Month`:t=W.ImplVolPerc1M;break;case`3-Month`:t=W.ImplVolPerc3M;break;case`6-Month`:t=W.ImplVolPerc6M;break;case`YTD`:t=W.ImplVolPercYTD}this.curves[0].fields[0]=t,e.outFields[0]=t;break}case`OPTIV`:{let t=[W.WeighImplVolHigh,W.WeighImplVol,W.WeighImplVolLow];switch(e.inputs.TimeFrame){case`Implied Volatility`:default:break;case`5-Day Average IV`:t=[W.WeighImplVolHigh5D,W.WeighImplVol5D,W.WeighImplVolLow5D];break;case`1-Month Average IV`:t=[W.WeighImplVolHigh1M,W.WeighImplVol1M,W.WeighImplVolLow1M];break;case`3-Month Average IV`:t=[W.WeighImplVolHigh3M,W.WeighImplVol3M,W.WeighImplVolLow3M];break;case`6-Month Average IV`:t=[W.WeighImplVolHigh6M,W.WeighImplVol6M,W.WeighImplVolLow6M];break;case`1-Year Average IV`:t=[W.WeighImplVolHigh1Y,W.WeighImplVol1Y,W.WeighImplVolLow1Y];break;case`YTD Average IV`:t=[W.WeighImplVolHighYTD,W.WeighImplVolYTD,W.WeighImplVolLowYTD]}this.curves[0].fields[0]=t[0],this.curves[1].fields[0]=t[1],this.curves[2].fields[0]=t[2],e.outFields=[...t];break}case`PC`:{let t=e.inputs.PeriodForecast-1;this.curves.forEach(e=>e.shift=t);let n=this.curves[11],r=this.curves[12],i=_M(`ProbabilityCones`,!0,{[z.AT_LINE]:{color:n.colors[0],width:n.lineWidth,dashStyle:n.dashStyle},[z.AT_LINE_2]:{color:r.colors[0],width:r.lineWidth,dashStyle:r.dashStyle}},this.id)(this.axis,!1);i.setOptions(e.inputs),this.setStudyAnnotation(i);break}case`TARGP`:this.curves.forEach(e=>e.shift=1)}return n}getValueAt(e,t,n){return this.isPivotPoints?this.annotations[0].getValueAt(e,t):this.isVolAP?this.annotations[0].getValueAt(e,t,n):super.getValueAt(e,t,n)}getColorOf(e){if(this.isPivotPoints)return this.curves.find(t=>t.fields.includes(e))?.colors[0]??null;if(!this.isVolAP&&!this.isZigZag&&!this.isLinRegChannel)return null;let t=this.curves[0].colors;if(this.isZigZag)return t[0];switch(e){case W.UPVOL:return t[1];case W.DNVOL:return t[0];case W.TOTVOL:return t[2];case W.POC:case W.VAREA:case W.BARBACK:return z.COLOR_TRANSPARENT;case W.LINRUP:return t[0];case W.LINRMID:return this.curves[1].colors[0];case W.LINRLOW:return this.curves[2].colors[0];default:throw Error(`Unexpected Volume At Price field`)}}isEmpty(){return this.isVolAP||this.isZigZag||this.isLinRegChannel||this.isPivotPoints?!1:super.isEmpty()}setCurveAttributes(e,t){let n=t=>this.curves[e].attributes=[m[t]];switch(t){case`LikeMain`:{let t=this.axis.pane.presenter.mainPlot.curves[0].attributes,r=$().config.defaultVolumeBarColoring;N(t)?this.curves[e].attributes=[t[0]]:N(r)?n(r===`OpenToClose`?`OpenVsClose`:`ChangeBased`):n(`OpenVsClose`);break}case`OpenToClose`:n(`OpenVsClose`);break;case`CloseToClose`:n(`ChangeBased`);break;default:throw Error(`Unexpected bar coloring choice: ${t}`)}}get hasEvents(){return!!this._hasEvents&&this.curves.every(e=>e.visible)}get eventsSeries(){return this.timeSeries}doesSeriesEmitEvents(){let e=this.timeSeries.helpers;return e.includes(W.Buy)||e.includes(W.Sell)}getEventFor(e){let t=this.model?.study===`PACROSS`||this.model?.study===`MACROSS`?this.curves[0]?.colors:void 0;switch(e){case W.Buy:return{show:!0,title:`B`,color:t?.[1]??`#03c03c`};case W.Sell:return{show:!0,title:`S`,color:t?.[0]??`#c23b22`};default:return null}}getEventFields(){return this.hasEvents?[W.Buy,W.Sell]:[]}getRefPlot(e){return this.axis?.pane.isMain&&this.basePlot?this.basePlot:super.getRefPlot(e)}#t(){return this.model.basis??{kind:`main`}}#n(e){let t=this.axis.pane.presenter.allPlots.find(t=>t.uid===e.uid&&t.isSeasonal&&t.offset===e.offset);if(N(t))return t;throw Error(`Unable to resolve seasonal basis plot for uid '${e.uid}' and offset '${e.offset}'`)}#r(){let e=this.#t();switch(e.kind){case`main`:return this.axis.pane.presenter.mainPlot;case`seasonal`:return this.#n(e);default:throw Error(`Unknown study basis kind '${e.kind}'`)}}async initialize(){return ma.call(this,async()=>{this.basePlot=this.#r(),await this.basePlot.initialize();let e=this.axis.pane.presenter.data.aggregation,t=xM(this.model,e,this.curves);if(this.basePlot.isSeasonal){let e=this.basePlot.mainCurve.fields[0];N(e)&&(t.source=e)}let n=this.applySpecifics(t);this.getMetaData(n);let r=this.basePlot.timeSeries;r instanceof qb&&(r=r.actual),this.timeSeries=vO(this.model.study,t,r),this._hasEvents=this.doesSeriesEmitEvents(),this.timeSeries.useNotifications=!0;let i=this.title;return this.timeSeries.ready().then(e=>{let t=this.basePlot.timeSeries instanceof ev||CM(this.timeSeries);!e&&!this.timeSeries.hasData&&!t&&!this.timeSeries.computedServerSide&&F(`Unable to calculate study values for ${i}`,`error`)}),!0})}get isJpi(){return[`JPI`,`CTTP`,`CTTI`].includes(this.model.study)}get isVolAP(){return this.model.study===`VOLAP`||this.model.study===`PVACP`}get isZigZag(){return this.model.study===`ZIGZAG`}get isLinRegChannel(){return this.model.study===`LINRCHN`}get isPivotPoints(){return this.model?.study===`PIVPTS`}invalidateAssociatedAnnotations(e){this.isVolAP&&this.annotations[0].invalidate(e)}onPriceDomainsUpdated(){this.invalidateAssociatedAnnotations(`PriceDomainsChanged`)}shouldPriceMap(e){return this.isJpi?this.shouldMaybePriceMap?e.id===W.JPIB.id||e.id===W.JPIS.id:!1:super.shouldPriceMap(e)}canPriceMap(e,t){if(!this.isJpi)return super.canPriceMap(e,t);this._canPriceMap=e>0}priceMap(e,t,n){if(!this.isJpi)return super.priceMap(e,t,n);if(t>this.visToIndex)return e;let r=(e,t)=>this.timeSeries.container.getData(e)[t],i=r(W.JPIB,t),a=r(W.JPIS,t);if(i===null&&n.id===W.JPIB.id||a===null&&n.id===W.JPIS.id)return null;let o=0,s=this.visFromIndex,c=this.timeSeries.helpers[0],l=this.timeSeries.helpers[2];for(;s<=t;){let e=r(l,s);o+=e===1?0:r(c,s),s++}return o}},TM=[W.Open,W.High,W.Low,W.Close,W.Volume],EM=class extends Fk{_expression;exprModel=null;symbols=null;errorText;get title(){return this.expression}get expression(){return this._expression}async parseExpression(){let e=ef(this._expression);if(this.exprModel=null,this.symbols=null,$d(e))this.errorText=e.error;else{let{model:t,clean:n,symbols:r}=e;this.errorText=void 0,this.symbols=r,this.exprModel=t,this._expression=n}}get isValid(){return!N(this.errorText)}#e(e){return{mapper:e=>e.query.symbol,loadMoreData:!0,recompute:d.Minimum,missing:u.UseNext,stretch:e=>!1,fieldMap:new Map(TM.map(e=>[e,e])),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:e}}getTimeSeries(){let e=this.getInnerSeries(),t=this.axis?.pane.presenter.data?.exprSkipLeadingEmpty??!1,n=new Rb(this.exprModel,e,this.#e(t));this.timeSeries=this.wrapIfAdvancedStyle(n);let r=this.title;this.timeSeries.ready().then(e=>{e||F(`Unable to calculate expression: ${r}`,`error`)})}getInnerSeries(){let e=of(this.exprModel),t=$().getTimeSeriesDataSource();return e.map(e=>{let n=this.makeQuery();return n.symbol=e,t.getTimeSeries(n)})}getRecord(){if(N(this.errorText))return;let e=this.metaData.inner.map(e=>[e.symbol,e.resolved]);this.record=new Rp(e,P(this.exprModel)),this.record.ready().then(e=>e)}getMetaData(){this.isValid&&(this.metaData=new Co(this.symbols),this.metaData.ready().then(e=>{e&&(this.getRecord(),this.presenter?.notifyHost(G.MD_CHANGED,{plot:this}))}))}fromModel(e){super.fromModel(e),this._expression=e.expression}async initialize(){return ma.call(this,async()=>(await this.parseExpression(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}},DM=class extends Fk{suffix;_forward;offset;errorText;fwdModel=null;outField;roots=null;symbols=[];get title(){return`${this.forward}${this.suffix}`}get forward(){return this._forward}fromModel(e){super.fromModel(e);let t=e;this.offset=t.offset,this._forward=t.forward}async parseForward(){let e=ef(this.forward),t=$d(e);if(t?(this.errorText=e.error,this.fwdModel=null,this._forward=e.text):(this.errorText=void 0,this.fwdModel=e.model,this._forward=e.clean),t)this.roots=null;else{this.offset>0?(this.suffix=` (${ue(Ig(this.offset),Fg(z.FMT_US_DATE_ONLY))(/* @__PURE__ */ new Date)})`,this.outField=new vp(`Close_${this.offset}`,v.Number,b.Forward,`Close (${this.offset})`),this.curves[0].fields[0]=this.outField):(this.suffix=``,this.outField=W.Close);let{yes:t,no:n}=O(e.symbols,e=>ki(`${e}*1`)),r=(await Promise.all(t.map(e=>qi(e)))).map(e=>e.map(e=>e.name));this.roots=t.reduce((e,t,n)=>(e[t]=r[n],e),{}),this.symbols=n}}get isValid(){return!N(this.errorText)}getMetaData(){if(this.isValid){let e=Object.values(this.roots).flat();this.metaData=new Co(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}}getForwardPolicy(e){return{mapper:e=>e.query.root,loadMoreData:!1,recompute:d.Everything,missing:u.UseNext,stretch:e=>!1,fieldMap:/* @__PURE__ */ new Map([[W.Close,this.outField]]),noDataApproach:f.NoAction,modelTransform:(e,t)=>null,skipLeadingEmpty:!1,valueProvider:e}}getTimeSeries(){let e=$().getTimeSeriesDataSource(),t=Object.keys(this.roots),n=this.offset===0?C.Forward:C.HistoricalForward,r=t.map(t=>{let r={seriesKind:n,root:t,offset:this.offset,symbols:this.roots[t],getHashKey:()=>`${n}|${t}|${this.offset}`};return e.getTimeSeries(r)}),i=this.symbols.length>0?new ov(this.symbols):void 0;this.timeSeries=new Rb(this.fwdModel,r,this.getForwardPolicy(i)),this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:ie.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return ma.call(this,async()=>(await this.parseForward(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}},OM=e=>e.substring(0,e.lastIndexOf(`::`)),kM=class extends Fk{isAverage;hasComputation;offset;offsets;_seasonal;symbolToOffset;errorText;seaModel=null;isPlain=!1;isFutures=!1;suffix=``;outField;symbols;coreModel;coreHasComputation;refSeasonal;get title(){if(this.isAverage){let e=`YB `;return this.offset<-1&&(e=`${Math.abs(this.offset)}y `),`${e}Average`}return!this.hasComputation&&(this.symbols?.length??0)>0?this.outField.name:`${this.seasonal}${this.suffix}`}get seasonal(){return this._seasonal}fromModel(e){super.fromModel(e);let t=e;this.offset=t.offset,this.offsets=t.offsets,this.isAverage=t.offset<0,this._seasonal=this.refSeasonal=t.seasonal}constructSeasonal(e,t){return af(cf(e,e=>this.applyOffset(e,t)))}constructAverage(e,t=null){let n=t===null?null:t.map(e=>this.symbolToOffset[e]),r=n===null,i=this.offsets.filter(e=>r?!0:n.includes(e)).map(t=>`(${this.constructSeasonal(e,t)})`);return`(${i.join(`+`)})/${i.length}`}prepareFields(){let e=this.isPlain?`${this.yearFromOffset(this.offset)}`:`${this.offset}Y`,t=this.isAverage?`Avg`:e;this.suffix=this.offset===0?``:` (${t})`,this.outField=new vp(`Close_${t}`,v.Number,b.Seasonal,`Close${this.suffix}`),this.curves[0].fields[0]=this.outField}applyOffset(e,t){return`${this.isPlain?e:$i(e,-t)}::${t}`}createSymbolToOffsetMapping(e){this.symbolToOffset={},e.forEach(e=>{this.offsets.forEach(t=>{this.symbolToOffset[this.applyOffset(e,t)]=t})})}async parseSeasonal(){let e=ef(this.seasonal,!0),t=$d(e),n=e=>(this.errorText=e,this.seaModel=null,null);if(t)return n(e.error);let{model:r,symbols:i}=e;this.prepareFields();let a=/* @__PURE__ */ new Map;for(let e of i){let t=Ui(await Di(e));a.set(e,t)}r=cf(r,e=>a.get(e)),i=Array.from(a.values());let o=i.every(e=>ki(e)||ji(e)),s=i.every(e=>Ni(e)),c=i.every(e=>!ki(e)&&!Ni(e)&&!ji(e));if(!o&&!s&&!c)return n(`Mixed types of symbols aren't supported yet`);this.isPlain=c,this.isFutures=o,this.createSymbolToOffsetMapping(i),this.coreModel=this.isAverage?r:null,this.coreHasComputation=sf(r);let{model:l,symbols:u}=ef(this.isAverage?this.constructAverage(r):this.constructSeasonal(r,this.offset),!0);this.seaModel=l,this.hasComputation=sf(l),this._seasonal=af(cf(l,OM)),this.symbols=u,this.outField.name=this.outField.shortName=this.fixupFieldDescription()}get isValid(){return!N(this.errorText)}getActualSymbols(){return[...new Set(this.symbols.map(OM))]}fixupFieldDescription(){if(!this.hasComputation&&!this.isAverage){let e=OM(this.symbols[0]);if(this.isPlain)return`${e} ${(/* @__PURE__ */ new Date()).getFullYear()-this.offset}`;if(this.isFutures)return Ui(e,!0)}return this.title}getMetaData(){if(this.isValid){let e=this.getActualSymbols(),t=e.length===1&&!this.hasComputation&&!this.isAverage,n=$().getMetaDataSource();this.metaData=t?n.getMetaData(e[0]):new Co(e),this.metaData.ready().then(e=>{e&&this.presenter?.notifyHost(G.MD_CHANGED,{plot:this})})}}getNoDataApproach(){return this.isAverage&&!this.coreHasComputation?f.ModelTransformRequired:this.hasComputation?f.NoAction:f.IgnoreTimelineOnly}get seasonalPolicy(){return{mapper:e=>e.query.surrogate||e.query.symbol,loadMoreData:!1,recompute:d.Everything,missing:this.hasComputation?u.UsePrevious:u.UseNone,stretch:e=>this.shouldStretch(e),fieldMap:/* @__PURE__ */ new Map([[W.Close,this.outField]]),noDataApproach:this.getNoDataApproach(),modelTransform:(e,t)=>t.length===0?this.seaModel:ef(this.constructAverage(this.coreModel,e)).model,skipLeadingEmpty:!1}}shouldStretch(e){return this.symbolToOffset[e]===0&&(this.isAverage&&this.symbols.length>1||this.offset>0)}shiftYears(e){return An(/* @__PURE__ */ new Date,-e)}yearFromOffset(e){return oi(this.shiftYears(e))}getCmdtyRange(e){let t=this.shiftYears(e);return[or(t),ar(t)]}getSeasonalRange(e,t,n){let r=N(e[0],e[1]);return this.isPlain&&!r?this.getCmdtyRange(t):this.isFutures?n!=null&&(n.from!=null||n.to!=null)?[null,null]:[An(e[1]??/* @__PURE__ */ new Date,-(t+z.SEASONAL_FUTURES_FETCH_YEARS)),null]:this.isPlain&&t>0&&r?e.map(e=>An(e,-t)):e}getTimeSeries(){if(!this.isValid)return;let e=$().getTimeSeriesDataSource(),t=Object.keys(this.symbolToOffset).map(t=>{let n=this.makeQuery();return n.surrogate=t,n.symbol=OM(t),n.offset=this.symbolToOffset[t],n.cacheMe=!this.isPlain||n.offset===0,n.range=this.getSeasonalRange(n.range,n.offset,n.visibleRange),n.offset>0&&(n.disableStreamingUpdates=!0),e.getTimeSeries(n)}),n=new Rb(this.seaModel,t,this.seasonalPolicy);n.seasonalAverageOffset=this.offset,this.timeSeries=n,this.timeSeries.ready().then(e=>{if(e){let e={series:this.timeSeries,part:ie.Unspecified};this.presenter?.notifyHost(G.TS_MANYCHANGED,e)}})}async initialize(){return ma.call(this,async()=>(await this.parseSeasonal(),!this.isShutDown&&(this.getMetaData(),this.getTimeSeries(),!0)))}},AM=[`top`,`bottom`,`right`,`left`],jM={bottom:`center`,top:`center`,right:`start`,left:`end`},MM=class{lineWidth;arrowLength;position;textAlign;fontSize;fontFamily;padding;strokeColor;textColor;backgroundColor;constructor(e){this.lineWidth=1,this.arrowLength=7,this.position=`bottom`,this.textAlign=`center`,this.fontSize=12,this.fontFamily=`Arial`,this.padding=4,this.strokeColor=`white`,this.textColor=`white`,this.backgroundColor=`black`,e&&this.configure(e)}configure(e){Object.assign(this,e)}draw(e,t,n,r,i,a){let o=N(i);if(a||=this.fontSize+this.padding+this.padding+(o?this.padding:0),!AM.includes(this.position.toLowerCase())){F(`Can not draw indicator in position [${this.position}]`,`error`);return}e.font=`bold ${this.fontSize}px ${this.fontFamily}`,e.textAlign=jM[this.position],e.strokeStyle=this.strokeColor,e.fillStyle=Ho(this.backgroundColor),e.lineWidth=this.lineWidth;let s=[r,i??``].map(t=>e.measureText(t).width),c=Math.max(...s),l=this.position===`bottom`||this.position===`top`,u=l?0:this.arrowLength,d=Math.round(c+u+this.padding+this.padding),f=Math.round(d/2),p=Math.round(a/2);e.setLineDash([]);let m=t;e.beginPath(),e.moveTo(m,n);let h=n+p,g=n+2*p,_=n-p;if(this.position===`right`){e.lineTo(m,h);let t=m+d;o&&(e.lineTo(m,g),e.lineTo(t,g)),e.lineTo(t,h),e.lineTo(t,_),e.lineTo(m,_)}else if(this.position===`left`){e.lineTo(m,h);let t=m-d;o&&(e.lineTo(m,g),e.lineTo(t,g)),e.lineTo(t,h),e.lineTo(t,_),e.lineTo(m,n-p)}else if(l){let t=this.position===`top`?n-a:n+a,r=m-f,i=m+f;e.lineTo(m,n),e.lineTo(i,n),e.lineTo(i,t),e.lineTo(r,t),e.lineTo(r,n),e.lineTo(m,n)}if(e.closePath(),e.stroke(),e.fill(),e.fillStyle=this.textColor,e.textBaseline=`middle`,l){let t=this.position===`top`?n-a:n;e.fillText(r,m,t+cs(e,1))}else if(this.position===`right`){let t=m+this.arrowLength+this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+p)}else if(this.position===`left`){let t=m-this.arrowLength-this.padding;e.fillText(r,t,n),o&&e.fillText(i,t,n+this.padding+p)}}},NM=({y:e,halfHeight:t})=>e-t,PM=({y:e,halfHeight:t})=>e+t;function FM(e,t){e.forEach((e,n,r)=>{if(n===0&&e.y-e.halfHeight<t.y)e.y=t.y+e.halfHeight+1;else if(n>0){let i=r[n-1],a=NM(e),o=PM(i);a<o&&(e.y=o+1+e.halfHeight),PM(e)>t.y+t.height&&(e.y=t.y+t.height-e.halfHeight-1)}})}var IM=4,LM=({x:e,halfWidth:t})=>e-t-IM,RM=({x:e,halfWidth:t})=>e+t+IM,zM=(e,t)=>e-1-t-IM,BM=(e,t)=>e+1+t+IM;function VM(e,t){let n=e.length-1;e.forEach((e,r,i)=>{let a=r===0,o=a?null:i[r-1],s=LM(e),c=a?t.x:RM(o);if(e.x-e.halfWidth<t.x&&(e.x=BM(t.x,e.halfWidth)),s<c)e.x=BM(c,e.halfWidth+IM);else{let t=RM(e),a=r<n?LM(i[r+1]):2**53-1;if(t>a){let n=zM(e.x,t-a),r=zM(e.x,e.halfWidth-2),i=BM(c,o?.halfWidth??0);e.x=Math.max(r,n,i)}}RM(e)>t.x+t.width&&(e.x=zM(t.x+t.width,e.halfWidth))})}var HM=Array.from([,,,,,,],(e,t)=>++t).reverse(),UM=`8`,WM=/\d/g;function GM(e){return e.replace(WM,UM)}function KM(e,t){let n=e.timeSeries.container;if(n===null||n.size<1)return[null,-1];let r=n.getLastDataPoint(t),i=n.getData(t),a=i.length-1,o=e.type===S.Study&&[`JPI`,`CTTP`,`CTTI`].includes(e.model.study);return r==null&&!o&&(a=be(i,e=>e!==null),r=a===-1?null:i[a]),[r,a]}function qM(e){let t=e.plot.timeSeries.container;return t===null||t.size<1?null:e.getColor(t.size-1)}function JM(e){return e.curves.filter(t=>e.isVisible&&t.visible&&(e.type!==S.Study||t.style!==h.Ribbon)).map(t=>{let n=t.pickMainField(),[r,i]=KM(e,n);return{value:r,color:qM(t),field:n,index:i}})}var YM=class{pane;annotationUndoOwner={axis:this};annotations=[];id;isCustomDomain=!1;primary=!1;onTheRight=!0;viewBox;plots=[];comparison;scale;yScale;label=``;crosshairIndicator;ticks;lastUsedOptions;config;_fullDomain;constructor(e){this.pane=e,this.id=xt(),this.ticks=null,this.lastUsedOptions=null;let{chart:{fontSize:t},yAxis:{fontSize:n}}=this.pane.presenter.display,r=n||t||12;this.config={innerTickSize:7,tickPadding:5,indicatorPadding:4,fontWeight:400,fontSize:r},this.crosshairIndicator=new MM({fontSize:this.config.fontSize,arrowLength:this.config.innerTickSize})}makePlot(e){let t=null;switch(S[e.type]){case S.Symbol:t=new Ik;break;case S.Expression:t=new EM;break;case S.Study:t=new wM;break;case S.IncomeStatement:t=new Lk(C.IncomeStatement);break;case S.BalanceSheet:t=new Lk(C.BalanceSheet);break;case S.Forward:t=new DM;break;case S.Seasonal:t=new kM;break;default:throw Error(`${e.type} isn't supported yet`)}return t.axis=this,t.fromModel(e),t}toPrice(e){let t=this.yScale.yToPrice(e);return this.comparison===x.None?t:this.pane.presenter.mainPlot.priceMap(t,void 0,W.Close,!0)}toTime(e){return this.pane.presenter.view.toTime(e)}toAnnotationPoint(e){let t=this.toPrice(e.y),n=this.toTime(e.x);return new Uk(this,t,n||void 0)}toX(e){return this.pane.presenter.view.toX(e)}priceMap(e){return this.comparison===x.None?e:this.pane.presenter.mainPlot.priceMap(e,void 0,W.Close)}toY(e){let t=this.priceMap(e);return this.yScale.priceToY(t)}get plotAnnotations(){let e=[];return this.plots.forEach(t=>{t.isVisible&&t.annotations&&e.push(...t.annotations)}),e}annTimeToX(e){return this.pane.presenter.view.xAxis?.annTimeToX(e)}snapTo(e){let t={x:this.annTimeToX(e.time),y:this.toY(e.price)},n=this.pane.presenter,r=n.activeTool,i=r.annotation;return r.alignPointsMode&&i&&i.alignPointsSupported&&i.points.includes(e)?this.alignPoints(i,e,t):r.snapToSupported&&n.display.yAxis.snapAnnotationsToPrices&&!e.passive&&(e.moveDirection===ne.Both||e.moveDirection===ne.Vertical)&&this.snapToPrices(e,t),t}snapToPrices(e,t){let n=this.plots.find(e=>e.main);if(n&&n.timeSeries&&n.timeSeries.hasData){let r=n.timeSeries.container,i=A(r.getTimeData(),+e.time,Number),a=[].concat(...n.curves.map(e=>e.fields)).filter(e=>r.hasField(e)).map(e=>{let n=r.getData(e)[i],a=this.toY(n);return{priceSnap:n,ySnap:a,dist:Math.abs(a-t.y)}}).filter(e=>e.dist<=z.SNAP_PROXIMITY_PIXELS).reduce((e,t)=>e===null||t.dist<e.dist?t:e,null);N(a)&&(e.price=a.priceSnap,t.y=a.ySnap,e.time=r.getTimeData()[i],t.x=this.toX(e.time))}}alignPoints(e,t,n){let r=e.points.find(e=>e!==t);if(t!==r&&r&&r.point){let e=r.point,i=(360+-zo(e,n)*180/Math.PI)%360,a=i>337.5||i<45/2||i>157.5&&i<202.5,o=i>67.5&&i<112.5||i>247.5&&i<292.5;if(a)n.y=e.y,t.price=this.toPrice(n.y);else if(o)n.x=e.x,t.time=this.toTime(n.x);else{let r=Math.abs(n.x-e.x),i=e.y>n.y?-1:1;n.y=e.y+r*i,t.price=this.toPrice(n.y)}}}toPoint(e){if(N(this.pane.presenter.view))return this.snapTo(e)}makeAnnotation(e,t=!0){let n=_M(e.id,!0,e.traits)(this,!1);t&&e.uid&&(n.uid=e.uid);let r=n.activePoints,i=e.points.length-r.length;return i>0&&n.addPoints(i),n.activePoints.forEach((t,n)=>{let r=e.points[n];Qe(r.price)&&Qe(r.time)&&t.update(r.price,r.time)}),n.visible=e.visible,n.locked=e.locked,n}expand(e){let t=[];switch(e.type){case`Forward`:{let n=e.curves,r=e.offsets;delete e.curves,delete e.offsets;for(let i=0;i<n.length;i++){let a=Object.assign({},e);a.curves=[n[i]],a.offset=r[i],t.push(a)}break}case`Seasonal`:{let n=e.curves,r=e.offsets;delete e.curves,delete e.offsets;let i=r.filter(e=>e>=0);for(let a=0;a<n.length;a++){let o=Object.assign({},e);o.curves=[n[a]],o.offset=r[a];let s=o.offset<0;o.offsets=s?o.offset===-1?i:Oe(Math.abs(o.offset),e=>e+1):[o.offset],(!s||o.offsets.length>1)&&t.push(o)}break}default:t.push(e)}return t}fromModel(e){this.comparison=x[e.comparison??`None`],this.scale=ee[e.scale??`Linear`],this.yScale=new gk(this.scale,this),this.label=e.label,this.plots=[].concat(...e.plots.map(e=>this.expand(e))).map(e=>this.makePlot(e));let t=e.annotations||[];this.annotations=t.map(e=>this.makeAnnotation(e));let{chart:{fontFamily:n,backgroundColor:r},yAxis:{textColor:i,crosshair:{color:a},primaryOnTheLeft:o}}=this.pane.presenter.display,s=o??!1;this.onTheRight=this.primary&&!s||!this.primary&&s,this.crosshairIndicator.configure({position:this.onTheRight?`right`:`left`,fontFamily:n,strokeColor:a,textColor:i,backgroundColor:Jo(.15)(r)})}findIndex(e){return this.annotations.findIndex(t=>t.uid===e.uid)}addAnnotation(e){let t=this.makeAnnotation(e,!0);if(this.appendAnnotation(t),e.isUndoRedo&&e.position!==void 0){this.annotations.splice(this.findIndex(t),1);let n=St(0,this.annotations.length,e.position);this.annotations.splice(n,0,t)}t.requestRedraw(),this.fireAnnotationsChanged()}appendAnnotation(e){this.findIndex(e)===-1&&this.annotations.push(e)}fireAnnotationsChanged(e=!1){this.pane.presenter.onAnnotationsUpdated(this,e)}deleteAnnotation(e,t=!0){e.isSelected&&this.pane.presenter.clearSelection();let n=this.findIndex(e);n!==-1&&this.annotations.splice(n,1),t&&this.fireAnnotationsChanged(!e.isSelected)}fliphorizontalAnnotation(e){e.flip(!0),this.fireAnnotationsChanged(!0)}flipverticalAnnotation(e){e.flip(!1),this.fireAnnotationsChanged(!0)}duplicateAnnotation(e){let t=e.axis,n=this.makeAnnotation(e.toModel(),!1);n.drawPoints(null,!0),n.offset({x:z.ANN_DUPLICATE_OFFSET,y:z.ANN_DUPLICATE_OFFSET}),t.appendAnnotation(n),n.requestRedraw(),this.fireAnnotationsChanged()}updateAnnotation(e,t){e.isSelected&&!this.pane.presenter.annotationManipulation&&this.pane.presenter.clearSelection(),iu(e.name,t.traits),e.updateFrom(t.traits,t.extras,t.isUndoRedo?null:t.points,t.visible,t.locked),t.isUndoRedo&&N(t.points)&&e.updateActivePoints(t.points),e.isSelected&&!e.isVisible&&this.pane.presenter.clearSelection(),t.isUndoRedo||this.pane.presenter.undoRedoManager.done(Gk(e,D.Moved)),e.requestRedraw(),this.fireAnnotationsChanged()}setViewBox(e){this.viewBox=e;let{y:t,height:n}=this.viewBox;this.yScale.range([Math.floor(t),Math.floor(t+n)]),this.plots.forEach(t=>t.setViewBox(e))}get fullDomain(){return N(this._fullDomain)||(this._fullDomain=this.getDataDomain().domain),this._fullDomain}updateFullDomain(e=null){if(e===null&&this.comparison!==x.None)return;let t=this.fullDomain;this._fullDomain=this.getDataDomain([e,e],t).domain}getPlotDataDomain(e,t,n){let r=e.timeSeries;if(!r.hasData)return{domain:null};let i=r.container,a=i.getTimeData(),o=e=>A(a,+e,Number),s=N(t),c=s?o(t):0,l=N(n),u=l?o(n):a.length-1,d=e.curves.map(e=>e.fields).flat().filter(e=>e.id!==W.Change.id),f=N(e.targetFields);f&&d.push(...e.targetFields);let p={},m=t=>{let n=f?e.curves[0]:e.curves.find(e=>e.fields.includes(t));if(!N(n)||n.shift===0)return[c,u];if(!N(p[n.id])){let e=n.shiftedTimeDomain;if(!N(e))return[c,u];p[n.id]=[o(e[0]),o(e[1])]}return p[n.id]},g=t=>{let[n,r]=m(t),a=i.getData(t),o=Math.max(n,0),s=Math.min(a.length-1,r);return a.slice(o,s+1).map((n,r)=>e.priceMapper(n,r,t))},_=e=>De(g(e)),v=[null,null],y=e=>e.id,b=new Set(Se(i.fields,d,y).map(y));e.curves.filter(e=>e.visible).map(e=>{let t=e.fields.filter(e=>b.has(e.id));e.isStackedColumn?j(De(t.map(e=>g(e)).reduce((e,t)=>t.map((t,n)=>(e[n]||0)+(t||0)),[])),v):t.map(e=>{j(_(e),v)})});let x=(e.annotations||[]).filter(e=>e.isVisible).flatMap(e=>{let t=e.getDomainPrices;return typeof t==`function`?t.call(e):[]}).filter(e=>Qe(e));x.length>0&&j(De(x),v);let ee=se.None,S=[h.Column,h.MultiColumn,h.StackedColumn];if(s&&l&&!e.main&&e.curves.some(e=>S.includes(e.style))){let e=v[0]>0,t=v[1]<0;e?(ee=se.Min,v[0]=0):t&&(ee=se.Max,v[1]=0)}return{domain:v,clamped:ee}}getDataDomain([e,t]=[null,null],n=[null,null]){let r=P(n),i=!1;for(let n of this.plots.filter(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale)){let{domain:a,clamped:o}=this.getPlotDataDomain(n,e,t);N(a)&&(j(a,r),i||=o!==se.None)}if(!N(r))return{domain:null};let[a,o]=r;if(!N(a,o))return{domain:null};let s=[Number(a),Number(o)];s[0]===s[1]&&(--s[0],s[1]+=1);let c=se.None;return i&&(s[0]===0?c=se.Min:s[1]===0&&(c=se.Max)),{domain:s,clamped:c}}setDomain(){let e=this.pane.presenter,t=e.view.xAxis.xScale.domain();if(!N(t))return;for(let e of this.plots.filter(e=>e.isVisible&&e.hasVisibleCurves&&e.hasDetachedScale)){let{domain:n}=this.getPlotDataDomain(e,t[0],t[1]);N(n)&&e.yScale.domain(n)}if(this.isCustomDomain)return;let{domain:n,clamped:r}=this.getDataDomain(t);if(this===e.mainAxis&&e.mainPlot?.showPrevious){let t=e.mainPlot.getPreviousValue(),r=it(e.display,!1,`chart`,`previous`,`forceVisible`);N(t,n)&&r&&(n[0]=Math.min(n[0],t),n[1]=Math.max(n[1],t))}if(this.yScale.domain(n),N(n)){let e=this.getPadding(r);N(e)&&this.yScale.padding(e)}}getInitialPadding(){let e=na(this.pane.presenter.hostElement),t=aa(`#${z.HEADER_SIZE_PLACEHOLDER_ID}`,e);if(!N(t)){t=ua(e,`div`),oa(t,{display:`none`}),sa(t,{id:z.HEADER_SIZE_PLACEHOLDER_ID,class:`bcharts-card bcharts-card-first`});let{lineHeight:n}=getComputedStyle(t);isNaN(Number.parseFloat(n))&&oa(t,{lineHeight:`120%`})}let{paddingTop:n,paddingBottom:r,marginTop:i,lineHeight:a}=getComputedStyle(t),o=this.pane.isMain?i:`0`;return this.pane.presenter.display.tooltip.mode===`cards`?[n,r,o,a].map(Number.parseFloat).reduce((e,t)=>e+t,0)+z.CARDS_Y_OFFSET:Number.parseFloat(o)}getPadding(e){let t=this.pane.presenter,n=this.viewBox?.height;if(n==null)return[0,0];let r=t.display,i=it(r,null,`yAxis`,`minPaddingPercent`),a=it(r,null,`yAxis`,`maxPaddingPercent`),o=N(i),s=N(a),c=o||s?0:this.getInitialPadding(),l=o?i:z.PANE_CAP_MIN_PADDING_PERCENT,u=s?a:z.PANE_CAP_MAX_PADDING_PERCENT,d=l*n,f=[s?u*n:Math.max(d,Math.min(u*n,c)),d];e===se.Max?f[0]=z.PANE_TINY_PADDING_PIXELS:e===se.Min&&(f[1]=z.PANE_TINY_PADDING_PIXELS);let p=t.mainPlot;return p&&p.hasEvents&&t.view&&(f[0]+=3*t.view.getEventRadius()),f}clearTicks(){this.ticks=null}getTicks(e,t=0){let{height:n}=this.viewBox,r=cs(e,1.3),i={height:n,approxLineHeight:r,domain:this.yScale.domain()};if(N(this.ticks)&&N(i.domain)&&N(this.lastUsedOptions)&&N(this.lastUsedOptions.domain)&&i.height===this.lastUsedOptions.height&&i.approxLineHeight===this.lastUsedOptions.approxLineHeight&&i.domain[0]===this.lastUsedOptions.domain[0]&&i.domain[1]===this.lastUsedOptions.domain[1])return this.ticks;this.lastUsedOptions=i;let a=Math.floor((n+40)/(r+40)),o=this.yScale.getTicks(a),s=it($().config,null,`overrides`,`yAxis`,`tickProvider`);if(N(s)&&typeof s==`function`&&i.height>0&&N(i.domain)){let e=P(i);e.autoTicks=P(o),o=s(e)}let{innerTickSize:c,tickPadding:l,fontSize:u}=this.config,d=null,f=this.yScale?.checkTicks(),p=f?30:40;return this.ticks=o.map(n=>{let r=Math.round(this.yScale.priceToY(n)),i=Math.abs(r-(d??r));if(f&&d!==null&&i<p)return null;d=r;let a=Bv(this,n),o=e.measureText(a).width,s={x1:0,x2:0,y1:r,y2:r,dy:0,label:a,labelX:0,labelY:r+u*.32};return this.onTheRight?(s.x1=t,s.x2=s.x1+c,s.labelX=s.x2+o+l):(s.x1=t-c,s.x2=s.x1+c,s.labelX=s.x1-l),s}).filter(e=>e!==null),this.ticks}widthNeeded(e){if(!N(this.fullDomain))return z.DEFAULT_PRICE_AXIS_WIDTH;e.save();let{fontWeight:t,fontSize:n}=this.config,{chart:{fontFamily:r}}=this.pane.presenter.display;e.font=`${t} ${n}px ${r}`;let i=Math.max(...this.fullDomain.map(t=>e.measureText(GM(Bv(this,t,!0))).width)),{innerTickSize:a,tickPadding:o}=this.config,s=N(this.label)?cs(e,1.6):0,c=i+a+2*o+s;return e.restore(),c}draw(e){let{chart:{fontFamily:t},yAxis:{gridLines:n,textColor:r,visible:i}}=this.pane.presenter.display;if(!i||!this.viewBox)return;e.save();let{x:a,y:o,width:s,height:c}=this.viewBox,{fontWeight:l,fontSize:u}=this.config;if(ns(e,this.viewBox),e.font=`${l} ${u}px ${t}`,e.lineWidth=2,e.strokeStyle=n.color,e.textAlign=`end`,N(this.label)){e.save(),e.fillStyle=qo(.4)(r),e.translate(0,0);let t=this.onTheRight?1:-1;e.rotate(t*Math.PI/2),e.textAlign=`center`;let n=cs(e),i=t*(o+c/2);this.onTheRight?e.fillText(this.label,i,-(a+s-n)):e.fillText(this.label,i,a+n),e.restore()}let d=this.onTheRight?a:s;e.setLineDash([]),_s(e,d,o,o+c);let f=this.getTicks(e,d);this.drawTicks(e,f,r),this.drawPriceAdornments(e),e.restore()}drawTicks(e,t,n){t&&(e.fillStyle=n,t.forEach(t=>{e.fillText(t.label,t.labelX,t.labelY+t.dy)}))}drawCrosshairIndicator(e,t){if(!this.plots.some(e=>e.isVisible&&e.hasVisibleCurves)||!this.pane.presenter.display.yAxis.crosshair.enabled||!Number.isFinite(t)||!this.yScale)return;let n=this.onTheRight?this.viewBox.x:this.viewBox.width,r=this.yScale.yToPrice(t);if(r==null)return;let i=Bv(this,r);this.crosshairIndicator.draw(e,n,t,i)}get indicatorHeight(){return this.config.fontSize+this.config.indicatorPadding+this.config.indicatorPadding}drawPriceAdornments(e){let t=this.pane.presenter,{chart:{fontFamily:n,previous:r},yAxis:{showLastValue:i,preventLabelOverlap:a,includePercentChangeWithLastValue:o}}=t.display,s=t.view,c=[],l=(e,t,n,r,i,a)=>{if(t!=null){let s=t;t=e.priceMapper(t,a,i);let l,u=e.is(S.Symbol)||e.is(S.Expression);if(o&&u){let t=e.axis.comparison===x.Percent?x.None:x.Percent;l=e.priceMapper(s,a,i,t)}let d=e.hasDetachedScale?e.metaData.format(t,i):void 0,f=N(l)?1:2;c.push({y:e.priceToY(t),formattedValue:d,value:t,auxValue:l,color:n,halfHeight:Math.round(this.indicatorHeight/f),priority:r})}};this.plots.forEach(e=>{if(e.isVisible&&e.hasVisibleCurves&&e.timeSeries&&e.timeSeries.hasData){if(i===`All`||i===`Main`&&e.main){let t=e.main?1:3;JM(e).filter(e=>e.value!=null&&e.index!==-1).forEach(n=>l(e,n.value,n.color,t,n.field,n.index))}e.showPrevious&&l(e,e.getPreviousValue(),r.color,2,W.PreviousClose,void 0)}}),this.annotations.concat(this.plotAnnotations).filter(e=>e.isVisible).forEach(e=>{c.push(...e.getPriceScaleAdornments().map(e=>({y:this.toY(e.price),value:this.priceMap(e.price),color:e.color,halfHeight:Math.round(this.indicatorHeight/2),priority:4})))}),c.sort((e,t)=>e.y-t.y),a&&FM(c,this.viewBox);let u=({y:t,value:r,formattedValue:i,color:a,auxValue:o})=>{let{leftOffset:c,rightOffset:l}=s,u=this.onTheRight?this.pane.viewBox.width-l:c,d=Qo(a),f=new MM({position:this.onTheRight?`right`:`left`,fontSize:this.config.fontSize,padding:this.config.indicatorPadding,fontFamily:n,textColor:d,strokeColor:a,backgroundColor:a}),p=i||Bv(this,r),m,h=this.comparison===x.Percent;M(o)&&(m=h?zv(this,o):Rv(o)),f.draw(e,u,t,p,m)};a?c.forEach(u):HM.forEach(e=>c.filter(t=>t.priority===e).forEach(u))}};function XM(e){let t=e.map(e=>e.plots).flat().filter(e=>S[e.type]==S.Symbol).map(e=>e.symbol).map(e=>Yi(e)).filter(e=>e!==null).map(e=>e.getFullYear());return t.length==0?null:Math.max(...t)}var ZM=Symbol.for(`__dloacip__`),QM=class{presenter;id;axes=[];height=0;alignedToYear=null;viewBox;constructor(e){this.presenter=e,this.id=xt()}fromModel(e){this.height=e.height,e.alignOnExpirations===!0&&(this.alignedToYear=XM(e.axes)),this.axes=e.axes.map((e,t)=>{let n=new YM(this);return n.primary=t===0,n.fromModel(e),n},this)}getBounds(){return this.viewBox}setViewBox(e){this.viewBox=e}drawBackground(e){N(this.viewBox)&&(this.drawAxes(e),e.save(),this.clipToNoScales(e),this.drawGrid(e),e.restore())}draw(e){N(this.viewBox)&&(e.save(),this.clipToNoScales(e),this.drawPrevious(e),this.drawPlots(e),this.drawAnnotations(e),this.drawLogo(e),e.restore())}drawLogo(e){this.isMain&&this.presenter[ZM]!==!1&&MA(e,this.getBoundsWithoutScales())}drawAxes(e){for(let t of this.axes)t.draw(e)}drawPrevious(e){let t=this.presenter.mainPlot;if(t.showPrevious&&this.isMain){let n=t.getPreviousValue();if(n=t.priceMapper(n,void 0,W.PreviousClose),n!=null){let{leftOffset:r,rightOffset:i}=this.presenter.view,a=r,o=this.viewBox.width-i,s=t.axis.yScale.priceToY(n),{color:c,dashStyle:l,lineWidth:u}=this.presenter.display.chart.previous,d=Vo(l);e.save(),e.strokeStyle=c,e.lineWidth=u,e.setLineDash(d),vs(e,s,a,o),e.restore()}}}getBoundsWithoutScales(){let e=this.viewBox.duplicate(),t=this.presenter.view;return e.x=t.leftOffset,e.width-=t.leftOffset+t.rightOffset,e}clipToNoScales(e){ns(e,this.getBoundsWithoutScales())}drawAnnotations(e){e.save();try{let{chart:{fontFamily:t},yAxis:{fontSize:n}}=this.presenter.display;e.font=`${n??12}px ${t}`;let r=this.presenter.annotationPreviewUid,i=this.axes.flatMap(e=>e.annotations).find(e=>e.uid===r&&e.isVisible&&!e.computed),a=e=>i!==void 0&&e!==i,o=(t,n)=>{e.save();try{n&&(e.globalAlpha*=z.PLOT_HOVER_DIM_ALPHA),t.draw(e,!0)}finally{e.restore()}};this.axes.forEach(e=>{e.annotations.filter(e=>e.isVisible).forEach(e=>o(e,a(e))),e.plotAnnotations.filter(e=>e.isVisible).forEach(e=>o(e,!1))});let s=this.presenter.selectedAnnotation;this.presenter.annotationManipulation&&s?.axis.pane===this&&s.isVisible&&s.drawPoints(e,!1)}catch(e){throw this.presenter.setAnnotationPreview(),e}finally{e.restore()}}drawGrid(e){let{chart:{fontFamily:t},yAxis:{gridLines:n,visible:r,minorGridLines:i}}=this.presenter.display;if(!r||!n.visible)return;let{lineWidth:a,color:o,dashStyle:s}=n;e.save();let c=!(e=>e.plots.some(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale))(this.axes[0])&&this.axes.length>1,l=this.axes[+!!c],{fontWeight:u,fontSize:d}=l.config;e.font=`${u} ${d}px ${t}`;let f=l.getTicks(e),{leftOffset:p,rightOffset:m}=this.presenter.view,h=p,g=this.viewBox.width-m,_=(t,n,r)=>{e.lineWidth=t,e.strokeStyle=n,e.setLineDash(Vo(r)),e.beginPath()};if(_(a,o,s),f.forEach(t=>{e.moveTo(h,t.y1),e.lineTo(g,t.y2)}),e.stroke(),i&&i.visible&&f.length>=2){let{lineWidth:t,color:n,dashStyle:r}=i,a=(f[0].y1-f[1].y1)/5;_(t,n,r),f.forEach(t=>{for(let n=1;n<5;n++){let r=Math.ceil(t.y1+n*a);e.moveTo(h,r),e.lineTo(g,r)}}),e.stroke()}e.restore()}drawYCrosshair(e,t){let{yAxis:{crosshair:{enabled:n,showValue:r,color:i,dashStyle:a}}}=this.presenter.display;if(!n)return;let o=Vo(a);e.strokeStyle=i,e.setLineDash(o);let s=this.presenter.view.leftOffset,c=this.viewBox.width-this.presenter.view.rightOffset,l=Fs();l.prolog(e),vs(e,l.adjust(t.y),l.adjust(s),l.adjust(c)),l.epilog(e),r&&this.axes.forEach(n=>{n.drawCrosshairIndicator(e,t.y)})}drawNoData(e){e.save(),e.font=`800 14px ${this.presenter.display.chart.fontFamily}`,e.fillStyle=`#f00`,fs(e,$().config.noDataText||z.NO_DATA_TEXT,{x:this.viewBox.centerX,y:this.viewBox.centerY},w.Center),e.restore()}get isMain(){let e=this.presenter.mainPlot;return this.axes.some(t=>t.plots.includes(e))}drawPlots(e){e.save();let t=this.presenter.mainPlot,n=this.presenter.display.chart.showNoDataText,r=!N(n)||n,i=t=>t.draw(e),a=/* @__PURE__ */ new Map,o=t=>t.drawEventsTopmost(e,a),s=!0,c=n=>{for(let e of this.axes){for(let r of e.plots){let e=r.isEmpty();s=s&&r.main&&e,r!==t&&!e&&n(r)}e.plots.includes(t)&&!t.isEmpty()&&n(t)}r&&s&&this.drawNoData(e)};c(i),c(o),e.restore()}};function $M(e,t){return{width:e,spacing:t,get totalWidth(){return this.width+this.spacing},offset:0}}var eN=class extends ck{timeline;aggregation;marginBars;bar;resetBar;wasZoomed;fitAllData;constructor(e,t){super(),this.timeline=e,this.aggregation=t;let n=e.presenter.display;this.marginBars=n.xAxis.marginBars||0,this.bar=$M(it(n,z.DEFAULT_BAR_WIDTH,`chart`,`bar`,`width`),it(n,z.DEFAULT_BAR_SPACING,`chart`,`bar`,`spacing`)),this._extent=null,this.wasZoomed=!1,this.fitAllData=!1}extent(e){return sk.call(this,`_extent`,e)}get presenter(){return this.timeline.presenter}get display(){return this.presenter.display}scaleBarToFit(){if(this.wasZoomed)return;if(this.fitAllData)return this._domain=null,this.scaleBarToFitDensity(this.timeline.withoutPrologEpilogLength);let e=this.display.xAxis.visibleRange;if(N(e))return this.scaleBarToFitRange([e.from,e.to]);let t=this.display.density;if(Number.isFinite(t))return this.scaleBarToFitDensity(t);let n=this.display.period;if(n===z.YTD_PERIOD)return this.scaleBarToFitYtd();if(Number.isFinite(n))return this.scaleBarToFitPeriod(n)}deriveExtentsFromBarWidth(e){if(!N(this._range)||this.timeline.length===0)return null;let t=this._range[1]-this._range[0],n=t/e.totalWidth,r=Math.ceil(n);e.offset=t-r*e.totalWidth;let i=this.timeline.lastSeriesIndex+this.marginBars,a=this._domain&&this._domain[1];return a&&(i=A(this.timeline,+a,Number,Jv)),[i-r+1,i]}adjustDomain(){if(!N(this._range))return;this.scaleBarToFit();let e=this.deriveExtentsFromBarWidth(this.bar);if(N(e))this.extent(e);else return;this.setDomainFromExtent()}xToTime(e){if(!this.ready)return null;let t=this.xToIndex(e);return this.timeline.at(t)}xToIndex(e){if(!this.ready)return null;let t=e-this._range[0]-this.bar.offset,n=Math.floor(t/this.bar.totalWidth);return this._extent[0]+n}timeToIndex(e){return this.ready?(e=typeof e==`number`?e:+e,A(this.timeline,e,Number,Jv)):null}indexToX(e){let t=e-this._extent[0];return this.bar.width/2+this.range()[0]+this.bar.offset+t*this.bar.totalWidth}timeToX(e){if(!this.ready)return null;let t=this.timeToIndex(e);return this.indexToX(t)}zoom(e){let t=e,n=t*this.bar.width/100,r=this.bar.width-n,i=this.bar.spacing-t*this.bar.spacing/100;if(r>z.MAXIMUM_BAR_WIDTH||r<z.MINIMUM_BAR_WIDTH)return!1;let a=$M(r,i),o=this.deriveExtentsFromBarWidth(a);return this.isUsableExtent(o)?(this.setBar(r,i),this.adjustDomain(),this.wasZoomed=!0,!0):!1}scaleBarToFitRange(e,t=!0){let n=(e,t,n,r)=>N(e)?A(this.timeline,e,Number,Jv,n,r):t,{from:r,to:i}=this.presenter.data.range||{},a=+e[0]===r&&+e[1]===i,{firstSeriesIndex:o,lastSeriesIndex:s}=this.timeline,c=a?o:void 0,l=a?s:void 0,u=[n(e[0],o,c,l),n(e[1],s,c,l)];this.timeline.at(u[1])>e[1]&&(u[1]=Math.max(0,u[1]-1));let d=u[1]-u[0]+1,f=t?this.marginBars:0;u[1]+=f,this.extent(u),this.setDomainFromExtent(),this.scaleBarToFitDensity(d,t)}scaleBarToFitDensity(e,t=!0){let n=Math.max(z.MINIMUM_BARS_VISIBLE,e),r=t&&this.display.xAxis.marginBars||0,i=(this._range[1]-this._range[0])/(n+r);this.setBar(2/3*i,1/3*i,!1)}scaleBarToFitYtd(){let e=this.timeline.at(this.timeline.lastSeriesIndex);e&&this.scaleBarToFitRange([or(e),e])}scaleBarToFitPeriod(e){let t=this.timeline.lastSeriesIndex,n=this.timeline.at(t),r=n,i=t,a=this.presenter.data.aggregation;if(a.isEndOfDay||a.isIntraday&&e>=z.INTRA_THRESHOLD)for(;i>0&&Wn(n,r)<e;)i--,r=this.timeline.at(i);else if(!a.isTick){let t=Math.floor(e/z.ONE_DAY_MILLIS),r=e=>Yn(e,Sn(e)),a=r(n),o=n;for(;i>0;){let e=this.timeline.at(i),n=Ln(e,o);if(t===0){if(r(e)<=a||!n)break}else n||(t--,o=e);i--}}this.scaleBarToFitDensity(t-i+1)}setBar(e,t,n=!0){let[r,i]=bt(e,t,z.MINIMUM_BAR_WIDTH,z.MAXIMUM_BAR_WIDTH);this.bar.width=r,this.bar.spacing=i,this.wasZoomed||(this.resetBar={width:r,spacing:i}),n&&(this.presenter.model.display.chart.bar={width:e,spacing:t})}resetZoom(){N(this.resetBar)?(this.bar.width=this.resetBar.width,this.bar.spacing=this.resetBar.spacing):(this.bar.width=z.DEFAULT_BAR_WIDTH,this.bar.spacing=z.DEFAULT_BAR_SPACING),delete this.presenter.model.display.chart.bar,this.adjustDomain()}isUsableExtent(e){return N(e)&&N(e[0],e[1])&&e[0]>=0&&e[1]<this.timeline.withPrologEpilogLength&&e[1]-e[0]>=z.MINIMUM_BARS_VISIBLE}shiftBars(e,t=null){if(!this._extent)return;let n=this._extent.map(t=>t+e);this.isUsableExtent(n)&&(N(t)&&(this.bar.offset=t),this.extent(n),this.setDomainFromExtent())}setDomainFromExtent(){this.domain(this.extent().map(e=>this.timeline.at(e)))}pan(e){if(!Number.isFinite(e)||e===0)return;let t=e%this.bar.totalWidth,n=this.bar.offset+t,r=Math.sign(e),i=-(e<0?Math.ceil:Math.floor)(e/this.bar.totalWidth);(n>this.bar.totalWidth||n<-this.bar.totalWidth)&&(i+=n>0?-1:1,n-=r*this.bar.totalWidth),this.shiftBars(i,n)}getSeriesThatCouldLoadMoreData(){let e=this.domain();if(!N(e)||!N(e[0]))return[];let t=e[0].getTime();return this.timeline.presenter.allPlots.map(e=>e.timeSeries).filter(e=>{if(!N(e)||!e.hasData||e.container.size===0||e.canLoadMoreData!==!0)return!1;let n=e.container.getTimeData()[0];return N(n)&&t<=n.getTime()})}};function tN(e){return{date:e,priority:1,text:Lv(e)}}var nN=class{view;xScale;ticks;lastUsedOptions;wasPanned;panningXAxisAllowed;config;isVisible;crosshairIndicator;contentBounds;axisStrips=[];overrideTickGetter;overrideFormatter;contractParityCache=null;contractParityCacheKey=null;constructor(e){this.view=e,this.xScale=new eN(e.presenter.timeline,e.presenter.data.aggregation),this.ticks=null,this.lastUsedOptions=null,this.wasPanned=!1,this.panningXAxisAllowed=it(e.presenter.display,!0,`xAxis`,`panning`),this.updateConfigFromModel();let t=e.presenter.renderTo.id,n=it($().config,null,`overrides`,`xAxis`,`tickProvider`);N(n)&&typeof n==`function`&&(this.overrideTickGetter=ce(n,t));let r=it($().config,null,`overrides`,`xAxis`,`formatter`);N(r)&&typeof r==`function`&&(this.overrideFormatter=ce(r,t))}updateConfigFromModel(){let{chart:{fontFamily:e,backgroundColor:t,fontSize:n},xAxis:{textColor:r,visible:i,fontSize:a,crosshair:{color:o}}}=this.view.presenter.display,s=a||n||12;this.config={innerTickSize:5,tickPadding:5,indicatorPadding:5,fontWeight:400,fontSize:s},this.isVisible=i,this.crosshairIndicator=new MM({position:`bottom`,fontSize:this.config.fontSize,fontFamily:e,padding:this.config.indicatorPadding,strokeColor:o,textColor:r,backgroundColor:Jo(.15)(t),arrowLength:this.config.innerTickSize})}setDomain(){this.xScale.adjustDomain();let e=this.view.presenter.display.period===z.FIFTY_YEARS_MILLIS;N(this.xScale.extent())&&!e&&this.checkForMoreData()}zoom(e){let t=this.xScale.zoom(e);return this.checkForMoreData(),t}checkForMoreData(){this.xScale.getSeriesThatCouldLoadMoreData().forEach(e=>e.loadMoreData())}shouldScrollIntoView(e){let t=this.xScale.extent();return N(t)?e-this.xScale.timeline.lastSeriesIndex>=0&&e-t[1]<=1:!1}pan(e){this.panningXAxisAllowed&&(this.xScale.pan(e),this.checkForMoreData(),this.view.setPriceAxesDomains(),this.wasPanned=!0)}get wasVisibleRangeChanged(){return this.wasPanned||this.xScale.wasZoomed}resetZoom(){this.xScale.resetZoom()}get barsToLast(){let e=this.xScale.timeline.lastSeriesIndex+this.getMaxCurveOffset(),t=this.xScale.extent();return e-(t?t[1]:e)}canGoToLast(){return this.barsToLast>0}getMaxCurveOffset(){return Math.max(...this.view.presenter.allCurves.map(e=>e.shift))}goToLatest(e=!1){if(this.canGoToLast()||e){let e=this.barsToLast===0?0:this.barsToLast+this.xScale.marginBars+1;this.xScale.shiftBars(e),this.view.setPriceAxesDomains(),this.view.redraw()}}get position(){return this.view.presenter.display.xAxis.position??`bottom`}setViewBox(e,t,n){this.contentBounds=e;let{x:r,y:i,width:a,height:o}=e;this.xScale.range([r,r+a]),this.axisStrips=[],t>0&&this.axisStrips.push({position:`top`,bounds:new rs(r,i-t,a,t),baseline:i}),n>0&&this.axisStrips.push({position:`bottom`,bounds:new rs(r,i+o,a,n),baseline:i+o})}contains(e){return this.axisStrips.some(t=>t.bounds.contains(e))}heightNeeded(e){if(!this.isVisible)return 0;let t=this.view.presenter.display.chart.fontFamily,{fontWeight:n,fontSize:r}=this.config;e.save(),e.font=`${n} ${r}px ${t}`;let{innerTickSize:i,tickPadding:a,indicatorPadding:o}=this.config,s=cs(e,1)+i+a+o;return e.restore(),s}getTickGetter(e){if(this.overrideTickGetter)return this.overrideTickGetter;let t=this.view.presenter.display.xAxis.isOrdinal||!1,n=bv(e);return t?tN:e=>n.getTick(e)}getTicks(e){if(N(this.lastUsedOptions)&&((e,t)=>e.unit===t.unit&&e.size===t.size&&e.spec===t.spec)(e.agg,this.lastUsedOptions.agg)&&e.unitWidth===this.lastUsedOptions.unitWidth&&e.barWidth===this.lastUsedOptions.barWidth&&e.extent[0]===this.lastUsedOptions.extent[0]&&e.extent[1]===this.lastUsedOptions.extent[1]&&e.formatString===this.lastUsedOptions.formatString&&e.minTickInterval===this.lastUsedOptions.minTickInterval&&N(this.ticks))return this.ticks;this.lastUsedOptions=e;let t=this.getTickGetter(e),n=Math.max(0,e.extent[0]),r=Math.min(this.xScale.timeline.withPrologEpilogLength-1,e.extent[1]+1);return this.ticks=this.view.presenter.timeline.slice(n,r).map((e,r)=>{if(!N(e)||Number.isNaN(e.getTime()))return null;let i=t(e);return N(i)&&(i.index=n+r),i}).filter(e=>N(e)),this.ticks}normalizeDuration(e){let t=yv(),n=t.Year,r=Object.keys(t);for(let i=0;i<r.length-1;++i){let a=t[r[i]].Multipliers,o=t[r[i+1]].Multipliers;if(e<=(Ce(a)+we(o))/2){n=t[r[i]];break}}let i=n.Multipliers,a=i.findIndex(t=>e<t),o=a===-1?Ce(i):i[a];return n.Period===`P1M`?o*=.9:n.Period===`P1W`&&(o*=.84),o}draw(e){if(!this.isVisible)return;let{xAxis:{gridLines:t,textColor:n,minTickInterval:r,tickPixelInterval:i,format:a,forceTicksVisible:o},chart:{fontFamily:s}}=this.view.presenter.display,{fontWeight:c,fontSize:l,innerTickSize:u,tickPadding:d}=this.config,{x:f,y:p,width:m,height:h}=this.contentBounds,{lineWidth:g,color:_,dashStyle:v}=t,y=Vo(v);e.textAlign=`center`,e.textBaseline=`alphabetic`,e.font=`${c} ${l}px ${s}`,e.lineWidth=1,e.strokeStyle=_,e.fillStyle=n,e.setLineDash([]),this.axisStrips.forEach(t=>vs(e,t.baseline,f,f+m));let b=this.xScale.extent(),x=e=>!N(e)||!N(e[0],e[1]);if(x(b))return;let ee=t=>e.measureText(t).width,S=(e,t)=>N(e)?Wn(t,e):z.FIFTY_YEARS_MILLIS,C=i>0?i:120,w=this.xScale.domain();if(x(w))return;let te=(w[1].getTime()-w[0].getTime())*C*.6/m,T=this.normalizeDuration(te),E=this.view.presenter.data.aggregation.isEndOfDay,ne=(e,t)=>{if(e.date.valueOf()===z.ZERO_DATE.valueOf())return!0;if(S(e.date,t.date)<r)return!1;let n=t.x-e.x,i=t.date.getTime()-e.date.getTime()>=T,a=n>C;return!(e.x+e.textWidth/2>=t.x-t.textWidth/2)&&(a||(E?i:!1))},re=f+m,ie=({text:n,x:r,date:i,forced:a})=>{N(i)&&(this.axisStrips.forEach(({position:t,baseline:i})=>{let o=t===`top`,s=i+(o?-1:1)*u,c=o?s-d:s+d+l*.71;a||_s(e,r,i,s),e.fillText(n,r,c)}),t.visible&&!a&&(e.save(),e.lineWidth=g,e.setLineDash(y),_s(e,r,p,p+h),e.restore()))},ae={agg:this.view.presenter.data.aggregation,unitWidth:ee(`M`),barWidth:this.xScale.bar.width,extent:b,formatString:a,minTickInterval:r||0,duration:te},oe=this.getTicks(ae),D=e=>{let{x:t,textWidth:n}=e,r=t;if(o){let i=n/2;r=t-i<f?f+i:t,r=r+i>re?re-i:r,e.x=r,e.forced=t!==r}else e.forced=!1},se={date:z.ZERO_DATE,priority:999,x:-999,text:``,index:-1,textWidth:0};oe.forEach(e=>{e.x=this.xScale.indexToX(e.index),e.textWidth=ee(e.text),D(e),ne(se,e)?(ie(se),se=e):e.priority<se.priority&&(se=e)}),ie(se),this.drawTimeTransitions(e),this.drawTimeAdornments(e)}drawTransitionsFor(e,t,n,r,i){let a=this.xScale.domain(),o=this.view.presenter?.mainPlot?.timeSeries.container;if(!M(o))return;let s=o.getTimeData(),c=t===null?s:o.getData(t);if(!N(c))return;let l=A(s,+a[0],Number),u=A(s,+a[1],Number,Ee,l);if(l<u){let{y:t,height:a}=this.contentBounds,o=this.view.leftOffset,d=this.contentBounds.x+this.contentBounds.width;if(r.save(),i){r.fillStyle=e.fillColor;let f=c[l],p=Math.max(o,this.xScale.timeToX(s[l]));for(let e=l+1;e<=u;++e){let o=e<c.length?c[e]:null;if(e===u||n(o,f)){let n=e<s.length?s[e]:null,c=M(n)?this.xScale.timeToX(n):d;c=Math.min(c,d),i(f)%2==0&&r.fillRect(p,t,c-p,a),f=o,p=c}}}let f=Fs();f.prolog(r),r.strokeStyle=e.color,r.lineWidth=e.width,r.setLineDash(Vo(e.dashStyle));let p=null;for(let e=l;e<u;++e){let i=c[e];if(n(i,p)){let n=s[e],o=this.xScale.timeToX(n);N(o,p)&&_s(r,o,t,t+a),p=i}}f.epilog(r),r.restore()}}drawTimeTransitions(e){let t=this.xScale.domain();if(!M(t)||!N(t[0],t[1]))return;let n=this.view.presenter,{xAxis:{contractTransition:r,cycleTransition:i}}=n.display,a=(e,t)=>e!==t;if(r.enabled&&n?.data?.aggregation.isMultiContract){let t=(n?.mainPlot?.timeSeries.container)?.getData(W.Symbol);if(t&&t.length>0){let n=t[0];if(this.contractParityCacheKey!==n||!this.contractParityCache){let e=[...new Set(t)];e.sort((e,t)=>{let n=Yi(e),r=Yi(t);return(n?.getTime()??0)-(r?.getTime()??0)});let r=0;if(this.contractParityCache)for(let t=0;t<e.length;t++){let n=e[t],i=this.contractParityCache.get(n);if(i!==void 0){r=(i-t)%2==0?0:1;break}}this.contractParityCache=/* @__PURE__ */ new Map,e.forEach((e,t)=>this.contractParityCache.set(e,t+r)),this.contractParityCacheKey=n}this.drawTransitionsFor(r,W.Symbol,a,e,e=>this.contractParityCache.get(e)??0)}}i.enabled&&(n?.data?.aggregation.isIntraday?this.drawTransitionsFor(i,W.TradingDay,a,e,e=>e):n?.data?.aggregation.unit===g.Day?this.drawTransitionsFor(i,null,(e,t)=>!hi(e,t),e,e=>e.getMonth()):n?.data?.aggregation.unit===g.Week&&this.drawTransitionsFor(i,null,(e,t)=>!_i(e,t),e,e=>e.getFullYear()))}getAnnXScore(e,t){return[Ln,pi,hi,_i].map((n,r)=>(4-r)*Number(n(e,t))).reduce((e,t)=>e+t,0)}annTimeToX(e){let t=this.xScale.timeToIndex(e);if(!M(t))return null;let n=this.xScale.timeline.at(t),r=this.xScale.timeToX(e);if(t>0&&n.valueOf()!==e.valueOf()){let i=t-1,a=this.xScale.timeline.at(i),o=this.xScale.indexToX(i);if(!this.view.presenter.display?.xAxis?.isOrdinal){if(a.valueOf()>e.valueOf())return r;let t=this.getAnnXScore(a,e),i=this.getAnnXScore(n,e);return t>i?o:i>t?r:this.view.presenter?.data?.aggregation?.isIntraday?o:r}let s=(e.valueOf()-a.valueOf())/(n.valueOf()-a.valueOf());return o+(r-o)*s}return r}drawTimeAdornments(e){e.save();let t=this.view.presenter,{chart:{fontFamily:n},xAxis:{preventLabelOverlap:r}}=t.display,i=[],a=t.mainPane?.getBoundsWithoutScales()??new rs(0,0,0,0);t.allAnnotations.concat(t.plotAnnotations).filter(e=>e.isVisible).forEach(n=>{i.push(...n.getTimeScaleAdornments().map(n=>{let r=this.annTimeToX(n.time);if(r<a.x||r>a.x+a.width)return null;let i=this.view.presenter?.display?.xAxis?.isOrdinal?n.time:this.xScale.xToTime(r),o=Vv(t,i),s=e.measureText(o).width/2;return{x:r,value:o,color:n.color,halfWidth:s}}).filter(e=>e!=null))}),i.sort((e,t)=>e.x-t.x),r&&VM(i,this.contentBounds),i.forEach(t=>{let r=Qo(t.color),i=new MM({position:`bottom`,fontSize:this.config.fontSize,fontFamily:n,padding:this.config.indicatorPadding,strokeColor:z.COLOR_TRANSPARENT,textColor:r,backgroundColor:t.color,arrowLength:this.config.innerTickSize});this.axisStrips.forEach(({position:n,baseline:r})=>{i.configure({position:n}),i.draw(e,t.x,r+(n===`top`?-1:1),t.value)})}),e.restore()}drawCrosshair(e,{x:t}){if(!Number.isFinite(t))return!1;let n=this.view.presenter,r=n.display.xAxis,{enabled:i,showValue:a,color:o,dashStyle:s,format:c}=r.crosshair,l=this.xScale.xToTime(t);if(!(N(l)&&zn(l)))return!1;if(!i)return!0;t=this.xScale.timeToX(l);let u=Vo(s);e.strokeStyle=o,e.setLineDash(u);let d=Fs();d.prolog(e);let{y:f,height:p}=this.contentBounds;if(_s(e,d.adjust(t),f,d.adjust(f+p)),d.epilog(e),!a||!r.visible)return!0;let m=Vv(n,l,N(r.format)?c:void 0);this.axisStrips.forEach(({position:n,baseline:r,bounds:i})=>{this.crosshairIndicator.configure({position:n}),this.crosshairIndicator.draw(e,t,r+(n===`top`?-1:1),m,void 0,i.height-2)});let{plotHover:h}=n.display.chart;return h&&n.allPlots.filter(e=>e.isVisible&&!n.shouldDimPlot(e)).forEach(n=>n.curves.forEach(n=>n.drawHover(e,l,t))),!0}},rN={mousedown:`onMouseDown`,mousemove:`onMouseMove`,mouseup:`onMouseUp`,dblclick:`onMouseDblClick`,contextmenu:`onContextMenu`,mouseover:`onMouseEnter`,mouseout:`onMouseLeave`,wheel:`onWheel`,touchstart:`onMouseDown`,touchmove:`onMouseMove`,touchend:`onMouseUp`,keydown:`onKeyDown`},iN={Shift:`shiftKey`,Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`},aN=e=>e.startsWith(`touch`),oN=class{view;subscriptions=[];constructor(e){this.view=e}init(e){let t=Le();Object.keys(rN).filter(e=>!aN(e)||t).forEach(t=>{let n=e=>{let n=rN[t];this.notifyActiveTool(n,e)===!0&&e.preventDefault()};e.addEventListener(t,n),this.subscriptions.push(()=>{e.removeEventListener(t,n)})})}shutdown(){this.subscriptions.forEach(e=>e()),this.subscriptions=[]}notifyActiveTool(e,t){let n=this.view.presenter;if(n===void 0||n.activeTool===null)return!1;let r=this.getPayload(t,n),i=n.activeTool,a=!1;return typeof i[e]==`function`&&(a=i[e](r)||!1),a}getPayload(e,t){let n=e instanceof MouseEvent,r=Le()&&e instanceof TouchEvent;if(n||r){let i={x:0,y:0};if(r&&e.touches.length===1){let t=e.touches[0],{left:n,top:r}=e.target.getBoundingClientRect();i.x=t.clientX-n,i.y=t.clientY-r}else n&&(i.x=e.offsetX,i.y=e.offsetY);let a={button:n?e.which:T.Left,offset:i,view:t.view,presenter:t,originalEvent:e,getModifier:t=>e[iN[E[t]]]};if(e instanceof WheelEvent&&(a.delta=e.shiftKey?e.deltaX:e.deltaY),r&&e.touches.length===2){let t=e.touches[0],n=e.touches[1];a.pinchZoom=!0;let r=t.clientX-n.clientX,i=t.clientY-n.clientY;a.pinchDistance=Math.sqrt(r*r+i*i)}return this.view.splitters.forEach((e,t)=>{e?.contains(i)&&(a.splitter=[t,t+1])}),t.panes.forEach(e=>{let t=e.getBounds();if(N(t)&&t.contains(i)){let t=e.axes.find(e=>e.viewBox?.contains(i));if(t)a.priceAxis=t;else{let t=e.axes.find(e=>e.primary);t&&(a.point=t.toAnnotationPoint(i))}}}),a}if(e instanceof KeyboardEvent)return{key:e.key??e.keyIdentifier,code:e.keyCode||e.charCode,repeat:e.repeat,presenter:t,getModifier:t=>e.getModifierState(E[t])}}},sN=g_.concat(W.PercentChange);function cN(e){let t=[],n=/* @__PURE__ */ new Map;for(let r of e){if(!r.isSeasonal){t.push([r]);continue}let e=n.get(r.uid);e||(e=[],n.set(r.uid,e),t.push(e)),e.push(r)}return t}function lN(e,t){let n=cN(t),r=e.isSeasonal?n.find(t=>t.some(t=>t.uid===e.uid)):void 0,i=[];return r&&i.push(r),n.forEach(e=>{e!==r&&i.push(e)}),i}function uN(e,t){return lN(e,t).flat().filter(t=>t!==e)}var dN=class{view;id;isOptionsChart=!1;constructor(e){this.view=e,this.id=`bc-legend-${xt()}`}getLegendElem(){let e=this.view.el;return ca(this.id,e,`div`)}update(){let e=this.getLegendElem(),t=by(this.presenter.mainPane);if(!N(t))return;this.isOptionsChart=this.mainPlot?.title?.startsWith(z.FAKE_SYMBOL_PREFIX)??!1;let{left:n,right:r,top:i,width:a}=t;SA(e,`row`,n,r,i,a),la(e,{"bcharts-card":!0,"bcharts-legend":!0});let o=this.mainPlot,s=o.isSeasonal||this.isOptionsChart?this.getFirstColorBadge(o):``,c=this.getPlotTitle(o),l=this.maybeGetQuote();e.innerHTML=o.isSeasonal?this.renderSeasonalLegend():`${this.div(`${s} ${c} `)+this.div(`${l}`)} ${this.maybeGetAdditionalPlots()}`}remove(){ia(this.getLegendElem())}get presenter(){return this.view.presenter}get mainPlot(){return this.presenter.mainPlot}getAttributes(e){return Object.entries(e).map(([e,t])=>t===null?``:`${e} = "${ot(Array.isArray(t)?t.join(` `):t)}" `).join(` `)}span(e,t={}){return`<span ${this.getAttributes(t)}>${e}</span>`}div(e){return`<div class="plot" style="flex: 0 0 auto">${e}</div>`}spanAsPlot(e){return`<span class="plot" style="display:inline-flex; align-items:center">${e}</span>`}divAsGroup(e,t=!1){return`<div class="plot-group" style="display:block; flex:0 0 100%;${t?` margin-top:2px;`:``}">${e}</div>`}get meta(){return this.mainPlot.metaData}isSingleSymbolSeasonal(e){return e.isSeasonal&&!e.hasComputation}format(e,t,n){return(n??this.meta).format(e,t)}spanAsName(e){return this.span(at(e),{class:`field-name`})}spanAsValue(e,t=null,n=null){return this.span(at(e),{class:[`field-value`,t],style:n})}getQuoteFromRecord(e){let t=sN.map(t=>e.getValue(t));if(ge(t)){let e=t[4],n=`field-${e>0?`up`:e<0?`down`:`same`}-value`;return`${t.slice(0,-1).map((e,t)=>{let r=sN[t],i=this.format(e,r),a=Ty(r);return`${this.spanAsName(a)}${this.spanAsValue(i,n)}`}).join(` `)} ${this.spanAsValue(`(${this.format(Ce(t),Ce(sN))})`,n)}`}return``}maybeGetQuote(){if(this.mainPlot.isSymbol&&this.mainPlot.timeSeries?.record?.isValid){let e=$().getRecordSource().getRecord(this.mainPlot.timeSeries.record.symbol);return this.getQuoteFromRecord(e)}if(this.mainPlot.isExpression&&this.mainPlot.record.isValid){let e=this.mainPlot.record;return e.evaluate(),this.getQuoteFromRecord(e)}return``}getTitle(e,t,n,r=e.symbol){let i=t?`value-main`:null,a=`${at(e.name)} (${at(r)})`,o=this.span(a,{"data-plot-uid":n,class:[`value-title`,i]}),s=at(e.exchange);return`${o}${t?` ${this.span(s,{class:`value-subtitle`})}`:``}`}getPlotTitle(e){if(e.isSymbol){let t=gy(e.title,e.metaData.symbol);return this.getTitle(e.metaData,e.main,e.uid,t)}if(this.isSingleSymbolSeasonal(e)&&e.offset===0&&(e.symbols?.length??0)>0){let t=$().getMetaDataSource().getMetaData(e.getActualSymbols()[0]);return this.getTitle(t,!0,e.uid)}{let t=at(_y(e)??e.title);return this.span(t,{"data-plot-uid":e.uid,class:`value-title`})}}getCondensedSeasonalTitle(e){return!this.isSingleSymbolSeasonal(e)||!e.isPlain||!Qe(e.offset)?null:String((/* @__PURE__ */ new Date()).getFullYear()-e.offset)}getSeasonalFamilyTitle(e,t){if(t)return this.getPlotTitle(e);let n=this.getCondensedSeasonalTitle(e);return n?this.span(n,{"data-plot-uid":e.uid,class:`value-title`}):this.getPlotTitle(e)}renderSeasonalLegend(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat();return lN(this.mainPlot,e).map((e,t)=>{let n=e.map((e,t)=>{let n=this.getFirstColorBadge(e),r=e.isSeasonal?this.getSeasonalFamilyTitle(e,t===0):this.getPlotTitle(e);return this.spanAsPlot(`${n} ${r}`)}).join(` `);return e[0]?.isSeasonal?this.divAsGroup(n,t>0):n}).join(` `)}getFirstColorBadge(e){return iy(`rectangle`,e.mainCurve.colors[0])}getLastValues(e){return this.isOptionsChart?``:JM(e).filter(e=>N(e.value)).map(t=>{let n=this.format(t.value,t.field,e.metaData);return this.spanAsValue(n,null,`color:${t.color}`)}).join(` `)}canBeDeleted(e){return e.isStudy||!e.main&&(e.isSymbol||this.isOptionsChart)}maybeGetAdditionalPlots(){let e=this.presenter.mainPane.axes.map(e=>e.plots).flat(),t=uN(this.mainPlot,e),n=this.presenter.display.yAxis.showLastValue;return t.length>0?t.map(e=>{let t=this.getFirstColorBadge(e),r=this.getPlotTitle(e),i=this.canBeDeleted(e)?my(e.uid):``,a=n!==`All`&&!e.isSeasonal?this.getLastValues(e):``;return this.div(`${i} ${t} ${r} ${a}`)}).join(` `):``}},fN=class{presenter;splitters=[];canvasContainer=null;mouseCanvas=null;mainCanvas=null;mouseContext;mainContext;leftOffset=0;rightOffset=0;legend;notifyLayoutChanged;el=null;listeners=[];tooltip;width;height;customEventPopup=null;goToLatestButton=null;xAxis;eventCapture;resetZoomAndVisibleRange=!1;constructor(){this.legend=new dN(this),this.draw=this.draw.bind(this),this.notifyLayoutChanged=Je(G.CH_CHTLAYOUTCHANGED,z.LAYOUT_THROTTLE_DELAY)}get canShowLegend(){if(!this.presenter.hasLegend)return!1;let e=this.presenter.display.chart.showLegend;return!(typeof e==`boolean`&&!e)}updateLegend(){this.canShowLegend&&this.legend.update()}removeLegend(){this.legend.remove()}findSvgParentWithClass(e,t){return[e,e.parentElement,e.parentElement.parentElement].find(e=>N(e)&&e.className===t)}onNonToolHandledMouseDown(e){let t=this.presenter,n=e.target;if(typeof n.className==`string`&&n.className.split(` `).includes(`value-title`))t.onCardClicked(n);else{let r=this.findSvgParentWithClass(n,`move-pane`);if(M(r)){t.onMovePaneClicked(r);return}let i=this.findSvgParentWithClass(n,`delete-plot`);if(M(i)){t.deletePlotClicked(i);return}let a=this.findSvgParentWithClass(n,`show-hide-plot`);if(M(a)){t.showHidePlotClicked(a);return}let o=this.findSvgParentWithClass(n,`more-actions`);if(M(o)){t.plotMoreActionsClicked(o,e);return}}}initialize(e){this.presenter=e,this.el=this.presenter.hostElement;let t=new ResizeObserver(e=>{for(let t of e){let{width:e,height:n}=t.contentRect;this.setSize(e,n,!0),N(this.tooltip)&&this.tooltip.repositionAuto()}});t.observe(this.el.parentElement),this.listeners.push(()=>t.unobserve(this.el.parentElement));let n=e=>this.onNonToolHandledMouseDown(e);this.el.addEventListener(`mousedown`,n),this.listeners.push(()=>this.el.removeEventListener(`mousedown`,n)),oa(this.el,{flex:1,display:`flex`,position:`relative`,"flex-direction":`column`,"touch-action":`pan-x pan-y`}),this.tooltip=new yA(this);let r=$().config.getCustomEventPopup;this.customEventPopup=r?r(this):null;let{clientHeight:i,clientWidth:a}=this.el;this.width=a,this.height=i,this.canvasContainer=ua(this.el,`div`),sa(this.canvasContainer,{class:`chart-canvas-container`}),oa(this.canvasContainer,{flex:1,display:`flex`,"flex-direction":`column`,position:`relative`,height:`100%`}),this.mainCanvas=ua(this.canvasContainer,`canvas`);let o={height:`${i}px`,width:`${a}px`,"z-index":2,position:`absolute`,top:0,left:0};oa(this.mainCanvas,o),this.mouseCanvas=ua(this.canvasContainer,`canvas`),sa(this.mouseCanvas,{tabIndex:0}),o[`z-index`]=3,o.outline=`none`,oa(this.mouseCanvas,o),this.goToLatestButton=ua(this.el,`button`),fa(this.goToLatestButton,`<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
|
|
40
40
|
<path d="M13.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0zM6.707 17.707l5-5c0.391-0.391 0.391-1.024 0-1.414l-5-5c-0.391-0.391-1.024-0.391-1.414 0s-0.391 1.024 0 1.414l4.293 4.293-4.293 4.293c-0.391 0.391-0.391 1.024 0 1.414s1.024 0.391 1.414 0z"></path>
|
|
41
41
|
</svg>`),oa(this.goToLatestButton,{position:`absolute`,right:0,bottom:0,"z-index":3}),sa(this.goToLatestButton,{class:`go-to-latest`}),this.goToLatestButton.onclick=()=>{this.xAxis.goToLatest()},this.listeners.push(()=>{this.goToLatestButton.onclick=null}),this.mainContext=this.mainCanvas.getContext(`2d`),this.mouseContext=this.mouseCanvas.getContext(`2d`),this.splitters=[],this.xAxis=new nN(this),this.eventCapture=new oN(this),this.eventCapture.init(this.mouseCanvas),this.setChartSize(a,i);let s=na(this.el);N(aa(`.${z.SVG_ICONS_DOM_NODE}`,s))||Qv(s)}reinitialize(){this.el&&da(`.bcharts-card`,this.el).forEach(e=>e.remove()),this.customEventPopup?.hide(),this.drawCrosshair({ap:void 0}),this.tooltip.hide(),this.tooltip.setMode(this.presenter.display.tooltip.mode),this.resetZoomAndVisibleRange?this.xAxis=new nN(this):this.xAxis?.updateConfigFromModel(),this.recalculateLayout(),this.redraw()}setSize(e,t,n=!1){this.setChartSize(e,t),this.redraw(n)}setChartSize(e,t){let n={width:`${e}px`,height:`${t}px`};oa(this.el,n),this.width=e,this.height=t;let r=globalThis.devicePixelRatio||1,i={height:this.height*r,width:this.width*r};[this.mainCanvas,this.mouseCanvas].forEach(e=>{sa(e,i),oa(e,n)}),this.mainContext.scale(r,r),this.mouseContext.scale(r,r),this.recalculateLayout(),this.presenter&&bA(this.presenter)}widthNeeded(e,t){let n=this.presenter.allAxes.filter(e=>e.onTheRight===t&&e.plots.some(e=>e.isVisible&&e.hasVisibleCurves&&!e.hasDetachedScale));return n.length===0?0:Math.max(...n.map(t=>t.widthNeeded(e)))}recalculateLayout(){if(!this.isHostElementVisible)return;this.leftOffset=0,this.rightOffset=0,this.presenter.allAxes.forEach(e=>e.clearTicks()),this.splitters.length=0;let e=this.xAxis.heightNeeded(this.mainContext),t=this.widthNeeded(this.mainContext,!0),n=this.widthNeeded(this.mainContext,!1),r=this.xAxis.position===`bottom`?0:e,i=this.xAxis.position===`top`?0:e,a=Math.max(0,this.height-r-i),o=this.presenter.panes,s=me(o.map(e=>e.height)),c=r,l=z.PANE_SPLITTER_PERCENT_HEIGHT/100,u=Math.floor(l*a);s*=1+(o.length-1)*l;let d=this.presenter.display?.yAxis?.primaryOnTheLeft??!1;this.presenter.display.yAxis.visible&&(o.some(e=>e.axes.length>1)?(this.leftOffset=n,this.rightOffset=t):d?this.leftOffset=n:this.rightOffset=t),o.forEach((e,n,r)=>{let i=n===r.length-1,o=Math.floor(a*e.height/s),l=new rs(0,c,this.width,o);e.setViewBox(l);let d=new rs(this.width-this.rightOffset,c,t,o),f=new rs(0,c,this.leftOffset,o),p=e=>e.setViewBox(e.onTheRight?d:f);if(p(e.axes[0]),e.axes[1]&&p(e.axes[1]),c+=o,!i){let e=new rs(this.leftOffset,c,this.width-this.rightOffset-this.leftOffset,u);this.splitters.push(e),c+=u}});let f=new rs(this.leftOffset,r,this.width-this.rightOffset-this.leftOffset,c-r);this.xAxis.setViewBox(f,r,i),this.tooltip?.repositionForLayout(),oa(this.goToLatestButton,{right:`${t+5}px`,bottom:`${i+5}px`}),this.updateLegend(),this.xAxis.setDomain(),this.setPriceAxesDomains(),this.notifyLayoutChanged({chart:this.presenter.accessor})}setPriceAxesDomains(){this.presenter.allAxes.forEach(e=>{e.setDomain(),e.updateFullDomain()}),this.presenter.priceDomainsUpdated()}draw(){this.mainContext.save(),this.mainContext.miterLimit=1,this.drawBackground(this.mainContext);for(let e of this.presenter.panes)e.drawBackground(this.mainContext);this.xAxis.draw(this.mainContext);for(let e of this.presenter.panes)e.draw(this.mainContext);this.drawSplitters(this.mainContext),this.presenter.title.draw(this.mainContext),this.goToLatestButton.style.display=this.canShowGoToLatestButton()?`block`:`none`,this.mainContext.restore()}canShowGoToLatestButton(){let e=$().config.showGoToLatest,{showGoToLatest:t}=this.presenter.display.chart;return!!(N(e)?e:t)&&this.xAxis.panningXAxisAllowed&&this.xAxis.canGoToLast()}get isHostElementVisible(){return N(this.el)&&N(this.el.offsetParent)}redraw(e=!1){this.isHostElementVisible&&(e?this.draw():$().redraw(this.presenter.hostElement))}drawBackground(e){let t=this.presenter.display.chart.backgroundColor;e.clearRect(0,0,this.width,this.height),e.fillStyle=t,e.fillRect(0,0,this.width,this.height)}drawCrosshair({ap:e,offset:t}){let n=this.mouseContext;return n.clearRect(0,0,this.width,this.height),!e||!t||!this.xAxis||!this.xAxis.drawCrosshair(n,t)?!1:(this.presenter.display.yAxis.visible&&e.axis?.pane&&e.axis.pane.drawYCrosshair(n,t),!0)}drawSplitters(e){let t=this.presenter.display.chart.backgroundColor;e.strokeStyle=Ko(t),e.lineWidth=2,this.splitters.forEach(t=>{let{x:n,y:r,width:i,height:a}=t,o=r+a/2;e.beginPath(),e.moveTo(n,o),e.lineTo(n+i,o),e.stroke()})}toTime(e){return this.xAxis.xScale.xToTime(e)}toIndex(e){return this.xAxis.xScale.timeToIndex(e)}toX(e){return this.xAxis.xScale.timeToX(e)}setCursor(e){let t=pN(e);oa(this.el,{cursor:t})}shutdown(){this.listeners.forEach(e=>e()),this.eventCapture&&this.eventCapture.shutdown(),this.tooltip&&this.tooltip.remove(),this.el&&da(`.bcharts-card`,this.el).forEach(e=>e.remove()),this.canvasContainer.remove()}getEventRadius(){let e=this.xAxis.xScale.bar.width/2;return Math.max(e,z.MIN_EVENT_RADIUS)}};function pN(e){switch(e){case te.Arrow:default:return`default`;case te.Crosshair:return`crosshair`;case te.Hand:return`pointer`;case te.Move:return`move`;case te.ResizeVertical:return`ns-resize`;case te.Grabbing:return`grabbing`;case te.ResizeHorizontal:return`ew-resize`}}var mN=class{view;popupElement;date;value;visible;_initialized;constructor(e){this.view=e,this.date=null,this.value=null,this.visible=!1,this._initialized=!1}initialize(){this.popupElement=ua(this.view.el,`div`),sa(this.popupElement,{id:`${this.view.presenter.elementId}-custom-event-host`}),oa(this.popupElement,{visibility:`hidden`,position:`absolute`,"z-index":30,top:`0px`,left:`0px`,padding:`5px 10px 10px 10px`,display:`flex`,"flex-direction":`column`,background:`var(--chartPopupElemBg, #999)`,"box-shadow":`0px 2px 10px rgba(0,0,0,.3)`,"border-radius":`4px`,border:`1px solid var(--chartPopupElemBorderColor, #888)`,"max-height":`400px`,overflow:`auto`});let e=ua(this.popupElement,`a`);sa(e,{class:`custom-event-close-button`}),oa(e,{position:`absolute`,right:`10px`,top:`5px`,fill:`var(--text-color,#888)`,cursor:`pointer`}),e.innerHTML=`<svg xmlns:xlink="http://www.w3.org/1999/xlink" width="12px" height="12px"><use xlink:href="#bchart-icon-delete"></use></svg>`,e.addEventListener(`click`,e=>this.hide()),this._initialized=!0}showValue(){}show(e,t,n){this._initialized||this.initialize(),this.date=t,this.value!==n&&(this.value=n,this.showValue()),oa(this.popupElement,{visibility:`visible`,top:`${e.y}px`,left:`${e.x}px`,width:`310px`}),this.visible=!0}hideValue(){}hide(){this.visible&&=(this.hideValue(),oa(this.popupElement,{visibility:`hidden`}),!1)}};function hN(e,t){return H(e,`..axes[${t.axisIndex}]`,e=>(e.annotations=t.annotations,e))}function gN(e){return e.annotations&&e.annotations.length>0}function _N(e,t){gN(e)&&(t.annotations=(t.annotations||[]).concat(e.annotations))}var vN=`..axes{..plots{.type==="Study"}}`;function yN(e){return V(e,`..plots{.type==="Study"}.study`)}function bN(e,t){let n=yN(e),r=yN(t);return n.length===r.length&&ve(n,r)}function xN(e,t,n){let r=t.find(t=>!n.has(t)&&bN(e,t));if(M(r))return r;let[i]=yN(e);return t.find(e=>!n.has(e)&&i===yN(e)[0])}function SN(e,t){let{mainAxis:n}=Tf(e),{mainAxis:r}=Tf(t);_N(n,r);let i=V(e,vN).filter(e=>e!==n),a=V(t,vN).filter(e=>e!==r),o=/* @__PURE__ */ new Set;return i.forEach(e=>{let t=xN(e,a,o);M(t)&&(o.add(t),_N(e,t))}),t}function CN(e,t){let n=e=>`..panes[${e}]`,r=e;return t.paneHeights.forEach(e=>{r=H(r,n(e.index),t=>(t.height=e.relativeHeight,t))}),r}var wN={ok:!1,change:void 0,toApply:void 0};function TN(e){return e.toolChange===D.Reordered}var EN=class{presenter;paused=null;undoStack=[];redoStack=[];initial=/* @__PURE__ */ new Map;isPaused=!1;constructor(e){this.presenter=e,this.clear()}clear(e=!1){this.undoStack=[],this.redoStack=[],this.initial=/* @__PURE__ */ new Map,e&&this.presenter.allAnnotations.forEach(e=>this.initial.set(e.uid,Gk(e,D.Moved)))}rebindOwners(e){let t=new Set(this.presenter.panes.flatMap(e=>e.axes)),n=(e,n)=>{e.annotationUndoOwner.axis=n,n&&(n.annotationUndoOwner=e.annotationUndoOwner,t.delete(n))},r=e.flatMap(e=>e.axes);for(let e of[`annotations`,`plots`])r=r.filter(r=>{let i=new Set(r[e].map(e=>e.uid)),a=[...t].filter(t=>t[e].some(e=>i.has(e.uid)));return a.length!==1||(n(r,a[0]),!1)});for(let e of r){let i=e.pane,a=i.axes.map(e=>e.annotationUndoOwner.axis?.pane),o=new Set(a.filter(e=>e&&this.presenter.panes.includes(e))),s=o.size===1?[...o][0]:void 0,c=s?[...t].filter(e=>e.pane===s):[],l=e.plots.length===0&&e.annotations.length===0,u=r.filter(e=>e.pane===i).length===1;n(e,l&&u&&c.length===1?c[0]:void 0)}}done(e){this.isPaused?this.paused=e:(this.undoStack.push(e),this.redoStack.length=0)}undo(){this.undoRedo(this.undoStack,this.redoStack,!0)}pause(){this.isPaused=!0}resume(e){this.isPaused=!1,e&&M(this.paused)&&this.done(this.paused),this.paused=null}redo(){this.undoRedo(this.redoStack,this.undoStack,!1)}delete(e){let t={...e,id:`Delete`};this.presenter.handleAnnotationChange(t)}add(e){let t={annotation:e,id:`Add`};this.presenter.handleAnnotationChange(t)}applyOrder(e,t){let n=this.presenter.allAnnotations.find(t=>t.uid===e.uid)?.axis??e.owner?.axis;if(!n)return;let r=t?e.before:e.after,i=n.annotations.filter(e=>r.includes(e.uid));if(i.length<2)return;i.sort((e,t)=>r.indexOf(e.uid)-r.indexOf(t.uid));let a=0;n.annotations=n.annotations.map(e=>r.includes(e.uid)?i[a++]:e),this.presenter.onAnnotationsUpdated(n),this.presenter.view?.redraw();let o=n.annotations.find(t=>t.uid===e.uid),s=t?D.Undo:D.Redo;o&&this.presenter.onAnnotationModifiedByTool(o,s,!1,!0)}apply(e,t,n=!1){if(!N(e))return!1;if(TN(e))return this.applyOrder(e,n),!0;let r=e;switch(t){case D.None:case D.Undo:case D.Redo:F(`Unexpected tool change ${D[t]} for undo/redo`,`warn`);break;case D.Created:n?this.delete(r):this.add(r);break;case D.Deleted:n?this.add(r):this.delete(r);break;default:{let e={...r,id:`Update`};this.presenter.handleAnnotationChange(e);break}}let i=this.presenter.allAnnotations.find(e=>e.uid===r.uid),a=n?D.Undo:D.Redo;return N(i)&&this.presenter.onAnnotationModifiedByTool(i,a),!0}can(e){let t=e?this.undoStack:this.redoStack;if(t.length<1)return wN;let n=Ce(t),r=n.toolChange;if(TN(n)||!(e&&r!==D.Deleted&&r!==D.Created))return{ok:!0,change:r,toApply:n};let i=Te(t,e=>e.uid===n.uid&&!TN(e),t.length-2),a=i===-1?null:t[i],o=a===null;return o&&!this.initial.has(n.uid)?wN:{ok:!0,change:r,toApply:o?this.initial.get(n.uid):a}}get canUndo(){return this.can(!0).ok}get canRedo(){return this.can(!1).ok}undoRedo(e,t,n){let{ok:r,change:i,toApply:a}=this.can(n);r&&this.apply(a,i,n)&&t.push(e.pop())}},DN=class{presenter;text=null;align=`center`;verticalAlign=`top`;x=0;y=0;style={color:`#333`,fontSize:18};constructor(e){this.presenter=e}update({style:e,...t}){Object.assign(this,t),Object.assign(this.style,e)}draw(e){if(!this.text)return;let{fontFamily:t}=this.presenter.display.chart,{fontSize:n,color:r,fontWeight:i}=this.style,{x:a,y:o,width:s,height:c}=this.presenter.mainPlot.axis.pane.getBounds(),l=a+this.presenter.view.leftOffset,u=a+s-this.presenter.view.rightOffset,d=l;d=this.align===`center`?s/2:this.align===`right`?u:l;let f=o+n;this.verticalAlign===`middle`?f=o+n+c/2:this.verticalAlign===`bottom`&&(f=o+c),d+=this.x,f+=this.y,e.save(),e.font=`${i||`normal`} ${n}px ${t}`,e.textAlign=this.align,e.textBaseline=`bottom`,e.fillStyle=r,e.fillText(this.text,d,f),e.restore()}},ON=/* @__PURE__ */ new Set([`BALTIC`,`BALTIC_FREE`,`SGFRT`]);function kN(e){return!!e&&e.allPlots.length>0&&e.allPlots.every(e=>AN(e.metaData))}function AN(e){if(!e.isReady)return!1;if(e instanceof Co)return e.inner.every(AN);let t=e.exchange.trim().toUpperCase();return(!e.symbol||t.length>0)&&!ON.has(t)}function jN(e){let t=e.offset;return typeof t==`number`?t:void 0}function MN(e,t,n){let r=t.axis,i=r?.pane,a=i?e.panes.indexOf(i):-1,o=i&&r?i.axes.indexOf(r):-1,s=r?r.plots.indexOf(t):-1,c=t.uid??t.id,l=jN(t);return{id:typeof l==`number`&&(t.isSeasonal||t.isForward)?`${c}:${l}`:c,plotUid:c,plotType:S[t.type],plotTitle:_y(t)??t.title,fieldIds:n.map(({field:e})=>e.id),seasonalOffset:t.isSeasonal?l:void 0,paneIndex:a,axisIndex:o,plotIndex:s,main:t.main}}function NN(e){return e.view?.xAxis?.xScale.extent()??null}function PN(e,t,n){let r=/* @__PURE__ */ new Map;return t.main&&(r.set(W.DateTime,{field:W.DateTime,shift:0}),e.data.aggregation.isMultiContract&&!t.isExpression&&r.set(W.Symbol,{field:W.Symbol,shift:0})),t.curves.forEach(e=>{e.fields.forEach(t=>{n.includes(t.id)||r.set(t,{field:t,shift:e.shift})})}),Array.from(r.values())}function FN(e,t){let n=t.excludeFields??[],r=e.allPlots.map(t=>{let r=PN(e,t,n);return{plot:t,fields:r,source:MN(e,t,r)}}).filter(({fields:e})=>e.length>0);return t.sourceOrder?r.map((e,t)=>({source:e,index:t})).sort((e,n)=>t.sourceOrder(e.source.source,n.source.source)||e.index-n.index).map(({source:e})=>e):r}function IN(e,t,n){let r=`${t.id}.${n.id}`,i=r,a=2;for(;e.has(i);)i=`${r}.${a++}`;return e.add(i),i}function LN(e){let t=/* @__PURE__ */ new Set;return e.flatMap(({source:e,fields:n})=>n.map(({field:n})=>({id:IN(t,e,n),name:n.name,fieldId:n.id,source:e})))}function RN(e,t){let n=[0,0];return e.allCurves.forEach(e=>{e.fields.every(e=>t.includes(e.id))||(e.shift<0&&(n[0]=Math.min(n[0],e.shift)),e.shift>0&&(n[1]=Math.max(n[1],e.shift)))}),n}function zN(e,t){return t.some(t=>{if(t.fieldId===W.DateTime.id)return!1;let n=e[t.id];return n!=null&&n!==``})}function BN(e,t,n,r,i,a){let o=e.timeline.at(r),s=n.plot.timeSeries.container,c=s.getTimeData(),l=t[n.plot.id]||0,u=A(c,+o,Number,Ee,l),d=+o==+c[u];if(d&&(t[n.plot.id]=u),a===0)return d?s.getData(i)[u]??``:i===W.DateTime?o:``;let f=e.timeline.at(r-a);if(!N(f))return``;let p=A(c,+f,Number,Ee,0);return+f==+c[p]?s.getData(i)[p]??``:``}function VN(e={}){let t=this.allPlots.every(e=>N(e.timeSeries)&&e.timeSeries.hasData),n=this.data.aggregation.isEndOfDay?z.FMT_ISO_DATE_ONLY:z.FMT_EXPORT_ALL_BUT_MILLIS;if(!t||!kN(this))return{columns:[],rows:[],dateFormatHint:n};let r=e.excludeFields??[],i=FN(this,e),a=LN(i),o={},s=this.timeline.lastSeriesIndex,c=we(this.mainPlot.timeSeries.container.getTimeData()),l=A(this.timeline,+c,Number,Jv),u=RN(this,r),d=e.visibleRange?NN(this):null,f=d?d[0]:l+u[0],p=d?d[1]:s+u[1],m=[];for(let e=f;e<=p;e++){let t={};i.forEach(n=>{n.fields.forEach(({field:r,shift:i})=>{let s=a.find(e=>e.source===n.source&&e.fieldId===r.id);t[s.id]=BN(this,o,n,e,r,i)})}),zN(t,a)&&m.push(t)}return{columns:a,rows:m,dateFormatHint:n}}function HN(e){return`"${e}"`}function UN(e,t,n,r){return e instanceof Date?$r(e,n.dateFormatHint??z.FMT_EXPORT_ALL_BUT_MILLIS):typeof e==`number`&&N(r.numDecimals)?Ze(e,r.numDecimals)?.toString()??``:e?.toString()??``}function WN(e,t){return t?.source.id===e.source.id?``:HN(`${e.source.plotType}: ${e.source.plotTitle}`)}function GN(e,t={}){if(e.columns.length===0)return`No data to export`;let n=t.excludeHeader??!1,r=[];return n||(r.push(e.columns.map((t,n)=>WN(t,e.columns[n-1]??null)).join(`,`)),r.push(e.columns.map(e=>HN(e.name)).join(`,`))),e.rows.forEach(n=>{let i=e.columns.map(r=>UN(n[r.id],r,e,t));e.columns.some((e,t)=>e.fieldId!==W.DateTime.id&&i[t].length>0)&&r.push(i.join(`,`))}),r.join(`
|
|
42
|
-
`)}function KN(e={}){return GN(VN.call(this,e),e)}function qN(e={}){let t=this.view.mainCanvas,{width:n,height:r}=t,{width:i,height:a,title:o}=e,s=(e,t)=>{let n=document.createElement(`canvas`);return n.width=e,n.height=t,n.getContext(`2d`)},c=s(n,r),l=globalThis.devicePixelRatio;if(c.drawImage(t,0,0),c.scale(l,l),M(o)){let e=new DN(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(W.DateTime);if(M(u)){let{fontFamily:e}=this.display.chart,{fontWeight:n,fontSize:r}=this.mainAxis.config;c.font=`${n} ${r*1.2}px ${e}`,c.textBaseline=`top`;let i=r*1.5,a=getComputedStyle(t),o=a.getPropertyValue(`--app-hc-color`),s=a.getPropertyValue(`--app-color-pl`),l={x:z.CARDS_X_OFFSET,y:z.CARDS_Y_OFFSET},d=vy(this,u,l,void 0,!1,0),f=`${d.date} ${d.time??``}`.trim(),[p,m]=[1,5],h=(e,t)=>c.measureText(e).width+t,g=(e,t,n,r,i)=>(c.fillStyle=r,c.fillText(e,t,n),h(e,i)),_=(e,t)=>e.type===S[t],v=e=>{let t=e.name;return e.isMain&&_(e,`Symbol`)?t=`${e.description} (${e.name}) [${e.exchange}]`:_(e,`Study`)&&(t=`${e.description} ${e.name.substring(e.name.indexOf(` `))}`),t};d.panes.forEach(e=>{let{top:t,left:n,width:r,right:a}=e.bounds,c=n+r-a-m,u=n+l.x,d=t+l.y;e.plots.some(e=>e.isMain)&&(u+=g(f,u,d,o,m)),e.plots.forEach((e,t)=>{let r=v(e),a=!_(e,`Study`)&&e.values.length>1;if(!e.isMain&&t>0){let t=u+h(r,m);e.values.forEach(e=>{a&&(t+=h(e.abbreviation,p)),t+=h(e.value,m)}),t>=c&&(u=n+l.x,d+=i)}u+=g(r,u,d,o,m),e.values.forEach(e=>{a&&(u+=g(e.abbreviation,u,d,s,p)),u+=g(e.value,u,d,e.color,m)})})})}let d=e=>({width:i??n,height:a??r,data:e.toDataURL(`image/png`)});if(M(i)&&M(a)){let e=s(i,a);return e.drawImage(c.canvas,0,0,i,a),d(e.canvas)}return d(c.canvas)}function JN(e){if(e!==void 0)return e===z.YTD_PERIOD?e:yt(e)}var YN=Symbol.for(`__ias__`),XN=class{accessor;view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken=``;metaChangedToken=``;streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;annotationPreviewUid;hoverHighlightPlotIds=null;hoverDimPlotIds=null;hoverBasisByDependentPlotId=/* @__PURE__ */ new Map;hoverDependentsByBasisPlotId=/* @__PURE__ */ new Map;hoverHighlightablePlotIds=/* @__PURE__ */ new Set;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=_M(`Default`),this._activeTool=this.defaultTool,this.timeline=new Yv(this),this.undoRedoManager=new EN(this),this.title=new DN(this),this.notifySelectionChanged=qe(G.CH_ANNSELECTIONCHANGED),this.notifyRecreated=qe(G.CH_RECREATED),this.notifyDefinitionChanged=qe(G.CH_DEFINITION_CHANGED)}traceChart(e,t={}){yg(e,{chartId:this.elementId,...t})}getModel(){return this.model}get isEmpty(){return!N(this.model)}notifyHost(e,t){Ke(e,t)}async fromModel(e,t){if(this._isShutdown)return;this.traceChart(`chart:fromModel:start`,{hadModel:N(this.model)}),N(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.annotationPreviewUid=void 0,this.clearSelection(),this.model=e;let n=P(e);this.data=n.data,this.data.aggregation=fd(n.data.aggregation),this.display=n.display,this.display.period=JN(n.display?.period);let r=this.panes;this.panes=n.panes.map(e=>{let t=new QM(this);return t.fromModel(e),t},this),this.undoRedoManager.rebindOwners(r);let i=this.allPlots.map(e=>e.initialize());await Promise.all(i),!this._isShutdown&&(this.rebuildHoverHighlightRelations(),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),N(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view){if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{let n=!t||tP(e,t,this);this.view.resetZoomAndVisibleRange=n,n&&(this._maxOffset=0)}}}closeView(){N(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(N(this.view)?this.view.reinitialize():(this.view=new fN,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){let t={metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size};this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e)),this.traceChart(`chart:cacheable-entities`,{plotCount:this.allPlots.length,addedMetaData:e.metaData.size-t.metaData,addedRecords:e.records.size-t.records,addedTimeSeries:e.timeSeries.size-t.timeSeries})}get activeTool(){return this._activeTool}set activeTool(e){N(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,N(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(G.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.isVisible&&t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){let e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}get hasStudyBasisFocus(){return this.display?.chart?.studyBasisFocus===!0}get hasHoverHighlight(){return this.hoverHighlightPlotIds!==null||this.hoverDimPlotIds!==null}getStudyBasis(e){return e.isStudy?e.basePlot??null:null}isHoverSourcePlot(e){return e.isSeasonal||e.isSymbol}hasMultipleHoverSourcePlots(){return this.allPlots.filter(e=>e.isVisible&&this.isHoverSourcePlot(e)).length>1}get annotationManipulation(){return $()?.config.annotationManipulation===!0}setAnnotationPreview(e){this.annotationPreviewUid!==e&&(this.annotationPreviewUid=e,this.view?.redraw())}clearHoverHighlight(){this.hoverHighlightPlotIds=null,this.hoverDimPlotIds=null}clearHoverHighlightRelations(){this.hoverBasisByDependentPlotId.clear(),this.hoverDependentsByBasisPlotId.clear(),this.hoverHighlightablePlotIds.clear()}rebuildHoverHighlightRelations(){if(this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.hasStudyBasisFocus&&this.hasMultipleHoverSourcePlots())for(let e of this.allPlots){if(this.isHoverSourcePlot(e)&&this.hoverHighlightablePlotIds.add(e.id),!e.isStudy)continue;let t=this.getStudyBasis(e);if(!N(t))continue;this.hoverBasisByDependentPlotId.set(e.id,t.id);let n=this.hoverDependentsByBasisPlotId.get(t.id);N(n)||(n=/* @__PURE__ */ new Set,this.hoverDependentsByBasisPlotId.set(t.id,n)),n.add(e.id),this.hoverHighlightablePlotIds.add(e.id),this.hoverHighlightablePlotIds.add(t.id)}}isHoverHighlightable(e){return this.hasStudyBasisFocus&&N(e)&&this.hoverHighlightablePlotIds.has(e.id)}getRelatedHoverPlotIdsForPlot(e){if(!this.isHoverHighlightable(e))return null;let t=/* @__PURE__ */ new Set,n=this.hoverBasisByDependentPlotId.get(e.id);if(N(n))return t.add(e.id),t.add(n),t;let r=this.hoverDependentsByBasisPlotId.get(e.id);return N(r)&&r.size>0?(t.add(e.id),r.forEach(e=>t.add(e)),t):(t.add(e.id),t)}getRelatedHoverPlotIds(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.getRelatedHoverPlotIdsForPlot(n);e!==null&&e.forEach(e=>t.add(e))}return t.size>0?t:null}getHoverDimPlotIds(e){if(!this.hasStudyBasisFocus||e===null)return null;let t=/* @__PURE__ */ new Set;for(let n of this.hoverHighlightablePlotIds)e.has(n)||t.add(n);return t}sameHoverHighlight(e){let t=this.hoverHighlightPlotIds;if(t===null||e===null)return t===e;if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}setHoverHighlight(e){if(!this.hasStudyBasisFocus)return this.hasHoverHighlight&&(this.clearHoverHighlight(),this.view?.redraw()),!1;let t=this.getRelatedHoverPlotIds(e);return this.sameHoverHighlight(t)?this.hoverHighlightPlotIds!==null:(this.hoverHighlightPlotIds=t,this.hoverDimPlotIds=this.getHoverDimPlotIds(t),this.view?.redraw(),t!==null)}shouldDimPlot(e){return this.hasStudyBasisFocus&&(this.hoverDimPlotIds?.has(e.id)??!1)}fixupDensityForForwards(){let e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;let n=t.series,r=e=>e.timeSeries===n||e.eventsSeries===n,i=this.allPlots.find(r);if(!N(i))return;let a=N(i)&&i.main,o=!1,s=!1;if(e===G.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}let c=N(t.index)?n.container.getTimeData()[t.index]:null,l=e===G.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===G.TS_MANYCHANGED||l){if(a&&this.data.checkRange){if(N(this.display.xAxis.visibleRange)){let e={id:`Period`,context:{range:this.display.xAxis.visibleRange}};e[YN]=!0,this.accessor.change(e);return}delete this.data.checkRange}i.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;i.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0)),i.invalidateAssociatedAnnotations(`NewChunkArrived`));let n=N(this.display?.xAxis?.visibleRange);if((i.isSeasonal&&!u.wasVisibleRangeChanged&&!n||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===ie.Tail){let e=A(this.timeline,c,Number,Jv);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===G.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(c);e!=-1&&u.shouldScrollIntoView(e)?(d.shiftBars(1),o=!0):s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointAdded`)}else e===G.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(G.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),s&&(o&&F(`Performance : redundant call to recompute price domains (layout recalculation took care of this)`,`warn`),this.allAxes.filter(e=>e.plots.includes(i)).forEach(e=>{e.setDomain(),N(c)&&e.updateFullDomain(c)})),!this.sentInitialLoadNotification&&e===G.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(G.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),bA(this);let e=this.display.period===z.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===G.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(t.plot.main&&this.allAnnotations.forEach(e=>e.onFormatterChanged()),this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){let t=this.panes.indexOf(e.pane),n=e.pane.axes.indexOf(e),r={chart:this.accessor,paneIndex:t,axisIndex:n};this.notifyHost(G.CH_AXISSCALECHANGED,r)}get previousMask(){return N(this._previousMask)||(this._previousMask=wp(W.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){if(!N(this._hasLegend)){let e=re[$()?.config.mode??`Unspecified`];this._hasLegend=[re.cmdtyView,re.EqPlus].includes(e)}return this._hasLegend}onStreamingUpdates(e){N(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return N(this._ohlcMask)||(this._ohlcMask=wp(W.Open,W.High,W.Low,W.Close,W.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)===0)return!1;let n=(e,t)=>M(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?n(this.mainPlot.timeSeries.record,t):this.mainPlot.isExpression?n(this.mainPlot.record,t):!1}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return N(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:aa(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=Ib.default.subscribe(G.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=Ib.default.subscribe(G.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return Ib.default.unsubscribe(this.seriesChangedToken),Ib.default.unsubscribe(this.metaChangedToken),N(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(G.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation!==e&&(this.selectedAnnotation&&this.clearSelection(),this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor}))}clearSelection(){N(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(te.Arrow)}print(e={}){let t=ua(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=qN.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),pa(i).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),N(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===z.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,n=Le();!e&&t.visible&&t.mode===z.TOOLTIP_CARDS&&da(`.bcharts-card`,this.hostElement).forEach(e=>{let t=e.classList.contains(`bcharts-card-move`);n&&t||e.classList.contains(`bcharts-legend`)||(e.style.display=`none`)})}handleAnnotationChange(e){let t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if(e.id===`List`)return this.allAnnotations.map(t);if(e.id===`Cache`)return V(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`){let t=e.annotation;return(t.isUndoRedo?t.owner?.axis??this.mainAxis:this.mainAxis)?.addAnnotation(t)}let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){if(e.id===`Delete`&&!e.isUndoRedo)return this.deleteAnnotationWithUndo(n);let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e);return}}throw Error(`Unknown sub-action ${e.id} for action ${z.ANN_ACTION_ID}`)}deleteAnnotationWithUndo(e){this.undoRedoManager.done(Gk(e,D.Deleted)),e.axis.deleteAnnotation(e),this.onAnnotationModifiedByTool(e,D.Deleted,!1)}getPlotInfoFromDom(e){let t=e.attributes.getNamedItem(`data-plot-uid`);if(!t)throw Error(`Unable to resolve plot info: missing data-plot-uid attribute.`);let n=t.value,r=0;for(let e of this.model.panes)for(let t of e.axes)for(let e of t.plots){if(e.uid===n)return{type:e.type,index:r};r++}throw Error(`Unable to resolve plot info: model plot index not found for uid '${n}'.`)}getSimplePlot(e,t){return this.accessor.change({id:`Plot`,context:{id:z.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:n};this.notifyHost(G.CH_CARDPLOTCLICKED,r)}deletePlotClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index);this.accessor.change({id:`Plot`,context:{id:`Delete`,type:t.type,index:t.index}});let r={chart:this.accessor,plot:n};this.notifyHost(G.CH_CARDPLOTREMOVED,r)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let t=this.getPlotInfoFromDom(e),n=e.attributes.getNamedItem(`data-act`).value===`Show`;this.accessor.change({id:`Plot`,context:{id:`Update`,type:t.type,index:t.index,visible:n}});let r=this.getSimplePlot(t.type,t.index),i={chart:this.accessor,plot:r,visible:n};this.notifyHost(G.CH_CARDPLOTVISIBILITYCHANGED,i)}plotMoreActionsClicked(e,t){let n=this.getPlotInfoFromDom(e),r=this.getSimplePlot(n.type,n.index),i={x:t.clientX,y:t.clientY},a={chart:this.accessor,plot:r,offset:i,originalEvent:t};this.notifyHost(G.CH_PLOTNEEDSCONTEXTMENU,a)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem(`data-pane`).value),n=e.attributes.getNamedItem(`data-dir`).value===`Down`,r=t+ +!!n,i=t-+!n;setTimeout(()=>{this.accessor.change({id:`MovePane`,context:{from:r,to:i}}),this.notifyHost(G.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=hN(this.model,{axisIndex:n,annotations:r});try{this.model=hp(i,z.CHART_SCHEMA)}catch(e){F(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(G.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0,r=!1){if(t!==D.None){if(n&&t!==D.Undo&&t!==D.Redo){let n=Gk(e,t);this.undoRedoManager.done(n)}let i=Kk(e);i.toolChange=D[t],(r||t===D.Reordered)&&(i.orderOnly=!0),this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,i)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:D[t]};this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=CN(this.model,{paneHeights:e}),this.notifyHost(G.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!N(e)||e.size===0)return null;let t=e.getTimeData(),n=we(t),r=Ce(t);return N(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function ZN(e,t){return e?.from===t?.from&&e?.to===t?.to}var QN=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function $N(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function eP(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=QN.includes(r.style),o=QN.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&$N(ft(e.inputs),ft(t.inputs))):!1:!0}function tP(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if($N(dd(LF(r,t,n)),dd(LF(r,e,n)))||!ZN(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!ZN(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;let i=wf(t),a=wf(e);if(eP(i,a))return!0;let o=(e,t)=>e.type===t,s=e=>{let t=e.toLowerCase();return o(a,e)&&o(i,e)&&i[t]!==a[t]},c=i.type!==a.type,l=s(`Forward`),u=s(`Expression`),d=s(`Symbol`);return c||l||u||d}function nP(e,t,n){if(`paneIndex`in t||`axisIndex`in t)throw Error(`AnnotationManipulation paneIndex and axisIndex are output-only metadata; use uid`);let r=n?.selectedAnnotation?.uid,i=n?.annotationPreviewUid;return e.panes.flatMap((e,n)=>e.axes.flatMap((e,a)=>(e.annotations||[]).map((e,t)=>({uid:e.uid,paneIndex:n,axisIndex:a,position:t,selected:r===e.uid,preview:i===e.uid})).filter(e=>t.uid===void 0||e.uid===t.uid)))}function rP(e,t){return e===`Front`?t-1:e===`Back`?0:St(0,t-1,e)}function iP(e,t,n){let{uid:r,position:i,selected:a,preview:o}=t;if(t.id!==void 0&&t.id!==`Update`)throw Error(`Invalid AnnotationManipulation sub-action`);if(i!==void 0&&i!==`Front`&&i!==`Back`&&!(Number.isInteger(i)&&i>=0))throw Error(`Annotation position must be Front, Back, or a non-negative integer`);if((i!==void 0||a===!0||o===!0)&&r===void 0)throw Error(`AnnotationManipulation requires uid for position, selection, or preview`);let s=nP(e,t,n),c=r===void 0?void 0:s[0],l=c&&n?.panes[c.paneIndex]?.axes[c.axisIndex],u=l?.annotations.find(e=>e.uid===r),d=u?.isVisible&&!u.computed?u:void 0;if(c&&i!==void 0){let t=e.panes[c.paneIndex].axes[c.axisIndex].annotations,r=rP(i,t.length);if(r!==c.position){let e=t.map(e=>e.uid);if(l&&u&&n){let t=[...e];t.splice(r,0,t.splice(c.position,1)[0]),l.annotations.sort((e,n)=>t.indexOf(e.uid)-t.indexOf(n.uid)),n.undoRedoManager.done({owner:l.annotationUndoOwner,uid:u.uid,toolChange:D.Reordered,before:e,after:t}),n.onAnnotationsUpdated(l),n.onAnnotationModifiedByTool(u,D.Reordered,!1),u.requestRedraw()}else t.splice(r,0,t.splice(c.position,1)[0])}}return n&&o!==void 0&&(o&&d?n.setAnnotationPreview(d.uid):!o&&(r===void 0||n.annotationPreviewUid===r)&&n.setAnnotationPreview()),n&&a!==void 0&&(a&&d?n.setSelection(d):!a&&s.some(e=>e.selected)&&n.clearSelection()),e}function aP(e,t){let[n,r]=$e(t.crosshair),{color:i,dashStyle:a}=t.horizontal||{},{color:o,dashStyle:s}=t.vertical||{},c=(e,t,n)=>{t&&(e.color=t),n&&(e.dashStyle=n)},l=H(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=H(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),N(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=H(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function oP(e,t){return H(e,`.display.tooltip`,e=>(t.visible!=null&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),t.showMainTitle!=null&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))}function sP(e,t){let n=P(t);return Object.keys(t).forEach(e=>{z.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{z.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),H(e,Cf,e=>(e.type===`Symbol`&&(e.events=e.events||{},Object.keys(n).forEach(t=>{e.events[t]=e.events[t]||{},lt(e.events[t],n[t],!1)})),e))}function cP(e,t){let n=H(e,`..panes{${Cf}}.axes`,e=>(M(t.scale)&&(e.scale=t.scale),e));n=H(n,`.display.xAxis`,e=>(M(t.horizontalAxisPosition)&&(e.position=t.horizontalAxisPosition),M(t.marginBars)&&(e.marginBars=t.marginBars),M(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),M(t.ordinalName)&&(e.ordinalName=t.ordinalName),M(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e));let r=()=>F(`The 'minPadding' and 'maxPadding' are deprecated (ignored)`,`warn`),i=()=>F(`The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'`,`warn`);return n=H(n,`.display.yAxis`,e=>{(N(t.minPadding)||N(t.maxPadding))&&r();let n=M(t.preventLabelOverlap)&&!M(t.preventVerticalLabelOverlap);n&&i();let a=n?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return M(a)&&(e.preventLabelOverlap=a),N(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),N(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),N(t.primaryOnTheLeft)&&(e.primaryOnTheLeft=t.primaryOnTheLeft),e}),N(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:r,index:i,paneIndex:a}=e;N(t,r,i)&&t===`vertical`&&Number.isInteger(i)&&(n=H(n,`..panes[${a??0}]..axes[${i}]`,e=>N(e)?(e.label=r,e):z.NULL_OBJECT))}),M(t.contractTransition)&&(n=H(n,`.display.xAxis`,e=>(ut(e.contractTransition,t.contractTransition),e))),M(t.cycleTransition)&&(n=H(n,`.display.xAxis`,e=>(ut(e.cycleTransition,t.cycleTransition),e))),n}function lP(e,t,n){let r=e;if(N(t.comparisonMode)&&typeof t.comparisonMode==`string`&&rt(x,t.comparisonMode)&&(r=H(r,`..panes{${Cf}}.axes`,e=>(e.comparison=t.comparisonMode,e))),N(t.gridLines)){let[e,n]=$e(t.gridLines);r=H(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=H(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(N(t.minorGridLines)){let[,e]=$e(t.minorGridLines);r=H(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}N(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=H(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),N(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=H(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),N(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=H(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),N(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=H(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),N(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),N(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),N(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),N(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=H(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),M(t.hiddenItems)&&yk.includes(t.hiddenItems)&&(r=H(r,`.display`,e=>(e.hiddenItems=t.hiddenItems,e))),N(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=H(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e))),typeof t.useLastTrade==`boolean`&&(r=H(r,`.data`,e=>(e.useLastTrade=t.useLastTrade,e)));let i=[];if(N(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=H(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),N(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=H(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),N(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=H(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(G.CH_HOST_PROPS_CHANGED,e)}return r}var uP=`MARKED_FOR_DELETION`;function dP(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=bP(n,e);if(t===void 0)continue;let r=_P(t),i=vP(n,r);N(i)&&(N(e.type)&&i.type!==e.type||(n=H(n,r,e=>(e[uP]=!0,e))))}return n=H(n,`..plots{.${uP} === true}`,e=>z.NULL_OBJECT),n=H(n,`..plots{.type === "Study"}`,e=>{let t=B(e.study);return N(t)&&Sf(n,t,e.basis).eligible?e:z.NULL_OBJECT}),gp(n)}function fP(e,t,n,r){let i=S[e.type],a={curves:P(e.curves),type:e.type,uid:e.uid};a.precision=e.precision,a.visible=e.visible,a.detachedScale=e.detachedScale;let o=(e,t)=>{N(e[t])?a[t]=e[t].map(e=>P(e)):a[t]=[]},s=(e,t,n=!1)=>{t.main===!0&&(e.main=!0,e.showPrevious=t.showPrevious,n&&t.events!=null&&(e.events=P(t.events)))},c=(e,t=e=>!0)=>{N(r)&&(e.subtitles=r.allPlots.filter(e=>e.type===i).filter(t).map(e=>e.title))};switch(i){case S.Symbol:{a.title=e.symbol;let t=a.curves[0].style,n=t=>{o(e,`inputs`),a.inputs.length===0&&(a.inputs=P(t))};switch(t){case`Renko`:n(z.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(z.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(z.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(z.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(z.DEFAULT_BASELINE_INPUTS)}s(a,e,!0);break}case S.Study:{o(e,`inputs`);let r=B(e.study),i=a.inputs,s=r.id===`AVWAP`?TT(i):i.map(e=>e.value),c=s.length===0?``:` (${s.join(`, `)})`,l=a.curves.map(e=>Number(e.shift)).filter(e=>e>0),u=l.length===0?``:` [${l.join(`, `)}]`;a.title=`${r.id}${c}${u}`,a.studyId=r.id,o(e,`levels`),o(e,`bands`),a.basis=P(e.basis)||{kind:`main`},a.placement=t?n?`overlay`:`withMain`:`standalone`;break}case S.BalanceSheet:case S.IncomeStatement:{let t=W[e.curves[0].fields[0]];a.title=`${t.name} (${e.fundamental.substring(0,1)})`,a.fundamentalId=t.id,a.frequency=e.fundamental;break}case S.Expression:a.title=e.expression,s(a,e);break;case S.Forward:a.title=e.forward,o(e,`offsets`),c(a),s(a,e);break;case S.Seasonal:a.title=e.seasonal,c(a,e=>e.refSeasonal===a.title),o(e,`offsets`),s(a,e);break;default:throw Error(`Unexpected plot type`)}return a}function pP(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=V(e,`..panes`).map((e,t)=>{let n=V(e,o).length===1;return V(e,`..axes`).map((e,r)=>{let i=V(e,o).length===1;return V(e,`..plots`).map(e=>{let o=fP(e,n,i,a);return o.paneIndex=t,o.axisIndex=r,o})})}).flat(2).map((e,t)=>(e.index=t,e));if(N(i))return s.filter(e=>e.uid===i);if(t)return s.filter(e=>e.main);if(N(n)){let e=s.filter(e=>e.type===n);return N(r)?e.filter(e=>e.index===r):e}return s}var mP=[`overlay`,`standalone`,`withMain`,`clone`];function hP(e,t,n){t[n]&&(e[n]=t[n])}function gP(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),SP(e)?N(t.curves)&&(e.curves=t.curves):DP(e.curves,t.curves);let n=S[t.type],r=e;if(N(t.precision)?r.precision=t.precision:delete r.precision,n===S.Symbol)N(t.symbol)&&(e.symbol=t.symbol);else if(n===S.Study)N(t.basis)&&(e.basis=P(t.basis)),OP(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>hP(e,t,n));else if((n===S.BalanceSheet||n===S.IncomeStatement)&&t.frequency)e.fundamental=t.frequency;else if(n===S.Expression){let n=e;N(t.expression)&&(n.expression=t.expression)}else if(n===S.Forward){let n=e;N(t.offsets)&&(n.offsets=t.offsets),N(t.forward)&&(n.forward=t.forward)}else if(n===S.Seasonal){let n=e;N(t.offsets)&&(n.offsets=t.offsets),N(t.seasonal)&&(n.seasonal=t.seasonal),N(t.usesInAverage)&&(r.usesInAverage=t.usesInAverage),Bu(n)}}var _P=e=>`..plots[${e}]`;function vP(e,t){let n=V(e,t);return n.length===1?n[0]:null}function yP(e,t){let n=0;for(let r of e.panes)for(let e of r.axes)for(let r of e.plots){if(r.uid===t)return n;n+=1}}function bP(e,t){return N(t.uid)?yP(e,t.uid):t.index}function xP(e){let t=S[e.type];return t===S.Symbol||t===S.Expression}function SP(e){let t=S[e.type];return t===S.Forward||t===S.Seasonal}function CP(e){let t=S[e.type];return t===S.Symbol||t===S.Expression||t===S.Seasonal}function wP(e,t,n){if(N(t))return t;let r=n?.uid;return typeof r==`string`?yP(e,r):void 0}function TP(e,t,n){if(N(t.placement)&&!mP.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=bP(e,t),i=r===void 0?t.main?Cf:``:_P(r);if(!i)return e;let a=vP(e,i);if(!M(a)||M(t.type)&&a.type!==t.type)return e;let o=wP(e,r,a);if(t.type===S[S.Study]){let n=a,r=B(t.studyId??n.study);if(!M(r))return e;let i=N(t.basis)?t.basis:n.basis,o=Sf(e,r,i);if(!o.eligible)return F(`Cannot update study "${r.meta.title}" because ${o.reason}.`,`error`),e}if(M(t.visible))return a.visible=t.visible,e;if(a.main&&xP(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=If(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=If(e,{unit:`Intraday`,size:100,spec:`PerRange`}))}t.type||=a.type;let n=a;N(t.precision)?n.precision=t.precision:delete n.precision,N(t.showPrevious)&&(e=H(e,Cf,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?Fd(e,t):e;return N(t.oppositeScale)&&CP(a)&&N(o)&&(r=vf(r,o,+!!t.oppositeScale)),r}{let s=H(e,i,e=>(gP(e,t),e));if(N(t.oppositeScale)&&CP(a)&&N(o)&&(s=vf(s,o,+!!t.oppositeScale)),!(t.type===S[S.Study]&&N(t.placement)))return s;let c=N(r)?r:t.index,l=pP(s,{...t,index:c},n).find(e=>e.index===c);if(!N(l))return e;if(t.placement===l.placement)return s;let u=vP(s,i);if(!N(u))return e;s=dP(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=NP(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function EP(e){return e!==void 0}function DP(e,t){if(EP(t)&&t.length===e.length)for(let n=0;n<e.length;++n){let r=t[n],i=e[n];ut(i,r);for(let e of[`shift`,`dashStyle`,`lineSmoothing`,`lineMarker`]){let t=r[e];N(t)&&(i[e]=t)}}}function OP(e,t,n){let r=ft(e),i=ft(t);ut(r,i);let a=pt(i);a.length>0&&(n.inputs=a)}function kP(){return{plots:[]}}function AP(e){let t=e.display.chart.newPaneHeight??1;return{axes:[kP()],height:t}}function jP(e){let t=AP(e);return e.panes.push(t),t}function MP(e,t){let n=M(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:jP(e),r=n.axes[0];return t.oppositeScale??!1?$P(n,r):r}function NP(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Tf(e),c=(()=>{if(i?.kind!==`seasonal`)return null;for(let t of e.panes)for(let e of t.axes)for(let n of e.plots){if(n.uid!==i.uid||n.type!==`Seasonal`)continue;let r=n.offsets;if(Array.isArray(r)&&r.includes(i.offset))return{pane:t,axis:e}}return null})();switch(t){case`withMain`:a=c?$P(c.pane,c.axis):$P(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=jP(e).axes[0];break;case`clone`:{let t={main:!1,type:S[S.Study]};if(typeof r==`string`&&r.length>0?t.uid=r:typeof n==`number`&&(t.index=n),t.uid||typeof t.index==`number`){let n=pP(e,t).find(e=>e.type===S[S.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=V(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function PP(e,t){let n=B(t.studyId);if(!M(n))return F(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Sf(e,n,t.basis);if(!r.eligible)return F(`Cannot add study "${n.meta.title}" because ${r.reason}.`,`error`),e;let i=t.placement||(n.meta.overlay?`overlay`:`standalone`),a=t.uid??xt();N(t.uid)&&pf(e,a);let o={uid:a,type:`Study`,study:t.studyId,visible:!0};i===`overlay`&&t.studyId===`VOL`&&(o.detachedScale=!0),t.curves!==void 0&&(o.curves=n.defaults.curves),gP(o,t);let s=NP(e,i,t.cloneIndex,t.cloneUid,t.basis);N(s)&&s.plots.push(o);let c=e.data.aggregation;return Ff(e,c.unit===`Tick`&&c.spec===`None`)}function FP(e,t){e.panes.push({axes:[{plots:[t]}]})}function IP(e,t){let n=wf(e);if(n.type!==S[S.Symbol])throw Error(`Cannot add fundamental to the chart whose main plot is not a Symbol plot.`);let r=n.symbol,i=t.uid??xt();N(t.uid)&&pf(e,i);let a={uid:i,curves:[{fields:[t.fundamentalId],lineWidth:2,style:`Line`,varyColorPerBar:!1,visible:!0,colors:[`#888`]}],fundamental:`Quarter`,symbol:r,type:b[W[t.fundamentalId].category],visible:!0};return gP(a,t),FP(e,a),e}var LP=[{fields:[W.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function RP(e){return e.type===`Symbol`}function zP(e,t){let n=wf(e),r=P(RP(n)?n.curves:LP),i=t.uid??xt();N(t.uid)&&pf(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return gP(a,t),MP(e,t).plots.push(a),e}function BP(e,t){let n=t.uid??xt();N(t.uid)&&pf(e,n);let r={uid:n,curves:P(LP),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return gP(r,t),MP(e,t).plots.push(r),e}var VP={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function HP(e,t){let n=wf(e),r=$().getDefaultMultiFieldCurve(),i=N(r)?r:VP,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>P(e?n.curves:[i]))(RP(n)):t.curves,s=t.uid??xt();N(t.uid)&&pf(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return gP(c,t),MP(e,t).plots.push(c),e}function UP(e,t){switch(t.type){case`Study`:return PP(e,t);case`IncomeStatement`:case`BalanceSheet`:return IP(e,t);case`Expression`:return zP(e,t);case`Symbol`:return HP(e,t);case`Seasonal`:return BP(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var WP=0,GP=z.AUTO_COLORS,KP=`Symbol`,qP=`Expression`,JP=`Seasonal`;function YP(e,t){let n={attributes:[],colors:GP.slice(WP,WP+1),fields:e?[W.Last.id]:[W.Close.id],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0},r={uid:t.uid??xt(),curves:[n]},{curves:i,oppositeScale:a,...o}=t;return dt(r,o),M(i)&&(r.curves=i.map(e=>{let t=P(e);return dt(t,n),t})),r.main=!1,WP=(WP+1)%GP.length,r}function XP(e){return N(e.symbols)&&(F(`Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types`,`warn`),e.plots=e.symbols.map(e=>(e.type=KP,e))),e.plots?.some(e=>N(e.leftScale))?(F(`Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'`,`warn`),e.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}function ZP(e,t){let n=XP(t),r=n.map(e=>e.uid).filter(e=>typeof e==`string`),i=/* @__PURE__ */ new Set;for(let t of r){if(i.has(t))throw Error(`Plot uid '${t}' is duplicated in the Compare request.`);i.add(t),pf(e,t)}let{yes:a,no:o}=O(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Tf(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=$P(s,c),u=e=>![KP,qP,JP].includes(e.type);l.plots=l.plots.filter(u);let d=c.plots.filter(e=>e.main||u(e)),f=e.data.aggregation.unit===`Tick`;WP=0;let p=ce(YP,f);return c.plots=d.concat(o.map(p)),a.length>0&&(l.plots.push(...a.map(p)),l.comparison=c.comparison,l.scale=c.scale),gp(e)}var QP=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function $P(e,t){let n=e.axes.find(e=>e!==t);return N(n)||(n=kP(),e.axes.push(n)),n}function eF(e,t){let n=V(e,QP),r=V(t,QP),i=Math.max(0,4-r.length);if(i===0)return t;let a=n.filter(e=>!r.find(t=>e.symbol===t.symbol)).slice(0,i);if(a.length===0)return t;let{mainPane:o,mainAxis:s}=Tf(t),{mainAxis:c}=Tf(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):$P(o,s).plots.push(e)}),t}function tF(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var nF=()=>z.NULL_OBJECT;function rF(e){return H(e,`..axes.annotations`,nF)}function iF(e){return gp(H(e,`..plots{.type === "Symbol" && .main !== true}`,nF))}function aF(e,t){let n=P(e);if(t.strip.main){let e=wf(n),t=e.type.toLowerCase();e[t]=z.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=rF(n)),t.strip.compare&&(n=iF(n)),n=H(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function oF(e,t,n){let r=pP(e,{main:!0},n)[0],i=r.title===z.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=ef(r.title),c=[];return o&&!$d(s)?c=s.symbols:i||(c=[r.title]),{isTemplate:i,isDefinition:!i,main:{isSymbol:a,isExpression:o,symbols:c,title:i?null:r.title},compare:V(e,QP).map(e=>e.symbol),annotations:V(e,`..annotations`).map(e=>e.id),studies:pP(e,{type:`Study`},n).map(e=>e.title)}}function sF(e,t,n){let r=V(e,`..panes`).map((e,t)=>V(e,`..axes`).map((e,n)=>V(e,`.annotations`).map(e=>({...e,paneIndex:t,axisIndex:n})))).flat(2).map((e,t)=>({...e,index:t}));return N(t.index)&&Number.isFinite(t.index)?t.index<r.length?[r[t.index]]:z.EMPTY_ARRAY:r}function cF(e,t){let n=lF(t.annotation),{mainAxis:r}=Tf(e);return r.annotations??=[],r.annotations.some(e=>e.uid===n.uid)||r.annotations.push(n),e}function lF(e){let t={id:e.id,uid:e.uid,points:(e.points??[]).map(e=>({price:e.price,time:e.time}))};return e.traits!==void 0&&(t.traits=P(e.traits)),e.visible!==void 0&&(t.visible=e.visible),e.locked!==void 0&&(t.locked=e.locked),t}function uF(e,t){let n=V(e,`..axes`);for(let e of n){let n=e.annotations?.find(e=>e.uid===t.uid);if(n){t.traits!==void 0&&(n.traits=P(t.traits)),t.points!==void 0&&(n.points=t.points.map(e=>({price:e.price,time:e.time}))),t.visible!==void 0&&(n.visible=t.visible),t.locked!==void 0&&(n.locked=t.locked);break}}return e}function dF(e,t){let n=V(e,`..axes`);for(let e of n)if(e.annotations?.some(e=>e.uid===t.uid)){e.annotations=e.annotations.filter(e=>e.uid!==t.uid);break}return e}function fF(e,t,n){let r=V(e,`..panes{${Cf}}.axes.comparison`)[0],i=e.display,a=(e,t)=>it(e,!1,t,`visible`),o=e=>et(a(i.xAxis,e),a(i.yAxis,e)),s=it(i.chart,!0,`showLegend`);return{comparison:r,gridLines:o(`gridLines`),minorGridLines:o(`minorGridLines`),newPaneHeight:i.chart.newPaneHeight,showLastValue:i.yAxis.showLastValue,showLegend:s,showMinMaxArc:i.chart.showMinMaxArc,allAnnotationsLocked:i.allAnnotationsLocked,hiddenItems:xk(i),exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,useLastTrade:e.data?.useLastTrade??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function pF(e,t){let n=e,{backgroundColor:r,axis:{gridLinesColor:i,textColor:a,crosshairColor:o,gridLinesStyle:s},fontSize:c}=t,{chart:l,xAxis:u,yAxis:d}=c||{};if((r||l)&&(n=H(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=H(n,`.display.xAxis`,e),n=H(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=H(n,`.display.xAxis.crosshair`,e),n=H(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=H(n,`.display.xAxis`,e(u))),d&&(n=H(n,`.display.yAxis`,e(d)))}return n}function mF(e,t,n){let{chart:r,xAxis:i,yAxis:a}=e.display||{},{fontSize:o,backgroundColor:s}=r||{},{fontSize:c,gridLines:l,textColor:u,crosshair:d}=i||{},{color:f,dashStyle:p}=l||{},{fontSize:m}=a||{},{color:h}=d||{};return{backgroundColor:s,axis:{gridLinesColor:f,textColor:u,crosshairColor:h,gridLinesStyle:p},fontSize:{chart:o,xAxis:c,yAxis:m}}}function hF(e,t,n){let{mainAxis:r}=Tf(e),i=V(e,`.display.xAxis`)[0],a=V(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,horizontalAxisPosition:i.position??`bottom`,preventLabelOverlap:a.preventLabelOverlap,preventVerticalLabelOverlap:a.preventLabelOverlap,preventHorizontalLabelOverlap:i.preventLabelOverlap,snapAnnotationsToPrices:a.snapAnnotationsToPrices,primaryOnTheLeft:a.primaryOnTheLeft??!1,nonEodLabelWithDate:i.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:a.includePercentChangeWithLastValue??!1,ordinalName:i.ordinalName??``,contractTransition:i.contractTransition,cycleTransition:i.cycleTransition}}function gF(e,t,n){let r=t=>V(e,t)[0],i=r(`.display.chart`),a=r(`.display.xAxis.crosshair`),o=r(`.display.yAxis.crosshair`),s=`none`;return a.enabled&&o.enabled?s=`both`:a.enabled?s=`vertical`:o.enabled&&(s=`horizontal`),{crosshair:s,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:a.color,dashStyle:a.dashStyle},haloTracking:i.plotHover}}function _F(e,t,n){return P(e.data.aggregation)}function vF(e,t){let n=V(e,QP),{mainPane:r,mainAxis:i}=Tf(e),a=[];for(let e of n){let t=!i.plots.includes(e),n=e.type.toLowerCase(),r={curves:P(e.curves),type:e.type,[n]:e[n],oppositeScale:t,leftScale:t};a.push(r)}return{plots:a,alignOnExpirations:r.alignOnExpirations}}function yF(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>z.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,D.Deleted,!1)),s=H(s,`${o}..annotations`,c)),a===!0&&(s=H(s,`${o}..plots{.type=="Study"}`,c)),s=gp(s),s}var bF=`.display.chart.previous`;function xF(e,t,n){return V(e,bF)[0]}function SF(e,t,n){return H(e,bF,e=>(ut(e,t),e))}function CF(e,t,n){let r=[],i=bP(e,t);if(i===void 0||vP(e,_P(i))?.type!==t.type)return r;let a=hf(e,i);if(a===null)return r;let o=a.pane,s=o===0,c=o===e.panes.length-1,l=e.panes[o].axes.reduce((e,t)=>e+t.plots.length,0)===1;return s||r.push(`ExistingAbove`),l||r.push(`NewAbove`),c||r.push(`ExistingBelow`),l||r.push(`NewBelow`),r}function wF(e,t,n){if(!CF(e,t,n).includes(t.targetPane))return e;let r=bP(e,t);if(r===void 0)return e;let i=hf(e,r);if(i===null)return e;let a=vP(e,_P(r));e.panes[i.pane].axes[i.axis].plots.splice(i.plot,1);let o=i.pane,s=!0;switch(t.targetPane){case`ExistingAbove`:o--;break;case`NewAbove`:e.panes.splice(o,0,AP(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,AP(e))}let{mainPane:c}=Tf(e),l=e.panes[o]===c;s&&l&&a?.type===`Study`&&a.study===`VOL`&&(a.detachedScale=!0);let u=e.panes[o];u.axes.length<2&&u.axes[0].plots.length>0&&u.axes.push(kP());let d=u.axes.findIndex(e=>e.plots.length===0),f=d===-1?u.axes.length-1:d;u.axes[f].plots.push(a);let p=_f(e,i.pane);return p=_f(p,o),gp(p)}function TF(e,t,n){return N(t.period)&&t.period&&(delete e.display.period,Pf(e),n&&(n.forceResetVisibleRange=!0)),e}function EF(e,t,n){let r=[],i=bP(e,t);if(i===void 0)return r;let a=vP(e,_P(i));if(a?.type!==t.type)return r;let o=hf(e,i);if(o===null)return r;let s=e.panes[o.pane],c=o.axis===0,l=s.axes.some((e,t)=>e.plots.some((e,n)=>(t!==o.axis||n!==o.plot)&&!e.detachedScale)),u=a.detachedScale===!0;return(c||u)&&r.push(`SecondaryAxis`),(!c||u)&&r.push(`PrimaryAxis`),l&&r.push(`NoAxis`),r}function DF(e,t,n){if(!EF(e,t,n).includes(t.targetAxis))return e;let r=bP(e,t);if(r===void 0)return e;let i=-1;switch(t.targetAxis){case`PrimaryAxis`:i=0;break;case`SecondaryAxis`:i=1;break;case`NoAxis`:return yf(e,r)}return vf(e,r,i)}function OF(e,t,n){let r=V(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var kF=`..plots{.type === "Seasonal" && .main === true}`,AF=`..plots{.type === "Seasonal" && .main !== true}`,jF=z.AUTO_COLORS;function MF(e){return JSON.parse(JSON.stringify(e))}function NF(e,t){let n=V(e,kF);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=V(e,AF);for(let e of a){let t=e.offsets??[],n=e.curves??[],r=/* @__PURE__ */ new Map;t.length===n.length?t.forEach((e,t)=>{let i=n[t];i&&r.set(e,MF(i))}):n.forEach((e,t)=>{let n=i[t];e&&N(n)&&r.set(n,MF(e))});let a=r.get(0);a?.colors?.[0];let o=i.map((e,t)=>{let n=r.get(e);if(n)return n;let i=jF[t%jF.length];return{...a?MF(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return gp(e)}var PF={MainPlot:Nf,Aggregation:{Update:If,Get:_F},Period:{Update:Ed,Delete:TF},Crosshair:{Update:aP,Get:gF},Tooltip:{Update:oP,Get:OF},Events:sP,Scale:{Update:cP,Get:hF},Other:{Update:lP,Get:fF},Plot:{Add:UP,Get:pP,Delete:dP,Update:TP},Compare:{Update:ZP,Get:vF},AnnotationManipulation:{Get:nP,Update:iP},Annotation:{Get:sF,Add:cF,Update:uF,Delete:dF},MovePane:tF,Template:aF,Outline:oF,Theme:{Update:pF,Get:mF},Clear:yF,Previous:{Update:SF,Get:xF},MovePlot:{Update:wF,Get:CF},PinPlot:{Update:DF,Get:EF},SeasonalOffsets:{Update:NF}};function FF(e){return typeof e==`function`}function IF(e,t){let n=PF[e];if(FF(n))return n;{let e=t===void 0?void 0:n[t];if(!FF(e)&&(e=n[z.DEFAULT_ACCESSOR_SUBACTION],!FF(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function LF(e,t,n){return IF(e.id,e.context.id)(t,e.context,n)}function RF(e){return{id:`MainPlot`,context:e}}var zF={id:`SeasonalOffsets`,context:{}};function BF(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function VF(e){let{id:t,context:n}=e;if(!N(n))return!1;if(t===`Compare`)return BF(n.plots);if(t!==z.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===z.ACTION_DELETE&&BF(n.plots)}function HF(e){return e.some(VF)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var UF={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},WF=Symbol.for(`__ias__`),GF=class{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new XN(this)}get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless)F(`You cannot initialize a headless chart.`,`error`);else if(this.presenter.initialize(e),M(t)){let e=typeof t==`string`;e?F(`Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.`,`warn`):(t.template&&this.load(t.template),delete t.template);let n=e?{symbol:t}:t;this.change(RF(n))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,n=null){if(!this.headless){if(N(e)){au(e,t),iu(e,t);let r=_M(e,!1,t,n,this.presenter);r.isDrawingAnnotation&&this.presenter.view.setCursor(te.Crosshair),this.presenter.activeTool=r,Le()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}setMainAxisAnnotations(e){let t=this.presenter?.mainAxis;N(t)&&(t.annotations=e.map(e=>t.makeAnnotation(e)),t.fireAnnotationsChanged(),this.presenter.view?.redraw())}toMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!N(t))return null;let n=t.toAnnotationPoint(e);return{price:n.price,time:n.time}}fromMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!N(t))return null;let n=t.toX(new Date(e.time)),r=t.toY(e.price);return!N(n)||!N(r)?null:{x:n,y:r}}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return gI()}get model(){return(this.headless?this._model:this.presenter.getModel())||gI()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:z.ACTION_TEMPLATE,context:{strip:e}})}change(...e){if(e.length>1&&e.some(e=>e.id===`AnnotationManipulation`))throw Error(`AnnotationManipulation must be executed as a standalone action`);let t={chart:this,actions:e.filter(e=>!e[WF])};t.actions.length>0&&this.presenter?.notifyHost(G.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?hp(e,z.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===z.ACTION_TEMPLATE||e.context.id===z.ACTION_GET)return LF(e,this.model,this.presenter);if(!this.headless&&e.id===`AnnotationManipulation`){LF(e,this.model,this.presenter);return}if(!this.headless&&e.id===z.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=O(r,e=>e.id===z.ACTION_PLOT&&N(e.context)&&e.context.id===z.ACTION_DELETE),o=P(this.model),s=P(this.model),c=a;i.length>0&&c.push({id:z.ACTION_PLOT,context:{id:z.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=LF(e,s,this.presenter),!N(s))throw Error(`Forgot to return model from accessor`)}),HF(c)&&(s=LF(zF,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=hp(e,z.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...UF,...t},r=hp(JSON.parse(e),z.CHART_SCHEMA),i=this.model,a=P(i);if(N(i)){if(r=Ef(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=rF(r)),n.keepOldAnnotations&&(r=SN(i,r)),n.keepNewCompare||(r=iF(r)),n.keepOldCompare&&(r=eF(i,r)),n.keepOldAggregation){let e={id:z.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=LF(e,r,this.presenter),n.keepNewBarWidth&&N(t)&&(r.display.density=t)}await this.fromModel(r,a),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){!this.headless&&this.presenter?.undoRedoManager&&this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=gI();if(this.headless)this._model=t;else if(this.presenter.getModel()){let n=this.presenter.mainPlot,r=null,i=n;if(n.isSymbol?r={symbol:i.symbol}:n.isExpression?r={expression:i.expression}:n.isForward?r={forward:i.forward}:n.isSeasonal&&(r={seasonal:i.seasonal}),N(r)){let n=LF({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=LF(RF(r),t,this.presenter);e&&(i=LF({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(G.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){F(`Obsolete: please use 'exportImage' method instead.`,`warn`)}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}isDataExportAllowed(){return kN(this.presenter)}exportData(e={}){return this.headless?null:KN.call(this.presenter,e)}exportTable(e={}){return this.headless?null:VN.call(this.presenter,e)}exportImage(e={}){return this.headless?null:qN.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&(this.presenter?.undoRedoManager?.canUndo??!1)}get canRedo(){return!this.headless&&(this.presenter?.undoRedoManager?.canRedo??!1)}undo(){this.canUndo&&this.presenter?.undoRedoManager?.undo()}redo(){this.canRedo&&this.presenter?.undoRedoManager?.redo()}pauseUndoRedo(){this.headless||this.presenter?.undoRedoManager?.pause()}resumeUndoRedo(e){this.headless||this.presenter?.undoRedoManager?.resume(e)}priceToY(e,t=0,n=0){let r=this.presenter;if(this.headless||t<0||n<0||t>r.panes.length)return null;let i=r.panes[t];return n>i.axes.length?null:i.axes[n].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[n,r]of t.panes.entries()){let t=r.getBounds();if(N(t)&&e>=t.y&&e<=t.y+t.height)return{pane:n,prices:r.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(G.CH_DIDBECOMEACTIVE,{chart:this})}};function KF(e){let t=e.split(`.`);if(!t||t.length!==4)return!1;let n=t.map(Number);if(!n.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[r,i]=n;return r===10||r===172&&i>=16&&i<=31||r===192&&i===168}function qF(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||KF(e)}function JF(){let e=document.domain,t=e.split(`.`),n=`__tld`+(/* @__PURE__ */ new Date()).getTime(),r=0;for(;r<t.length-1&&document.cookie.indexOf(`${n}=${n}`)===-1;)e=t.slice(-1-++r).join(`.`),document.cookie=`${n}=${n};domain=${e};`;return document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function YF(e,t){return st(t),`${e}/?${new URLSearchParams(t).toString()}`}var XF=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,ZF=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function QF(e,t=``){return YF(atob(XF),{module:atob(ZF),secret:t,referer:e})}function $F(e,t){return e+Math.random()*(t-e)}var eI=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),tI=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),nI=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiIHx8IG0gPT09ICJFcVBsdXMiOw==`)),rI=`YXV0aG9yaXplZA==`,iI=`ZGF0YS1lbmRwb2ludA==`,aI=`YWxsb3dDcmVkZW50aWFscw==`;async function oI(e,t){if(t&&!nI(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=qF()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=QF(t?``:JF(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(rI)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(iI)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(aI)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&sI()}function sI(){setTimeout(eI,$F(2e3,3e3)),setTimeout(()=>tI($()),$F(4e3,5e3))}var cI={major:2,minor:414,patch:0,prerelease:!1},lI={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${z.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:`wheel+shift`,bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:`Auto`,tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:`Unspecified`,hostingModel:`Page`,overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,annotationManipulation:void 0,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,extras:`/extras`,timeseries:`/proxies/timeseries`,timeseriesNew:`/proxies/new-timeseries`,ondemand:`/proxies/ondemand`,options:`/proxies/core-api`},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){let n=this.baseUrl[e],r=`${n}${t}`;if(nI(this.mode)&&this.knownSite){let{username:i,password:a}=this.credentials||{},o=N(i,a),s=(e===`timeseries`||e===`timeseriesNew`)&&o&&this.allowCredentials?`&username=${i}&password=${a}`:``;r=`https://${this.dataEndpoint}${n}${t}${s}`}return await(await fetch(r)).text()},getCustomEventPopup:e=>null};async function uI(e,t){let n=$()?.config;if(!n||!n.fetch)throw Error(`You should call initFeed first`);let r=t;return e===`timeseries`?r=`/historical${t}`:e===`options`&&(r=`/options-historical${t}`),await n.fetch.call(n,e,r)}var dI=!1,fI=null;function pI(){let e=cI,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function mI(e){let t=e.extensions?.studyProvider;if(!N(t))return;let n=t.getFields(),r=t.getStudies(),i=P(Dc(z.CHART_SCHEMA)),a=i.definitions,o=a.studyField.enum,s=a.study.enum;for(let e of n)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(s.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...n.map(e=>e.id)),s.push(...r.map(e=>e.id)),dp(z.CHART_SCHEMA,i),xp(n),Mc(r)}function hI(e,t={}){if(dI)throw Error(`You should only call initFeed once during page's lifetime`);dI=!0;let n=Object.assign(lI);return ut(n,t),M(n.logo)&&kA(n.logo,n.logoClickable??!1),mI(n),fI=new e(n),fI.version=pI(),F(`%cBarchart Chart version ${fI.version}`,`info`,`font-size: larger`),fI.cachesData&&(fI.subject?.subscribe(fI.onPerformInternalGc.bind(fI)),Ib.default.subscribe(G.CH_ALL,fI.onChartChanged.bind(fI))),fI}function $(){return fI}function gI(){return P($()?.template)}function _I(){M(fI)&&(fI.shutdown(),dI=!1,fI=null)}function vI(){return new GF(!0)}function yI(e){let t=vI();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function bI(e,t,n,r=null){return new Proxy(e,{get:function(e,i,a){return i===t?function(t){let a=r?t[r]:t;return(n.handlesRequestsFor(a)?n:e)[i](t)}:Reflect.get(e,i,a)}})}var xI=class{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;onBrowserOnline;constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=/* @__PURE__ */ new Map,this.pendingRedraw=/* @__PURE__ */ new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=xt(),this.onBrowserOnline=()=>{this.cachesData&&!this.isAuxiliary&&(this.traceFeed(`refresh:online`),this.refreshCaches())},globalThis.addEventListener?.(`online`,this.onBrowserOnline)}traceFeed(e,t={}){yg(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!M(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:z.INTERNAL_GC_MILLIS}),this._subject=new Im().pipe(vh(z.INTERNAL_GC_MILLIS),_h(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=bI(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=bI(this.metaDataSource,`getMetaData`,e),this.recordSource=bI(this.recordSource,`getRecord`,e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!M(this.timeSeriesSource))throw Error(`No time series source defined`);return this.timeSeriesSource}getMetaDataSource(){if(!M(this.metaDataSource))throw Error(`No metadata source defined`);return this.metaDataSource}getRecordSource(){if(!M(this.recordSource))throw Error(`No record source defined`);return this.recordSource}async ready(){return ma.call(this,async()=>{let e=this instanceof EI||this instanceof SI||this instanceof kI;await oI(this.config,e);let t=this.config.defaultTemplate;if(!t)throw Error(`Must provide a default template`);return typeof t==`string`&&(t=await(await fetch(t)).json()),this.template=hp(t,z.CHART_SCHEMA),!0})}getHeadlessChart(){return vI()}fixupRenderTo(e){if(!M(e))return null;if(e instanceof HTMLElement)return e;let t=aa(`#${e}`);if(M(t))return t;let n=[...this.charts.keys()].find(t=>t.id===e);return M(n)?n:null}checkChart(e,t){let n=this.fixupRenderTo(e),r=M(n)&&this.charts.has(n);return M(t)&&t!==r&&F(`There is ${t?`no`:`already a`} chart inside the element ${e}`,`error`),n}addChart(e,t=null){let n=this.checkChart(e,!1),r=new GF;return this.charts.set(n,r),r.initialize(e,t),r}removeChart(e){let t=this.checkChart(e,!0);M(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return M(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);M(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),M(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!M(t?.presenter?.view))return;let n=t.presenter.view;n.isHostElementVisible&&n.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:/* @__PURE__ */ new Set,records:/* @__PURE__ */ new Set,timeSeries:/* @__PURE__ */ new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{M(t)&&(M(t.record)&&e.records.add(t.record),M(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){let e=this.getCacheableEntities();this.traceFeed(`refresh:caches`,{metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.getMetaDataSource().refresh?.(),this.getRecordSource().refresh?.(e.records),e.timeSeries.forEach(e=>{e.isCached||e.refresh()}),this.getTimeSeriesDataSource().refresh(),Ke(G.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.traceFeed(`gc:run`,{chartCount:this.charts.size,metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.evictUnused(e)}triggerGc(e=`unknown`){this.traceFeed(`gc:request`,{reason:e}),this.subject?.next()}onChartChanged(e,t){(e===G.CH_RECREATED||e===G.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc(`${e}:aux:${this.id}`):this.triggerGc(e))}getDefaultMultiFieldCurve(){if(!M(this.template))return null;if(!this.knowDefaultCurve){let e=wf(this.template);this.defaultOhlcCurve=e.curves.length===1&&Dd(e.curves[0].style)?P(e.curves[0]):null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=P(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){globalThis.removeEventListener?.(`online`,this.onBrowserOnline),this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}},SI=class extends xI{constructor(e){super(e),this.timeSeriesSource=new uv(!1),this.metaDataSource=new To,this.recordSource=new Cg}},CI=class extends xI{constructor(e){super(e),this.timeSeriesSource=new uv(!0),this.metaDataSource=new To,this.recordSource=new wg}},wI=class extends xI{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new uv(!0),this.metaDataSource=new To,this.recordSource=new Cg}},TI=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],EI=class extends xI{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new uv(!0),this.metaDataSource=new Eo,this.recordSource=new Tg,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,M(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){M(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug(`need to refresh caches`),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on(`events`,this.onEvents),this.connection.on(`timestamp`,this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&TI.includes(this.connection._username)&&F(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===z.BC_EVENT_DISCONNECTED||e===z.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===z.BC_EVENT_LOGGED_IN||e===z.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),M(this._connection)&&(this.connection.off(`timestamp`,this.onTimestamp),this.connection.off(`events`,this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}};function DI(e,t){return new OI(e,t)}var OI=class{_client;_subscriptions=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;constructor(e,t){this._client=e;let n=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let r=e.marketSnapshot;if(M(r)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onSnapshot?.(r,e))}let i=e.marketUpdate;if(M(i)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onUpdate?.(i,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return M(await this._client.connection)}shutdown(){M(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!M(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!M(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){return await(await this._client.connection)?.getInstrument(e)??[]}},kI=class extends xI{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new uv(!0),this.metaDataSource=new Do,this.recordSource=new Eg,Ib.default.subscribe(G.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let n of this._auxFeeds)n.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&Ke(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error(`Cannot set adapter on auxiliary feed`);this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let e=await this._mainFeed?.ready()??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await this._adapter?.ready()??!1}subscribe(e){this.traceFeed(`openfeed:subscribe`,{symbol:e}),this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.traceFeed(`openfeed:unsubscribe`,{symbol:e}),this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){let t=this._auxFeeds.findIndex(t=>t.id==e.id);t!==-1&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc(`removeAuxFeed:${e.id}`))}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(let t of this._auxFeeds)t.getAllCacheableEntities(e)}};function AI(e,t,n,r={}){switch(e){case`VOLAP`:return jI(t,n,r);default:throw Error(`Study ${e} does not provide custom output`)}}function jI(e,t,n){if(!(e instanceof IE))throw Error(`Expected the series created for VOLAP`);if(t.LevelMode===`MinIncrements`&&!Number.isFinite(n.minMovement))throw Error(`VOLAP in "MinIncrements" level mode needs the minMovement option`);let r=qj(t,()=>!1,n.minMovement??1),i=e.innCont(0)?.getTimeData()??[],a=e.innCont(1);if(!a||i.length===0)return{study:`VOLAP`,profiles:[]};let o=tM(a,n.from??i[0],n.to??i[i.length-1],r);return{study:`VOLAP`,profiles:o?[o]:[]}}var MI=Ib.default;export{yd as Aggregation,_ as AggregationSpec,g as AggregationUnit,SI as BarchartSiteDataFeed,xI as BaseDataFeed,Sg as BaseRecordSource,ie as ChunkPart,tv as ContainerWrapperTimeSeries,mN as CustomEventPopup,Op as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,Rb as ExpressionSeries,vp as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,W as Fields,EI as MarketDataFeed,wI as MiniWidgetDataFeed,Qg as OHLCDataPointBuilder,kI as OpenFeed,MI as PubSub,C as SeriesKind,CI as SnapshotDataFeed,q as StudySeries,e_ as TimeSeriesContainer,Fb as TimeSeriesQuery,G as Topics,DI as adaptOpenFeedClient,ua as appendDOMElement,ma as asyncReady,Bc as canBeBasedOnSeasonal,AI as computeCustomStudyOutput,X as convertSeries,GN as convertTableToCsv,Kg as dateToOptionValue,sf as doesExpressionHaveComputation,Rc as doesStudyExist,tf as evaluateExpression,af as formatExpression,po as formatPriceWithDecimals,xt as generateUid,Ic as getAnnotationTraits,yI as getChartOutline,mo as getCombinedMetaData,of as getExpressionSymbols,$ as getFeed,Zo as getLightness,xM as getStudyOptions,Gc as getTaxonomies,Gi as hasOpenInterest,hI as initFeed,UO as linReg,Lb as makeExpression,K as makeHelperField,vO as makeStudy,Z as mapSeries,J as movAvg,Y as movExp,CO as movHul,xO as movSmo,SO as movWei,Gg as optionValueToDate,ef as parseExpression,cf as replaceExpressionSymbols,PO as roc,sa as setAttributesDOMElement,_I as shutdownFeed,LO as stdDev,oa as styleDOMElement,kO as trueRange,NO as typical};
|
|
42
|
+
`)}function KN(e={}){return GN(VN.call(this,e),e)}function qN(e={}){let t=this.view.mainCanvas,{width:n,height:r}=t,{width:i,height:a,title:o}=e,s=(e,t)=>{let n=document.createElement(`canvas`);return n.width=e,n.height=t,n.getContext(`2d`)},c=s(n,r),l=globalThis.devicePixelRatio;if(c.drawImage(t,0,0),c.scale(l,l),M(o)){let e=new DN(this);e.update(o),e.draw(c)}let u=this.mainPlot?.timeSeries.container?.getLastDataPoint(W.DateTime);if(M(u)){let{fontFamily:e}=this.display.chart,{fontWeight:n,fontSize:r}=this.mainAxis.config;c.font=`${n} ${r*1.2}px ${e}`,c.textBaseline=`top`;let i=r*1.5,a=getComputedStyle(t),o=a.getPropertyValue(`--app-hc-color`),s=a.getPropertyValue(`--app-color-pl`),l={x:z.CARDS_X_OFFSET,y:z.CARDS_Y_OFFSET},d=vy(this,u,l,void 0,!1,0),f=`${d.date} ${d.time??``}`.trim(),[p,m]=[1,5],h=(e,t)=>c.measureText(e).width+t,g=(e,t,n,r,i)=>(c.fillStyle=r,c.fillText(e,t,n),h(e,i)),_=(e,t)=>e.type===S[t],v=e=>{let t=e.name;return e.isMain&&_(e,`Symbol`)?t=`${e.description} (${e.name}) [${e.exchange}]`:_(e,`Study`)&&(t=`${e.description} ${e.name.substring(e.name.indexOf(` `))}`),t};d.panes.forEach(e=>{let{top:t,left:n,width:r,right:a}=e.bounds,c=n+r-a-m,u=n+l.x,d=t+l.y;e.plots.some(e=>e.isMain)&&(u+=g(f,u,d,o,m)),e.plots.forEach((e,t)=>{let r=v(e),a=!_(e,`Study`)&&e.values.length>1;if(!e.isMain&&t>0){let t=u+h(r,m);e.values.forEach(e=>{a&&(t+=h(e.abbreviation,p)),t+=h(e.value,m)}),t>=c&&(u=n+l.x,d+=i)}u+=g(r,u,d,o,m),e.values.forEach(e=>{a&&(u+=g(e.abbreviation,u,d,s,p)),u+=g(e.value,u,d,e.color,m)})})})}let d=e=>({width:i??n,height:a??r,data:e.toDataURL(`image/png`)});if(M(i)&&M(a)){let e=s(i,a);return e.drawImage(c.canvas,0,0,i,a),d(e.canvas)}return d(c.canvas)}function JN(e){if(e!==void 0)return e===z.YTD_PERIOD?e:yt(e)}var YN=Symbol.for(`__ias__`),XN=class{accessor;view;defaultTool;_activeTool;tooltipEnabled=!0;timeline;sentInitialLoadNotification=!1;_hostElement=null;undoRedoManager;title;display;model;data;panes=[];_hasLegend;renderTo;seriesChangedToken=``;metaChangedToken=``;streamingSubscription=null;_previousMask=0;_ohlcMask;selectedAnnotation;annotationPreviewUid;hoverHighlightPlotIds=null;hoverDimPlotIds=null;hoverBasisByDependentPlotId=/* @__PURE__ */ new Map;hoverDependentsByBasisPlotId=/* @__PURE__ */ new Map;hoverHighlightablePlotIds=/* @__PURE__ */ new Set;forceResetVisibleRange=!1;_maxOffset=0;_isShutdown=!1;notifySelectionChanged;notifyRecreated;notifyDefinitionChanged;constructor(e){this.accessor=e,this.defaultTool=_M(`Default`),this._activeTool=this.defaultTool,this.timeline=new Yv(this),this.undoRedoManager=new EN(this),this.title=new DN(this),this.notifySelectionChanged=qe(G.CH_ANNSELECTIONCHANGED),this.notifyRecreated=qe(G.CH_RECREATED),this.notifyDefinitionChanged=qe(G.CH_DEFINITION_CHANGED)}traceChart(e,t={}){yg(e,{chartId:this.elementId,...t})}getModel(){return this.model}get isEmpty(){return!N(this.model)}notifyHost(e,t){Ke(e,t)}async fromModel(e,t){if(this._isShutdown)return;this.traceChart(`chart:fromModel:start`,{hadModel:N(this.model)}),N(this.model)&&this.allPlots.forEach(e=>e.shutdown()),this.sentInitialLoadNotification=!1,this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.annotationPreviewUid=void 0,this.clearSelection(),this.model=e;let n=P(e);this.data=n.data,this.data.aggregation=fd(n.data.aggregation),this.display=n.display,this.display.period=JN(n.display?.period);let r=this.panes;this.panes=n.panes.map(e=>{let t=new QM(this);return t.fromModel(e),t},this),this.undoRedoManager.rebindOwners(r);let i=this.allPlots.map(e=>e.initialize());await Promise.all(i),!this._isShutdown&&(this.rebuildHoverHighlightRelations(),this.traceChart(`chart:fromModel:plots-ready`,{plotCount:this.allPlots.length}),this.timeline.invalidate(),this.checkZoomAndVisibleRange(e,t),N(e,t)&&this.notifyDefinitionChanged({chart:this.accessor}),this.reinitializeView())}checkZoomAndVisibleRange(e,t){if(this.view){if(this.forceResetVisibleRange)this.forceResetVisibleRange=!1,this.view.resetZoomAndVisibleRange=!0,this._maxOffset=0;else{let n=!t||tP(e,t,this);this.view.resetZoomAndVisibleRange=n,n&&(this._maxOffset=0)}}}closeView(){N(this.view)&&(this.view.shutdown(),this.view=void 0)}reinitializeView(){this._isShutdown||(N(this.view)?this.view.reinitialize():(this.view=new fN,this.view.initialize(this)),this.notifyRecreated({elementId:this.elementId}))}getCacheableEntities(e){let t={metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size};this.isEmpty||this.allPlots.map(t=>t.getCacheableEntities(e)),this.traceChart(`chart:cacheable-entities`,{plotCount:this.allPlots.length,addedMetaData:e.metaData.size-t.metaData,addedRecords:e.records.size-t.records,addedTimeSeries:e.timeSeries.size-t.timeSeries})}get activeTool(){return this._activeTool}set activeTool(e){N(this._activeTool.deactivated)&&this._activeTool.deactivated(this),this._activeTool=e,N(this._activeTool.activated)&&this._activeTool.activated(this),this.notifyHost(G.TL_CHANGED,{chart:this.accessor})}get mainPlot(){return this.allPlots.find(e=>e.main)}get mainAxis(){return this.mainPlot?.axis}get mainPane(){return this.mainAxis?.pane}get allAxes(){let e=[];return this.panes.forEach(t=>{t.axes.forEach(t=>{e.push(t)})}),e}get plotAnnotations(){let e=[];return this.allPlots.forEach(t=>{t.isVisible&&t.annotations?.forEach(t=>{e.push(t)})}),e}get allAnnotations(){let e=[];return this.allAxes.forEach(t=>{t.annotations.forEach(t=>{e.push(t)})}),e}get allPlots(){let e=[];return this.allAxes.forEach(t=>{t.plots.forEach(t=>{e.push(t)})}),e}findAxis(e){return this.allAxes.find(t=>t.id===e)}findPlot(e){return this.allPlots.find(t=>t.id===e)}get allCurves(){let e=[];return this.allPlots.forEach(t=>{t.curves.forEach(t=>{e.push(t)})}),e}findCurve(e){return this.allCurves.find(t=>t.id===e)}get hasStudyBasisFocus(){return this.display?.chart?.studyBasisFocus===!0}get hasHoverHighlight(){return this.hoverHighlightPlotIds!==null||this.hoverDimPlotIds!==null}getStudyBasis(e){return e.isStudy?e.basePlot??null:null}isHoverSourcePlot(e){return e.isSeasonal||e.isSymbol}hasMultipleHoverSourcePlots(){return this.allPlots.filter(e=>e.isVisible&&this.isHoverSourcePlot(e)).length>1}get annotationManipulation(){return $()?.config.annotationManipulation===!0}setAnnotationPreview(e){this.annotationPreviewUid!==e&&(this.annotationPreviewUid=e,this.view?.redraw())}clearHoverHighlight(){this.hoverHighlightPlotIds=null,this.hoverDimPlotIds=null}clearHoverHighlightRelations(){this.hoverBasisByDependentPlotId.clear(),this.hoverDependentsByBasisPlotId.clear(),this.hoverHighlightablePlotIds.clear()}rebuildHoverHighlightRelations(){if(this.clearHoverHighlight(),this.clearHoverHighlightRelations(),this.hasStudyBasisFocus&&this.hasMultipleHoverSourcePlots())for(let e of this.allPlots){if(this.isHoverSourcePlot(e)&&this.hoverHighlightablePlotIds.add(e.id),!e.isStudy)continue;let t=this.getStudyBasis(e);if(!N(t))continue;this.hoverBasisByDependentPlotId.set(e.id,t.id);let n=this.hoverDependentsByBasisPlotId.get(t.id);N(n)||(n=/* @__PURE__ */ new Set,this.hoverDependentsByBasisPlotId.set(t.id,n)),n.add(e.id),this.hoverHighlightablePlotIds.add(e.id),this.hoverHighlightablePlotIds.add(t.id)}}isHoverHighlightable(e){return this.hasStudyBasisFocus&&N(e)&&this.hoverHighlightablePlotIds.has(e.id)}getRelatedHoverPlotIdsForPlot(e){if(!this.isHoverHighlightable(e))return null;let t=/* @__PURE__ */ new Set,n=this.hoverBasisByDependentPlotId.get(e.id);if(N(n))return t.add(e.id),t.add(n),t;let r=this.hoverDependentsByBasisPlotId.get(e.id);return N(r)&&r.size>0?(t.add(e.id),r.forEach(e=>t.add(e)),t):(t.add(e.id),t)}getRelatedHoverPlotIds(e){let t=/* @__PURE__ */ new Set;for(let n of e){let e=this.getRelatedHoverPlotIdsForPlot(n);e!==null&&e.forEach(e=>t.add(e))}return t.size>0?t:null}getHoverDimPlotIds(e){if(!this.hasStudyBasisFocus||e===null)return null;let t=/* @__PURE__ */ new Set;for(let n of this.hoverHighlightablePlotIds)e.has(n)||t.add(n);return t}sameHoverHighlight(e){let t=this.hoverHighlightPlotIds;if(t===null||e===null)return t===e;if(t.size!==e.size)return!1;for(let n of t)if(!e.has(n))return!1;return!0}setHoverHighlight(e){if(!this.hasStudyBasisFocus)return this.hasHoverHighlight&&(this.clearHoverHighlight(),this.view?.redraw()),!1;let t=this.getRelatedHoverPlotIds(e);return this.sameHoverHighlight(t)?this.hoverHighlightPlotIds!==null:(this.hoverHighlightPlotIds=t,this.hoverDimPlotIds=this.getHoverDimPlotIds(t),this.view?.redraw(),t!==null)}shouldDimPlot(e){return this.hasStudyBasisFocus&&(this.hoverDimPlotIds?.has(e.id)??!1)}fixupDensityForForwards(){let e=this.allPlots.filter(e=>e.isForward).map(e=>e.timeSeries.container?.size??0);e.some(e=>e>0)&&(this.display.density=Math.max(...e))}onSeriesChanged(e,t){if(!this.view||!this.allPlots)return;let n=t.series,r=e=>e.timeSeries===n||e.eventsSeries===n,i=this.allPlots.find(r);if(!N(i))return;let a=N(i)&&i.main,o=!1,s=!1;if(e===G.TS_TIMELINECORRECTION){if(!this.timeline.tryToCorrectLastBar(t.from,t.to))return;o=!0}let c=N(t.index)?n.container.getTimeData()[t.index]:null,l=e===G.TS_EVENTSCHANGED,u=this.view.xAxis,d=u.xScale;if(e===G.TS_MANYCHANGED||l){if(a&&this.data.checkRange){if(N(this.display.xAxis.visibleRange)){let e={id:`Period`,context:{range:this.display.xAxis.visibleRange}};e[YN]=!0,this.accessor.change(e);return}delete this.data.checkRange}i.isForward&&this.fixupDensityForForwards();let e=this.view.xAxis?.getMaxCurveOffset()??0;i.isStudy&&(e!==this._maxOffset&&(this._maxOffset=e,u.goToLatest(!0)),i.invalidateAssociatedAnnotations(`NewChunkArrived`));let n=N(this.display?.xAxis?.visibleRange);if((i.isSeasonal&&!u.wasVisibleRangeChanged&&!n||this.display?.xAxis?.isOrdinal)&&u.goToLatest(!0),t.part===ie.Tail){let e=A(this.timeline,c,Number,Jv);u.shouldScrollIntoView(e)&&d.shiftBars(t.count)}this.timeline.invalidate(),this.allPlots.forEach(e=>e.invalidatePriceMappingCache()),o=!0}else if(e===G.TS_DATAPOINTADDED){let e=this.timeline.mergeDateIntoTimeline(c);e!=-1&&u.shouldScrollIntoView(e)?(d.shiftBars(1),o=!0):s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointAdded`)}else e===G.TS_DATAPOINTCHANGED&&(s=!0,i.isStudy&&i.invalidateAssociatedAnnotations(`DataPointChanged`));if(!l&&r(this.mainPlot)&&n.hasData&&n.container.size===0&&this.notifyHost(G.CH_NODATAFORMAINSYMBOL,{chart:this.accessor}),o&&this.view.recalculateLayout(),s&&(o&&F(`Performance : redundant call to recompute price domains (layout recalculation took care of this)`,`warn`),this.allAxes.filter(e=>e.plots.includes(i)).forEach(e=>{e.setDomain(),N(c)&&e.updateFullDomain(c)})),!this.sentInitialLoadNotification&&e===G.TS_MANYCHANGED&&this.allPlots.every(e=>e.timeSeries&&e.timeSeries.hasData)){this.sentInitialLoadNotification=!0,this.notifyHost(G.CH_ALL_DATA_PROJECTED,{chart:this.accessor}),bA(this);let e=this.display.period===z.FIFTY_YEARS_MILLIS;this.mainPlot&&e&&(d.fitAllData=!0,d.adjustDomain())}this.view.redraw()}onMetaChanged(e,t){e===G.MD_CHANGED&&this.view&&this.allPlots&&this.allPlots.find(e=>e.id===t.plot.id)&&(t.plot.main&&this.allAnnotations.forEach(e=>e.onFormatterChanged()),this.view.recalculateLayout(),this.view.redraw())}priceDomainsUpdated(){this.allPlots.forEach(e=>{e.notifyAboutPriceDomains&&e.onPriceDomainsUpdated()})}onScaleDomainChanged(e){let t=this.panes.indexOf(e.pane),n=e.pane.axes.indexOf(e),r={chart:this.accessor,paneIndex:t,axisIndex:n};this.notifyHost(G.CH_AXISSCALECHANGED,r)}get previousMask(){return N(this._previousMask)||(this._previousMask=wp(W.PreviousClose)),this._previousMask}hasMatch(e,t){return e.some(e=>e.updated&&t)}get hasLegend(){if(!N(this._hasLegend)){let e=re[$()?.config.mode??`Unspecified`];this._hasLegend=[re.cmdtyView,re.EqPlus].includes(e)}return this._hasLegend}onStreamingUpdates(e){N(this.view)&&(this.mainPlot.showPrevious&&this.hasMatch(e,this.previousMask)&&this.view.redraw(),this.hasLegend&&this.hasMatch(e,this.ohlcMask)&&this.view.updateLegend())}get ohlcMask(){return N(this._ohlcMask)||(this._ohlcMask=wp(W.Open,W.High,W.Low,W.Close,W.PreviousClose)),this._ohlcMask}updateMatches(e,t){if((e&this.ohlcMask)===0)return!1;let n=(e,t)=>M(e)&&e.isValid&&e.hasSymbol(t);return this.mainPlot.isSymbol?n(this.mainPlot.timeSeries.record,t):this.mainPlot.isExpression?n(this.mainPlot.record,t):!1}getStreamingSubscription(){return $().getRecordSource().subject.pipe(mh(e=>e.filter(e=>this.updateMatches(e.updated,e.data.symbol))),_h(e=>e.length>0)).subscribe(this.onStreamingUpdates.bind(this))}get hostElement(){return this._hostElement}get elementId(){return N(this._hostElement)?this._hostElement.id:null}initialize(e){if(this._hostElement=e instanceof HTMLElement?e:aa(`#${e}`),!this._hostElement)throw Error(`There is no element ${e} in the DOM`);this.renderTo=e,this.seriesChangedToken=Ib.default.subscribe(G.TS_ALL,this.onSeriesChanged.bind(this)),this.metaChangedToken=Ib.default.subscribe(G.MD_ALL,this.onMetaChanged.bind(this)),this.streamingSubscription=this.getStreamingSubscription()}shutdown(){return Ib.default.unsubscribe(this.seriesChangedToken),Ib.default.unsubscribe(this.metaChangedToken),N(this.streamingSubscription)&&this.streamingSubscription.unsubscribe(),this.allPlots.forEach(e=>e.shutdown()),this.model=void 0,this.closeView(),this.notifyHost(G.CH_SHUTDOWN,{elementId:this.elementId}),this._isShutdown=!0,!0}setSelection(e){this.selectedAnnotation!==e&&(this.selectedAnnotation&&this.clearSelection(),this.selectedAnnotation=e,this.selectedAnnotation.isSelected=!0,this.selectedAnnotation.requestRedraw(),this.notifySelectionChanged({chart:this.accessor}))}clearSelection(){N(this.selectedAnnotation)&&(this.selectedAnnotation.isSelected=!1,this.selectedAnnotation.requestRedraw(),this.selectedAnnotation=void 0),this.notifySelectionChanged({chart:this.accessor})}resetActiveTool(){this.activeTool=this.defaultTool,this.view.setCursor(te.Arrow)}print(e={}){let t=ua(document.body,`iframe`);t.src=``,t.style.display=`none`,t.onload=()=>{let{title:n}=e,r=qN.call(this,{title:n}),i=new Image;i.src=r.data,i.style.width=`100%`,t.contentDocument.body.appendChild(i),pa(i).then(()=>{let e=t.contentWindow;t.focus(),e.print(),t.remove()})}}setTitle(e,t=!1){this.title.update(e),N(this.view)&&this.view.redraw(t)}enableTooltip(e){this.tooltipEnabled=e;let t=this.display.tooltip.mode===z.TOOLTIP_CARDS;!e&&t&&this.hideCards()}get showTooltip(){return this.display.tooltip.visible&&this.tooltipEnabled}hideCards(e=!1){let t=this.display.tooltip,n=Le();!e&&t.visible&&t.mode===z.TOOLTIP_CARDS&&da(`.bcharts-card`,this.hostElement).forEach(e=>{let t=e.classList.contains(`bcharts-card-move`);n&&t||e.classList.contains(`bcharts-legend`)||(e.style.display=`none`)})}handleAnnotationChange(e){let t=(e,t=!0)=>({id:t?e.name:e.id,uid:e.uid,visible:e.visible});if(e.id===`List`)return this.allAnnotations.map(t);if(e.id===`Cache`)return V(this.model,`..annCache{.annotations}`).map(e=>({symbol:e.symbol,annotations:e.annotations.map(e=>t(e,!1))}));if(e.id===`Add`){let t=e.annotation;return(t.isUndoRedo?t.owner?.axis??this.mainAxis:this.mainAxis)?.addAnnotation(t)}let n=this.allAnnotations.find(t=>t.uid===e.uid);if(n!==void 0){if(e.id===`Delete`&&!e.isUndoRedo)return this.deleteAnnotationWithUndo(n);let t=n.axis,r=t[`${e.id.toLowerCase()}Annotation`];if(typeof r==`function`){r.call(t,n,e);return}}throw Error(`Unknown sub-action ${e.id} for action ${z.ANN_ACTION_ID}`)}deleteAnnotationWithUndo(e){this.undoRedoManager.done(Gk(e,D.Deleted)),e.axis.deleteAnnotation(e),this.onAnnotationModifiedByTool(e,D.Deleted,!1)}getPlotInfoFromDom(e){let t=e.attributes.getNamedItem(`data-plot-uid`);if(!t)throw Error(`Unable to resolve plot info: missing data-plot-uid attribute.`);let n=t.value,r=0;for(let e of this.model.panes)for(let t of e.axes)for(let e of t.plots){if(e.uid===n)return{type:e.type,index:r};r++}throw Error(`Unable to resolve plot info: model plot index not found for uid '${n}'.`)}getSimplePlot(e,t){return this.accessor.change({id:`Plot`,context:{id:z.ACTION_GET,type:e,index:t}})[0]}onCardClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index),r={chart:this.accessor,plot:n};this.notifyHost(G.CH_CARDPLOTCLICKED,r)}deletePlotClicked(e){let t=this.getPlotInfoFromDom(e),n=this.getSimplePlot(t.type,t.index);this.accessor.change({id:`Plot`,context:{id:`Delete`,type:t.type,index:t.index}});let r={chart:this.accessor,plot:n};this.notifyHost(G.CH_CARDPLOTREMOVED,r)}showHidePlotClicked(e){this.defaultTool.hideCrosshairAndTooltips(this.view,!0);let t=this.getPlotInfoFromDom(e),n=e.attributes.getNamedItem(`data-act`).value===`Show`;this.accessor.change({id:`Plot`,context:{id:`Update`,type:t.type,index:t.index,visible:n}});let r=this.getSimplePlot(t.type,t.index),i={chart:this.accessor,plot:r,visible:n};this.notifyHost(G.CH_CARDPLOTVISIBILITYCHANGED,i)}plotMoreActionsClicked(e,t){let n=this.getPlotInfoFromDom(e),r=this.getSimplePlot(n.type,n.index),i={x:t.clientX,y:t.clientY},a={chart:this.accessor,plot:r,offset:i,originalEvent:t};this.notifyHost(G.CH_PLOTNEEDSCONTEXTMENU,a)}onMovePaneClicked(e){let t=parseInt(e.attributes.getNamedItem(`data-pane`).value),n=e.attributes.getNamedItem(`data-dir`).value===`Down`,r=t+ +!!n,i=t-+!n;setTimeout(()=>{this.accessor.change({id:`MovePane`,context:{from:r,to:i}}),this.notifyHost(G.CH_PANESREORDERED,{chart:this.accessor})})}onAnnotationsUpdated(e,t=!1){let n=this.allAxes.indexOf(e),r=e.annotations.map(e=>e.toModel()),i=hN(this.model,{axisIndex:n,annotations:r});try{this.model=hp(i,z.CHART_SCHEMA)}catch(e){F(`Cannot update annotation (corrupts definition), error is: ${e.message}`,`error`)}t&&this.view.draw(),this.notifyHost(G.CH_ANNOTATIONCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}onAnnotationModifiedByTool(e,t,n=!0,r=!1){if(t!==D.None){if(n&&t!==D.Undo&&t!==D.Redo){let n=Gk(e,t);this.undoRedoManager.done(n)}let i=Kk(e);i.toolChange=D[t],(r||t===D.Reordered)&&(i.orderOnly=!0),this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,i)}}onAnnotationDone(e,t){let n={id:e,chart:this.accessor,toolChange:D[t]};this.notifyHost(G.CH_ANNMODIFIEDBYTOOL,n)}onPaneHeightsUpdated(){let e=this.panes.map((e,t)=>({index:t,relativeHeight:e.height}));this.model=CN(this.model,{paneHeights:e}),this.notifyHost(G.CH_PANEHEIGHTSCHANGED,{chart:this.accessor}),this.notifyDefinitionChanged({chart:this.accessor})}getDataStats(){let e=this.mainPlot.timeSeries.container;if(!N(e)||e.size===0)return null;let t=e.getTimeData(),n=we(t),r=Ce(t);return N(n,r)?{dataRange:{from:n.getTime(),to:r.getTime()},barCount:e.size}:null}};function ZN(e,t){return e?.from===t?.from&&e?.to===t?.to}var QN=[`Renko`,`Range`,`LineBreak`,`Kagi`,`PointAndFigure`];function $N(e,t){for(let n of Object.keys(e))if(e[n]!==t[n])return!0}function eP(e,t){let n=e=>e.curves[0],r=n(e),i=n(t),a=QN.includes(r.style),o=QN.includes(i.style);return a===o?o?!!(r.style!==i.style||t.inputs&&$N(ft(e.inputs),ft(t.inputs))):!1:!0}function tP(e,t,n){let r={id:`Aggregation`,context:{id:`Get`}};if($N(dd(LF(r,t,n)),dd(LF(r,e,n)))||!ZN(e.display?.xAxis?.visibleRange,t.display?.xAxis?.visibleRange)||e.display?.xAxis?.marginBars!==t.display?.xAxis?.marginBars||!ZN(e.data?.range,t.data?.range)||e.data?.extendedHours!==t.data?.extendedHours||e.display?.period!==t.display?.period||e.display?.density!==t.display?.density)return!0;let i=wf(t),a=wf(e);if(eP(i,a))return!0;let o=(e,t)=>e.type===t,s=e=>{let t=e.toLowerCase();return o(a,e)&&o(i,e)&&i[t]!==a[t]},c=i.type!==a.type,l=s(`Forward`),u=s(`Expression`),d=s(`Symbol`);return c||l||u||d}function nP(e,t,n){if(`paneIndex`in t||`axisIndex`in t)throw Error(`AnnotationManipulation paneIndex and axisIndex are output-only metadata; use uid`);let r=n?.selectedAnnotation?.uid,i=n?.annotationPreviewUid;return e.panes.flatMap((e,n)=>e.axes.flatMap((e,a)=>(e.annotations||[]).map((e,t)=>({uid:e.uid,paneIndex:n,axisIndex:a,position:t,selected:r===e.uid,preview:i===e.uid})).filter(e=>t.uid===void 0||e.uid===t.uid)))}function rP(e,t){return e===`Front`?t-1:e===`Back`?0:St(0,t-1,e)}function iP(e,t,n){let{uid:r,position:i,selected:a,preview:o}=t;if(t.id!==void 0&&t.id!==`Update`)throw Error(`Invalid AnnotationManipulation sub-action`);if(i!==void 0&&i!==`Front`&&i!==`Back`&&!(Number.isInteger(i)&&i>=0))throw Error(`Annotation position must be Front, Back, or a non-negative integer`);if((i!==void 0||a===!0||o===!0)&&r===void 0)throw Error(`AnnotationManipulation requires uid for position, selection, or preview`);let s=nP(e,t,n),c=r===void 0?void 0:s[0],l=c&&n?.panes[c.paneIndex]?.axes[c.axisIndex],u=l?.annotations.find(e=>e.uid===r),d=u?.isVisible&&!u.computed?u:void 0;if(c&&i!==void 0){let t=e.panes[c.paneIndex].axes[c.axisIndex].annotations,r=rP(i,t.length);if(r!==c.position){let e=t.map(e=>e.uid);if(l&&u&&n){let t=[...e];t.splice(r,0,t.splice(c.position,1)[0]),l.annotations.sort((e,n)=>t.indexOf(e.uid)-t.indexOf(n.uid)),n.undoRedoManager.done({owner:l.annotationUndoOwner,uid:u.uid,toolChange:D.Reordered,before:e,after:t}),n.onAnnotationsUpdated(l),n.onAnnotationModifiedByTool(u,D.Reordered,!1),u.requestRedraw()}else t.splice(r,0,t.splice(c.position,1)[0])}}return n&&o!==void 0&&(o&&d?n.setAnnotationPreview(d.uid):!o&&(r===void 0||n.annotationPreviewUid===r)&&n.setAnnotationPreview()),n&&a!==void 0&&(a&&d?n.setSelection(d):!a&&s.some(e=>e.selected)&&n.clearSelection()),e}function aP(e,t){let[n,r]=$e(t.crosshair),{color:i,dashStyle:a}=t.horizontal||{},{color:o,dashStyle:s}=t.vertical||{},c=(e,t,n)=>{t&&(e.color=t),n&&(e.dashStyle=n)},l=H(e,`.display.xAxis.crosshair`,e=>(e.enabled=n,c(e,o,s),e));return l=H(l,`.display.yAxis.crosshair`,e=>(e.enabled=r,c(e,i,a),e)),N(t.haloTracking)&&typeof t.haloTracking==`boolean`&&(l=H(l,`.display.chart`,e=>(e.plotHover=t.haloTracking,e))),l}function oP(e,t){return H(e,`.display.tooltip`,e=>(t.visible!=null&&(e.visible=t.visible),t.mode&&(e.mode=t.mode),t.showMainTitle!=null&&(e.showMainTitle=t.showMainTitle),t.mainTitle&&(e.mainTitle=t.mainTitle),e))}function sP(e,t){let n=P(t);return Object.keys(t).forEach(e=>{z.EVENTS.includes(e)||delete n[e];let r=t[e];typeof r==`boolean`?r={show:t[e]}:Object.keys(r).forEach(e=>{z.EVENT_PROPERTIES.includes(e)||delete r[e]}),n[e]=r}),H(e,Cf,e=>(e.type===`Symbol`&&(e.events=e.events||{},Object.keys(n).forEach(t=>{e.events[t]=e.events[t]||{},lt(e.events[t],n[t],!1)})),e))}function cP(e,t){let n=H(e,`..panes{${Cf}}.axes`,e=>(M(t.scale)&&(e.scale=t.scale),e));n=H(n,`.display.xAxis`,e=>(M(t.horizontalAxisPosition)&&(e.position=t.horizontalAxisPosition),M(t.marginBars)&&(e.marginBars=t.marginBars),M(t.nonEodLabelWithDate)&&(e.nonEodLabelWithDate=t.nonEodLabelWithDate),M(t.ordinalName)&&(e.ordinalName=t.ordinalName),M(t.preventHorizontalLabelOverlap)&&(e.preventLabelOverlap=t.preventHorizontalLabelOverlap),e));let r=()=>F(`The 'minPadding' and 'maxPadding' are deprecated (ignored)`,`warn`),i=()=>F(`The 'preventLabelOverlap' is deprecated, please use 'preventVerticalLabelOverlap'`,`warn`);return n=H(n,`.display.yAxis`,e=>{(N(t.minPadding)||N(t.maxPadding))&&r();let n=M(t.preventLabelOverlap)&&!M(t.preventVerticalLabelOverlap);n&&i();let a=n?t.preventLabelOverlap:t.preventVerticalLabelOverlap;return M(a)&&(e.preventLabelOverlap=a),N(t.includePercentChangeWithLastValue)&&(e.includePercentChangeWithLastValue=t.includePercentChangeWithLastValue),N(t.snapAnnotationsToPrices)&&(e.snapAnnotationsToPrices=t.snapAnnotationsToPrices),N(t.primaryOnTheLeft)&&(e.primaryOnTheLeft=t.primaryOnTheLeft),e}),N(t.labels)&&Array.isArray(t.labels)&&t.labels.forEach(e=>{let{axis:t,text:r,index:i,paneIndex:a}=e;N(t,r,i)&&t===`vertical`&&Number.isInteger(i)&&(n=H(n,`..panes[${a??0}]..axes[${i}]`,e=>N(e)?(e.label=r,e):z.NULL_OBJECT))}),M(t.contractTransition)&&(n=H(n,`.display.xAxis`,e=>(ut(e.contractTransition,t.contractTransition),e))),M(t.cycleTransition)&&(n=H(n,`.display.xAxis`,e=>(ut(e.cycleTransition,t.cycleTransition),e))),n}function lP(e,t,n){let r=e;if(N(t.comparisonMode)&&typeof t.comparisonMode==`string`&&rt(x,t.comparisonMode)&&(r=H(r,`..panes{${Cf}}.axes`,e=>(e.comparison=t.comparisonMode,e))),N(t.gridLines)){let[e,n]=$e(t.gridLines);r=H(r,`.display.xAxis.gridLines`,t=>(t.visible=e,t)),r=H(r,`.display.yAxis.gridLines`,e=>(e.visible=n,e))}if(N(t.minorGridLines)){let[,e]=$e(t.minorGridLines);r=H(r,`.display.yAxis.minorGridLines`,t=>(t.visible=e,t))}N(t.newPaneHeight)&&typeof t.newPaneHeight==`number`&&(r=H(r,`.display.chart{.newPaneHeight > 0}`,e=>(e.newPaneHeight=t.newPaneHeight,e))),N(t.showNavigator)&&typeof t.showNavigator==`boolean`&&(r=H(r,`.display.scrollbar`,e=>(e.visible=t.showNavigator,e))),N(t.plotHover)&&typeof t.plotHover==`boolean`&&(r=H(r,`.display.chart`,e=>(e.plotHover=t.plotHover,e))),N(t.showLastValue)&&typeof t.showLastValue==`string`&&(r=H(r,`.display.yAxis`,e=>(e.showLastValue=t.showLastValue,e))),N(t.showMinMaxArc)&&typeof t.showMinMaxArc==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showMinMaxArc=t.showMinMaxArc,e))),N(t.showGoToLatest)&&typeof t.showGoToLatest==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showGoToLatest=t.showGoToLatest,e))),N(t.showLegend)&&typeof t.showLegend==`boolean`&&(r=H(r,`.display.chart`,e=>(e.showLegend=t.showLegend,e)),t.showLegend||n.view.removeLegend()),N(t.allAnnotationsLocked)&&typeof t.allAnnotationsLocked==`boolean`&&(r=H(r,`.display`,e=>(e.allAnnotationsLocked=t.allAnnotationsLocked,e))),M(t.hiddenItems)&&yk.includes(t.hiddenItems)&&(r=H(r,`.display`,e=>(e.hiddenItems=t.hiddenItems,e))),N(t.exprSkipLeadingEmpty)&&typeof t.exprSkipLeadingEmpty==`boolean`&&(r=H(r,`.data`,e=>(e.exprSkipLeadingEmpty=t.exprSkipLeadingEmpty,e))),typeof t.useLastTrade==`boolean`&&(r=H(r,`.data`,e=>(e.useLastTrade=t.useLastTrade,e)));let i=[];if(N(t.extendedHours)&&typeof t.extendedHours==`boolean`&&(r=H(r,`.data`,e=>(e.extendedHours=t.extendedHours,e))),N(t.realTimeCboeBzx)&&typeof t.realTimeCboeBzx==`boolean`&&(r=H(r,`.data`,e=>(e.realTimeCboeBzx!==t.realTimeCboeBzx&&i.push(`realTimeCboeBzx`),e.realTimeCboeBzx=t.realTimeCboeBzx,e))),N(t.buildContinuation)&&typeof t.buildContinuation==`boolean`&&(r=H(r,`.data`,e=>(e.buildContinuation=t.buildContinuation,e))),i.length>0){let e={chart:n.accessor,hostPropsChanged:i};n.notifyHost(G.CH_HOST_PROPS_CHANGED,e)}return r}var uP=`MARKED_FOR_DELETION`;function dP(e,t){if(t.plots.length===0)return e;let n=e;for(let e of t.plots){let t=bP(n,e);if(t===void 0)continue;let r=_P(t),i=vP(n,r);N(i)&&(N(e.type)&&i.type!==e.type||(n=H(n,r,e=>(e[uP]=!0,e))))}return n=H(n,`..plots{.${uP} === true}`,e=>z.NULL_OBJECT),n=H(n,`..plots{.type === "Study"}`,e=>{let t=B(e.study);return N(t)&&Sf(n,t,e.basis).eligible?e:z.NULL_OBJECT}),gp(n)}function fP(e,t,n,r){let i=S[e.type],a={curves:P(e.curves),type:e.type,uid:e.uid};a.precision=e.precision,a.visible=e.visible,a.detachedScale=e.detachedScale;let o=(e,t)=>{N(e[t])?a[t]=e[t].map(e=>P(e)):a[t]=[]},s=(e,t,n=!1)=>{t.main===!0&&(e.main=!0,e.showPrevious=t.showPrevious,n&&t.events!=null&&(e.events=P(t.events)))},c=(e,t=e=>!0)=>{N(r)&&(e.subtitles=r.allPlots.filter(e=>e.type===i).filter(t).map(e=>e.title))};switch(i){case S.Symbol:{a.title=e.symbol;let t=a.curves[0].style,n=t=>{o(e,`inputs`),a.inputs.length===0&&(a.inputs=P(t))};switch(t){case`Renko`:n(z.DEFAULT_RENKO_INPUTS);break;case`Kagi`:n(z.DEFAULT_KAGI_INPUTS);break;case`PointAndFigure`:n(z.DEFAULT_PNF_INPUTS);break;case`LineBreak`:n(z.DEFAULT_LINEBREAK_INPUTS);break;case`Baseline`:n(z.DEFAULT_BASELINE_INPUTS)}s(a,e,!0);break}case S.Study:{o(e,`inputs`);let r=B(e.study),i=a.inputs,s=r.id===`AVWAP`?TT(i):i.map(e=>e.value),c=s.length===0?``:` (${s.join(`, `)})`,l=a.curves.map(e=>Number(e.shift)).filter(e=>e>0),u=l.length===0?``:` [${l.join(`, `)}]`;a.title=`${r.id}${c}${u}`,a.studyId=r.id,o(e,`levels`),o(e,`bands`),a.basis=P(e.basis)||{kind:`main`},a.placement=t?n?`overlay`:`withMain`:`standalone`;break}case S.BalanceSheet:case S.IncomeStatement:{let t=W[e.curves[0].fields[0]];a.title=`${t.name} (${e.fundamental.substring(0,1)})`,a.fundamentalId=t.id,a.frequency=e.fundamental;break}case S.Expression:a.title=e.expression,s(a,e);break;case S.Forward:a.title=e.forward,o(e,`offsets`),c(a),s(a,e);break;case S.Seasonal:a.title=e.seasonal,c(a,e=>e.refSeasonal===a.title),o(e,`offsets`),s(a,e);break;default:throw Error(`Unexpected plot type`)}return a}function pP(e,{main:t,type:n,index:r,uid:i},a){let o=`..plots{.main === true}`,s=V(e,`..panes`).map((e,t)=>{let n=V(e,o).length===1;return V(e,`..axes`).map((e,r)=>{let i=V(e,o).length===1;return V(e,`..plots`).map(e=>{let o=fP(e,n,i,a);return o.paneIndex=t,o.axisIndex=r,o})})}).flat(2).map((e,t)=>(e.index=t,e));if(N(i))return s.filter(e=>e.uid===i);if(t)return s.filter(e=>e.main);if(N(n)){let e=s.filter(e=>e.type===n);return N(r)?e.filter(e=>e.index===r):e}return s}var mP=[`overlay`,`standalone`,`withMain`,`clone`];function hP(e,t,n){t[n]&&(e[n]=t[n])}function gP(e,t){e.type===`Study`&&t.curves?.forEach(e=>delete e.varyColorPerBar),SP(e)?N(t.curves)&&(e.curves=t.curves):DP(e.curves,t.curves);let n=S[t.type],r=e;if(N(t.precision)?r.precision=t.precision:delete r.precision,n===S.Symbol)N(t.symbol)&&(e.symbol=t.symbol);else if(n===S.Study)N(t.basis)&&(e.basis=P(t.basis)),OP(e.inputs,t.inputs,e),[`bands`,`levels`,`detachedScale`].forEach(n=>hP(e,t,n));else if((n===S.BalanceSheet||n===S.IncomeStatement)&&t.frequency)e.fundamental=t.frequency;else if(n===S.Expression){let n=e;N(t.expression)&&(n.expression=t.expression)}else if(n===S.Forward){let n=e;N(t.offsets)&&(n.offsets=t.offsets),N(t.forward)&&(n.forward=t.forward)}else if(n===S.Seasonal){let n=e;N(t.offsets)&&(n.offsets=t.offsets),N(t.seasonal)&&(n.seasonal=t.seasonal),N(t.usesInAverage)&&(r.usesInAverage=t.usesInAverage),Bu(n)}}var _P=e=>`..plots[${e}]`;function vP(e,t){let n=V(e,t);return n.length===1?n[0]:null}function yP(e,t){let n=0;for(let r of e.panes)for(let e of r.axes)for(let r of e.plots){if(r.uid===t)return n;n+=1}}function bP(e,t){return N(t.uid)?yP(e,t.uid):t.index}function xP(e){let t=S[e.type];return t===S.Symbol||t===S.Expression}function SP(e){let t=S[e.type];return t===S.Forward||t===S.Seasonal}function CP(e){let t=S[e.type];return t===S.Symbol||t===S.Expression||t===S.Seasonal}function wP(e,t,n){if(N(t))return t;let r=n?.uid;return typeof r==`string`?yP(e,r):void 0}function TP(e,t,n){if(N(t.placement)&&!mP.includes(t.placement))throw Error(`Unknown placement: ${t.placement}`);let r=bP(e,t),i=r===void 0?t.main?Cf:``:_P(r);if(!i)return e;let a=vP(e,i);if(!M(a)||M(t.type)&&a.type!==t.type)return e;let o=wP(e,r,a);if(t.type===S[S.Study]){let n=a,r=B(t.studyId??n.study);if(!M(r))return e;let i=N(t.basis)?t.basis:n.basis,o=Sf(e,r,i);if(!o.eligible)return F(`Cannot update study "${r.meta.title}" because ${o.reason}.`,`error`),e}if(M(t.visible))return a.visible=t.visible,e;if(a.main&&xP(a)){if(t.curves){let n=e=>e.curves[0].style===h[h.Range],[r,i]=[n(a),n(t)];r&&!i?e=If(e,{unit:`Day`,size:1,spec:`None`}):!r&&i&&(e=If(e,{unit:`Intraday`,size:100,spec:`PerRange`}))}t.type||=a.type;let n=a;N(t.precision)?n.precision=t.precision:delete n.precision,N(t.showPrevious)&&(e=H(e,Cf,e=>(e.showPrevious=t.showPrevious,e)));let r=t.curves?Fd(e,t):e;return N(t.oppositeScale)&&CP(a)&&N(o)&&(r=vf(r,o,+!!t.oppositeScale)),r}{let s=H(e,i,e=>(gP(e,t),e));if(N(t.oppositeScale)&&CP(a)&&N(o)&&(s=vf(s,o,+!!t.oppositeScale)),!(t.type===S[S.Study]&&N(t.placement)))return s;let c=N(r)?r:t.index,l=pP(s,{...t,index:c},n).find(e=>e.index===c);if(!N(l))return e;if(t.placement===l.placement)return s;let u=vP(s,i);if(!N(u))return e;s=dP(s,{id:`Delete`,plots:[{uid:u.uid,type:t.type}]});let d=NP(s,t.placement,t.cloneIndex,t.cloneUid);return d!==null&&d.plots.push(u),s}}function EP(e){return e!==void 0}function DP(e,t){if(EP(t)&&t.length===e.length)for(let n=0;n<e.length;++n){let r=t[n],i=e[n];ut(i,r);for(let e of[`shift`,`dashStyle`,`lineSmoothing`,`lineMarker`]){let t=r[e];N(t)&&(i[e]=t)}}}function OP(e,t,n){let r=ft(e),i=ft(t);ut(r,i);let a=pt(i);a.length>0&&(n.inputs=a)}function kP(){return{plots:[]}}function AP(e){let t=e.display.chart.newPaneHeight??1;return{axes:[kP()],height:t}}function jP(e){let t=AP(e);return e.panes.push(t),t}function MP(e,t){let n=M(t.paneIndex)&&t.paneIndex<e.panes.length?e.panes[t.paneIndex]:jP(e),r=n.axes[0];return t.oppositeScale??!1?$P(n,r):r}function NP(e,t,n,r,i){let a=null,{mainPane:o,mainAxis:s}=Tf(e),c=(()=>{if(i?.kind!==`seasonal`)return null;for(let t of e.panes)for(let e of t.axes)for(let n of e.plots){if(n.uid!==i.uid||n.type!==`Seasonal`)continue;let r=n.offsets;if(Array.isArray(r)&&r.includes(i.offset))return{pane:t,axis:e}}return null})();switch(t){case`withMain`:a=c?$P(c.pane,c.axis):$P(o,s);break;case`overlay`:a=c?.axis??s;break;case`standalone`:a=jP(e).axes[0];break;case`clone`:{let t={main:!1,type:S[S.Study]};if(typeof r==`string`&&r.length>0?t.uid=r:typeof n==`number`&&(t.index=n),t.uid||typeof t.index==`number`){let n=pP(e,t).find(e=>e.type===S[S.Study]&&(t.uid?e.uid===t.uid:e.index===t.index));if(!n)break;a=V(e,`..panes[${n.paneIndex}]..axes[${n.axisIndex}]`)[0]}break}}return a}function PP(e,t){let n=B(t.studyId);if(!M(n))return F(`Unknown or unavailable study with the id '${t.studyId}'`,`error`),e;let r=Sf(e,n,t.basis);if(!r.eligible)return F(`Cannot add study "${n.meta.title}" because ${r.reason}.`,`error`),e;let i=t.placement||(n.meta.overlay?`overlay`:`standalone`),a=t.uid??xt();N(t.uid)&&pf(e,a);let o={uid:a,type:`Study`,study:t.studyId,visible:!0};i===`overlay`&&t.studyId===`VOL`&&(o.detachedScale=!0),t.curves!==void 0&&(o.curves=n.defaults.curves),gP(o,t);let s=NP(e,i,t.cloneIndex,t.cloneUid,t.basis);N(s)&&s.plots.push(o);let c=e.data.aggregation;return Ff(e,c.unit===`Tick`&&c.spec===`None`)}function FP(e,t){e.panes.push({axes:[{plots:[t]}]})}function IP(e,t){let n=wf(e);if(n.type!==S[S.Symbol])throw Error(`Cannot add fundamental to the chart whose main plot is not a Symbol plot.`);let r=n.symbol,i=t.uid??xt();N(t.uid)&&pf(e,i);let a={uid:i,curves:[{fields:[t.fundamentalId],lineWidth:2,style:`Line`,varyColorPerBar:!1,visible:!0,colors:[`#888`]}],fundamental:`Quarter`,symbol:r,type:b[W[t.fundamentalId].category],visible:!0};return gP(a,t),FP(e,a),e}var LP=[{fields:[W.Close.id],colors:[`#888`],style:`Line`,lineWidth:2,varyColorPerBar:!1,visible:!0}];function RP(e){return e.type===`Symbol`}function zP(e,t){let n=wf(e),r=P(RP(n)?n.curves:LP),i=t.uid??xt();N(t.uid)&&pf(e,i);let a={uid:i,curves:r,expression:``,type:`Expression`,visible:!0};return gP(a,t),MP(e,t).plots.push(a),e}function BP(e,t){let n=t.uid??xt();N(t.uid)&&pf(e,n);let r={uid:n,curves:P(LP),offsets:[0],seasonal:``,type:`Seasonal`,visible:!0,main:!1};return gP(r,t),MP(e,t).plots.push(r),e}var VP={attributes:[`OpenVsClose`],colors:[`#b63400`,`#007f3e`,`#1664db`],fields:[`Open`,`High`,`Low`,`Close`,`Change`],style:`Candlestick`,varyColorPerBar:!0,lineWidth:1};function HP(e,t){let n=wf(e),r=$().getDefaultMultiFieldCurve(),i=N(r)?r:VP,a=n.curves?.length,o=a===t.curves.length&&a===1?(e=>P(e?n.curves:[i]))(RP(n)):t.curves,s=t.uid??xt();N(t.uid)&&pf(e,s);let c={uid:s,curves:o,symbol:``,type:`Symbol`,visible:!0};return gP(c,t),MP(e,t).plots.push(c),e}function UP(e,t){switch(t.type){case`Study`:return PP(e,t);case`IncomeStatement`:case`BalanceSheet`:return IP(e,t);case`Expression`:return zP(e,t);case`Symbol`:return HP(e,t);case`Seasonal`:return BP(e,t);default:throw Error("Unexpected plot type '${type}', not supported currently")}}var WP=0,GP=z.AUTO_COLORS,KP=`Symbol`,qP=`Expression`,JP=`Seasonal`;function YP(e,t){let n={attributes:[],colors:GP.slice(WP,WP+1),fields:e?[W.Last.id]:[W.Close.id],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2,lineMarker:void 0,lineSmoothing:void 0},r={uid:t.uid??xt(),curves:[n]},{curves:i,oppositeScale:a,...o}=t;return dt(r,o),M(i)&&(r.curves=i.map(e=>{let t=P(e);return dt(t,n),t})),r.main=!1,WP=(WP+1)%GP.length,r}function XP(e){return N(e.symbols)&&(F(`Use of 'symbols' for Compare API is deprecated. Please see docs for the latest version which supports more plot types`,`warn`),e.plots=e.symbols.map(e=>(e.type=KP,e))),e.plots?.some(e=>N(e.leftScale))?(F(`Use of 'leftScale' for Compare API is deprecated. Please use 'oppositeScale'`,`warn`),e.plots.map(e=>{let t=e.leftScale;return delete e.leftScale,{...e,oppositeScale:t}})):e.plots}function ZP(e,t){let n=XP(t),r=n.map(e=>e.uid).filter(e=>typeof e==`string`),i=/* @__PURE__ */ new Set;for(let t of r){if(i.has(t))throw Error(`Plot uid '${t}' is duplicated in the Compare request.`);i.add(t),pf(e,t)}let{yes:a,no:o}=O(n,e=>e.oppositeScale??!1),{mainPane:s,mainAxis:c}=Tf(e);s.alignOnExpirations=t.alignOnExpirations||!1;let l=$P(s,c),u=e=>![KP,qP,JP].includes(e.type);l.plots=l.plots.filter(u);let d=c.plots.filter(e=>e.main||u(e)),f=e.data.aggregation.unit===`Tick`;WP=0;let p=ce(YP,f);return c.plots=d.concat(o.map(p)),a.length>0&&(l.plots.push(...a.map(p)),l.comparison=c.comparison,l.scale=c.scale),gp(e)}var QP=`..plots{(.type === "Symbol" || .type === "Expression" || .type === "Seasonal") && .main !== true}`;function $P(e,t){let n=e.axes.find(e=>e!==t);return N(n)||(n=kP(),e.axes.push(n)),n}function eF(e,t){let n=V(e,QP),r=V(t,QP),i=Math.max(0,4-r.length);if(i===0)return t;let a=n.filter(e=>!r.find(t=>e.symbol===t.symbol)).slice(0,i);if(a.length===0)return t;let{mainPane:o,mainAxis:s}=Tf(t),{mainAxis:c}=Tf(e);return a.forEach(e=>{c.plots.includes(e)?s.plots.push(e):$P(o,s).plots.push(e)}),t}function tF(e,t){let n=e.panes;return n.splice(t.to,0,n.splice(t.from,1)[0]),e}var nF=()=>z.NULL_OBJECT;function rF(e){return H(e,`..axes.annotations`,nF)}function iF(e){return gp(H(e,`..plots{.type === "Symbol" && .main !== true}`,nF))}function aF(e,t){let n=P(e);if(t.strip.main){let e=wf(n),t=e.type.toLowerCase();e[t]=z.PLACEHOLDER_SYMBOL_NAME}return t.strip.annotations&&(n=rF(n)),t.strip.compare&&(n=iF(n)),n=H(n,`.data`,e=>(e.range&&(delete e.range,e.checkRange=!0),e)),n}function oF(e,t,n){let r=pP(e,{main:!0},n)[0],i=r.title===z.PLACEHOLDER_SYMBOL_NAME,a=r.type===`Symbol`,o=r.type===`Expression`,s=ef(r.title),c=[];return o&&!$d(s)?c=s.symbols:i||(c=[r.title]),{isTemplate:i,isDefinition:!i,main:{isSymbol:a,isExpression:o,symbols:c,title:i?null:r.title},compare:V(e,QP).map(e=>e.symbol),annotations:V(e,`..annotations`).map(e=>e.id),studies:pP(e,{type:`Study`},n).map(e=>e.title)}}function sF(e,t,n){let r=V(e,`..panes`).map((e,t)=>V(e,`..axes`).map((e,n)=>V(e,`.annotations`).map(e=>({...e,paneIndex:t,axisIndex:n})))).flat(2).map((e,t)=>({...e,index:t}));return N(t.index)&&Number.isFinite(t.index)?t.index<r.length?[r[t.index]]:z.EMPTY_ARRAY:r}function cF(e,t){let n=lF(t.annotation),{mainAxis:r}=Tf(e);return r.annotations??=[],r.annotations.some(e=>e.uid===n.uid)||r.annotations.push(n),e}function lF(e){let t={id:e.id,uid:e.uid,points:(e.points??[]).map(e=>({price:e.price,time:e.time}))};return e.traits!==void 0&&(t.traits=P(e.traits)),e.visible!==void 0&&(t.visible=e.visible),e.locked!==void 0&&(t.locked=e.locked),t}function uF(e,t){let n=V(e,`..axes`);for(let e of n){let n=e.annotations?.find(e=>e.uid===t.uid);if(n){t.traits!==void 0&&(n.traits=P(t.traits)),t.points!==void 0&&(n.points=t.points.map(e=>({price:e.price,time:e.time}))),t.visible!==void 0&&(n.visible=t.visible),t.locked!==void 0&&(n.locked=t.locked);break}}return e}function dF(e,t){let n=V(e,`..axes`);for(let e of n)if(e.annotations?.some(e=>e.uid===t.uid)){e.annotations=e.annotations.filter(e=>e.uid!==t.uid);break}return e}function fF(e,t,n){let r=V(e,`..panes{${Cf}}.axes.comparison`)[0],i=e.display,a=(e,t)=>it(e,!1,t,`visible`),o=e=>et(a(i.xAxis,e),a(i.yAxis,e)),s=it(i.chart,!0,`showLegend`);return{comparison:r,gridLines:o(`gridLines`),minorGridLines:o(`minorGridLines`),newPaneHeight:i.chart.newPaneHeight,showLastValue:i.yAxis.showLastValue,showLegend:s,showMinMaxArc:i.chart.showMinMaxArc,allAnnotationsLocked:i.allAnnotationsLocked,hiddenItems:xk(i),exprSkipLeadingEmpty:e.data?.exprSkipLeadingEmpty??!1,useLastTrade:e.data?.useLastTrade??!1,extendedHours:e.data?.extendedHours??!1,realTimeCboeBzx:e.data?.realTimeCboeBzx??!1,buildContinuation:e.data?.buildContinuation??!1}}function pF(e,t){let n=e,{backgroundColor:r,axis:{gridLinesColor:i,textColor:a,crosshairColor:o,gridLinesStyle:s},fontSize:c}=t,{chart:l,xAxis:u,yAxis:d}=c||{};if((r||l)&&(n=H(e,`.display.chart`,e=>(r&&(e.backgroundColor=r),l&&(e.fontSize=l),e))),i){let e=e=>(e.color=i,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(s){let e=e=>(e.dashStyle=s,e);n=H(n,`.display.xAxis.gridLines`,e),n=H(n,`.display.yAxis.gridLines`,e),n=H(n,`.display.yAxis.minorGridLines`,e)}if(a){let e=e=>(e.textColor=a,e);n=H(n,`.display.xAxis`,e),n=H(n,`.display.yAxis`,e)}if(o){let e=e=>(e.color=o,e);n=H(n,`.display.xAxis.crosshair`,e),n=H(n,`.display.yAxis.crosshair`,e)}if(u||d){let e=e=>t=>(t.fontSize=e,t);u&&(n=H(n,`.display.xAxis`,e(u))),d&&(n=H(n,`.display.yAxis`,e(d)))}return n}function mF(e,t,n){let{chart:r,xAxis:i,yAxis:a}=e.display||{},{fontSize:o,backgroundColor:s}=r||{},{fontSize:c,gridLines:l,textColor:u,crosshair:d}=i||{},{color:f,dashStyle:p}=l||{},{fontSize:m}=a||{},{color:h}=d||{};return{backgroundColor:s,axis:{gridLinesColor:f,textColor:u,crosshairColor:h,gridLinesStyle:p},fontSize:{chart:o,xAxis:c,yAxis:m}}}function hF(e,t,n){let{mainAxis:r}=Tf(e),i=V(e,`.display.xAxis`)[0],a=V(e,`.display.yAxis`)[0];return{scale:r.scale,marginBars:i.marginBars??0,horizontalAxisPosition:i.position??`bottom`,preventLabelOverlap:a.preventLabelOverlap,preventVerticalLabelOverlap:a.preventLabelOverlap,preventHorizontalLabelOverlap:i.preventLabelOverlap,snapAnnotationsToPrices:a.snapAnnotationsToPrices,primaryOnTheLeft:a.primaryOnTheLeft??!1,nonEodLabelWithDate:i.nonEodLabelWithDate??!1,includePercentChangeWithLastValue:a.includePercentChangeWithLastValue??!1,ordinalName:i.ordinalName??``,contractTransition:i.contractTransition,cycleTransition:i.cycleTransition}}function gF(e,t,n){let r=t=>V(e,t)[0],i=r(`.display.chart`),a=r(`.display.xAxis.crosshair`),o=r(`.display.yAxis.crosshair`),s=`none`;return a.enabled&&o.enabled?s=`both`:a.enabled?s=`vertical`:o.enabled&&(s=`horizontal`),{crosshair:s,horizontal:{color:o.color,dashStyle:o.dashStyle},vertical:{color:a.color,dashStyle:a.dashStyle},haloTracking:i.plotHover}}function _F(e,t,n){return P(e.data.aggregation)}function vF(e,t){let n=V(e,QP),{mainPane:r,mainAxis:i}=Tf(e),a=[];for(let e of n){let t=!i.plots.includes(e),n=e.type.toLowerCase(),r={curves:P(e.curves),type:e.type,[n]:e[n],oppositeScale:t,leftScale:t};a.push(r)}return{plots:a,alignOnExpirations:r.alignOnExpirations}}function yF(e,t,n){let{paneIndex:r,annotations:i,studies:a}=t||{},o=`..panes${Number.isInteger(r)?`[${r}]`:``}`,s=e,c=e=>z.NULL_OBJECT;return i===!0&&(n.allAnnotations.forEach(e=>n.onAnnotationModifiedByTool(e,D.Deleted,!1)),s=H(s,`${o}..annotations`,c)),a===!0&&(s=H(s,`${o}..plots{.type=="Study"}`,c)),s=gp(s),s}var bF=`.display.chart.previous`;function xF(e,t,n){return V(e,bF)[0]}function SF(e,t,n){return H(e,bF,e=>(ut(e,t),e))}function CF(e,t,n){let r=[],i=bP(e,t);if(i===void 0||vP(e,_P(i))?.type!==t.type)return r;let a=hf(e,i);if(a===null)return r;let o=a.pane,s=o===0,c=o===e.panes.length-1,l=e.panes[o].axes.reduce((e,t)=>e+t.plots.length,0)===1;return s||r.push(`ExistingAbove`),l||r.push(`NewAbove`),c||r.push(`ExistingBelow`),l||r.push(`NewBelow`),r}function wF(e,t,n){if(!CF(e,t,n).includes(t.targetPane))return e;let r=bP(e,t);if(r===void 0)return e;let i=hf(e,r);if(i===null)return e;let a=vP(e,_P(r));e.panes[i.pane].axes[i.axis].plots.splice(i.plot,1);let o=i.pane,s=!0;switch(t.targetPane){case`ExistingAbove`:o--;break;case`NewAbove`:e.panes.splice(o,0,AP(e)),s=!1;break;case`ExistingBelow`:o++;break;case`NewBelow`:o++,s=!1,e.panes.splice(o,0,AP(e))}let{mainPane:c}=Tf(e),l=e.panes[o]===c;s&&l&&a?.type===`Study`&&a.study===`VOL`&&(a.detachedScale=!0);let u=e.panes[o];u.axes.length<2&&u.axes[0].plots.length>0&&u.axes.push(kP());let d=u.axes.findIndex(e=>e.plots.length===0),f=d===-1?u.axes.length-1:d;u.axes[f].plots.push(a);let p=_f(e,i.pane);return p=_f(p,o),gp(p)}function TF(e,t,n){return N(t.period)&&t.period&&(delete e.display.period,Pf(e),n&&(n.forceResetVisibleRange=!0)),e}function EF(e,t,n){let r=[],i=bP(e,t);if(i===void 0)return r;let a=vP(e,_P(i));if(a?.type!==t.type)return r;let o=hf(e,i);if(o===null)return r;let s=e.panes[o.pane],c=o.axis===0,l=s.axes.some((e,t)=>e.plots.some((e,n)=>(t!==o.axis||n!==o.plot)&&!e.detachedScale)),u=a.detachedScale===!0;return(c||u)&&r.push(`SecondaryAxis`),(!c||u)&&r.push(`PrimaryAxis`),l&&r.push(`NoAxis`),r}function DF(e,t,n){if(!EF(e,t,n).includes(t.targetAxis))return e;let r=bP(e,t);if(r===void 0)return e;let i=-1;switch(t.targetAxis){case`PrimaryAxis`:i=0;break;case`SecondaryAxis`:i=1;break;case`NoAxis`:return yf(e,r)}return vf(e,r,i)}function OF(e,t,n){let r=V(e,`.display.tooltip`)[0];return{visible:r.visible,mode:r.mode,showMainTitle:r.showMainTitle,mainTitle:r.mainTitle}}var kF=`..plots{.type === "Seasonal" && .main === true}`,AF=`..plots{.type === "Seasonal" && .main !== true}`,jF=z.AUTO_COLORS;function MF(e){return JSON.parse(JSON.stringify(e))}function NF(e,t){let n=V(e,kF);if(n.length===0)return e;let r=n[0];if(!r.offsets||r.offsets.length===0)return e;let i=r.offsets,a=V(e,AF);for(let e of a){let t=e.offsets??[],n=e.curves??[],r=/* @__PURE__ */ new Map;t.length===n.length?t.forEach((e,t)=>{let i=n[t];i&&r.set(e,MF(i))}):n.forEach((e,t)=>{let n=i[t];e&&N(n)&&r.set(n,MF(e))});let a=r.get(0);a?.colors?.[0];let o=i.map((e,t)=>{let n=r.get(e);if(n)return n;let i=jF[t%jF.length];return{...a?MF(a):{},colors:[i],fields:[`Close`],style:`Line`,dashStyle:`Solid`,varyColorPerBar:!1,lineWidth:2}});e.offsets=[...i],e.curves=o}return gp(e)}var PF={MainPlot:Nf,Aggregation:{Update:If,Get:_F},Period:{Update:Ed,Delete:TF},Crosshair:{Update:aP,Get:gF},Tooltip:{Update:oP,Get:OF},Events:sP,Scale:{Update:cP,Get:hF},Other:{Update:lP,Get:fF},Plot:{Add:UP,Get:pP,Delete:dP,Update:TP},Compare:{Update:ZP,Get:vF},AnnotationManipulation:{Get:nP,Update:iP},Annotation:{Get:sF,Add:cF,Update:uF,Delete:dF},MovePane:tF,Template:aF,Outline:oF,Theme:{Update:pF,Get:mF},Clear:yF,Previous:{Update:SF,Get:xF},MovePlot:{Update:wF,Get:CF},PinPlot:{Update:DF,Get:EF},SeasonalOffsets:{Update:NF}};function FF(e){return typeof e==`function`}function IF(e,t){let n=PF[e];if(FF(n))return n;{let e=t===void 0?void 0:n[t];if(!FF(e)&&(e=n[z.DEFAULT_ACCESSOR_SUBACTION],!FF(e)))throw Error(`Invalid accesor id and/or sub id`);return e}}function LF(e,t,n){return IF(e.id,e.context.id)(t,e.context,n)}function RF(e){return{id:`MainPlot`,context:e}}var zF={id:`SeasonalOffsets`,context:{}};function BF(e){return Array.isArray(e)&&e.some(e=>e?.type===`Seasonal`)}function VF(e){let{id:t,context:n}=e;if(!N(n))return!1;if(t===`Compare`)return BF(n.plots);if(t!==z.ACTION_PLOT)return!1;let r=n.id;return r===`Add`||r===`Update`?n.type===`Seasonal`:r===z.ACTION_DELETE&&BF(n.plots)}function HF(e){return e.some(VF)?e[e.length-1]?.id!==`SeasonalOffsets`:!1}var UF={keepOldAnnotations:!1,keepNewAnnotations:!0,keepOldCompare:!1,keepNewCompare:!0,keepOldAggregation:!1,keepNewBarWidth:!1},WF=Symbol.for(`__ias__`),GF=class{headless;presenter;_model;constructor(e=!1){this.headless=e,this.presenter=e?null:new XN(this)}get elementId(){return this.headless?null:this.presenter?.elementId??null}get hostElement(){return this.headless?null:this.presenter?.hostElement??null}initialize(e,t=null){if(this.headless)F(`You cannot initialize a headless chart.`,`error`);else if(this.presenter.initialize(e),M(t)){let e=typeof t==`string`;e?F(`Initializing the chart with symbol name is deprecated. Please use object form instead (see docs for details). This API will be removed in the future.`,`warn`):(t.template&&this.load(t.template),delete t.template);let n=e?{symbol:t}:t;this.change(RF(n))}}shutdown(){if(!this.headless){let e=this.presenter?.shutdown();return this.presenter=null,e}return!1}annotate(e,t=null,n=null){if(!this.headless){if(N(e)){au(e,t),iu(e,t);let r=_M(e,!1,t,n,this.presenter);r.isDrawingAnnotation&&this.presenter.view.setCursor(te.Crosshair),this.presenter.activeTool=r,Le()||this.presenter.view.mouseCanvas.focus({preventScroll:!0})}else this.presenter.resetActiveTool()}}cancelAnnotation(){this.headless||this.presenter.resetActiveTool()}setMainAxisAnnotations(e){let t=this.presenter?.mainAxis;N(t)&&(t.annotations=e.map(e=>t.makeAnnotation(e)),t.fireAnnotationsChanged(),this.presenter.view?.redraw())}toMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!N(t))return null;let n=t.toAnnotationPoint(e);return{price:n.price,time:n.time}}fromMainAxisPoint(e){let t=this.presenter?.mainAxis;if(!N(t))return null;let n=t.toX(new Date(e.time)),r=t.toY(e.price);return!N(n)||!N(r)?null:{x:n,y:r}}zoom(e){!this.headless&&typeof e==`boolean`&&(e?this.annotate(`ZoomIn`):this.presenter.defaultTool.resetView(this.presenter))}getDefaultTemplate(){return gI()}get model(){return(this.headless?this._model:this.presenter.getModel())||gI()}asTemplate(e={main:!0,annotations:!1,compare:!1}){return this.change({id:z.ACTION_TEMPLATE,context:{strip:e}})}change(...e){if(e.length>1&&e.some(e=>e.id===`AnnotationManipulation`))throw Error(`AnnotationManipulation must be executed as a standalone action`);let t={chart:this,actions:e.filter(e=>!e[WF])};t.actions.length>0&&this.presenter?.notifyHost(G.CH_API_ACTIONS_RECEIVED,t);let n=$().config.validateInput,r=e.map(e=>n?hp(e,z.ACCESSOR_SCHEMA):e);if(r.length===1){let e=r[0];if(e.id===z.ACTION_TEMPLATE||e.context.id===z.ACTION_GET)return LF(e,this.model,this.presenter);if(!this.headless&&e.id===`AnnotationManipulation`){LF(e,this.model,this.presenter);return}if(!this.headless&&e.id===z.ANN_ACTION_ID)return this.presenter.handleAnnotationChange(e.context)}let{yes:i,no:a}=O(r,e=>e.id===z.ACTION_PLOT&&N(e.context)&&e.context.id===z.ACTION_DELETE),o=P(this.model),s=P(this.model),c=a;i.length>0&&c.push({id:z.ACTION_PLOT,context:{id:z.ACTION_DELETE,plots:i.map(e=>e.context)}}),c.forEach(e=>{if(s=LF(e,s,this.presenter),!N(s))throw Error(`Forgot to return model from accessor`)}),HF(c)&&(s=LF(zF,s,this.presenter)),this.fromModel(s,o)}async fromModel(e,t){let n=hp(e,z.CHART_SCHEMA);this.headless?this._model=n:await this.presenter?.fromModel(n,t)}async load(e,t){let n={...UF,...t},r=hp(JSON.parse(e),z.CHART_SCHEMA),i=this.model,a=P(i);if(N(i)){if(r=Ef(i,r,n.keepNewAnnotations),n.keepNewAnnotations||(r=rF(r)),n.keepOldAnnotations&&(r=SN(i,r)),n.keepNewCompare||(r=iF(r)),n.keepOldCompare&&(r=eF(i,r)),n.keepOldAggregation){let e={id:z.ACTION_AGGREGATION,context:i.data.aggregation},t=r.display.density;r=LF(e,r,this.presenter),n.keepNewBarWidth&&N(t)&&(r.display.density=t)}await this.fromModel(r,a),this.clearUndoRedo()}}save(){return JSON.stringify(this.model)}clearUndoRedo(){!this.headless&&this.presenter?.undoRedoManager&&this.presenter.undoRedoManager.clear(!0)}reset(e=!0){let t=gI();if(this.headless)this._model=t;else if(this.presenter.getModel()){let n=this.presenter.mainPlot,r=null,i=n;if(n.isSymbol?r={symbol:i.symbol}:n.isExpression?r={expression:i.expression}:n.isForward?r={forward:i.forward}:n.isSeasonal&&(r={seasonal:i.seasonal}),N(r)){let n=LF({id:`Theme`,context:{id:`Get`}},this.model,this.presenter),i=LF(RF(r),t,this.presenter);e&&(i=LF({id:`Theme`,context:n},i,this.presenter)),this.presenter?.fromModel(i)}}this.clearUndoRedo(),this.presenter?.notifyHost(G.CH_RESET,{elementId:this.elementId})}print(e={}){this.headless||this.presenter.print(e)}getSVGForExport(){F(`Obsolete: please use 'exportImage' method instead.`,`warn`)}setTitle(e){this.headless||this.presenter.setTitle(e)}getPaneBounds(e=!0){if(!this.headless)return this.presenter.panes.map(t=>e?t.getBounds():t.getBoundsWithoutScales())}isDataExportAllowed(){return kN(this.presenter)}exportData(e={}){return this.headless?null:KN.call(this.presenter,e)}exportTable(e={}){return this.headless?null:VN.call(this.presenter,e)}exportImage(e={}){return this.headless?null:qN.call(this.presenter,e)}getDataStats(){return this.presenter.getDataStats()}get canUndo(){return!this.headless&&(this.presenter?.undoRedoManager?.canUndo??!1)}get canRedo(){return!this.headless&&(this.presenter?.undoRedoManager?.canRedo??!1)}undo(){this.canUndo&&this.presenter?.undoRedoManager?.undo()}redo(){this.canRedo&&this.presenter?.undoRedoManager?.redo()}pauseUndoRedo(){this.headless||this.presenter?.undoRedoManager?.pause()}resumeUndoRedo(e){this.headless||this.presenter?.undoRedoManager?.resume(e)}priceToY(e,t=0,n=0){let r=this.presenter;if(this.headless||t<0||n<0||t>r.panes.length)return null;let i=r.panes[t];return n>i.axes.length?null:i.axes[n].toY(e)}yToPrices(e){let t=this.presenter;if(this.headless)return null;for(let[n,r]of t.panes.entries()){let t=r.getBounds();if(N(t)&&e>=t.y&&e<=t.y+t.height)return{pane:n,prices:r.axes.map(t=>t.toPrice(e))}}return{pane:-1,prices:[]}}activate(){this.presenter?.notifyHost(G.CH_DIDBECOMEACTIVE,{chart:this})}};function KF(e){let t=e.split(`.`);if(!t||t.length!==4)return!1;let n=t.map(Number);if(!n.every(e=>Number.isFinite(e)&&e>=0&&e<=255))return!1;let[r,i]=n;return r===10||r===172&&i>=16&&i<=31||r===192&&i===168}function qF(){let e=globalThis.parent?.location?.hostname||``;return[``,`localhost`,`127.0.0.1`].includes(e)||KF(e)}function JF(){let e=document.domain,t=e.split(`.`),n=`__tld`+(/* @__PURE__ */ new Date()).getTime(),r=0;for(;r<t.length-1&&document.cookie.indexOf(`${n}=${n}`)===-1;)e=t.slice(-1-++r).join(`.`),document.cookie=`${n}=${n};domain=${e};`;return document.cookie=`${n}=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=${e};`,e}function YF(e,t){return st(t),`${e}/?${new URLSearchParams(t).toString()}`}var XF=`aHR0cHM6Ly9iYXJjaGFydHdpZGdldHMud2Vic29sLmJhcmNoYXJ0LmNvbQ==`,ZF=`YXV0aGVudGljYXRlQ2hhcnRSZWZlcmVy`;function QF(e,t=``){return YF(atob(XF),{module:atob(ZF),secret:t,referer:e})}function $F(e,t){return e+Math.random()*(t-e)}var eI=Function(atob(`Y29uc29sZS5sb2coIlBsZWFzZSBjb250YWN0IEJhcmNoYXJ0IGluIG9yZGVyIHRvIG9idGFpbiB0aGUgbGljZW5zZSBmb3IgdGhlIGNoYXJ0IGNvbXBvbmVudC4iKTsg`)),tI=Function(`f`,atob(`Zi5yZW1vdmVBbGxDaGFydHMoKTsg`)),nI=Function(`m`,atob(`cmV0dXJuIG0gPT09ICJJbnRlcm5hbEZlZWQiIHx8IG0gPT09ICJXaWRnZXQiIHx8IG0gPT09ICJGcmVlV2lkZ2V0IiB8fCBtID09PSAiRGVtb1NpdGUiIHx8IG0gPT09ICJFcVBsdXMiOw==`)),rI=`YXV0aG9yaXplZA==`,iI=`ZGF0YS1lbmRwb2ludA==`,aI=`YWxsb3dDcmVkZW50aWFscw==`;async function oI(e,t){if(t&&!nI(e.mode))return;let n=!1,r=0,i=25;for(;!n&&r<5;){let t=qF()||e.mode===`FreeWidget`,a=t?e.apiKey:``;try{let i=QF(t?``:JF(),a),o=await fetch(i);if(!o.ok)r++;else{let t=await o.json(),r=t[atob(rI)];e.knownSite=r,r?(e.dataEndpoint=(t[atob(iI)]||``).replace(/\/$/g,``),e.allowCredentials=t[atob(aI)]):(e.dataEndpoint=``,e.allowCredentials=!1),n=!0;break}}catch{}r++,i*=2,await new Promise(e=>setTimeout(e,i))}(!n||!e.knownSite)&&sI()}function sI(){setTimeout(eI,$F(2e3,3e3)),setTimeout(()=>tI($()),$F(4e3,5e3))}var cI={major:2,minor:414,patch:1,prerelease:!1},lI={environment:`Browser`,validateInput:!1,throttleMillis:0,isAlt64:!0,defaultTemplate:`/${z.CHART_DEFINITION}`,cachedAnnotationsCount:0,showResizeHandles:!1,scrollBehavior:`wheel+shift`,bypassSmoothing:!1,showGoToLatest:void 0,tooltipMovement:`Auto`,tooltipHeaders:void 0,touchCrosshairTimeoutMillis:void 0,touchCrosshairDelayMillis:void 0,mode:`Unspecified`,hostingModel:`Page`,overrides:void 0,logo:void 0,logoClickable:void 0,noDataText:void 0,useAllFieldsForComparison:void 0,colorfulAnnotations:!1,annotationManipulation:void 0,baseUrl:{instruments:`/proxies/instruments`,futures:`/proxies/futures`,extras:`/extras`,timeseries:`/proxies/timeseries`,timeseriesNew:`/proxies/new-timeseries`,ondemand:`/proxies/ondemand`,options:`/proxies/core-api`},credentials:void 0,apiKey:void 0,extensions:void 0,defaultVolumeBarColoring:void 0,defaultMainPlotBarColoring:void 0,async fetch(e,t){let n=this.baseUrl[e],r=`${n}${t}`;if(nI(this.mode)&&this.knownSite){let{username:i,password:a}=this.credentials||{},o=N(i,a),s=(e===`timeseries`||e===`timeseriesNew`)&&o&&this.allowCredentials?`&username=${i}&password=${a}`:``;r=`https://${this.dataEndpoint}${n}${t}${s}`}return await(await fetch(r)).text()},getCustomEventPopup:e=>null};async function uI(e,t){let n=$()?.config;if(!n||!n.fetch)throw Error(`You should call initFeed first`);let r=t;return e===`timeseries`?r=`/historical${t}`:e===`options`&&(r=`/options-historical${t}`),await n.fetch.call(n,e,r)}var dI=!1,fI=null;function pI(){let e=cI,t=e.prerelease?`-${e.prerelease.identifier}.${e.prerelease.ordinal}`:``;return`${e.major}.${e.minor}.${e.patch}${t}`}function mI(e){let t=e.extensions?.studyProvider;if(!N(t))return;let n=t.getFields(),r=t.getStudies(),i=P(Dc(z.CHART_SCHEMA)),a=i.definitions,o=a.studyField.enum,s=a.study.enum;for(let e of n)if(o.includes(e.id))throw Error(`Field with id ${e.id} already exists`);for(let e of r)if(s.includes(e.id))throw Error(`Study with id ${e.id} already exists`);o.push(...n.map(e=>e.id)),s.push(...r.map(e=>e.id)),dp(z.CHART_SCHEMA,i),xp(n),Mc(r)}function hI(e,t={}){if(dI)throw Error(`You should only call initFeed once during page's lifetime`);dI=!0;let n=Object.assign(lI);return ut(n,t),M(n.logo)&&kA(n.logo,n.logoClickable??!1),mI(n),fI=new e(n),fI.version=pI(),F(`%cBarchart Chart version ${fI.version}`,`info`,`font-size: larger`),fI.cachesData&&(fI.subject?.subscribe(fI.onPerformInternalGc.bind(fI)),Ib.default.subscribe(G.CH_ALL,fI.onChartChanged.bind(fI))),fI}function $(){return fI}function gI(){return P($()?.template)}function _I(){M(fI)&&(fI.shutdown(),dI=!1,fI=null)}function vI(){return new GF(!0)}function yI(e){let t=vI();return t.load(e),t.change({id:`Outline`,context:{id:`Get`}})}function bI(e,t,n,r=null){return new Proxy(e,{get:function(e,i,a){return i===t?function(t){let a=r?t[r]:t;return(n.handlesRequestsFor(a)?n:e)[i](t)}:Reflect.get(e,i,a)}})}var xI=class{config;version;cachesData;timeSeriesSource;metaDataSource;recordSource;charts;pendingRedraw;template;ongoingAnimationCallbackId;_altDataSource;_subject;knowDefaultCurve;defaultOhlcCurve;knowDefaultAggregation;defaultAggregation;knowDefaultPeriod;defaultPeriod;knowDefaultDensity;defaultDensity;id;_mainFeed=null;onBrowserOnline;constructor(e){this.config=e,this.timeSeriesSource=this.metaDataSource=this.recordSource=null,this.charts=/* @__PURE__ */ new Map,this.pendingRedraw=/* @__PURE__ */ new Set,this.ongoingAnimationCallbackId=null,this.drawCharts=this.drawCharts.bind(this),this.template=null,this.cachesData=!1,this._altDataSource=null,this._subject=null,this.id=xt(),this.onBrowserOnline=()=>{this.cachesData&&!this.isAuxiliary&&(this.traceFeed(`refresh:online`),this.refreshCaches())},globalThis.addEventListener?.(`online`,this.onBrowserOnline)}traceFeed(e,t={}){yg(e,{feedId:this.id,isAuxiliary:this.isAuxiliary,...t})}get subject(){return!this.isAuxiliary&&!M(this._subject)&&(this.traceFeed(`gc:stream:init`,{gcMillis:z.INTERNAL_GC_MILLIS}),this._subject=new Im().pipe(vh(z.INTERNAL_GC_MILLIS),_h(e=>e.length>0))),this._subject}get isAuxiliary(){return window.opener!==null}setAltDataSource(e){this._altDataSource=e,this.timeSeriesSource=bI(this.timeSeriesSource,`getTimeSeries`,e,`symbol`),this.metaDataSource=bI(this.metaDataSource,`getMetaData`,e),this.recordSource=bI(this.recordSource,`getRecord`,e)}replaceDataSources(e){this._altDataSource=e._altDataSource,this.timeSeriesSource=e.timeSeriesSource,this.metaDataSource=e.metaDataSource,this.recordSource=e.recordSource}getAltDataSource(){return this._altDataSource}getTimeSeriesDataSource(){if(!M(this.timeSeriesSource))throw Error(`No time series source defined`);return this.timeSeriesSource}getMetaDataSource(){if(!M(this.metaDataSource))throw Error(`No metadata source defined`);return this.metaDataSource}getRecordSource(){if(!M(this.recordSource))throw Error(`No record source defined`);return this.recordSource}async ready(){return ma.call(this,async()=>{let e=this instanceof EI||this instanceof SI||this instanceof kI;await oI(this.config,e);let t=this.config.defaultTemplate;if(!t)throw Error(`Must provide a default template`);return typeof t==`string`&&(t=await(await fetch(t)).json()),this.template=hp(t,z.CHART_SCHEMA),!0})}getHeadlessChart(){return vI()}fixupRenderTo(e){if(!M(e))return null;if(e instanceof HTMLElement)return e;let t=aa(`#${e}`);if(M(t))return t;let n=[...this.charts.keys()].find(t=>t.id===e);return M(n)?n:null}checkChart(e,t){let n=this.fixupRenderTo(e),r=M(n)&&this.charts.has(n);return M(t)&&t!==r&&F(`There is ${t?`no`:`already a`} chart inside the element ${e}`,`error`),n}addChart(e,t=null){let n=this.checkChart(e,!1),r=new GF;return this.charts.set(n,r),r.initialize(e,t),r}removeChart(e){let t=this.checkChart(e,!0);M(t)&&(this.charts.get(t).shutdown(),this.charts.delete(t))}removeAllCharts(){for(let e of this.charts.keys())this.removeChart(e)}getChart(e){let t=this.checkChart(e);return M(t)?this.charts.get(t):null}redraw(e){let t=this.checkChart(e,!0);M(this.ongoingAnimationCallbackId)||(this.ongoingAnimationCallbackId=requestAnimationFrame(this.drawCharts)),M(t)&&this.pendingRedraw.add(t)}drawCharts(){this.ongoingAnimationCallbackId=null,this.pendingRedraw.forEach(e=>{let t=this.getChart(e);if(!M(t?.presenter?.view))return;let n=t.presenter.view;n.isHostElementVisible&&n.draw()}),this.pendingRedraw.clear()}get emptyEntities(){return{metaData:/* @__PURE__ */ new Set,records:/* @__PURE__ */ new Set,timeSeries:/* @__PURE__ */ new Set}}getAllCacheableEntities(e){for(let t of this.charts.values())t.presenter.getCacheableEntities(e)}getCacheableEntities(){let e=this.emptyEntities;return this.getAllCacheableEntities(e),e.timeSeries.forEach(t=>{M(t)&&(M(t.record)&&e.records.add(t.record),M(t.records)&&Object.values(t.records).forEach(t=>e.records.add(t)))}),e}clearCaches(){this.evictUnused(this.emptyEntities)}refreshCaches(){let e=this.getCacheableEntities();this.traceFeed(`refresh:caches`,{metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.getMetaDataSource().refresh?.(),this.getRecordSource().refresh?.(e.records),e.timeSeries.forEach(e=>{e.isCached||e.refresh()}),this.getTimeSeriesDataSource().refresh(),Ke(G.DF_STREAMRECONNECTED,{})}evictUnused(e){this.getMetaDataSource().evictUnused(e.metaData),this.getRecordSource().evictUnused(e.records),this.getTimeSeriesDataSource().evictUnused(e.timeSeries)}onPerformInternalGc(){let e=this.getCacheableEntities();this.traceFeed(`gc:run`,{chartCount:this.charts.size,metaData:e.metaData.size,records:e.records.size,timeSeries:e.timeSeries.size}),this.evictUnused(e)}triggerGc(e=`unknown`){this.traceFeed(`gc:request`,{reason:e}),this.subject?.next()}onChartChanged(e,t){(e===G.CH_RECREATED||e===G.CH_SHUTDOWN)&&(this.isAuxiliary?this._mainFeed?.triggerGc(`${e}:aux:${this.id}`):this.triggerGc(e))}getDefaultMultiFieldCurve(){if(!M(this.template))return null;if(!this.knowDefaultCurve){let e=wf(this.template);this.defaultOhlcCurve=e.curves.length===1&&Dd(e.curves[0].style)?P(e.curves[0]):null,this.knowDefaultCurve=!0}return this.defaultOhlcCurve}getDefaultAggregation(){return!this.knowDefaultAggregation&&this.template&&(this.defaultAggregation=P(this.template.data.aggregation),this.knowDefaultAggregation=!0),this.defaultAggregation}getDefaultPeriod(){return!this.knowDefaultPeriod&&this.template&&(this.defaultPeriod=this.template.display?.period,this.knowDefaultPeriod=!0),this.defaultPeriod}getDefaultDensity(){return!this.knowDefaultDensity&&this.template&&(this.defaultDensity=this.template.display?.density,this.knowDefaultDensity=!0),this.defaultDensity}shutdown(){globalThis.removeEventListener?.(`online`,this.onBrowserOnline),this.isAuxiliary||this.clearCaches(),this.removeAllCharts()}},SI=class extends xI{constructor(e){super(e),this.timeSeriesSource=new uv(!1),this.metaDataSource=new To,this.recordSource=new Cg}},CI=class extends xI{constructor(e){super(e),this.timeSeriesSource=new uv(!0),this.metaDataSource=new To,this.recordSource=new wg}},wI=class extends xI{constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new uv(!0),this.metaDataSource=new To,this.recordSource=new Cg}},TI=[`drazen.dotlic@barchart.com`,`princec`,`b.hebert24@barchart.com`],EI=class extends xI{lastStreamingTimestamp=null;_isActivelyStreaming=null;needToResubscribe=!1;_connection;constructor(e){super(e),this.cachesData=!0,this.timeSeriesSource=new uv(!0),this.metaDataSource=new Eo,this.recordSource=new Tg,this.onEvents=this.onEvents.bind(this),this.onTimestamp=this.onTimestamp.bind(this),this.resetStreamingState()}resetStreamingState(){this.lastStreamingTimestamp=null,this._isActivelyStreaming=null,this.needToResubscribe=!1}get connection(){return this._connection}set connection(e){this._connection=e,M(e)&&this.initializeStreaming()}addChart(e,t=null){return this.needToResubscribe&&this.initializeStreaming(),super.addChart(e,t)}set isActivelyStreaming(e){M(this._isActivelyStreaming)&&!this._isActivelyStreaming&&e&&(this.debug(`need to refresh caches`),this.refreshCaches()),this._isActivelyStreaming=e}get isActivelyStreaming(){return this._isActivelyStreaming}initializeStreaming(){this.resetStreamingState(),this.connection.on(`events`,this.onEvents),this.connection.on(`timestamp`,this.onTimestamp)}onTimestamp(e){this.isActivelyStreaming&&(this.lastStreamingTimestamp=e)}debug(e){this.connection&&TI.includes(this.connection._username)&&F(`[chart] Connection ${e}, last timestamp ${this.lastStreamingTimestamp}`)}onEvents({event:e}){e===z.BC_EVENT_DISCONNECTED||e===z.BC_EVENT_FEED_PAUSED?(this.debug(e),this.isActivelyStreaming=!1):(e===z.BC_EVENT_LOGGED_IN||e===z.BC_EVENT_FEED_RESUMED)&&(this.debug(e),this.isActivelyStreaming=!0)}shutdown(){super.shutdown(),M(this._connection)&&(this.connection.off(`timestamp`,this.onTimestamp),this.connection.off(`events`,this.onEvents),this.resetStreamingState(),this.connection.disconnect(),this.connection=null)}};function DI(e,t){return new OI(e,t)}var OI=class{_client;_subscriptions=/* @__PURE__ */ new Map;_listeners=/* @__PURE__ */ new Set;constructor(e,t){this._client=e;let n=e=>e.find(e=>this._subscriptions.has(e))??null;t.onConnected=()=>{this._listeners.forEach(e=>e?.onConnected())},t.onMessageWithMetadata=(e,t)=>{let r=e.marketSnapshot;if(M(r)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onSnapshot?.(r,e))}let i=e.marketUpdate;if(M(i)){let e=n(t);e!==null&&this._listeners.forEach(t=>t.onUpdate?.(i,e))}},t.onDisconnected=()=>{this._listeners.forEach(e=>e?.onDisconnected())},t.onHeartBeat=e=>{this._listeners.forEach(t=>t.onHeartBeat?.(e))}}addListener(e){this._listeners.add(e)}removeListener(e){this._listeners.delete(e)}async ready(){return M(await this._client.connection)}shutdown(){M(this._client)&&(this._client.dispose(),this._subscriptions.clear(),this._listeners.clear())}subscribeToRealTime(e){if(this._subscriptions.has(e)||!M(this._client))return;let t=this._client.subscribe(1,5,0,[e],null,null,null);this._subscriptions.set(e,t)}unsubscribeFromRealTime(e){if(!this._subscriptions.has(e)||!M(this._client))return;let t=this._subscriptions.get(e);this._client.unsubscribe(t),this._subscriptions.delete(e)}async getInstrument(e){return await(await this._client.connection)?.getInstrument(e)??[]}},kI=class extends xI{_adapter=null;_auxFeeds=[];constructor(e){super(e),this.cachesData=!0,this.isAuxiliary||(this.timeSeriesSource=new uv(!0),this.metaDataSource=new Do,this.recordSource=new Eg,Ib.default.subscribe(G.TS_ALL,this.onTimeSeriesMessage.bind(this)))}onTimeSeriesMessage(e,t){if(!this.isAuxiliary)for(let n of this._auxFeeds)n.notifySeriesMessage(e,t)}notifySeriesMessage(e,t){this.isAuxiliary&&Ke(e,t)}getAdapter(){return this.isAuxiliary?this._mainFeed?._adapter:this._adapter}setAdapter(e){if(this.isAuxiliary)throw Error(`Cannot set adapter on auxiliary feed`);this._adapter=e,this._adapter.addListener(this)}async ready(){if(this.isAuxiliary){let e=await this._mainFeed?.ready()??!1;return e&&(this.template=this._mainFeed.template),e}return await super.ready(),await this._adapter?.ready()??!1}subscribe(e){this.traceFeed(`openfeed:subscribe`,{symbol:e}),this.getAdapter()?.subscribeToRealTime(e)}unsubscribe(e){this.traceFeed(`openfeed:unsubscribe`,{symbol:e}),this.getAdapter()?.unsubscribeFromRealTime(e)}shutdown(){super.shutdown(),this.isAuxiliary?(this._mainFeed?.removeAuxFeed(this),this._mainFeed=null):this._adapter?.shutdown()}onConnected(){this.refreshCaches()}onDisconnected(){}onHeartBeat(){}onUpdate(e,t){this.ofRecordSource.onUpdate(e,t)}onSnapshot(e,t){this.ofRecordSource.onSnapshot(e,t)}get ofRecordSource(){return this.recordSource}replaceDataSources(e){super.replaceDataSources(e),this._mainFeed=e}addAuxFeed(e){e.replaceDataSources(this),this._auxFeeds.push(e),this._adapter?.addListener(e)}removeAuxFeed(e){let t=this._auxFeeds.findIndex(t=>t.id==e.id);t!==-1&&(this._auxFeeds.splice(t,1),this._adapter?.removeListener(e),this.triggerGc(`removeAuxFeed:${e.id}`))}getAllCacheableEntities(e){if(super.getAllCacheableEntities(e),!this.isAuxiliary)for(let t of this._auxFeeds)t.getAllCacheableEntities(e)}};function AI(e,t,n,r={}){switch(e){case`VOLAP`:return jI(t,n,r);default:throw Error(`Study ${e} does not provide custom output`)}}function jI(e,t,n){if(!(e instanceof IE))throw Error(`Expected the series created for VOLAP`);if(t.LevelMode===`MinIncrements`&&!Number.isFinite(n.minMovement))throw Error(`VOLAP in "MinIncrements" level mode needs the minMovement option`);let r=qj(t,()=>!1,n.minMovement??1),i=e.innCont(0)?.getTimeData()??[],a=e.innCont(1);if(!a||i.length===0)return{study:`VOLAP`,profiles:[]};let o=tM(a,n.from??i[0],n.to??i[i.length-1],r);return{study:`VOLAP`,profiles:o?[o]:[]}}var MI=Ib.default;export{yd as Aggregation,_ as AggregationSpec,g as AggregationUnit,SI as BarchartSiteDataFeed,xI as BaseDataFeed,Sg as BaseRecordSource,ie as ChunkPart,tv as ContainerWrapperTimeSeries,mN as CustomEventPopup,Op as EmptyRecord,u as ExpressionMissingBar,f as ExpressionNoDataApproach,d as ExpressionRecompute,Rb as ExpressionSeries,vp as Field,b as FieldCategory,y as FieldFormat,v as FieldValueType,W as Fields,EI as MarketDataFeed,wI as MiniWidgetDataFeed,Qg as OHLCDataPointBuilder,kI as OpenFeed,MI as PubSub,C as SeriesKind,CI as SnapshotDataFeed,q as StudySeries,e_ as TimeSeriesContainer,Fb as TimeSeriesQuery,G as Topics,DI as adaptOpenFeedClient,ua as appendDOMElement,ma as asyncReady,Bc as canBeBasedOnSeasonal,AI as computeCustomStudyOutput,X as convertSeries,GN as convertTableToCsv,Kg as dateToOptionValue,sf as doesExpressionHaveComputation,Rc as doesStudyExist,tf as evaluateExpression,af as formatExpression,po as formatPriceWithDecimals,xt as generateUid,Ic as getAnnotationTraits,yI as getChartOutline,mo as getCombinedMetaData,of as getExpressionSymbols,$ as getFeed,Zo as getLightness,xM as getStudyOptions,Gc as getTaxonomies,Gi as hasOpenInterest,hI as initFeed,UO as linReg,Lb as makeExpression,K as makeHelperField,vO as makeStudy,Z as mapSeries,J as movAvg,Y as movExp,CO as movHul,xO as movSmo,SO as movWei,Gg as optionValueToDate,ef as parseExpression,cf as replaceExpressionSymbols,PO as roc,sa as setAttributesDOMElement,_I as shutdownFeed,LO as stdDev,oa as styleDOMElement,kO as trueRange,NO as typical};
|