@guihz/trading-vue-editor-tes 0.0.291 → 0.0.292

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.
@@ -73,7 +73,7 @@ ${Ho}rows: ${o.rows}
73
73
  ${Ho}columns: ${o.columns}
74
74
  }`}function Q6(o,e,t,r,M){const{rows:n,columns:b}=o,z=Math.min(n,e),i=Math.min(b,t),c=[];if(M==="auto"){M=!1;e:for(let O=0;O<z;O++)for(let s=0;s<i;s++)if(o.get(O,s)<0){M=!0;break e}}for(let O=0;O<z;O++){let s=[];for(let u=0;u<i;u++)s.push(Z6(o.get(O,u),r,M));c.push(`${s.join(" ")}`)}return i!==b&&(c[c.length-1]+=` ... ${b-t} more columns`),z!==n&&c.push(`... ${n-e} more rows`),c.join(`
75
75
  ${N3}`)}function Z6(o,e,t){return(o>=0&&t?` ${B3(o,e-1)}`:B3(o,e)).padEnd(e)}function B3(o,e){let t=o.toString();if(t.length<=e)return t;let r=o.toFixed(e);if(r.length>e&&(r=o.toFixed(Math.max(0,e-(r.length-e)))),r.length<=e&&!r.startsWith("0.000")&&!r.startsWith("-0.000"))return r;let M=o.toExponential(e);return M.length>e&&(M=o.toExponential(Math.max(0,e-(M.length-e)))),M.slice(0)}function e_(o,e){o.prototype.add=function(r){return typeof r=="number"?this.addS(r):this.addM(r)},o.prototype.addS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)+r);return this},o.prototype.addM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)+r.get(M,n));return this},o.add=function(r,M){return new e(r).add(M)},o.prototype.sub=function(r){return typeof r=="number"?this.subS(r):this.subM(r)},o.prototype.subS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)-r);return this},o.prototype.subM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)-r.get(M,n));return this},o.sub=function(r,M){return new e(r).sub(M)},o.prototype.subtract=o.prototype.sub,o.prototype.subtractS=o.prototype.subS,o.prototype.subtractM=o.prototype.subM,o.subtract=o.sub,o.prototype.mul=function(r){return typeof r=="number"?this.mulS(r):this.mulM(r)},o.prototype.mulS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)*r);return this},o.prototype.mulM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)*r.get(M,n));return this},o.mul=function(r,M){return new e(r).mul(M)},o.prototype.multiply=o.prototype.mul,o.prototype.multiplyS=o.prototype.mulS,o.prototype.multiplyM=o.prototype.mulM,o.multiply=o.mul,o.prototype.div=function(r){return typeof r=="number"?this.divS(r):this.divM(r)},o.prototype.divS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)/r);return this},o.prototype.divM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)/r.get(M,n));return this},o.div=function(r,M){return new e(r).div(M)},o.prototype.divide=o.prototype.div,o.prototype.divideS=o.prototype.divS,o.prototype.divideM=o.prototype.divM,o.divide=o.div,o.prototype.mod=function(r){return typeof r=="number"?this.modS(r):this.modM(r)},o.prototype.modS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)%r);return this},o.prototype.modM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)%r.get(M,n));return this},o.mod=function(r,M){return new e(r).mod(M)},o.prototype.modulus=o.prototype.mod,o.prototype.modulusS=o.prototype.modS,o.prototype.modulusM=o.prototype.modM,o.modulus=o.mod,o.prototype.and=function(r){return typeof r=="number"?this.andS(r):this.andM(r)},o.prototype.andS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)&r);return this},o.prototype.andM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)&r.get(M,n));return this},o.and=function(r,M){return new e(r).and(M)},o.prototype.or=function(r){return typeof r=="number"?this.orS(r):this.orM(r)},o.prototype.orS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)|r);return this},o.prototype.orM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)|r.get(M,n));return this},o.or=function(r,M){return new e(r).or(M)},o.prototype.xor=function(r){return typeof r=="number"?this.xorS(r):this.xorM(r)},o.prototype.xorS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)^r);return this},o.prototype.xorM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)^r.get(M,n));return this},o.xor=function(r,M){return new e(r).xor(M)},o.prototype.leftShift=function(r){return typeof r=="number"?this.leftShiftS(r):this.leftShiftM(r)},o.prototype.leftShiftS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)<<r);return this},o.prototype.leftShiftM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)<<r.get(M,n));return this},o.leftShift=function(r,M){return new e(r).leftShift(M)},o.prototype.signPropagatingRightShift=function(r){return typeof r=="number"?this.signPropagatingRightShiftS(r):this.signPropagatingRightShiftM(r)},o.prototype.signPropagatingRightShiftS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)>>r);return this},o.prototype.signPropagatingRightShiftM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)>>r.get(M,n));return this},o.signPropagatingRightShift=function(r,M){return new e(r).signPropagatingRightShift(M)},o.prototype.rightShift=function(r){return typeof r=="number"?this.rightShiftS(r):this.rightShiftM(r)},o.prototype.rightShiftS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)>>>r);return this},o.prototype.rightShiftM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,this.get(M,n)>>>r.get(M,n));return this},o.rightShift=function(r,M){return new e(r).rightShift(M)},o.prototype.zeroFillRightShift=o.prototype.rightShift,o.prototype.zeroFillRightShiftS=o.prototype.rightShiftS,o.prototype.zeroFillRightShiftM=o.prototype.rightShiftM,o.zeroFillRightShift=o.rightShift,o.prototype.not=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,~this.get(r,M));return this},o.not=function(r){return new e(r).not()},o.prototype.abs=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.abs(this.get(r,M)));return this},o.abs=function(r){return new e(r).abs()},o.prototype.acos=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.acos(this.get(r,M)));return this},o.acos=function(r){return new e(r).acos()},o.prototype.acosh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.acosh(this.get(r,M)));return this},o.acosh=function(r){return new e(r).acosh()},o.prototype.asin=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.asin(this.get(r,M)));return this},o.asin=function(r){return new e(r).asin()},o.prototype.asinh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.asinh(this.get(r,M)));return this},o.asinh=function(r){return new e(r).asinh()},o.prototype.atan=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.atan(this.get(r,M)));return this},o.atan=function(r){return new e(r).atan()},o.prototype.atanh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.atanh(this.get(r,M)));return this},o.atanh=function(r){return new e(r).atanh()},o.prototype.cbrt=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.cbrt(this.get(r,M)));return this},o.cbrt=function(r){return new e(r).cbrt()},o.prototype.ceil=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.ceil(this.get(r,M)));return this},o.ceil=function(r){return new e(r).ceil()},o.prototype.clz32=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.clz32(this.get(r,M)));return this},o.clz32=function(r){return new e(r).clz32()},o.prototype.cos=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.cos(this.get(r,M)));return this},o.cos=function(r){return new e(r).cos()},o.prototype.cosh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.cosh(this.get(r,M)));return this},o.cosh=function(r){return new e(r).cosh()},o.prototype.exp=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.exp(this.get(r,M)));return this},o.exp=function(r){return new e(r).exp()},o.prototype.expm1=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.expm1(this.get(r,M)));return this},o.expm1=function(r){return new e(r).expm1()},o.prototype.floor=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.floor(this.get(r,M)));return this},o.floor=function(r){return new e(r).floor()},o.prototype.fround=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.fround(this.get(r,M)));return this},o.fround=function(r){return new e(r).fround()},o.prototype.log=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.log(this.get(r,M)));return this},o.log=function(r){return new e(r).log()},o.prototype.log1p=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.log1p(this.get(r,M)));return this},o.log1p=function(r){return new e(r).log1p()},o.prototype.log10=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.log10(this.get(r,M)));return this},o.log10=function(r){return new e(r).log10()},o.prototype.log2=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.log2(this.get(r,M)));return this},o.log2=function(r){return new e(r).log2()},o.prototype.round=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.round(this.get(r,M)));return this},o.round=function(r){return new e(r).round()},o.prototype.sign=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.sign(this.get(r,M)));return this},o.sign=function(r){return new e(r).sign()},o.prototype.sin=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.sin(this.get(r,M)));return this},o.sin=function(r){return new e(r).sin()},o.prototype.sinh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.sinh(this.get(r,M)));return this},o.sinh=function(r){return new e(r).sinh()},o.prototype.sqrt=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.sqrt(this.get(r,M)));return this},o.sqrt=function(r){return new e(r).sqrt()},o.prototype.tan=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.tan(this.get(r,M)));return this},o.tan=function(r){return new e(r).tan()},o.prototype.tanh=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.tanh(this.get(r,M)));return this},o.tanh=function(r){return new e(r).tanh()},o.prototype.trunc=function(){for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.set(r,M,Math.trunc(this.get(r,M)));return this},o.trunc=function(r){return new e(r).trunc()},o.pow=function(r,M){return new e(r).pow(M)},o.prototype.pow=function(r){return typeof r=="number"?this.powS(r):this.powM(r)},o.prototype.powS=function(r){for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,Math.pow(this.get(M,n),r));return this},o.prototype.powM=function(r){if(r=e.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let M=0;M<this.rows;M++)for(let n=0;n<this.columns;n++)this.set(M,n,Math.pow(this.get(M,n),r.get(M,n)));return this}}function be(o,e,t){let r=t?o.rows:o.rows-1;if(e<0||e>r)throw new RangeError("Row index out of range")}function pe(o,e,t){let r=t?o.columns:o.columns-1;if(e<0||e>r)throw new RangeError("Column index out of range")}function Xr(o,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==o.columns)throw new RangeError("vector size must be the same as the number of columns");return e}function Er(o,e){if(e.to1DArray&&(e=e.to1DArray()),e.length!==o.rows)throw new RangeError("vector size must be the same as the number of rows");return e}function fp(o,e){if(!C2.isAnyArray(e))throw new TypeError("row indices must be an array");for(let t=0;t<e.length;t++)if(e[t]<0||e[t]>=o.rows)throw new RangeError("row indices are out of range")}function lp(o,e){if(!C2.isAnyArray(e))throw new TypeError("column indices must be an array");for(let t=0;t<e.length;t++)if(e[t]<0||e[t]>=o.columns)throw new RangeError("column indices are out of range")}function dp(o,e,t,r,M){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if(Go("startRow",e),Go("endRow",t),Go("startColumn",r),Go("endColumn",M),e>t||r>M||e<0||e>=o.rows||t<0||t>=o.rows||r<0||r>=o.columns||M<0||M>=o.columns)throw new RangeError("Submatrix indices are out of range")}function Yo(o,e=0){let t=[];for(let r=0;r<o;r++)t.push(e);return t}function Go(o,e){if(typeof e!="number")throw new TypeError(`${o} must be a number`)}function Tr(o){if(o.isEmpty())throw new Error("Empty matrix has no elements to index")}function t_(o){let e=Yo(o.rows);for(let t=0;t<o.rows;++t)for(let r=0;r<o.columns;++r)e[t]+=o.get(t,r);return e}function r_(o){let e=Yo(o.columns);for(let t=0;t<o.rows;++t)for(let r=0;r<o.columns;++r)e[r]+=o.get(t,r);return e}function M_(o){let e=0;for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)e+=o.get(t,r);return e}function o_(o){let e=Yo(o.rows,1);for(let t=0;t<o.rows;++t)for(let r=0;r<o.columns;++r)e[t]*=o.get(t,r);return e}function n_(o){let e=Yo(o.columns,1);for(let t=0;t<o.rows;++t)for(let r=0;r<o.columns;++r)e[r]*=o.get(t,r);return e}function b_(o){let e=1;for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)e*=o.get(t,r);return e}function p_(o,e,t){const r=o.rows,M=o.columns,n=[];for(let b=0;b<r;b++){let z=0,i=0,c=0;for(let O=0;O<M;O++)c=o.get(b,O)-t[b],z+=c,i+=c*c;e?n.push((i-z*z/M)/(M-1)):n.push((i-z*z/M)/M)}return n}function z_(o,e,t){const r=o.rows,M=o.columns,n=[];for(let b=0;b<M;b++){let z=0,i=0,c=0;for(let O=0;O<r;O++)c=o.get(O,b)-t[b],z+=c,i+=c*c;e?n.push((i-z*z/r)/(r-1)):n.push((i-z*z/r)/r)}return n}function i_(o,e,t){const r=o.rows,M=o.columns,n=r*M;let b=0,z=0,i=0;for(let c=0;c<r;c++)for(let O=0;O<M;O++)i=o.get(c,O)-t,b+=i,z+=i*i;return e?(z-b*b/n)/(n-1):(z-b*b/n)/n}function c_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)-e[t])}function a_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)-e[r])}function s_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)-e)}function O_(o){const e=[];for(let t=0;t<o.rows;t++){let r=0;for(let M=0;M<o.columns;M++)r+=Math.pow(o.get(t,M),2)/(o.columns-1);e.push(Math.sqrt(r))}return e}function u_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)/e[t])}function A_(o){const e=[];for(let t=0;t<o.columns;t++){let r=0;for(let M=0;M<o.rows;M++)r+=Math.pow(o.get(M,t),2)/(o.rows-1);e.push(Math.sqrt(r))}return e}function f_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)/e[r])}function l_(o){const e=o.size-1;let t=0;for(let r=0;r<o.columns;r++)for(let M=0;M<o.rows;M++)t+=Math.pow(o.get(M,r),2)/e;return Math.sqrt(t)}function d_(o,e){for(let t=0;t<o.rows;t++)for(let r=0;r<o.columns;r++)o.set(t,r,o.get(t,r)/e)}class j0{static from1DArray(e,t,r){if(e*t!==r.length)throw new RangeError("data length does not match given dimensions");let n=new d0(e,t);for(let b=0;b<e;b++)for(let z=0;z<t;z++)n.set(b,z,r[b*t+z]);return n}static rowVector(e){let t=new d0(1,e.length);for(let r=0;r<e.length;r++)t.set(0,r,e[r]);return t}static columnVector(e){let t=new d0(e.length,1);for(let r=0;r<e.length;r++)t.set(r,0,e[r]);return t}static zeros(e,t){return new d0(e,t)}static ones(e,t){return new d0(e,t).fill(1)}static rand(e,t,r={}){if(typeof r!="object")throw new TypeError("options must be an object");const{random:M=Math.random}=r;let n=new d0(e,t);for(let b=0;b<e;b++)for(let z=0;z<t;z++)n.set(b,z,M());return n}static randInt(e,t,r={}){if(typeof r!="object")throw new TypeError("options must be an object");const{min:M=0,max:n=1e3,random:b=Math.random}=r;if(!Number.isInteger(M))throw new TypeError("min must be an integer");if(!Number.isInteger(n))throw new TypeError("max must be an integer");if(M>=n)throw new RangeError("min must be smaller than max");let z=n-M,i=new d0(e,t);for(let c=0;c<e;c++)for(let O=0;O<t;O++){let s=M+Math.round(b()*z);i.set(c,O,s)}return i}static eye(e,t,r){t===void 0&&(t=e),r===void 0&&(r=1);let M=Math.min(e,t),n=this.zeros(e,t);for(let b=0;b<M;b++)n.set(b,b,r);return n}static diag(e,t,r){let M=e.length;t===void 0&&(t=M),r===void 0&&(r=t);let n=Math.min(M,t,r),b=this.zeros(t,r);for(let z=0;z<n;z++)b.set(z,z,e[z]);return b}static min(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let r=e.rows,M=e.columns,n=new d0(r,M);for(let b=0;b<r;b++)for(let z=0;z<M;z++)n.set(b,z,Math.min(e.get(b,z),t.get(b,z)));return n}static max(e,t){e=this.checkMatrix(e),t=this.checkMatrix(t);let r=e.rows,M=e.columns,n=new this(r,M);for(let b=0;b<r;b++)for(let z=0;z<M;z++)n.set(b,z,Math.max(e.get(b,z),t.get(b,z)));return n}static checkMatrix(e){return j0.isMatrix(e)?e:new d0(e)}static isMatrix(e){return e!=null&&e.klass==="Matrix"}get size(){return this.rows*this.columns}apply(e){if(typeof e!="function")throw new TypeError("callback must be a function");for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)e.call(this,t,r);return this}to1DArray(){let e=[];for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)e.push(this.get(t,r));return e}to2DArray(){let e=[];for(let t=0;t<this.rows;t++){e.push([]);for(let r=0;r<this.columns;r++)e[t].push(this.get(t,r))}return e}toJSON(){return this.to2DArray()}isRowVector(){return this.rows===1}isColumnVector(){return this.columns===1}isVector(){return this.rows===1||this.columns===1}isSquare(){return this.rows===this.columns}isEmpty(){return this.rows===0||this.columns===0}isSymmetric(){if(this.isSquare()){for(let e=0;e<this.rows;e++)for(let t=0;t<=e;t++)if(this.get(e,t)!==this.get(t,e))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let e=0;e<this.rows;e++)if(this.get(e,e)!==0)return!1;return!0}isEchelonForm(){let e=0,t=0,r=-1,M=!0,n=!1;for(;e<this.rows&&M;){for(t=0,n=!1;t<this.columns&&n===!1;)this.get(e,t)===0?t++:this.get(e,t)===1&&t>r?(n=!0,r=t):(M=!1,n=!0);e++}return M}isReducedEchelonForm(){let e=0,t=0,r=-1,M=!0,n=!1;for(;e<this.rows&&M;){for(t=0,n=!1;t<this.columns&&n===!1;)this.get(e,t)===0?t++:this.get(e,t)===1&&t>r?(n=!0,r=t):(M=!1,n=!0);for(let b=t+1;b<this.rows;b++)this.get(e,b)!==0&&(M=!1);e++}return M}echelonForm(){let e=this.clone(),t=0,r=0;for(;t<e.rows&&r<e.columns;){let M=t;for(let n=t;n<e.rows;n++)e.get(n,r)>e.get(M,r)&&(M=n);if(e.get(M,r)===0)r++;else{e.swapRows(t,M);let n=e.get(t,r);for(let b=r;b<e.columns;b++)e.set(t,b,e.get(t,b)/n);for(let b=t+1;b<e.rows;b++){let z=e.get(b,r)/e.get(t,r);e.set(b,r,0);for(let i=r+1;i<e.columns;i++)e.set(b,i,e.get(b,i)-e.get(t,i)*z)}t++,r++}}return e}reducedEchelonForm(){let e=this.echelonForm(),t=e.columns,r=e.rows,M=r-1;for(;M>=0;)if(e.maxRow(M)===0)M--;else{let n=0,b=!1;for(;n<r&&b===!1;)e.get(M,n)===1?b=!0:n++;for(let z=0;z<M;z++){let i=e.get(z,n);for(let c=n;c<t;c++){let O=e.get(z,c)-i*e.get(M,c);e.set(z,c,O)}}M--}return e}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(e={}){if(typeof e!="object")throw new TypeError("options must be an object");const{rows:t=1,columns:r=1}=e;if(!Number.isInteger(t)||t<=0)throw new TypeError("rows must be a positive integer");if(!Number.isInteger(r)||r<=0)throw new TypeError("columns must be a positive integer");let M=new d0(this.rows*t,this.columns*r);for(let n=0;n<t;n++)for(let b=0;b<r;b++)M.setSubMatrix(this,this.rows*n,this.columns*b);return M}fill(e){for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,e);return this}neg(){return this.mulS(-1)}getRow(e){be(this,e);let t=[];for(let r=0;r<this.columns;r++)t.push(this.get(e,r));return t}getRowVector(e){return d0.rowVector(this.getRow(e))}setRow(e,t){be(this,e),t=Xr(this,t);for(let r=0;r<this.columns;r++)this.set(e,r,t[r]);return this}swapRows(e,t){be(this,e),be(this,t);for(let r=0;r<this.columns;r++){let M=this.get(e,r);this.set(e,r,this.get(t,r)),this.set(t,r,M)}return this}getColumn(e){pe(this,e);let t=[];for(let r=0;r<this.rows;r++)t.push(this.get(r,e));return t}getColumnVector(e){return d0.columnVector(this.getColumn(e))}setColumn(e,t){pe(this,e),t=Er(this,t);for(let r=0;r<this.rows;r++)this.set(r,e,t[r]);return this}swapColumns(e,t){pe(this,e),pe(this,t);for(let r=0;r<this.rows;r++){let M=this.get(r,e);this.set(r,e,this.get(r,t)),this.set(r,t,M)}return this}addRowVector(e){e=Xr(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)+e[r]);return this}subRowVector(e){e=Xr(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)-e[r]);return this}mulRowVector(e){e=Xr(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)*e[r]);return this}divRowVector(e){e=Xr(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)/e[r]);return this}addColumnVector(e){e=Er(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)+e[t]);return this}subColumnVector(e){e=Er(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)-e[t]);return this}mulColumnVector(e){e=Er(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)*e[t]);return this}divColumnVector(e){e=Er(this,e);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)/e[t]);return this}mulRow(e,t){be(this,e);for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)*t);return this}mulColumn(e,t){pe(this,e);for(let r=0;r<this.rows;r++)this.set(r,e,this.get(r,e)*t);return this}max(e){if(this.isEmpty())return NaN;switch(e){case"row":{const t=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)>t[r]&&(t[r]=this.get(r,M));return t}case"column":{const t=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)>t[M]&&(t[M]=this.get(r,M));return t}case void 0:{let t=this.get(0,0);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)>t&&(t=this.get(r,M));return t}default:throw new Error(`invalid option: ${e}`)}}maxIndex(){Tr(this);let e=this.get(0,0),t=[0,0];for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)>e&&(e=this.get(r,M),t[0]=r,t[1]=M);return t}min(e){if(this.isEmpty())return NaN;switch(e){case"row":{const t=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)<t[r]&&(t[r]=this.get(r,M));return t}case"column":{const t=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)<t[M]&&(t[M]=this.get(r,M));return t}case void 0:{let t=this.get(0,0);for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)<t&&(t=this.get(r,M));return t}default:throw new Error(`invalid option: ${e}`)}}minIndex(){Tr(this);let e=this.get(0,0),t=[0,0];for(let r=0;r<this.rows;r++)for(let M=0;M<this.columns;M++)this.get(r,M)<e&&(e=this.get(r,M),t[0]=r,t[1]=M);return t}maxRow(e){if(be(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let r=1;r<this.columns;r++)this.get(e,r)>t&&(t=this.get(e,r));return t}maxRowIndex(e){be(this,e),Tr(this);let t=this.get(e,0),r=[e,0];for(let M=1;M<this.columns;M++)this.get(e,M)>t&&(t=this.get(e,M),r[1]=M);return r}minRow(e){if(be(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let r=1;r<this.columns;r++)this.get(e,r)<t&&(t=this.get(e,r));return t}minRowIndex(e){be(this,e),Tr(this);let t=this.get(e,0),r=[e,0];for(let M=1;M<this.columns;M++)this.get(e,M)<t&&(t=this.get(e,M),r[1]=M);return r}maxColumn(e){if(pe(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let r=1;r<this.rows;r++)this.get(r,e)>t&&(t=this.get(r,e));return t}maxColumnIndex(e){pe(this,e),Tr(this);let t=this.get(0,e),r=[0,e];for(let M=1;M<this.rows;M++)this.get(M,e)>t&&(t=this.get(M,e),r[0]=M);return r}minColumn(e){if(pe(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let r=1;r<this.rows;r++)this.get(r,e)<t&&(t=this.get(r,e));return t}minColumnIndex(e){pe(this,e),Tr(this);let t=this.get(0,e),r=[0,e];for(let M=1;M<this.rows;M++)this.get(M,e)<t&&(t=this.get(M,e),r[0]=M);return r}diag(){let e=Math.min(this.rows,this.columns),t=[];for(let r=0;r<e;r++)t.push(this.get(r,r));return t}norm(e="frobenius"){switch(e){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${e}`)}}cumulativeSum(){let e=0;for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)e+=this.get(t,r),this.set(t,r,e);return this}dot(e){j0.isMatrix(e)&&(e=e.to1DArray());let t=this.to1DArray();if(t.length!==e.length)throw new RangeError("vectors do not have the same size");let r=0;for(let M=0;M<t.length;M++)r+=t[M]*e[M];return r}mmul(e){e=d0.checkMatrix(e);let t=this.rows,r=this.columns,M=e.columns,n=new d0(t,M),b=new Float64Array(r);for(let z=0;z<M;z++){for(let i=0;i<r;i++)b[i]=e.get(i,z);for(let i=0;i<t;i++){let c=0;for(let O=0;O<r;O++)c+=this.get(i,O)*b[O];n.set(i,z,c)}}return n}strassen2x2(e){e=d0.checkMatrix(e);let t=new d0(2,2);const r=this.get(0,0),M=e.get(0,0),n=this.get(0,1),b=e.get(0,1),z=this.get(1,0),i=e.get(1,0),c=this.get(1,1),O=e.get(1,1),s=(r+c)*(M+O),u=(z+c)*M,l=r*(b-O),q=c*(i-M),A=(r+n)*O,h=(z-r)*(M+b),d=(n-c)*(i+O),m=s+q-A+d,_=l+A,R=u+q,g=s-u+l+h;return t.set(0,0,m),t.set(0,1,_),t.set(1,0,R),t.set(1,1,g),t}strassen3x3(e){e=d0.checkMatrix(e);let t=new d0(3,3);const r=this.get(0,0),M=this.get(0,1),n=this.get(0,2),b=this.get(1,0),z=this.get(1,1),i=this.get(1,2),c=this.get(2,0),O=this.get(2,1),s=this.get(2,2),u=e.get(0,0),l=e.get(0,1),q=e.get(0,2),A=e.get(1,0),h=e.get(1,1),d=e.get(1,2),m=e.get(2,0),_=e.get(2,1),R=e.get(2,2),g=(r+M+n-b-z-O-s)*h,L=(r-b)*(-l+h),y=z*(-u+l+A-h-d-m+R),D=(-r+b+z)*(u-l+h),T=(b+z)*(-u+l),N=r*u,w=(-r+c+O)*(u-q+d),E=(-r+c)*(q-d),P=(c+O)*(-u+q),H=(r+M+n-z-i-c-O)*d,Y=O*(-u+q+A-h-d-m+_),k=(-n+O+s)*(h+m-_),K=(n-s)*(h-_),e0=n*m,b0=(O+s)*(-m+_),O0=(-n+z+i)*(d+m-R),v0=(n-i)*(d-R),B0=(z+i)*(-m+R),A0=M*A,k0=i*_,I0=b*q,P0=c*l,W0=s*R,z1=N+e0+A0,Z0=g+D+T+N+k+e0+b0,i1=N+w+P+H+e0+O0+B0,t2=L+y+D+N+e0+O0+v0,W1=L+D+T+N+k0,F=e0+O0+v0+B0+I0,J=N+w+E+Y+k+K+e0,Z=k+K+e0+b0+P0,s0=N+w+E+P+W0;return t.set(0,0,z1),t.set(0,1,Z0),t.set(0,2,i1),t.set(1,0,t2),t.set(1,1,W1),t.set(1,2,F),t.set(2,0,J),t.set(2,1,Z),t.set(2,2,s0),t}mmulStrassen(e){e=d0.checkMatrix(e);let t=this.clone(),r=t.rows,M=t.columns,n=e.rows,b=e.columns;M!==n&&console.warn(`Multiplying ${r} x ${M} and ${n} x ${b} matrix: dimensions do not match.`);function z(s,u,l){let q=s.rows,A=s.columns;if(q===u&&A===l)return s;{let h=j0.zeros(u,l);return h=h.setSubMatrix(s,0,0),h}}let i=Math.max(r,n),c=Math.max(M,b);t=z(t,i,c),e=z(e,i,c);function O(s,u,l,q){if(l<=512||q<=512)return s.mmul(u);l%2===1&&q%2===1?(s=z(s,l+1,q+1),u=z(u,l+1,q+1)):l%2===1?(s=z(s,l+1,q),u=z(u,l+1,q)):q%2===1&&(s=z(s,l,q+1),u=z(u,l,q+1));let A=parseInt(s.rows/2,10),h=parseInt(s.columns/2,10),d=s.subMatrix(0,A-1,0,h-1),m=u.subMatrix(0,A-1,0,h-1),_=s.subMatrix(0,A-1,h,s.columns-1),R=u.subMatrix(0,A-1,h,u.columns-1),g=s.subMatrix(A,s.rows-1,0,h-1),L=u.subMatrix(A,u.rows-1,0,h-1),y=s.subMatrix(A,s.rows-1,h,s.columns-1),D=u.subMatrix(A,u.rows-1,h,u.columns-1),T=O(j0.add(d,y),j0.add(m,D),A,h),N=O(j0.add(g,y),m,A,h),w=O(d,j0.sub(R,D),A,h),E=O(y,j0.sub(L,m),A,h),P=O(j0.add(d,_),D,A,h),H=O(j0.sub(g,d),j0.add(m,R),A,h),Y=O(j0.sub(_,y),j0.add(L,D),A,h),k=j0.add(T,E);k.sub(P),k.add(Y);let K=j0.add(w,P),e0=j0.add(N,E),b0=j0.sub(T,N);b0.add(w),b0.add(H);let O0=j0.zeros(2*k.rows,2*k.columns);return O0=O0.setSubMatrix(k,0,0),O0=O0.setSubMatrix(K,k.rows,0),O0=O0.setSubMatrix(e0,0,k.columns),O0=O0.setSubMatrix(b0,k.rows,k.columns),O0.subMatrix(0,l-1,0,q-1)}return O(t,e,i,c)}scaleRows(e={}){if(typeof e!="object")throw new TypeError("options must be an object");const{min:t=0,max:r=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(t>=r)throw new RangeError("min must be smaller than max");let M=new d0(this.rows,this.columns);for(let n=0;n<this.rows;n++){const b=this.getRow(n);b.length>0&&L3(b,{min:t,max:r,output:b}),M.setRow(n,b)}return M}scaleColumns(e={}){if(typeof e!="object")throw new TypeError("options must be an object");const{min:t=0,max:r=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(t>=r)throw new RangeError("min must be smaller than max");let M=new d0(this.rows,this.columns);for(let n=0;n<this.columns;n++){const b=this.getColumn(n);b.length&&L3(b,{min:t,max:r,output:b}),M.setColumn(n,b)}return M}flipRows(){const e=Math.ceil(this.columns/2);for(let t=0;t<this.rows;t++)for(let r=0;r<e;r++){let M=this.get(t,r),n=this.get(t,this.columns-1-r);this.set(t,r,n),this.set(t,this.columns-1-r,M)}return this}flipColumns(){const e=Math.ceil(this.rows/2);for(let t=0;t<this.columns;t++)for(let r=0;r<e;r++){let M=this.get(r,t),n=this.get(this.rows-1-r,t);this.set(r,t,n),this.set(this.rows-1-r,t,M)}return this}kroneckerProduct(e){e=d0.checkMatrix(e);let t=this.rows,r=this.columns,M=e.rows,n=e.columns,b=new d0(t*M,r*n);for(let z=0;z<t;z++)for(let i=0;i<r;i++)for(let c=0;c<M;c++)for(let O=0;O<n;O++)b.set(M*z+c,n*i+O,this.get(z,i)*e.get(c,O));return b}kroneckerSum(e){if(e=d0.checkMatrix(e),!this.isSquare()||!e.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let t=this.rows,r=e.rows,M=this.kroneckerProduct(d0.eye(r,r)),n=d0.eye(t,t).kroneckerProduct(e);return M.add(n)}transpose(){let e=new d0(this.columns,this.rows);for(let t=0;t<this.rows;t++)for(let r=0;r<this.columns;r++)e.set(r,t,this.get(t,r));return e}sortRows(e=w3){for(let t=0;t<this.rows;t++)this.setRow(t,this.getRow(t).sort(e));return this}sortColumns(e=w3){for(let t=0;t<this.columns;t++)this.setColumn(t,this.getColumn(t).sort(e));return this}subMatrix(e,t,r,M){dp(this,e,t,r,M);let n=new d0(t-e+1,M-r+1);for(let b=e;b<=t;b++)for(let z=r;z<=M;z++)n.set(b-e,z-r,this.get(b,z));return n}subMatrixRow(e,t,r){if(t===void 0&&(t=0),r===void 0&&(r=this.columns-1),t>r||t<0||t>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let M=new d0(e.length,r-t+1);for(let n=0;n<e.length;n++)for(let b=t;b<=r;b++){if(e[n]<0||e[n]>=this.rows)throw new RangeError(`Row index out of range: ${e[n]}`);M.set(n,b-t,this.get(e[n],b))}return M}subMatrixColumn(e,t,r){if(t===void 0&&(t=0),r===void 0&&(r=this.rows-1),t>r||t<0||t>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");let M=new d0(r-t+1,e.length);for(let n=0;n<e.length;n++)for(let b=t;b<=r;b++){if(e[n]<0||e[n]>=this.columns)throw new RangeError(`Column index out of range: ${e[n]}`);M.set(b-t,n,this.get(b,e[n]))}return M}setSubMatrix(e,t,r){if(e=d0.checkMatrix(e),e.isEmpty())return this;let M=t+e.rows-1,n=r+e.columns-1;dp(this,t,M,r,n);for(let b=0;b<e.rows;b++)for(let z=0;z<e.columns;z++)this.set(t+b,r+z,e.get(b,z));return this}selection(e,t){fp(this,e),lp(this,t);let r=new d0(e.length,t.length);for(let M=0;M<e.length;M++){let n=e[M];for(let b=0;b<t.length;b++){let z=t[b];r.set(M,b,this.get(n,z))}}return r}trace(){let e=Math.min(this.rows,this.columns),t=0;for(let r=0;r<e;r++)t+=this.get(r,r);return t}clone(){return this.constructor.copy(this,new d0(this.rows,this.columns))}static copy(e,t){for(const[r,M,n]of e.entries())t.set(r,M,n);return t}sum(e){switch(e){case"row":return t_(this);case"column":return r_(this);case void 0:return M_(this);default:throw new Error(`invalid option: ${e}`)}}product(e){switch(e){case"row":return o_(this);case"column":return n_(this);case void 0:return b_(this);default:throw new Error(`invalid option: ${e}`)}}mean(e){const t=this.sum(e);switch(e){case"row":{for(let r=0;r<this.rows;r++)t[r]/=this.columns;return t}case"column":{for(let r=0;r<this.columns;r++)t[r]/=this.rows;return t}case void 0:return t/this.size;default:throw new Error(`invalid option: ${e}`)}}variance(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");const{unbiased:r=!0,mean:M=this.mean(e)}=t;if(typeof r!="boolean")throw new TypeError("unbiased must be a boolean");switch(e){case"row":{if(!C2.isAnyArray(M))throw new TypeError("mean must be an array");return p_(this,r,M)}case"column":{if(!C2.isAnyArray(M))throw new TypeError("mean must be an array");return z_(this,r,M)}case void 0:{if(typeof M!="number")throw new TypeError("mean must be a number");return i_(this,r,M)}default:throw new Error(`invalid option: ${e}`)}}standardDeviation(e,t){typeof e=="object"&&(t=e,e=void 0);const r=this.variance(e,t);if(e===void 0)return Math.sqrt(r);for(let M=0;M<r.length;M++)r[M]=Math.sqrt(r[M]);return r}center(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");const{center:r=this.mean(e)}=t;switch(e){case"row":{if(!C2.isAnyArray(r))throw new TypeError("center must be an array");return c_(this,r),this}case"column":{if(!C2.isAnyArray(r))throw new TypeError("center must be an array");return a_(this,r),this}case void 0:{if(typeof r!="number")throw new TypeError("center must be a number");return s_(this,r),this}default:throw new Error(`invalid option: ${e}`)}}scale(e,t={}){if(typeof e=="object"&&(t=e,e=void 0),typeof t!="object")throw new TypeError("options must be an object");let r=t.scale;switch(e){case"row":{if(r===void 0)r=O_(this);else if(!C2.isAnyArray(r))throw new TypeError("scale must be an array");return u_(this,r),this}case"column":{if(r===void 0)r=A_(this);else if(!C2.isAnyArray(r))throw new TypeError("scale must be an array");return f_(this,r),this}case void 0:{if(r===void 0)r=l_(this);else if(typeof r!="number")throw new TypeError("scale must be a number");return d_(this,r),this}default:throw new Error(`invalid option: ${e}`)}}toString(e){return y3(this,e)}[Symbol.iterator](){return this.entries()}*entries(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield[e,t,this.get(e,t)]}*values(){for(let e=0;e<this.rows;e++)for(let t=0;t<this.columns;t++)yield this.get(e,t)}}j0.prototype.klass="Matrix",typeof Symbol<"u"&&(j0.prototype[Symbol.for("nodejs.util.inspect.custom")]=J6);function w3(o,e){return o-e}function q_(o){return o.every(e=>typeof e=="number")}j0.random=j0.rand,j0.randomInt=j0.randInt,j0.diagonal=j0.diag,j0.prototype.diagonal=j0.prototype.diag,j0.identity=j0.eye,j0.prototype.negate=j0.prototype.neg,j0.prototype.tensorProduct=j0.prototype.kroneckerProduct;let d0=(Ir=class extends j0{constructor(t,r){super();ii(this,LM);C(this,"data");if(Ir.isMatrix(t))ci(this,LM,ai).call(this,t.rows,t.columns),Ir.copy(t,this);else if(Number.isInteger(t)&&t>=0)ci(this,LM,ai).call(this,t,r);else if(C2.isAnyArray(t)){const M=t;if(t=M.length,r=t?M[0].length:0,typeof r!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let n=0;n<t;n++){if(M[n].length!==r)throw new RangeError("Inconsistent array dimensions");if(!q_(M[n]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(M[n]))}this.rows=t,this.columns=r}else throw new TypeError("First argument must be a positive number or an array")}set(t,r,M){return this.data[t][r]=M,this}get(t,r){return this.data[t][r]}removeRow(t){return be(this,t),this.data.splice(t,1),this.rows-=1,this}addRow(t,r){return r===void 0&&(r=t,t=this.rows),be(this,t,!0),r=Float64Array.from(Xr(this,r)),this.data.splice(t,0,r),this.rows+=1,this}removeColumn(t){pe(this,t);for(let r=0;r<this.rows;r++){const M=new Float64Array(this.columns-1);for(let n=0;n<t;n++)M[n]=this.data[r][n];for(let n=t+1;n<this.columns;n++)M[n-1]=this.data[r][n];this.data[r]=M}return this.columns-=1,this}addColumn(t,r){typeof r>"u"&&(r=t,t=this.columns),pe(this,t,!0),r=Er(this,r);for(let M=0;M<this.rows;M++){const n=new Float64Array(this.columns+1);let b=0;for(;b<t;b++)n[b]=this.data[M][b];for(n[b++]=r[M];b<this.columns+1;b++)n[b]=this.data[M][b-1];this.data[M]=n}return this.columns+=1,this}},LM=new WeakSet,ai=function(t,r){if(this.data=[],Number.isInteger(r)&&r>=0)for(let M=0;M<t;M++)this.data.push(new Float64Array(r));else throw new TypeError("nColumns must be a positive integer");this.rows=t,this.columns=r},Ir);e_(j0,d0);const sn=class sn extends j0{constructor(t){super();ii(this,g2,void 0);if(d0.isMatrix(t)){if(!t.isSymmetric())throw new TypeError("not symmetric data");Mb(this,g2,d0.copy(t,new d0(t.rows,t.rows)))}else if(Number.isInteger(t)&&t>=0)Mb(this,g2,new d0(t,t));else if(Mb(this,g2,new d0(t)),!this.isSymmetric())throw new TypeError("not symmetric data")}get size(){return Be(this,g2).size}get rows(){return Be(this,g2).rows}get columns(){return Be(this,g2).columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(t){return d0.isMatrix(t)&&t.klassType==="SymmetricMatrix"}static zeros(t){return new this(t)}static ones(t){return new this(t).fill(1)}clone(){const t=new sn(this.diagonalSize);for(const[r,M,n]of this.upperRightEntries())t.set(r,M,n);return t}toMatrix(){return new d0(this)}get(t,r){return Be(this,g2).get(t,r)}set(t,r,M){return Be(this,g2).set(t,r,M),Be(this,g2).set(r,t,M),this}removeCross(t){return Be(this,g2).removeRow(t),Be(this,g2).removeColumn(t),this}addCross(t,r){r===void 0&&(r=t,t=this.diagonalSize);const M=r.slice();return M.splice(t,1),Be(this,g2).addRow(t,M),Be(this,g2).addColumn(t,r),this}applyMask(t){if(t.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const r=[];for(const[M,n]of t.entries())n||r.push(M);r.reverse();for(const M of r)this.removeCross(M);return this}toCompact(){const{diagonalSize:t}=this,r=new Array(t*(t+1)/2);for(let M=0,n=0,b=0;b<r.length;b++)r[b]=this.get(n,M),++M>=t&&(M=++n);return r}static fromCompact(t){const r=t.length,M=(Math.sqrt(8*r+1)-1)/2;if(!Number.isInteger(M))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(t)}`);const n=new sn(M);for(let b=0,z=0,i=0;i<r;i++)n.set(b,z,t[i]),++b>=M&&(b=++z);return n}*upperRightEntries(){for(let t=0,r=0;t<this.diagonalSize;void 0){const M=this.get(t,r);yield[t,r,M],++r>=this.diagonalSize&&(r=++t)}}*upperRightValues(){for(let t=0,r=0;t<this.diagonalSize;void 0)yield this.get(t,r),++r>=this.diagonalSize&&(r=++t)}};g2=new WeakMap;let Kt=sn;Kt.prototype.klassType="SymmetricMatrix";class Vo extends Kt{static isDistanceMatrix(e){return Kt.isSymmetricMatrix(e)&&e.klassSubType==="DistanceMatrix"}constructor(e){if(super(e),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(e,t,r){return e===t&&(r=0),super.set(e,t,r)}addCross(e,t){return t===void 0&&(t=e,e=this.diagonalSize),t=t.slice(),t[e]=0,super.addCross(e,t)}toSymmetricMatrix(){return new Kt(this)}clone(){const e=new Vo(this.diagonalSize);for(const[t,r,M]of this.upperRightEntries())t!==r&&e.set(t,r,M);return e}toCompact(){const{diagonalSize:e}=this,t=(e-1)*e/2,r=new Array(t);for(let M=1,n=0,b=0;b<r.length;b++)r[b]=this.get(n,M),++M>=e&&(M=++n+1);return r}static fromCompact(e){const t=e.length,r=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(r))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(e)}`);const M=new this(r);for(let n=1,b=0,z=0;z<t;z++)M.set(n,b,e[z]),++n>=r&&(n=++b+1);return M}}Vo.prototype.klassSubType="DistanceMatrix";class Mt extends j0{constructor(e,t,r){super(),this.matrix=e,this.rows=t,this.columns=r}}class h_ extends Mt{constructor(e,t){pe(e,t),super(e,e.rows,1),this.column=t}set(e,t,r){return this.matrix.set(e,this.column,r),this}get(e){return this.matrix.get(e,this.column)}}class W_ extends Mt{constructor(e,t){lp(e,t),super(e,e.rows,t.length),this.columnIndices=t}set(e,t,r){return this.matrix.set(e,this.columnIndices[t],r),this}get(e,t){return this.matrix.get(e,this.columnIndices[t])}}class __ extends Mt{constructor(e){super(e,e.rows,e.columns)}set(e,t,r){return this.matrix.set(e,this.columns-t-1,r),this}get(e,t){return this.matrix.get(e,this.columns-t-1)}}class m_ extends Mt{constructor(e){super(e,e.rows,e.columns)}set(e,t,r){return this.matrix.set(this.rows-e-1,t,r),this}get(e,t){return this.matrix.get(this.rows-e-1,t)}}class g_ extends Mt{constructor(e,t){be(e,t),super(e,1,e.columns),this.row=t}set(e,t,r){return this.matrix.set(this.row,t,r),this}get(e,t){return this.matrix.get(this.row,t)}}class R_ extends Mt{constructor(e,t){fp(e,t),super(e,t.length,e.columns),this.rowIndices=t}set(e,t,r){return this.matrix.set(this.rowIndices[e],t,r),this}get(e,t){return this.matrix.get(this.rowIndices[e],t)}}class Ko extends Mt{constructor(e,t,r){fp(e,t),lp(e,r),super(e,t.length,r.length),this.rowIndices=t,this.columnIndices=r}set(e,t,r){return this.matrix.set(this.rowIndices[e],this.columnIndices[t],r),this}get(e,t){return this.matrix.get(this.rowIndices[e],this.columnIndices[t])}}class v_ extends Mt{constructor(e,t,r,M,n){dp(e,t,r,M,n),super(e,r-t+1,n-M+1),this.startRow=t,this.startColumn=M}set(e,t,r){return this.matrix.set(this.startRow+e,this.startColumn+t,r),this}get(e,t){return this.matrix.get(this.startRow+e,this.startColumn+t)}}class L_ extends Mt{constructor(e){super(e,e.columns,e.rows)}set(e,t,r){return this.matrix.set(t,e,r),this}get(e,t){return this.matrix.get(t,e)}}class D3 extends j0{constructor(e,t={}){const{rows:r=1}=t;if(e.length%r!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=r,this.columns=e.length/r,this.data=e}set(e,t,r){let M=this._calculateIndex(e,t);return this.data[M]=r,this}get(e,t){let r=this._calculateIndex(e,t);return this.data[r]}_calculateIndex(e,t){return e*this.columns+t}}class j2 extends j0{constructor(e){super(),this.data=e,this.rows=e.length,this.columns=e[0].length}set(e,t,r){return this.data[e][t]=r,this}get(e,t){return this.data[e][t]}}function N_(o,e){if(C2.isAnyArray(o))return o[0]&&C2.isAnyArray(o[0])?new j2(o):new D3(o,e);throw new Error("the argument is not an array")}class Jo{constructor(e){e=j2.checkMatrix(e);let t=e.clone(),r=t.rows,M=t.columns,n=new Float64Array(r),b=1,z,i,c,O,s,u,l,q,A;for(z=0;z<r;z++)n[z]=z;for(q=new Float64Array(r),i=0;i<M;i++){for(z=0;z<r;z++)q[z]=t.get(z,i);for(z=0;z<r;z++){for(A=Math.min(z,i),s=0,c=0;c<A;c++)s+=t.get(z,c)*q[c];q[z]-=s,t.set(z,i,q[z])}for(O=i,z=i+1;z<r;z++)Math.abs(q[z])>Math.abs(q[O])&&(O=z);if(O!==i){for(c=0;c<M;c++)u=t.get(O,c),t.set(O,c,t.get(i,c)),t.set(i,c,u);l=n[O],n[O]=n[i],n[i]=l,b=-b}if(i<r&&t.get(i,i)!==0)for(z=i+1;z<r;z++)t.set(z,i,t.get(z,i)/t.get(i,i))}this.LU=t,this.pivotVector=n,this.pivotSign=b}isSingular(){let e=this.LU,t=e.columns;for(let r=0;r<t;r++)if(e.get(r,r)===0)return!0;return!1}solve(e){e=d0.checkMatrix(e);let t=this.LU;if(t.rows!==e.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let M=e.columns,n=e.subMatrixRow(this.pivotVector,0,M-1),b=t.columns,z,i,c;for(c=0;c<b;c++)for(z=c+1;z<b;z++)for(i=0;i<M;i++)n.set(z,i,n.get(z,i)-n.get(c,i)*t.get(z,c));for(c=b-1;c>=0;c--){for(i=0;i<M;i++)n.set(c,i,n.get(c,i)/t.get(c,c));for(z=0;z<c;z++)for(i=0;i<M;i++)n.set(z,i,n.get(z,i)-n.get(c,i)*t.get(z,c))}return n}get determinant(){let e=this.LU;if(!e.isSquare())throw new Error("Matrix must be square");let t=this.pivotSign,r=e.columns;for(let M=0;M<r;M++)t*=e.get(M,M);return t}get lowerTriangularMatrix(){let e=this.LU,t=e.rows,r=e.columns,M=new d0(t,r);for(let n=0;n<t;n++)for(let b=0;b<r;b++)n>b?M.set(n,b,e.get(n,b)):n===b?M.set(n,b,1):M.set(n,b,0);return M}get upperTriangularMatrix(){let e=this.LU,t=e.rows,r=e.columns,M=new d0(t,r);for(let n=0;n<t;n++)for(let b=0;b<r;b++)n<=b?M.set(n,b,e.get(n,b)):M.set(n,b,0);return M}get pivotPermutationVector(){return Array.from(this.pivotVector)}}function ot(o,e){let t=0;return Math.abs(o)>Math.abs(e)?(t=e/o,Math.abs(o)*Math.sqrt(1+t*t)):e!==0?(t=o/e,Math.abs(e)*Math.sqrt(1+t*t)):0}class qp{constructor(e){e=j2.checkMatrix(e);let t=e.clone(),r=e.rows,M=e.columns,n=new Float64Array(M),b,z,i,c;for(i=0;i<M;i++){let O=0;for(b=i;b<r;b++)O=ot(O,t.get(b,i));if(O!==0){for(t.get(i,i)<0&&(O=-O),b=i;b<r;b++)t.set(b,i,t.get(b,i)/O);for(t.set(i,i,t.get(i,i)+1),z=i+1;z<M;z++){for(c=0,b=i;b<r;b++)c+=t.get(b,i)*t.get(b,z);for(c=-c/t.get(i,i),b=i;b<r;b++)t.set(b,z,t.get(b,z)+c*t.get(b,i))}}n[i]=-O}this.QR=t,this.Rdiag=n}solve(e){e=d0.checkMatrix(e);let t=this.QR,r=t.rows;if(e.rows!==r)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let M=e.columns,n=e.clone(),b=t.columns,z,i,c,O;for(c=0;c<b;c++)for(i=0;i<M;i++){for(O=0,z=c;z<r;z++)O+=t.get(z,c)*n.get(z,i);for(O=-O/t.get(c,c),z=c;z<r;z++)n.set(z,i,n.get(z,i)+O*t.get(z,c))}for(c=b-1;c>=0;c--){for(i=0;i<M;i++)n.set(c,i,n.get(c,i)/this.Rdiag[c]);for(z=0;z<c;z++)for(i=0;i<M;i++)n.set(z,i,n.get(z,i)-n.get(c,i)*t.get(z,c))}return n.subMatrix(0,b-1,0,M-1)}isFullRank(){let e=this.QR.columns;for(let t=0;t<e;t++)if(this.Rdiag[t]===0)return!1;return!0}get upperTriangularMatrix(){let e=this.QR,t=e.columns,r=new d0(t,t),M,n;for(M=0;M<t;M++)for(n=0;n<t;n++)M<n?r.set(M,n,e.get(M,n)):M===n?r.set(M,n,this.Rdiag[M]):r.set(M,n,0);return r}get orthogonalMatrix(){let e=this.QR,t=e.rows,r=e.columns,M=new d0(t,r),n,b,z,i;for(z=r-1;z>=0;z--){for(n=0;n<t;n++)M.set(n,z,0);for(M.set(z,z,1),b=z;b<r;b++)if(e.get(z,z)!==0){for(i=0,n=z;n<t;n++)i+=e.get(n,z)*M.get(n,b);for(i=-i/e.get(z,z),n=z;n<t;n++)M.set(n,b,M.get(n,b)+i*e.get(n,z))}}return M}}class Cr{constructor(e,t={}){if(e=j2.checkMatrix(e),e.isEmpty())throw new Error("Matrix must be non-empty");let r=e.rows,M=e.columns;const{computeLeftSingularVectors:n=!0,computeRightSingularVectors:b=!0,autoTranspose:z=!1}=t;let i=!!n,c=!!b,O=!1,s;if(r<M)if(!z)s=e.clone(),console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose");else{s=e.transpose(),r=s.rows,M=s.columns,O=!0;let N=i;i=c,c=N}else s=e.clone();let u=Math.min(r,M),l=Math.min(r+1,M),q=new Float64Array(l),A=new d0(r,u),h=new d0(M,M),d=new Float64Array(M),m=new Float64Array(r),_=new Float64Array(l);for(let N=0;N<l;N++)_[N]=N;let R=Math.min(r-1,M),g=Math.max(0,Math.min(M-2,r)),L=Math.max(R,g);for(let N=0;N<L;N++){if(N<R){q[N]=0;for(let w=N;w<r;w++)q[N]=ot(q[N],s.get(w,N));if(q[N]!==0){s.get(N,N)<0&&(q[N]=-q[N]);for(let w=N;w<r;w++)s.set(w,N,s.get(w,N)/q[N]);s.set(N,N,s.get(N,N)+1)}q[N]=-q[N]}for(let w=N+1;w<M;w++){if(N<R&&q[N]!==0){let E=0;for(let P=N;P<r;P++)E+=s.get(P,N)*s.get(P,w);E=-E/s.get(N,N);for(let P=N;P<r;P++)s.set(P,w,s.get(P,w)+E*s.get(P,N))}d[w]=s.get(N,w)}if(i&&N<R)for(let w=N;w<r;w++)A.set(w,N,s.get(w,N));if(N<g){d[N]=0;for(let w=N+1;w<M;w++)d[N]=ot(d[N],d[w]);if(d[N]!==0){d[N+1]<0&&(d[N]=0-d[N]);for(let w=N+1;w<M;w++)d[w]/=d[N];d[N+1]+=1}if(d[N]=-d[N],N+1<r&&d[N]!==0){for(let w=N+1;w<r;w++)m[w]=0;for(let w=N+1;w<r;w++)for(let E=N+1;E<M;E++)m[w]+=d[E]*s.get(w,E);for(let w=N+1;w<M;w++){let E=-d[w]/d[N+1];for(let P=N+1;P<r;P++)s.set(P,w,s.get(P,w)+E*m[P])}}if(c)for(let w=N+1;w<M;w++)h.set(w,N,d[w])}}let y=Math.min(M,r+1);if(R<M&&(q[R]=s.get(R,R)),r<y&&(q[y-1]=0),g+1<y&&(d[g]=s.get(g,y-1)),d[y-1]=0,i){for(let N=R;N<u;N++){for(let w=0;w<r;w++)A.set(w,N,0);A.set(N,N,1)}for(let N=R-1;N>=0;N--)if(q[N]!==0){for(let w=N+1;w<u;w++){let E=0;for(let P=N;P<r;P++)E+=A.get(P,N)*A.get(P,w);E=-E/A.get(N,N);for(let P=N;P<r;P++)A.set(P,w,A.get(P,w)+E*A.get(P,N))}for(let w=N;w<r;w++)A.set(w,N,-A.get(w,N));A.set(N,N,1+A.get(N,N));for(let w=0;w<N-1;w++)A.set(w,N,0)}else{for(let w=0;w<r;w++)A.set(w,N,0);A.set(N,N,1)}}if(c)for(let N=M-1;N>=0;N--){if(N<g&&d[N]!==0)for(let w=N+1;w<M;w++){let E=0;for(let P=N+1;P<M;P++)E+=h.get(P,N)*h.get(P,w);E=-E/h.get(N+1,N);for(let P=N+1;P<M;P++)h.set(P,w,h.get(P,w)+E*h.get(P,N))}for(let w=0;w<M;w++)h.set(w,N,0);h.set(N,N,1)}let D=y-1,T=Number.EPSILON;for(;y>0;){let N,w;for(N=y-2;N>=-1&&N!==-1;N--){const E=Number.MIN_VALUE+T*Math.abs(q[N]+Math.abs(q[N+1]));if(Math.abs(d[N])<=E||Number.isNaN(d[N])){d[N]=0;break}}if(N===y-2)w=4;else{let E;for(E=y-1;E>=N&&E!==N;E--){let P=(E!==y?Math.abs(d[E]):0)+(E!==N+1?Math.abs(d[E-1]):0);if(Math.abs(q[E])<=T*P){q[E]=0;break}}E===N?w=3:E===y-1?w=1:(w=2,N=E)}switch(N++,w){case 1:{let E=d[y-2];d[y-2]=0;for(let P=y-2;P>=N;P--){let H=ot(q[P],E),Y=q[P]/H,k=E/H;if(q[P]=H,P!==N&&(E=-k*d[P-1],d[P-1]=Y*d[P-1]),c)for(let K=0;K<M;K++)H=Y*h.get(K,P)+k*h.get(K,y-1),h.set(K,y-1,-k*h.get(K,P)+Y*h.get(K,y-1)),h.set(K,P,H)}break}case 2:{let E=d[N-1];d[N-1]=0;for(let P=N;P<y;P++){let H=ot(q[P],E),Y=q[P]/H,k=E/H;if(q[P]=H,E=-k*d[P],d[P]=Y*d[P],i)for(let K=0;K<r;K++)H=Y*A.get(K,P)+k*A.get(K,N-1),A.set(K,N-1,-k*A.get(K,P)+Y*A.get(K,N-1)),A.set(K,P,H)}break}case 3:{const E=Math.max(Math.abs(q[y-1]),Math.abs(q[y-2]),Math.abs(d[y-2]),Math.abs(q[N]),Math.abs(d[N])),P=q[y-1]/E,H=q[y-2]/E,Y=d[y-2]/E,k=q[N]/E,K=d[N]/E,e0=((H+P)*(H-P)+Y*Y)/2,b0=P*Y*(P*Y);let O0=0;(e0!==0||b0!==0)&&(e0<0?O0=0-Math.sqrt(e0*e0+b0):O0=Math.sqrt(e0*e0+b0),O0=b0/(e0+O0));let v0=(k+P)*(k-P)+O0,B0=k*K;for(let A0=N;A0<y-1;A0++){let k0=ot(v0,B0);k0===0&&(k0=Number.MIN_VALUE);let I0=v0/k0,P0=B0/k0;if(A0!==N&&(d[A0-1]=k0),v0=I0*q[A0]+P0*d[A0],d[A0]=I0*d[A0]-P0*q[A0],B0=P0*q[A0+1],q[A0+1]=I0*q[A0+1],c)for(let W0=0;W0<M;W0++)k0=I0*h.get(W0,A0)+P0*h.get(W0,A0+1),h.set(W0,A0+1,-P0*h.get(W0,A0)+I0*h.get(W0,A0+1)),h.set(W0,A0,k0);if(k0=ot(v0,B0),k0===0&&(k0=Number.MIN_VALUE),I0=v0/k0,P0=B0/k0,q[A0]=k0,v0=I0*d[A0]+P0*q[A0+1],q[A0+1]=-P0*d[A0]+I0*q[A0+1],B0=P0*d[A0+1],d[A0+1]=I0*d[A0+1],i&&A0<r-1)for(let W0=0;W0<r;W0++)k0=I0*A.get(W0,A0)+P0*A.get(W0,A0+1),A.set(W0,A0+1,-P0*A.get(W0,A0)+I0*A.get(W0,A0+1)),A.set(W0,A0,k0)}d[y-2]=v0;break}case 4:{if(q[N]<=0&&(q[N]=q[N]<0?-q[N]:0,c))for(let E=0;E<=D;E++)h.set(E,N,-h.get(E,N));for(;N<D&&!(q[N]>=q[N+1]);){let E=q[N];if(q[N]=q[N+1],q[N+1]=E,c&&N<M-1)for(let P=0;P<M;P++)E=h.get(P,N+1),h.set(P,N+1,h.get(P,N)),h.set(P,N,E);if(i&&N<r-1)for(let P=0;P<r;P++)E=A.get(P,N+1),A.set(P,N+1,A.get(P,N)),A.set(P,N,E);N++}y--;break}}}if(O){let N=h;h=A,A=N}this.m=r,this.n=M,this.s=q,this.U=A,this.V=h}solve(e){let t=e,r=this.threshold,M=this.s.length,n=d0.zeros(M,M);for(let u=0;u<M;u++)Math.abs(this.s[u])<=r?n.set(u,u,0):n.set(u,u,1/this.s[u]);let b=this.U,z=this.rightSingularVectors,i=z.mmul(n),c=z.rows,O=b.rows,s=d0.zeros(c,O);for(let u=0;u<c;u++)for(let l=0;l<O;l++){let q=0;for(let A=0;A<M;A++)q+=i.get(u,A)*b.get(l,A);s.set(u,l,q)}return s.mmul(t)}solveForDiagonal(e){return this.solve(d0.diag(e))}inverse(){let e=this.V,t=this.threshold,r=e.rows,M=e.columns,n=new d0(r,this.s.length);for(let O=0;O<r;O++)for(let s=0;s<M;s++)Math.abs(this.s[s])>t&&n.set(O,s,e.get(O,s)/this.s[s]);let b=this.U,z=b.rows,i=b.columns,c=new d0(r,z);for(let O=0;O<r;O++)for(let s=0;s<z;s++){let u=0;for(let l=0;l<i;l++)u+=n.get(O,l)*b.get(s,l);c.set(O,s,u)}return c}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let e=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,t=0,r=this.s;for(let M=0,n=r.length;M<n;M++)r[M]>e&&t++;return t}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return d0.diag(this.s)}}function y_(o,e=!1){return o=j2.checkMatrix(o),e?new Cr(o).inverse():X3(o,d0.eye(o.rows))}function X3(o,e,t=!1){return o=j2.checkMatrix(o),e=j2.checkMatrix(e),t?new Cr(o).solve(e):o.isSquare()?new Jo(o).solve(e):new qp(o).solve(e)}function Qo(o){if(o=d0.checkMatrix(o),o.isSquare()){if(o.columns===0)return 1;let e,t,r,M;if(o.columns===2)return e=o.get(0,0),t=o.get(0,1),r=o.get(1,0),M=o.get(1,1),e*M-t*r;if(o.columns===3){let n,b,z;return n=new Ko(o,[1,2],[1,2]),b=new Ko(o,[1,2],[0,2]),z=new Ko(o,[1,2],[0,1]),e=o.get(0,0),t=o.get(0,1),r=o.get(0,2),e*Qo(n)-t*Qo(b)+r*Qo(z)}else return new Jo(o).determinant}else throw Error("determinant can only be calculated for a square matrix")}function B_(o,e){let t=[];for(let r=0;r<o;r++)r!==e&&t.push(r);return t}function w_(o,e,t,r=1e-9,M=1e-9){if(o>M)return new Array(e.rows+1).fill(0);{let n=e.addRow(t,[0]);for(let b=0;b<n.rows;b++)Math.abs(n.get(b,0))<r&&n.set(b,0,0);return n.to1DArray()}}function D_(o,e={}){const{thresholdValue:t=1e-9,thresholdError:r=1e-9}=e;o=d0.checkMatrix(o);let M=o.rows,n=new d0(M,M);for(let b=0;b<M;b++){let z=d0.columnVector(o.getRow(b)),i=o.subMatrixRow(B_(M,b)).transpose(),O=new Cr(i).solve(z),s=d0.sub(z,i.mmul(O)).abs().max();n.setRow(b,w_(s,O,b,t,r))}return n}function X_(o,e=Number.EPSILON){if(o=d0.checkMatrix(o),o.isEmpty())return o.transpose();let t=new Cr(o,{autoTranspose:!0}),r=t.leftSingularVectors,M=t.rightSingularVectors,n=t.diagonal;for(let b=0;b<n.length;b++)Math.abs(n[b])>e?n[b]=1/n[b]:n[b]=0;return M.mmul(d0.diag(n).mmul(r.transpose()))}function E_(o,e=o,t={}){o=new d0(o);let r=!1;if(typeof e=="object"&&!d0.isMatrix(e)&&!C2.isAnyArray(e)?(t=e,e=o,r=!0):e=new d0(e),o.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:M=!0}=t;M&&(o=o.center("column"),r||(e=e.center("column")));const n=o.transpose().mmul(e);for(let b=0;b<n.rows;b++)for(let z=0;z<n.columns;z++)n.set(b,z,n.get(b,z)*(1/(o.rows-1)));return n}function T_(o,e=o,t={}){o=new d0(o);let r=!1;if(typeof e=="object"&&!d0.isMatrix(e)&&!C2.isAnyArray(e)?(t=e,e=o,r=!0):e=new d0(e),o.rows!==e.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:M=!0,scale:n=!0}=t;M&&(o.center("column"),r||e.center("column")),n&&(o.scale("column"),r||e.scale("column"));const b=o.standardDeviation("column",{unbiased:!0}),z=r?b:e.standardDeviation("column",{unbiased:!0}),i=o.transpose().mmul(e);for(let c=0;c<i.rows;c++)for(let O=0;O<i.columns;O++)i.set(c,O,i.get(c,O)*(1/(b[c]*z[O]))*(1/(o.rows-1)));return i}let E3=class{constructor(e,t={}){const{assumeSymmetric:r=!1}=t;if(e=j2.checkMatrix(e),!e.isSquare())throw new Error("Matrix is not a square matrix");if(e.isEmpty())throw new Error("Matrix must be non-empty");let M=e.columns,n=new d0(M,M),b=new Float64Array(M),z=new Float64Array(M),i=e,c,O,s=!1;if(r?s=!0:s=e.isSymmetric(),s){for(c=0;c<M;c++)for(O=0;O<M;O++)n.set(c,O,i.get(c,O));C_(M,z,b,n),x_(M,z,b,n)}else{let u=new d0(M,M),l=new Float64Array(M);for(O=0;O<M;O++)for(c=0;c<M;c++)u.set(c,O,i.get(c,O));S_(M,u,l,n),F_(M,z,b,n,u)}this.n=M,this.e=z,this.d=b,this.V=n}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let e=this.n,t=this.e,r=this.d,M=new d0(e,e),n,b;for(n=0;n<e;n++){for(b=0;b<e;b++)M.set(n,b,0);M.set(n,n,r[n]),t[n]>0?M.set(n,n+1,t[n]):t[n]<0&&M.set(n,n-1,t[n])}return M}};function C_(o,e,t,r){let M,n,b,z,i,c,O,s;for(i=0;i<o;i++)t[i]=r.get(o-1,i);for(z=o-1;z>0;z--){for(s=0,b=0,c=0;c<z;c++)s=s+Math.abs(t[c]);if(s===0)for(e[z]=t[z-1],i=0;i<z;i++)t[i]=r.get(z-1,i),r.set(z,i,0),r.set(i,z,0);else{for(c=0;c<z;c++)t[c]/=s,b+=t[c]*t[c];for(M=t[z-1],n=Math.sqrt(b),M>0&&(n=-n),e[z]=s*n,b=b-M*n,t[z-1]=M-n,i=0;i<z;i++)e[i]=0;for(i=0;i<z;i++){for(M=t[i],r.set(i,z,M),n=e[i]+r.get(i,i)*M,c=i+1;c<=z-1;c++)n+=r.get(c,i)*t[c],e[c]+=r.get(c,i)*M;e[i]=n}for(M=0,i=0;i<z;i++)e[i]/=b,M+=e[i]*t[i];for(O=M/(b+b),i=0;i<z;i++)e[i]-=O*t[i];for(i=0;i<z;i++){for(M=t[i],n=e[i],c=i;c<=z-1;c++)r.set(c,i,r.get(c,i)-(M*e[c]+n*t[c]));t[i]=r.get(z-1,i),r.set(z,i,0)}}t[z]=b}for(z=0;z<o-1;z++){if(r.set(o-1,z,r.get(z,z)),r.set(z,z,1),b=t[z+1],b!==0){for(c=0;c<=z;c++)t[c]=r.get(c,z+1)/b;for(i=0;i<=z;i++){for(n=0,c=0;c<=z;c++)n+=r.get(c,z+1)*r.get(c,i);for(c=0;c<=z;c++)r.set(c,i,r.get(c,i)-n*t[c])}}for(c=0;c<=z;c++)r.set(c,z+1,0)}for(i=0;i<o;i++)t[i]=r.get(o-1,i),r.set(o-1,i,0);r.set(o-1,o-1,1),e[0]=0}function x_(o,e,t,r){let M,n,b,z,i,c,O,s,u,l,q,A,h,d,m,_;for(b=1;b<o;b++)e[b-1]=e[b];e[o-1]=0;let R=0,g=0,L=Number.EPSILON;for(c=0;c<o;c++){for(g=Math.max(g,Math.abs(t[c])+Math.abs(e[c])),O=c;O<o&&!(Math.abs(e[O])<=L*g);)O++;if(O>c)do{for(M=t[c],s=(t[c+1]-M)/(2*e[c]),u=ot(s,1),s<0&&(u=-u),t[c]=e[c]/(s+u),t[c+1]=e[c]*(s+u),l=t[c+1],n=M-t[c],b=c+2;b<o;b++)t[b]-=n;for(R=R+n,s=t[O],q=1,A=q,h=q,d=e[c+1],m=0,_=0,b=O-1;b>=c;b--)for(h=A,A=q,_=m,M=q*e[b],n=q*s,u=ot(s,e[b]),e[b+1]=m*u,m=e[b]/u,q=s/u,s=q*t[b]-m*M,t[b+1]=n+m*(q*M+m*t[b]),i=0;i<o;i++)n=r.get(i,b+1),r.set(i,b+1,m*r.get(i,b)+q*n),r.set(i,b,q*r.get(i,b)-m*n);s=-m*_*h*d*e[c]/l,e[c]=m*s,t[c]=q*s}while(Math.abs(e[c])>L*g);t[c]=t[c]+R,e[c]=0}for(b=0;b<o-1;b++){for(i=b,s=t[b],z=b+1;z<o;z++)t[z]<s&&(i=z,s=t[z]);if(i!==b)for(t[i]=t[b],t[b]=s,z=0;z<o;z++)s=r.get(z,b),r.set(z,b,r.get(z,i)),r.set(z,i,s)}}function S_(o,e,t,r){let M=0,n=o-1,b,z,i,c,O,s,u;for(s=M+1;s<=n-1;s++){for(u=0,c=s;c<=n;c++)u=u+Math.abs(e.get(c,s-1));if(u!==0){for(i=0,c=n;c>=s;c--)t[c]=e.get(c,s-1)/u,i+=t[c]*t[c];for(z=Math.sqrt(i),t[s]>0&&(z=-z),i=i-t[s]*z,t[s]=t[s]-z,O=s;O<o;O++){for(b=0,c=n;c>=s;c--)b+=t[c]*e.get(c,O);for(b=b/i,c=s;c<=n;c++)e.set(c,O,e.get(c,O)-b*t[c])}for(c=0;c<=n;c++){for(b=0,O=n;O>=s;O--)b+=t[O]*e.get(c,O);for(b=b/i,O=s;O<=n;O++)e.set(c,O,e.get(c,O)-b*t[O])}t[s]=u*t[s],e.set(s,s-1,u*z)}}for(c=0;c<o;c++)for(O=0;O<o;O++)r.set(c,O,c===O?1:0);for(s=n-1;s>=M+1;s--)if(e.get(s,s-1)!==0){for(c=s+1;c<=n;c++)t[c]=e.get(c,s-1);for(O=s;O<=n;O++){for(z=0,c=s;c<=n;c++)z+=t[c]*r.get(c,O);for(z=z/t[s]/e.get(s,s-1),c=s;c<=n;c++)r.set(c,O,r.get(c,O)+z*t[c])}}}function F_(o,e,t,r,M){let n=o-1,b=0,z=o-1,i=Number.EPSILON,c=0,O=0,s=0,u=0,l=0,q=0,A=0,h=0,d,m,_,R,g,L,y,D,T,N,w,E,P,H,Y;for(d=0;d<o;d++)for((d<b||d>z)&&(t[d]=M.get(d,d),e[d]=0),m=Math.max(d-1,0);m<o;m++)O=O+Math.abs(M.get(d,m));for(;n>=b;){for(R=n;R>b&&(q=Math.abs(M.get(R-1,R-1))+Math.abs(M.get(R,R)),q===0&&(q=O),!(Math.abs(M.get(R,R-1))<i*q));)R--;if(R===n)M.set(n,n,M.get(n,n)+c),t[n]=M.get(n,n),e[n]=0,n--,h=0;else if(R===n-1){if(y=M.get(n,n-1)*M.get(n-1,n),s=(M.get(n-1,n-1)-M.get(n,n))/2,u=s*s+y,A=Math.sqrt(Math.abs(u)),M.set(n,n,M.get(n,n)+c),M.set(n-1,n-1,M.get(n-1,n-1)+c),D=M.get(n,n),u>=0){for(A=s>=0?s+A:s-A,t[n-1]=D+A,t[n]=t[n-1],A!==0&&(t[n]=D-y/A),e[n-1]=0,e[n]=0,D=M.get(n,n-1),q=Math.abs(D)+Math.abs(A),s=D/q,u=A/q,l=Math.sqrt(s*s+u*u),s=s/l,u=u/l,m=n-1;m<o;m++)A=M.get(n-1,m),M.set(n-1,m,u*A+s*M.get(n,m)),M.set(n,m,u*M.get(n,m)-s*A);for(d=0;d<=n;d++)A=M.get(d,n-1),M.set(d,n-1,u*A+s*M.get(d,n)),M.set(d,n,u*M.get(d,n)-s*A);for(d=b;d<=z;d++)A=r.get(d,n-1),r.set(d,n-1,u*A+s*r.get(d,n)),r.set(d,n,u*r.get(d,n)-s*A)}else t[n-1]=D+s,t[n]=D+s,e[n-1]=A,e[n]=-A;n=n-2,h=0}else{if(D=M.get(n,n),T=0,y=0,R<n&&(T=M.get(n-1,n-1),y=M.get(n,n-1)*M.get(n-1,n)),h===10){for(c+=D,d=b;d<=n;d++)M.set(d,d,M.get(d,d)-D);q=Math.abs(M.get(n,n-1))+Math.abs(M.get(n-1,n-2)),D=T=.75*q,y=-.4375*q*q}if(h===30&&(q=(T-D)/2,q=q*q+y,q>0)){for(q=Math.sqrt(q),T<D&&(q=-q),q=D-y/((T-D)/2+q),d=b;d<=n;d++)M.set(d,d,M.get(d,d)-q);c+=q,D=T=y=.964}for(h=h+1,g=n-2;g>=R&&(A=M.get(g,g),l=D-A,q=T-A,s=(l*q-y)/M.get(g+1,g)+M.get(g,g+1),u=M.get(g+1,g+1)-A-l-q,l=M.get(g+2,g+1),q=Math.abs(s)+Math.abs(u)+Math.abs(l),s=s/q,u=u/q,l=l/q,!(g===R||Math.abs(M.get(g,g-1))*(Math.abs(u)+Math.abs(l))<i*(Math.abs(s)*(Math.abs(M.get(g-1,g-1))+Math.abs(A)+Math.abs(M.get(g+1,g+1))))));)g--;for(d=g+2;d<=n;d++)M.set(d,d-2,0),d>g+2&&M.set(d,d-3,0);for(_=g;_<=n-1&&(H=_!==n-1,_!==g&&(s=M.get(_,_-1),u=M.get(_+1,_-1),l=H?M.get(_+2,_-1):0,D=Math.abs(s)+Math.abs(u)+Math.abs(l),D!==0&&(s=s/D,u=u/D,l=l/D)),D!==0);_++)if(q=Math.sqrt(s*s+u*u+l*l),s<0&&(q=-q),q!==0){for(_!==g?M.set(_,_-1,-q*D):R!==g&&M.set(_,_-1,-M.get(_,_-1)),s=s+q,D=s/q,T=u/q,A=l/q,u=u/s,l=l/s,m=_;m<o;m++)s=M.get(_,m)+u*M.get(_+1,m),H&&(s=s+l*M.get(_+2,m),M.set(_+2,m,M.get(_+2,m)-s*A)),M.set(_,m,M.get(_,m)-s*D),M.set(_+1,m,M.get(_+1,m)-s*T);for(d=0;d<=Math.min(n,_+3);d++)s=D*M.get(d,_)+T*M.get(d,_+1),H&&(s=s+A*M.get(d,_+2),M.set(d,_+2,M.get(d,_+2)-s*l)),M.set(d,_,M.get(d,_)-s),M.set(d,_+1,M.get(d,_+1)-s*u);for(d=b;d<=z;d++)s=D*r.get(d,_)+T*r.get(d,_+1),H&&(s=s+A*r.get(d,_+2),r.set(d,_+2,r.get(d,_+2)-s*l)),r.set(d,_,r.get(d,_)-s),r.set(d,_+1,r.get(d,_+1)-s*u)}}}if(O!==0){for(n=o-1;n>=0;n--)if(s=t[n],u=e[n],u===0)for(R=n,M.set(n,n,1),d=n-1;d>=0;d--){for(y=M.get(d,d)-s,l=0,m=R;m<=n;m++)l=l+M.get(d,m)*M.get(m,n);if(e[d]<0)A=y,q=l;else if(R=d,e[d]===0?M.set(d,n,y!==0?-l/y:-l/(i*O)):(D=M.get(d,d+1),T=M.get(d+1,d),u=(t[d]-s)*(t[d]-s)+e[d]*e[d],L=(D*q-A*l)/u,M.set(d,n,L),M.set(d+1,n,Math.abs(D)>Math.abs(A)?(-l-y*L)/D:(-q-T*L)/A)),L=Math.abs(M.get(d,n)),i*L*L>1)for(m=d;m<=n;m++)M.set(m,n,M.get(m,n)/L)}else if(u<0)for(R=n-1,Math.abs(M.get(n,n-1))>Math.abs(M.get(n-1,n))?(M.set(n-1,n-1,u/M.get(n,n-1)),M.set(n-1,n,-(M.get(n,n)-s)/M.get(n,n-1))):(Y=Zo(0,-M.get(n-1,n),M.get(n-1,n-1)-s,u),M.set(n-1,n-1,Y[0]),M.set(n-1,n,Y[1])),M.set(n,n-1,0),M.set(n,n,1),d=n-2;d>=0;d--){for(N=0,w=0,m=R;m<=n;m++)N=N+M.get(d,m)*M.get(m,n-1),w=w+M.get(d,m)*M.get(m,n);if(y=M.get(d,d)-s,e[d]<0)A=y,l=N,q=w;else if(R=d,e[d]===0?(Y=Zo(-N,-w,y,u),M.set(d,n-1,Y[0]),M.set(d,n,Y[1])):(D=M.get(d,d+1),T=M.get(d+1,d),E=(t[d]-s)*(t[d]-s)+e[d]*e[d]-u*u,P=(t[d]-s)*2*u,E===0&&P===0&&(E=i*O*(Math.abs(y)+Math.abs(u)+Math.abs(D)+Math.abs(T)+Math.abs(A))),Y=Zo(D*l-A*N+u*w,D*q-A*w-u*N,E,P),M.set(d,n-1,Y[0]),M.set(d,n,Y[1]),Math.abs(D)>Math.abs(A)+Math.abs(u)?(M.set(d+1,n-1,(-N-y*M.get(d,n-1)+u*M.get(d,n))/D),M.set(d+1,n,(-w-y*M.get(d,n)-u*M.get(d,n-1))/D)):(Y=Zo(-l-T*M.get(d,n-1),-q-T*M.get(d,n),A,u),M.set(d+1,n-1,Y[0]),M.set(d+1,n,Y[1]))),L=Math.max(Math.abs(M.get(d,n-1)),Math.abs(M.get(d,n))),i*L*L>1)for(m=d;m<=n;m++)M.set(m,n-1,M.get(m,n-1)/L),M.set(m,n,M.get(m,n)/L)}for(d=0;d<o;d++)if(d<b||d>z)for(m=d;m<o;m++)r.set(d,m,M.get(d,m));for(m=o-1;m>=b;m--)for(d=b;d<=z;d++){for(A=0,_=b;_<=Math.min(m,z);_++)A=A+r.get(d,_)*M.get(_,m);r.set(d,m,A)}}}function Zo(o,e,t,r){let M,n;return Math.abs(t)>Math.abs(r)?(M=r/t,n=t+M*r,[(o+M*e)/n,(e-M*o)/n]):(M=t/r,n=r+M*t,[(M*o+e)/n,(M*e-o)/n])}class T3{constructor(e){if(e=j2.checkMatrix(e),!e.isSymmetric())throw new Error("Matrix is not symmetric");let t=e,r=t.rows,M=new d0(r,r),n=!0,b,z,i;for(z=0;z<r;z++){let c=0;for(i=0;i<z;i++){let O=0;for(b=0;b<i;b++)O+=M.get(i,b)*M.get(z,b);O=(t.get(z,i)-O)/M.get(i,i),M.set(z,i,O),c=c+O*O}for(c=t.get(z,z)-c,n&=c>0,M.set(z,z,Math.sqrt(Math.max(c,0))),i=z+1;i<r;i++)M.set(z,i,0)}this.L=M,this.positiveDefinite=!!n}isPositiveDefinite(){return this.positiveDefinite}solve(e){e=j2.checkMatrix(e);let t=this.L,r=t.rows;if(e.rows!==r)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let M=e.columns,n=e.clone(),b,z,i;for(i=0;i<r;i++)for(z=0;z<M;z++){for(b=0;b<i;b++)n.set(i,z,n.get(i,z)-n.get(b,z)*t.get(i,b));n.set(i,z,n.get(i,z)/t.get(i,i))}for(i=r-1;i>=0;i--)for(z=0;z<M;z++){for(b=i+1;b<r;b++)n.set(i,z,n.get(i,z)-n.get(b,z)*t.get(b,i));n.set(i,z,n.get(i,z)/t.get(i,i))}return n}get lowerTriangularMatrix(){return this.L}}class C3{constructor(e,t={}){e=j2.checkMatrix(e);let{Y:r}=t;const{scaleScores:M=!1,maxIterations:n=1e3,terminationCriteria:b=1e-10}=t;let z;if(r){if(C2.isAnyArray(r)&&typeof r[0]=="number"?r=d0.columnVector(r):r=j2.checkMatrix(r),r.rows!==e.rows)throw new Error("Y should have the same number of rows as X");z=r.getColumnVector(0)}else z=e.getColumnVector(0);let i=1,c,O,s,u;for(let l=0;l<n&&i>b;l++)s=e.transpose().mmul(z).div(z.transpose().mmul(z).get(0,0)),s=s.div(s.norm()),c=e.mmul(s).div(s.transpose().mmul(s).get(0,0)),l>0&&(i=c.clone().sub(u).pow(2).sum()),u=c.clone(),r?(O=r.transpose().mmul(c).div(c.transpose().mmul(c).get(0,0)),O=O.div(O.norm()),z=r.mmul(O).div(O.transpose().mmul(O).get(0,0))):z=c;if(r){let l=e.transpose().mmul(c).div(c.transpose().mmul(c).get(0,0));l=l.div(l.norm());let q=e.clone().sub(c.clone().mmul(l.transpose())),A=z.transpose().mmul(c).div(c.transpose().mmul(c).get(0,0)),h=r.clone().sub(c.clone().mulS(A.get(0,0)).mmul(O.transpose()));this.t=c,this.p=l.transpose(),this.w=s.transpose(),this.q=O,this.u=z,this.s=c.transpose().mmul(c),this.xResidual=q,this.yResidual=h,this.betas=A}else this.w=s.transpose(),this.s=c.transpose().mmul(c).sqrt(),M?this.t=c.clone().div(this.s.get(0,0)):this.t=c,this.xResidual=e.sub(c.mmul(s.transpose()))}}t1.AbstractMatrix=j0,t1.CHO=T3,t1.CholeskyDecomposition=T3,t1.DistanceMatrix=Vo,t1.EVD=E3;var I_=t1.EigenvalueDecomposition=E3;t1.LU=Jo,t1.LuDecomposition=Jo;var x3=t1.Matrix=d0;t1.MatrixColumnSelectionView=W_,t1.MatrixColumnView=h_,t1.MatrixFlipColumnView=__,t1.MatrixFlipRowView=m_,t1.MatrixRowSelectionView=R_,t1.MatrixRowView=g_,t1.MatrixSelectionView=Ko,t1.MatrixSubView=v_,t1.MatrixTransposeView=L_,t1.NIPALS=C3,t1.Nipals=C3,t1.QR=qp,t1.QrDecomposition=qp,t1.SVD=Cr,t1.SingularValueDecomposition=Cr,t1.SymmetricMatrix=Kt,t1.WrapperMatrix1D=D3,t1.WrapperMatrix2D=j2,t1.correlation=T_,t1.covariance=E_;var S3=t1.default=d0;t1.determinant=Qo,t1.inverse=y_,t1.linearDependencies=D_,t1.pseudoInverse=X_,t1.solve=X3,t1.wrap=N_;const F3=I_,I3=x3;S3.Matrix&&S3.Matrix;class P_{constructor(e){C(this,"_errorListener");C(this,"_array");this._errorListener=e,this._array=new mc(e)}new({rows:e,columns:t,initial_value:r,type:M}={}){return P3(e,t,r,M)}avg({id:e}){if(!e)return;let t=0,r=0;for(const n of e._value)for(const b of n._value)t+=u0(b)?0:b,r+=1;return t/r}col({id:e,column:t}){if(!e)return;const r=[],M=p1(0,void 0,e.typeName);if(u0(t))return M;for(const n of e._value)r.push(n._value[t]);return M._value=r,M}det({id:e}){if(e)return R3(e._matrixArray)}get({id:e,row:t,column:r}){var M,n;if(e&&!(u0(t)||u0(r)))return(n=(M=e._value[t])==null?void 0:M._value)==null?void 0:n[r]}inv({id:e}){if(!e)return;const t=jo(e._matrixArray);return this._newMatrix(t,e)}max({id:e}){if(e)return C6(e._matrixArray)}min({id:e}){if(e)return Ap(e._matrixArray)}pow({id:e,power:t}){if(!e)return;const r=u0(t)?e._matrixArray:S6(e._matrixArray,t);return this._newMatrix(r,e)}row({id:e,row:t}){if(e)return u0(t)?p1(0,void 0,e.typeName):e._value[t]}set({id:e,row:t,column:r,value:M}){e&&(u0(t)||u0(r)||(M===void 0&&e._isNumber&&(M=NaN),this._array.set({id:e._value[t],index:r,value:M}),this._getMatrixArray(e)))}sum({id1:e,id2:t}){if(!e)return;const r=WM(e._matrixArray,typeof t=="number"?t:t._matrixArray);return this._newMatrix(r,e)}copy({id:e}){if(e)return this._newMatrix(e._matrixArray,e)}diff({id1:e,id2:t}){if(!e)return;const r=B6(e._matrixArray,typeof t=="number"?t:t._matrixArray);return this._newMatrix(r,e)}rows({id:e}){if(e)return e._value.length}columns({id:e}){if(e)return e._matrixArray.length&&e._matrixArray[0].length}fill({id:e,value:t,from_row:r,to_row:M,from_column:n,to_column:b}){if(!e)return;u0(r)&&(r=0),u0(M)&&(M=this.rows({id:e})),u0(n)&&(n=0),u0(b)&&(b=this.columns({id:e}));let z=r||0;for(;z<(M||0);){let i=e._value[z];i||(i=p1(0,t,e.typeName),e._value[z]=i),this._array.fill({id:i,value:t,index_from:n,index_to:b}),z++}this._getMatrixArray(e)}kron({id1:e,id2:t}){if(!e)return;const r=N6(e._matrixArray,t==null?void 0:t._matrixArray);return this._newMatrix(r,e)}mode({id:e}){if(e)return Ap(d3(e._matrixArray))}mult({id1:e,id2:t}){if(!e)return;const r=typeof t=="number"?t:t!=null&&t._matrixArray?t._matrixArray:(t==null?void 0:t._value)||NaN,M=Dr(e._matrixArray,r);if(t!=null&&t.isArray){const n=p1(0,void 0,e.typeName);return n._value=M,n}return this._newMatrix(M,e)}pinv({id:e}){if(!e)return;const t=x6(e._matrixArray);return this._newMatrix(t,e)}rank({id:e}){if(e)return this._matrixRank(e._matrixArray)}sort({id:e,column:t,order:r}){e&&(u0(t)&&(t=0),e._value.sort((M,n)=>{const b=M._value[t],z=n._value[t];return r!==ur.descending?b-z:z-b}),this._getMatrixArray(e))}trace({id:e}){if(e)return T6(e._matrixArray)}concat({id1:e,id2:t}){if(e){for(const r of t._value)e._value.push(r);return this._getMatrixArray(e),e}}median({id:e}){if(e)return v3(e._matrixArray)}add_col({id:e,column:t,array_id:r}){if(e){u0(t)&&(t=this.columns({id:e}));for(const[M,n]of e._value.entries())this._array.insert({id:n,index:t,value:r?r._value[M]:void 0});this._getMatrixArray(e)}}add_row({id:e,row:t,array_id:r}){e&&(u0(t)&&(t=this.rows({id:e})),e._value.splice(t,0,r||p1(this.columns({id:e}),void 0,e.typeName)),this._getMatrixArray(e))}is_zero({id:e}){if(e)return e._matrixArray.every(t=>t.every(r=>r===0))}reshape({id:e,rows:t=0,columns:r=0},M){if(!e)return;if(t*r!==(this.columns({id:e})||0)*(this.rows({id:e})||0)){this._errorListener.addError(N1.matrixRehapeErr,M,K0.Error);return}const n=g6(e._matrixArray,[t,r]);e._value=n.map(b=>{const z=p1(0,void 0,e.typeName);return z._value=[...b],z}),this._getMatrixArray(e)}reverse({id:e}){if(e){e._value.reverse();for(const t of e._value)t._value.reverse();this._getMatrixArray(e)}}is_binary({id:e}){if(e)return e._matrixArray.every(t=>t.every(r=>r===0||r===1))}is_square({id:e}){if(e)return this.rows({id:e})===this.columns({id:e})}submatrix({id:e,from_row:t,to_row:r,from_column:M,to_column:n}){if(!e)return;u0(t)&&(t=0),u0(r)&&(r=this.rows({id:e})),u0(M)&&(M=0),u0(n)&&(n=this.columns({id:e}));const b=e._matrixArray.splice(t,r),z=[];for(const i of b)z.push(i.splice(M,n));return this._newMatrix(z,e)}swap_rows({id:e,row1:t,row2:r}){if(!e||u0(t)||u0(r))return;const M=e._value[t],n=e._value[r];e._value[t]=n,e._value[r]=M,this._getMatrixArray(e)}transpose({id:e}){if(!e)return;const t=h3(e._matrixArray);return this._newMatrix(t,e)}remove_col({id:e,column:t}){if(!e)return;u0(t)&&(t=this.columns({id:e}));const r=[];for(const n of e._value){const b=this._array.remove({id:n,index:t});r.push(b)}const M=p1(0,void 0,e.typeName);return M._value=r,this._getMatrixArray(e),M}remove_row({id:e,row:t}){if(!e)return;u0(t)&&(t=this.rows({id:e}));const r=e._value.splice(t,1);return this._getMatrixArray(e),r[0]}eigenvalues({id:e}){if(!e)return;const t=new F3(new I3(e._matrixArray)),r=p1(0,void 0,e.typeName);return r._value=t.realEigenvalues,r}is_diagonal({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;if(t!==r)return!1;const M=e._matrixArray;for(let n=0;n<t;n++)for(let b=0;b<r;b++)if(n!==b&&M[n][b]!==0)return!1;return!0}is_identity({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;if(t!==r)return!1;const M=e._matrixArray;for(let n=0;n<t;n++)for(let b=0;b<r;b++)if(n!==b&&M[n][b]!==0||n===b&&M[n][b]!==1)return!1;return!0}eigenvectors({id:e}){if(!e)return;const t=new F3(new I3(e._matrixArray));return this._newMatrix(t.eigenvectorMatrix.to2DArray(),e)}is_symmetric({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;if(t!==r)return!1;const M=e._matrixArray;for(let n=0;n<t;n++)for(let b=n+1;b<r;b++)if(M[n][b]!==M[b][n])return!1;return!0}swap_columns({id:e,column1:t,column2:r}){if(e&&!(u0(t)||u0(r))){for(const M of e._value){const n=M._value[t],b=M._value[r];this._array.set({id:M,index:t,value:b}),this._array.set({id:M,index:r,value:n})}this._getMatrixArray(e)}}is_stochastic({id:e}){if(!e)return;const t=e._matrixArray;for(let r=0;r<t.length;r++){let M=0;for(let n=0;n<t[r].length;n++){if(t[r][n]<0)return!1;M+=t[r][n]}if(Math.abs(M-1)>Number.EPSILON)return!1}return!0}is_triangular({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;return t!==r?!1:this._isUpperTriangular(t,e._matrixArray)||this._isLowerTriangular(t,e._matrixArray)}elements_count({id:e}){if(e)return R6(e._matrixArray)}is_antidiagonal({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;if(t!==r)return!1;const M=e._matrixArray;for(let n=0;n<t;n++)for(let b=0;b<t;b++)if(n+b!==t-1&&M[n][b]!==0)return!1;return!0}is_antisymmetric({id:e}){if(!e)return;const t=this.rows({id:e})||0,r=this.columns({id:e})||0;if(t!==r)return!1;const M=e._matrixArray;for(let n=0;n<t;n++)for(let b=0;b<t;b++)if(n!==b&&M[n][b]!==-M[b][n])return!1;return!0}_isUpperTriangular(e,t){for(let r=1;r<e;r++)for(let M=0;M<r;M++)if(t[r][M]!==0)return!1;return!0}_isLowerTriangular(e,t){for(let r=0;r<e-1;r++)for(let M=r+1;M<e;M++)if(t[r][M]!==0)return!1;return!0}_newMatrix(e,t){const r=P3(0,0,void 0,t.typeName);return r._value=e.map(M=>{const n=p1(0,void 0,t.typeName);return n._value=[...M],n}),this._getMatrixArray(r),r}_matrixRank(e){let t=0;const r=e.length,M=e[0].length,n=[...e].map(b=>[...b]);for(let b=0;b<r&&!(b>=M);b++){let z=b;for(;z<r&&n[z][b]===0;)z++;if(z===r)continue;if(z!==b){const c=n[z];n[z]=n[b],n[b]=c}const i=n[b][b];for(let c=0;c<M;c++)n[b][c]/=i;for(let c=b+1;c<r;c++){const O=n[c][b];n[c]=n[c].map((s,u)=>s-O*n[b][u]),n[c][b]=0}}for(let b=0;b<r;b++)n[b].some(z=>Number(z.toFixed(8))!==0)&&t++;return t}_getMatrixArray(e){e._matrixArray=e==null?void 0:e._value.map(t=>[...t._value])}}function P3(o=0,e=0,t=void 0,r){const M=[N0.INT,N0.FLOAT].includes(r);t===void 0&&M&&(t=NaN);const n=Array.from(new Array(o),()=>p1(e,t,r));return{isMatrix:!0,typeName:r,type:e1.MATRIX,_isNumber:M,_value:n,_matrixArray:n.map(b=>[...b._value])}}class k_{constructor(e){C(this,"_variables");C(this,"_cacheData");this._variables=e,this._cacheData={}}get _timeframeCacheData(){return this._cacheData}set _timeframeCacheData(e){this._cacheData=e}change({timeframe:e},t){if(!e)return!0;const{time:r,__period:M,bar_index:n}=this._variables,b=y2(e,r),z=y2(M,r);if(b<z)return!0;const i=`change_${t}`,c=this._cacheData[i];if((c==null?void 0:c.bar_index)===n)return(c==null?void 0:c.result)||!1;if(c)switch(c.type){case 1:const{nextTime:O,unit:s,preNum:u}=c;if(r>=O)return this._cacheData[i]={type:1,nextTime:O1(r).add(u,s).startOf(s).add(this._variables._offsetTime,"hour").valueOf(),unit:s,preNum:u,bar_index:n,result:!0},!0;break;default:if(c.offset){if(c.currentTime+c.offset<=r)return this._cacheData[i]={currentTime:r,offset:0,bar_index:n,result:!0},!0}else if(c.currentTime+b*1e3<=r)return this._cacheData[i]={currentTime:r,offset:0,bar_index:n,result:!0},!0;break}else{const[O,s]=ht(e);if(/[DWM]/.test(e)){const u=O1(r).add(O,s).startOf(s).add(this._variables._offsetTime,"hour").valueOf();this._cacheData[i]={type:1,nextTime:u,unit:s,preNum:O,bar_index:n,result:!1}}else{const u=this._calcTimeOffset(r,e);this._cacheData[i]={currentTime:r,offset:u,bar_index:n,result:!1}}return!1}return!1}in_seconds({timeframe:e}={}){const{time:t,__period:r}=this._variables;return y2(e||r,t)}from_seconds({seconds:e=0}){const t=e*1e3,r=O1.duration(t);if(r.years())return"12M";const n=r.asMonths();if($o(n))return`${n}M`;const b=r.asWeeks();if($o(b))return`${b}W`;const z=r.asDays();if(z>=1)return`${Math.ceil(z)}D`;const i=r.asMinutes();if(i>=1)return`${Math.ceil(i)}`;const c=r.asSeconds();return c<=1?"1S":c<=5?"5S":c<=10?"10S":c<=15?"15S":c<=30?"30S":"1"}_calcTimeOffset(e,t){let r=0;if(t.includes("W")){const z=O1(e).day();t="1D",z!==1&&(r=(8-z)*60*60*24*1e3)}else if(t.includes("M")){const z=O1(e).date();t="1D";const i=O1(e).daysInMonth();z!==1&&(r=(i-z+1)*60*60*24*1e3)}const M=this._variables.getTimeTradingday(e,t),n=y2(t,e)*1e3,b=e-M-Math.floor((e-M)/n)*n;return r?r-b:b}}var $_=20,U_=1,Jt=1e6,k3=1e6,j_=-7,H_=21,Y_=!1,mM="[big.js] ",Qt=mM+"Invalid ",en=Qt+"decimal places",G_=Qt+"rounding mode",$3=mM+"Division by zero",R1={},Se=void 0,V_=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function U3(){function o(e){var t=this;if(!(t instanceof o))return e===Se?U3():new o(e);if(e instanceof o)t.s=e.s,t.e=e.e,t.c=e.c.slice();else{if(typeof e!="string"){if(o.strict===!0&&typeof e!="bigint")throw TypeError(Qt+"value");e=e===0&&1/e<0?"-0":String(e)}K_(t,e)}t.constructor=o}return o.prototype=R1,o.DP=$_,o.RM=U_,o.NE=j_,o.PE=H_,o.strict=Y_,o.roundDown=0,o.roundHalfUp=1,o.roundHalfEven=2,o.roundUp=3,o}function K_(o,e){var t,r,M;if(!V_.test(e))throw Error(Qt+"number");for(o.s=e.charAt(0)=="-"?(e=e.slice(1),-1):1,(t=e.indexOf("."))>-1&&(e=e.replace(".","")),(r=e.search(/e/i))>0?(t<0&&(t=r),t+=+e.slice(r+1),e=e.substring(0,r)):t<0&&(t=e.length),M=e.length,r=0;r<M&&e.charAt(r)=="0";)++r;if(r==M)o.c=[o.e=0];else{for(;M>0&&e.charAt(--M)=="0";);for(o.e=t-r-1,o.c=[],t=0;r<=M;)o.c[t++]=+e.charAt(r++)}return o}function Zt(o,e,t,r){var M=o.c;if(t===Se&&(t=o.constructor.RM),t!==0&&t!==1&&t!==2&&t!==3)throw Error(G_);if(e<1)r=t===3&&(r||!!M[0])||e===0&&(t===1&&M[0]>=5||t===2&&(M[0]>5||M[0]===5&&(r||M[1]!==Se))),M.length=1,r?(o.e=o.e-e+1,M[0]=1):M[0]=o.e=0;else if(e<M.length){if(r=t===1&&M[e]>=5||t===2&&(M[e]>5||M[e]===5&&(r||M[e+1]!==Se||M[e-1]&1))||t===3&&(r||!!M[0]),M.length=e,r){for(;++M[--e]>9;)if(M[e]=0,e===0){++o.e,M.unshift(1);break}}for(e=M.length;!M[--e];)M.pop()}return o}function er(o,e,t){var r=o.e,M=o.c.join(""),n=M.length;if(e)M=M.charAt(0)+(n>1?"."+M.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)M="0"+M;M="0."+M}else if(r>0)if(++r>n)for(r-=n;r--;)M+="0";else r<n&&(M=M.slice(0,r)+"."+M.slice(r));else n>1&&(M=M.charAt(0)+"."+M.slice(1));return o.s<0&&t?"-"+M:M}R1.abs=function(){var o=new this.constructor(this);return o.s=1,o},R1.cmp=function(o){var e,t=this,r=t.c,M=(o=new t.constructor(o)).c,n=t.s,b=o.s,z=t.e,i=o.e;if(!r[0]||!M[0])return r[0]?n:M[0]?-b:0;if(n!=b)return n;if(e=n<0,z!=i)return z>i^e?1:-1;for(b=(z=r.length)<(i=M.length)?z:i,n=-1;++n<b;)if(r[n]!=M[n])return r[n]>M[n]^e?1:-1;return z==i?0:z>i^e?1:-1},R1.div=function(o){var e=this,t=e.constructor,r=e.c,M=(o=new t(o)).c,n=e.s==o.s?1:-1,b=t.DP;if(b!==~~b||b<0||b>Jt)throw Error(en);if(!M[0])throw Error($3);if(!r[0])return o.s=n,o.c=[o.e=0],o;var z,i,c,O,s,u=M.slice(),l=z=M.length,q=r.length,A=r.slice(0,z),h=A.length,d=o,m=d.c=[],_=0,R=b+(d.e=e.e-o.e)+1;for(d.s=n,n=R<0?0:R,u.unshift(0);h++<z;)A.push(0);do{for(c=0;c<10;c++){if(z!=(h=A.length))O=z>h?1:-1;else for(s=-1,O=0;++s<z;)if(M[s]!=A[s]){O=M[s]>A[s]?1:-1;break}if(O<0){for(i=h==z?M:u;h;){if(A[--h]<i[h]){for(s=h;s&&!A[--s];)A[s]=9;--A[s],A[h]+=10}A[h]-=i[h]}for(;!A[0];)A.shift()}else break}m[_++]=O?c:++c,A[0]&&O?A[h]=r[l]||0:A=[r[l]]}while((l++<q||A[0]!==Se)&&n--);return!m[0]&&_!=1&&(m.shift(),d.e--,R--),_>R&&Zt(d,R,t.RM,A[0]!==Se),d},R1.eq=function(o){return this.cmp(o)===0},R1.gt=function(o){return this.cmp(o)>0},R1.gte=function(o){return this.cmp(o)>-1},R1.lt=function(o){return this.cmp(o)<0},R1.lte=function(o){return this.cmp(o)<1},R1.minus=R1.sub=function(o){var e,t,r,M,n=this,b=n.constructor,z=n.s,i=(o=new b(o)).s;if(z!=i)return o.s=-i,n.plus(o);var c=n.c.slice(),O=n.e,s=o.c,u=o.e;if(!c[0]||!s[0])return s[0]?o.s=-i:c[0]?o=new b(n):o.s=1,o;if(z=O-u){for((M=z<0)?(z=-z,r=c):(u=O,r=s),r.reverse(),i=z;i--;)r.push(0);r.reverse()}else for(t=((M=c.length<s.length)?c:s).length,z=i=0;i<t;i++)if(c[i]!=s[i]){M=c[i]<s[i];break}if(M&&(r=c,c=s,s=r,o.s=-o.s),(i=(t=s.length)-(e=c.length))>0)for(;i--;)c[e++]=0;for(i=e;t>z;){if(c[--t]<s[t]){for(e=t;e&&!c[--e];)c[e]=9;--c[e],c[t]+=10}c[t]-=s[t]}for(;c[--i]===0;)c.pop();for(;c[0]===0;)c.shift(),--u;return c[0]||(o.s=1,c=[u=0]),o.c=c,o.e=u,o},R1.mod=function(o){var e,t=this,r=t.constructor,M=t.s,n=(o=new r(o)).s;if(!o.c[0])throw Error($3);return t.s=o.s=1,e=o.cmp(t)==1,t.s=M,o.s=n,e?new r(t):(M=r.DP,n=r.RM,r.DP=r.RM=0,t=t.div(o),r.DP=M,r.RM=n,this.minus(t.times(o)))},R1.neg=function(){var o=new this.constructor(this);return o.s=-o.s,o},R1.plus=R1.add=function(o){var e,t,r,M=this,n=M.constructor;if(o=new n(o),M.s!=o.s)return o.s=-o.s,M.minus(o);var b=M.e,z=M.c,i=o.e,c=o.c;if(!z[0]||!c[0])return c[0]||(z[0]?o=new n(M):o.s=M.s),o;if(z=z.slice(),e=b-i){for(e>0?(i=b,r=c):(e=-e,r=z),r.reverse();e--;)r.push(0);r.reverse()}for(z.length-c.length<0&&(r=c,c=z,z=r),e=c.length,t=0;e;z[e]%=10)t=(z[--e]=z[e]+c[e]+t)/10|0;for(t&&(z.unshift(t),++i),e=z.length;z[--e]===0;)z.pop();return o.c=z,o.e=i,o},R1.pow=function(o){var e=this,t=new e.constructor("1"),r=t,M=o<0;if(o!==~~o||o<-k3||o>k3)throw Error(Qt+"exponent");for(M&&(o=-o);o&1&&(r=r.times(e)),o>>=1,!!o;)e=e.times(e);return M?t.div(r):r},R1.prec=function(o,e){if(o!==~~o||o<1||o>Jt)throw Error(Qt+"precision");return Zt(new this.constructor(this),o,e)},R1.round=function(o,e){if(o===Se)o=0;else if(o!==~~o||o<-Jt||o>Jt)throw Error(en);return Zt(new this.constructor(this),o+this.e+1,e)},R1.sqrt=function(){var o,e,t,r=this,M=r.constructor,n=r.s,b=r.e,z=new M("0.5");if(!r.c[0])return new M(r);if(n<0)throw Error(mM+"No square root");n=Math.sqrt(+er(r,!0,!0)),n===0||n===1/0?(e=r.c.join(""),e.length+b&1||(e+="0"),n=Math.sqrt(e),b=((b+1)/2|0)-(b<0||b&1),o=new M((n==1/0?"5e":(n=n.toExponential()).slice(0,n.indexOf("e")+1))+b)):o=new M(n+""),b=o.e+(M.DP+=4);do t=o,o=z.times(t.plus(r.div(t)));while(t.c.slice(0,b).join("")!==o.c.slice(0,b).join(""));return Zt(o,(M.DP-=4)+o.e+1,M.RM)},R1.times=R1.mul=function(o){var e,t=this,r=t.constructor,M=t.c,n=(o=new r(o)).c,b=M.length,z=n.length,i=t.e,c=o.e;if(o.s=t.s==o.s?1:-1,!M[0]||!n[0])return o.c=[o.e=0],o;for(o.e=i+c,b<z&&(e=M,M=n,n=e,c=b,b=z,z=c),e=new Array(c=b+z);c--;)e[c]=0;for(i=z;i--;){for(z=0,c=b+i;c>i;)z=e[c]+n[i]*M[c-i-1]+z,e[c--]=z%10,z=z/10|0;e[c]=z}for(z?++o.e:e.shift(),i=e.length;!e[--i];)e.pop();return o.c=e,o},R1.toExponential=function(o,e){var t=this,r=t.c[0];if(o!==Se){if(o!==~~o||o<0||o>Jt)throw Error(en);for(t=Zt(new t.constructor(t),++o,e);t.c.length<o;)t.c.push(0)}return er(t,!0,!!r)},R1.toFixed=function(o,e){var t=this,r=t.c[0];if(o!==Se){if(o!==~~o||o<0||o>Jt)throw Error(en);for(t=Zt(new t.constructor(t),o+t.e+1,e),o=o+t.e+1;t.c.length<o;)t.c.push(0)}return er(t,!1,!!r)},R1[Symbol.for("nodejs.util.inspect.custom")]=R1.toJSON=R1.toString=function(){var o=this,e=o.constructor;return er(o,o.e<=e.NE||o.e>=e.PE,!!o.c[0])},R1.toNumber=function(){var o=+er(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(o.toString()))throw Error(mM+"Imprecise conversion");return o},R1.toPrecision=function(o,e){var t=this,r=t.constructor,M=t.c[0];if(o!==Se){if(o!==~~o||o<1||o>Jt)throw Error(Qt+"precision");for(t=Zt(new r(t),o,e);t.c.length<o;)t.c.push(0)}return er(t,o<=t.e||t.e<=r.NE||t.e>=r.PE,!!M)},R1.valueOf=function(){var o=this,e=o.constructor;if(e.strict===!0)throw Error(mM+"valueOf disallowed");return er(o,o.e<=e.NE||o.e>=e.PE,!0)};var gM=U3();class J_{constructor(e,t){C(this,"_errorListener");C(this,"_intlNumberFormatter");C(this,"_precision");C(this,"_intlFormat");this._errorListener=e,this._precision=t,this._intlNumberFormatter=new Intl.NumberFormat("en",{notation:"compact",maximumFractionDigits:3}),this._intlFormat=new Intl.NumberFormat("en-US")}pos({source:e="",str:t=""}){return e==null?void 0:e.indexOf(t)}trim({source:e=""}){return e==null?void 0:e.trim()}lower({source:e=""}){return e==null?void 0:e.toLocaleLowerCase()}match({source:e="",regex:t=""}){const r=e==null?void 0:e.match(new RegExp(t));return r?r[0]:""}split({string:e="",separator:t=""}){const r=e==null?void 0:e.split(t),M=p1(0,void 0,N0.STRING);return M._value=r||[],M}upper({source:e=""}){return e==null?void 0:e.toLocaleUpperCase()}format({formatString:e=""},t){return this._strFormat(e,t)}length({string:e=""}){return e==null?void 0:e.length}repeat({source:e="",repeat:t,separator:r=""},M){if(u0(t)){this._errorListener.addError(N1.arrLenErr,M,K0.Error);return}return Array.from(new Array(t),()=>e).join(r)}replace({source:e="",target:t="",replacement:r="",occurrence:M}){u0(M)&&(M=0);let n=-1;for(let b=0;b<M+1&&(n=e.indexOf(t,n+1),n!==-1);b++);return n!==-1?e.substring(0,n)+r+e.substring(n+t.length):e}contains({source:e="",str:t=""}){return e==null?void 0:e.includes(t)}endswith({source:e="",str:t=""}){return e==null?void 0:e.endsWith(t)}tonumber({string:e=""}){if(/[^[-\d].]/.test(e))return;const t=parseFloat(e);return isNaN(t)?void 0:t}tostring({value:e,format:t}){if(e===void 0)return"NaN";if(typeof e=="object"){if(e.isArray)return this._arrToStr(e._value,t);if(e.isMatrix){const r=[];for(const M of e._matrixArray)r.push(this._arrToStr(M,t));return r.join(`
76
- `)}}if(typeof e=="string")return e;if(typeof e=="boolean")return String(e);if(typeof e=="number")return String(this._toStringFormat(e,t))}_arrToStr(e,t){return`[${e.map(M=>typeof M=="number"?this._toStringFormat(M,t):M).toString()}]`}substring({source:e="",begin_pos:t=0,end_pos:r}){return u0(t)&&(t=0),u0(r)&&(r=void 0),e==null?void 0:e.substring(t,r)}startswith({source:e="",str:t=""}){return e==null?void 0:e.startsWith(t)}format_time({time:e,format:t="yyyy-MM-dd'T'HH:mm:ssZ",timezone:r}){return u0(e)&&(e=0),_e(e,r).format(t)}replace_all({source:e="",target:t="",replacement:r=""}){return e==null?void 0:e.replace(new RegExp(t,"g"),r)}_toStringFormat(e,t){if(!t)return this._numberDef(e);switch(t){case A1.mintick:return e==null?void 0:e.toFixed(this._precision);case A1.percent:return`${Number(e.toFixed(2))}%`;case A1.volume:return this._intlNumberFormatter.format(Math.round(e));default:return this._formatOthers(e,t)}}_numberDef(e){if(!e)return e;const t=String(Number(e.toFixed(10)));return/[eE]/.test(t)?new gM(t).toFixed():t}_formatOthers(e,t){var z;if(u0(e))return NaN;let[r,M]=t.split(".");t.split("%").length===2&&(e=Number((e*100).toFixed(2)));let[n,b=""]=String(e).split(".");if(r.includes("0")){r=r.replace(/#/g,"");const i=r.split("0");let c=i.length-1;for(;c>n.length;)n=`0${n}`,c--;i.splice(1,0,n),n=i.join("")}else if(r.includes("#")){if(r.includes(",")){const i=r.split(","),c=((z=i[i.length-1])==null?void 0:z.replace(/[^#]/g,"").length)||0;c&&(n=n.replace(new RegExp(`\\B(?=(\\d{${c}})+(?!\\d))`,"g"),",")),r=i.join("")}n=r.replace(/#/,n).replace(/#/g,"")}else n=`${r}${n}`;if(M&&M.includes("0")){M=M.replace(/#/g,"");const i=M.split("0");let c=i.length-1;if(b.length>c)b=b.substring(0,c);else for(;c>b.length;)b=`${b}0`,c--;return i.push(b),b=i.join(""),`${n}.${b}`}else if(M&&M.includes("#")){const i=M.split("#").length-1,c=+`${n}.${b}`;if(!isNaN(c)){const O=`${c.toFixed(i)}${M.replace(/#/g,"")}`,s=Number(O);return isNaN(s)?O:s}b=`${b.substring(0,i)}${M.replace(/#/g,"")}`}else b=M||"";if(b){const i=+`${n}.${b}`;return isNaN(i)?`${n}.${b}`:i}else return n}_formatNumber(e,t){if(!t)return Number(e==null?void 0:e.toFixed(this._precision));switch(t){case"integer":return String(Math.round(e));case"currency":return`$${e}`;case"percent":return`${e*100}%`;default:return this._formatOthers(e,t)}}strformat({formatString:e=""},t,r){return this._strFormat(e,t,r)}_strFormat(e,t,r){return e.replace(/{[^{}]+}/g,M=>{if(!M)return M;const n=M.replace(/[{}]/g,"").split(","),b=Number(n[0]);if(isNaN(b)||t.length<=b)return M;const z=t[b];if(n.length===1)return typeof z=="number"?r?this._intlFormat.format(z):Number(z.toFixed(this._precision)):z===void 0?"":z;if(n.length===2){const i=n[1].trim();return i==="number"?r?this._intlFormat.format(z):Number(z.toFixed(this._precision)):i==="date"?O1(z).format("LL"):M}else{const i=n[1].trim(),c=n[2].trim();if(i==="number")return this._formatNumber(z,c);if(i==="date"||i==="time"){let O="YYYY-MM-DD";switch(c){case"long":O="LL";break;case"short":O="L";break;default:c&&(O=c)}return O1(z).format(O)}return M}})}}class Q_{constructor(){}new({type:e}){const t=e.split(",");return j3(t)}copy({id:e}){if(!e)return;const t=j3([e.keyTypeName,e.typeName]);return t._value=Object.assign(Object.create(null),e._value),t}get({id:e,key:t}){if(e)return e._value[t]}put({id:e,key:t,value:r}){if(!e)return;const M=e._value[t];return e._value[t]=r,M}keys({id:e}){if(!e)return;const t=p1(0,void 0,e.keyTypeName);let r=Object.keys(e._value);return[N0.INT,N0.FLOAT].includes(e.keyTypeName)?r=r.map(M=>M==="undefined"?void 0:parseFloat(M)):e.keyTypeName===N0.BOOL&&(r=r.map(M=>M==="undefined"?void 0:M==="true")),t._value=r,t}size({id:e}){if(e)return Object.keys(e._value).length}clear({id:e}){e&&(e._value=Object.create(null))}remove({id:e,key:t}){if(!e)return;const r=e._value[t];return delete e._value[t],r}values({id:e}){if(!e)return;const t=p1(0,void 0,e.typeName);return t._value=Object.values(e._value),t}put_all({id:e,id2:t}){if(e){if(!t)return e;Object.assign(e._value,t._value)}}contains({id:e,key:t}){if(e)return t in e._value}}function j3(o){return{isMap:!0,keyTypeName:o[0],typeName:o[1],_value:Object.create(null),type:e1.MAP}}class Z_{constructor(e){C(this,"_variables");this._variables=e}new({price:e,time:t,index:r}){return RM(e,r,t)}now({price:e}){const{time:t,bar_index:r}=this._variables;return RM(e,r,t)}copy({id:e}){if(e)return RM(e.price,e.index,e.time)}from_index({price:e,index:t}){return RM(e,t)}from_time({price:e,time:t}){return RM(e,void 0,t)}}function RM(o,e,t){return{price:o,index:e&&Math.floor(e),time:t,type:e1.CHART_POINT,typeName:N0.CHART_POINT}}const em=["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"],tm=["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"];class rm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultLabel",{text:"",xloc:w1.bar_index,yloc:te.price,size:f2.normal,style:T1.styleLabelDown,textalign:S0.alignCenter});this._variables=e,this._errorListener=t}new(e,t,r){D0(this._errorListener,"label.new",this._variables.__requestName,t);const{time:M,high:n,low:b,bar_index:z}=this._variables,i=`label_${t}_${z}`;e=this._parameterHandle(e,r),I1(e,["color","textcolor"]);const c={...this._defaultLabel,...e,id:i,time:M,high:n,low:b,bar_index:z};e.x&&(c.x=e.x&&Math.floor(e.x)),e.point&&(c.x=c.xloc===w1.bar_index?e.point.index:e.point.time,c.y=e.point.price),c.yloc===te.abovebar?c.y=n:c.yloc===te.belowbar&&(c.y=b),this._verfiyArgs(e,t);const O=H3(i,c);return t.startsWith("export")||this._variables.label.add(i,c,O),O}_parameterHandle(e,t){const{x:r,y:M,point:n,...b}=e;if(typeof n=="object"||typeof r=="number"||typeof M=="number")return e;const z=b;if(t[0]===em[0]&&(typeof n=="number"||this._preVerfiyArgs(e)))for(const[i,c]of t.entries()){const O=z[c];z[c]=void 0,z[tm[i]]=O}return z}_preVerfiyArgs(e){const{xloc:t,yloc:r,style:M,size:n,textalign:b,text_font_family:z}=e;return this._paramVerfiyHandle(M,Object.values(T1))||this._paramVerfiyHandle(t,Object.values(w1))||this._paramVerfiyHandle(r,Object.values(te))||this._paramVerfiyHandle(n,Object.values(f2))||this._paramVerfiyHandle(b,[S0.alignLeft,S0.alignCenter,S0.alignRight])||this._paramVerfiyHandle(z,Object.values(Ue))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{xloc:r,yloc:M,style:n,size:b,textalign:z,text_font_family:i}=e,c="label.new";this._paramVerfiy(n,t,c,Object.values(T1),"style"),this._paramVerfiy(r,t,c,Object.values(w1),"xloc"),this._paramVerfiy(M,t,c,Object.values(te),"yloc"),this._paramVerfiy(b,t,c,Object.values(f2),"size"),this._paramVerfiy(z,t,c,[S0.alignLeft,S0.alignCenter,S0.alignRight],"textalign"),this._paramVerfiy(i,t,c,Object.values(Ue),"text_font_family")}_paramVerfiy(e="",t,r,M,n){this._paramVerfiyHandle(e,M)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}label(e){return e.x}copy({id:e},t){if(!e)return;D0(this._errorListener,"label.copy",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`label_${t}_${r}`,n=this._getLabel(e),b={...n||{},id:M,bar_index:r},z=H3(M,b);return n&&this._variables.label.add(M,b,z),z}get_x({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_x",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.x}get_y({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_y",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.y}set_x({id:e,x:t},r){if(!e)return;D0(this._errorListener,"label.set_x",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.x=t&&Math.floor(t))}set_y({id:e,y:t},r){if(!e)return;D0(this._errorListener,"label.set_y",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.y=t)}delete({id:e},t){if(!e)return;D0(this._errorListener,"label.delete",this._variables.__requestName,t);const r=this._getLabel(e);this._variables.label.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_text({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_text",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.text}set_xy({id:e,x:t,y:r},M){if(!e)return;D0(this._errorListener,"label.set_xy",this._variables.__requestName,M);const n=this._getLabel(e);n&&(n.x=t&&Math.floor(t),n.y=r)}set_size({id:e,size:t},r){if(!e)return;D0(this._errorListener,"label.set_size",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.size=t),this._paramVerfiy(t,r,"label.set_size",Object.values(f2),"size")}set_xloc({id:e,x:t,xloc:r},M){if(!e)return;D0(this._errorListener,"label.set_xloc",this._variables.__requestName,M);const n=this._getLabel(e);n&&(n.x=t&&Math.floor(t),n.xloc=r,this._paramVerfiy(r,M,"label.set_xloc",Object.values(w1),"xloc"))}set_yloc({id:e,yloc:t},r){if(!e)return;D0(this._errorListener,"label.set_yloc",this._variables.__requestName,r);const M=this._getLabel(e),{high:n,low:b}=this._variables;M&&(M.yloc=t,t===te.abovebar?M.y=n:t===te.belowbar&&(M.y=b),this._paramVerfiy(t,r,"label.set_yloc",Object.values(te),"yloc"))}set_style({id:e,style:t},r){if(!e)return;D0(this._errorListener,"label.set_style",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.style=t),this._paramVerfiy(t,r,"label.set_style",Object.values(T1),"style")}set_color({id:e,...t},r){if(!e)return;D0(this._errorListener,"label.set_color",this._variables.__requestName,r);const M=this._getLabel(e);I1(t,["color"]),M&&(M.color=t.color)}set_tooltip({id:e,tooltip:t},r){if(!e)return;D0(this._errorListener,"label.set_tooltip",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.tooltip=t)}set_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"label.set_point",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.x=M.xloc===w1.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,M.y=t==null?void 0:t.price)}set_text({id:e,text:t},r){if(!e)return;D0(this._errorListener,"label.set_text",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.text=t)}set_textcolor({id:e,...t},r){if(!e)return;D0(this._errorListener,"label.set_textcolor",this._variables.__requestName,r);const M=this._getLabel(e);I1(t,["textcolor"]),M&&(M.textcolor=t.textcolor)}set_textalign({id:e,textalign:t},r){if(!e)return;D0(this._errorListener,"label.set_textalign",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.textalign=t),this._paramVerfiy(t,r,"label.set_textalign",[S0.alignLeft,S0.alignCenter,S0.alignRight],"textalign")}set_text_font_family({id:e,text_font_family:t},r){if(!e)return;D0(this._errorListener,"label.set_text_font_family",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.text_font_family=t),this._paramVerfiy(t,r,"label.set_text_font_family",Object.values(Ue),"text_font_family")}_getLabel(e){return this._variables.label.get(e.id)||e.data}}function H3(o,e){return{type:e1.LABEL,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}const Mm={freq_all:fe.freqAll,freq_once_per_bar:fe.freqOncePerBar,freq_once_per_bar_close:fe.freqOncePerBarClose},om={gaps_off:ke.gapsOff,gaps_on:ke.gapsOn,lookahead_off:ke.lookaheadOff,lookahead_on:ke.lookaheadOn},xr={aqua:"#00BCD4",black:"#363A45",blue:"#2962ff",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#FF5252",silver:"#B2B5BE",teal:"#00897B",white:"#FFFFFF",yellow:"#FFEB3B"},Y3={AUD:"AUD",BTC:"BTC",CAD:"CAD",CHF:"CHF",ETH:"ETH",EUR:"EUR",GBP:"GBP",HKD:"HKD",INR:"INR",JPY:"JPY",KRW:"KRW",MYR:"MYR",NOK:"NOK",NONE:"NONE",NZD:"NZD",RUB:"RUB",SEK:"SEK",SGD:"SGD",TRY:"TRY",USD:"USD",USDT:"USDT",ZAR:"ZAR"},nm={friday:6,monday:2,saturday:7,sunday:1,thursday:5,tuesday:3,wednesday:4},G3={all:[le.dataWindow,le.pane,le.priceScale,le.statusLine],data_window:[le.dataWindow],none:[],pane:[le.pane],price_scale:[le.priceScale],status_line:[le.statusLine]},bm={both:P2.both,left:P2.left,none:P2.none,right:P2.right},pm={inherit:A1.inherit,mintick:A1.mintick,percent:A1.percent,price:A1.price,volume:A1.volume},zm={style_solid:HM.styleSolid,style_dashed:HM.styleDashed,style_dotted:HM.styleDotted},im={style_arrowdown:T1.styleArrowdown,style_arrowup:T1.styleArrowup,style_circle:T1.styleCircle,style_cross:T1.styleCross,style_diamond:T1.styleDiamond,style_flag:T1.styleFlag,style_label_center:T1.styleLabelCenter,style_label_down:T1.styleLabelDown,style_label_left:T1.styleLabelLeft,style_label_lower_left:T1.styleLabelLowerLeft,style_label_lower_right:T1.styleLabelLowerRight,style_label_right:T1.styleLabelRight,style_label_up:T1.styleLabelUp,style_label_upper_left:T1.styleLabelUpperLeft,style_label_upper_right:T1.styleLabelUpperRight,style_none:T1.styleNone,style_square:T1.styleSquare,style_text_outline:T1.styleTextOutline,style_triangledown:T1.styleTriangledown,style_triangleup:T1.styleTriangleup,style_xcross:T1.styleXcross},cm={style_arrow_both:G1.styleArrowBoth,style_arrow_left:G1.styleArrowLeft,style_arrow_right:G1.styleArrowRight,style_dashed:G1.styleDashed,style_dotted:G1.styleDotted,style_solid:G1.styleSolid},am={abovebar:$e.abovebar,absolute:$e.absolute,belowbar:$e.belowbar,bottom:$e.bottom,top:$e.top},sm={e:2.718281828459045,phi:1.618033988749895,pi:3.141592653589793,rphi:.6180339887498948},Om={style_area:ee.styleArea,style_areabr:ee.styleAreabr,style_circles:ee.styleCircles,style_columns:ee.styleColumns,style_cross:ee.styleCross,style_histogram:ee.styleHistogram,style_line:ee.styleLine,style_linebr:ee.styleLinebr,style_stepline:ee.styleStepline,style_stepline_diamond:ee.styleSteplineDiamond,style_steplinebr:ee.styleSteplinebr},um={bottom_center:k2.bottomCenter,bottom_left:k2.bottomLeft,bottom_right:k2.bottomRight,middle_center:k2.middleCenter,middle_left:k2.middleLeft,middle_right:k2.middleRight,top_center:k2.topCenter,top_left:k2.topLeft,top_right:k2.topRight},Am={left:YM.left,none:YM.none,right:YM.right},fm={arrowdown:X2.arrowdown,arrowup:X2.arrowup,circle:X2.circle,cross:X2.cross,diamond:X2.diamond,flag:X2.flag,labeldown:X2.labeldown,labelup:X2.labelup,square:X2.square,triangledown:X2.triangledown,triangleup:X2.triangleup,xcross:X2.xcross},lm={auto:f2.auto,huge:f2.huge,large:f2.large,normal:f2.normal,small:f2.small,tiny:f2.tiny},dm={cash:p2.cash,fixed:p2.fixed,percent_of_equity:p2.percentOfEquity,commission:{cash_per_contract:O2.cashPerContract,cash_per_order:O2.cashPerOrder,percent:O2.percent},direction:{all:a1.all,long:a1.long,short:a1.short},oca:{cancel:je.cancel,none:je.none,reduce:je.reduce}},qm={align_bottom:S0.alignBottom,align_center:S0.alignCenter,align_left:S0.alignLeft,align_right:S0.alignRight,align_top:S0.alignTop,wrap_auto:S0.wrapAuto,wrap_none:S0.wrapNone},hm={bar_index:w1.bar_index,bar_time:w1.bar_time},Wm={abovebar:te.abovebar,belowbar:te.belowbar,price:te.price},_m={actual:GM.actual,estimate:GM.estimate,standardized:GM.standardized};class hp{constructor(){C(this,"adjustment",{dividends:jM.dividends,none:jM.none,splits:jM.splits});C(this,"alert",Mm);C(this,"barmerge",om);C(this,"color",xr);C(this,"currency",Y3);C(this,"dayofweek",nm);C(this,"earnings",_m);C(this,"display",G3);C(this,"extend",bm);C(this,"font",{family_default:Ue.familyDefault,family_monospace:Ue.familyMonospace});C(this,"format",pm);C(this,"hline",zm);C(this,"label",im);C(this,"line",cm);C(this,"location",am);C(this,"math",sm);C(this,"order",{ascending:ur.ascending,descending:ur.descending});C(this,"plot",Om);C(this,"position",um);C(this,"scale",Am);C(this,"session",{extended:ft.extended,regular:ft.regular});C(this,"shape",fm);C(this,"size",lm);C(this,"splits",{denominator:"denominator",numerator:"numerator"});C(this,"strategy",dm);C(this,"text",qm);C(this,"xloc",hm);C(this,"yloc",Wm);C(this,"true",!0);C(this,"false",!1)}updateData(){}}class mm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultPolyline",{curved:!1,closed:!1,xloc:w1.bar_index,line_color:xr.blue,line_style:G1.styleSolid,line_width:1});this._variables=e,this._errorListener=t}new(e,t){var z;D0(this._errorListener,"polyline.new",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`polyline_${t}_${r}`,n=Object.assign({},this._defaultPolyline,e,{id:M,bar_index:r,points:(z=e.points)==null?void 0:z._value.map(i=>({time:i.time,index:i.index,price:i.price}))});I1(n,["line_color","fill_color"]);const b=gm(M,n);return this._verfiyArgs(e,t),t.startsWith("export")||this._variables.polyline.add(M,n,b),b}_verfiyArgs(e,t){const{line_style:r,xloc:M}=e,n="polyline.new";this._paramVerfiy(r,t,n,Object.values(G1),"line_style"),this._paramVerfiy(M,t,n,Object.values(w1),"xloc")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}delete({id:e}){if(!e)return;const t=this._variables.polyline.get(e.id)||e.data;this._variables.polyline.delete(e.id,this._variables.bar_index,t==null?void 0:t.id)}}function gm(o,e){return{type:e1.POLYLINE,id:o,data:e,_suffix:"",isDraw:!0,preId:""}}const Rm=["first_point","second_point","xloc","extend","color","style","width","force_overlay"],vm=["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"];class nt{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultLine",{xloc:w1.bar_index,extend:P2.none,style:G1.styleSolid});this._variables=e,this._errorListener=t}new(e,t,r){D0(this._errorListener,"line.new",this._variables.__requestName,t);const{bar_index:M}=this._variables,n=`line_${t}_${M}`;e=this._parameterHandle(e,r);const{first_point:b,second_point:z,...i}=e;I1(i,["color"]);const c={...this._defaultLine,...i,id:n,bar_index:M},{x1:O,x2:s}=c;if(O&&(c.x1=O&&Math.floor(O)),s&&(c.x2=s&&Math.floor(s)),b&&z){const l=c.xloc===w1.bar_index?b==null?void 0:b.index:b==null?void 0:b.time,q=c.xloc===w1.bar_index?z==null?void 0:z.index:z==null?void 0:z.time;Object.assign(c,{x1:l,y1:b==null?void 0:b.price,x2:q,y2:z==null?void 0:z.price})}this._verfiyArgs(i,t);const u=V3(n,c);return t.startsWith("export")||this._variables.line.add(n,c,u),u}_parameterHandle(e,t){const{x1:r,y1:M,x2:n,y2:b,first_point:z,second_point:i,...c}=e;if(typeof z=="object"||typeof i=="object"||typeof r=="number"||typeof M=="number"||typeof n=="number"||typeof b=="number")return e;const O=c;if(t[0]===vm[0]&&(typeof r=="object"||typeof M=="object"||typeof n=="string"||typeof b=="string"||this._preVerfiyArgs(e)))for(const[s,u]of t.entries()){const l=O[u];O[u]=void 0,O[Rm[s]]=l}return O}_preVerfiyArgs(e){const{extend:t,xloc:r,style:M}=e;return this._paramVerfiyHandle(M,Object.values(G1))||this._paramVerfiyHandle(r,Object.values(w1))||this._paramVerfiyHandle(t,Object.values(P2))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{extend:r,xloc:M,style:n}=e,b="line.new";this._paramVerfiy(n,t,b,Object.values(G1),"style"),this._paramVerfiy(r,t,b,Object.values(P2),"extend"),this._paramVerfiy(M,t,b,Object.values(w1),"xloc")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}static __setFillKeys(e,t){e.fillKeys.includes(t)||e.fillKeys.push(t)}static __updateFillKeys(e,t,r){const M=e.fillKeys.findIndex(n=>n===t);M!==-1?e.fillKeys.splice(M,1,r):e.fillKeys.push(r)}line(e){return e.x}copy({id:e},t){if(!e)return;const{bar_index:r}=this._variables,M=`line_${t}_${r}`,n=this._getLine(e,t,"copy"),b={...n,id:M,bar_index:r,isVar:void 0},z=V3(M,b);return n&&this._variables.line.add(M,b,z),z}delete({id:e},t){if(!e)return;for(const M of e.fillKeys)this._variables.linefill.delete(M,this._variables.bar_index);const r=this._getLine(e,t,"delete");this._variables.line.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_x1({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_x1"))==null?void 0:r.x1}get_x2({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_x2"))==null?void 0:r.x2}get_y1({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_y1"))==null?void 0:r.y1}get_y2({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_y2"))==null?void 0:r.y2}set_x1({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"set_x1");M&&(M.x1=t&&Math.floor(t))}set_x2({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"set_x2");M&&(M.x2=t&&Math.floor(t))}set_y1({id:e,y:t},r){if(!e)return;const M=this._getLine(e,r,"set_y1");M&&(M.y1=t)}set_y2({id:e,y:t},r){if(!e)return;const M=this._getLine(e,r,"set_y2");M&&(M.y2=t)}set_xy1({id:e,x:t,y:r},M){if(!e)return;const n=this._getLine(e,M,"set_xy1");n&&(n.x1=t&&Math.floor(t),n.y1=r)}set_xy2({id:e,x:t,y:r},M){if(!e)return;const n=this._getLine(e,M,"set_xy2");n&&(n.x2=t&&Math.floor(t),n.y2=r)}set_xloc({id:e,xloc:t,x1:r,x2:M},n){if(!e)return;const b=this._getLine(e,n,"set_xloc");b&&(b.xloc=t,b.x1=r&&Math.floor(r),b.x2=M&&Math.floor(M),this._paramVerfiy(t,n,"line.set_xloc",Object.values(w1),"xloc"))}get_price({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"get_price");if(t===void 0)return t;if(M&&M.xloc===w1.bar_index){const{x1:n,y1:b,x2:z,y2:i}=M;return n===void 0||z===void 0||b===void 0||i===void 0?void 0:(i-b)/(z-n)*(t-n)+b}}set_color({id:e,...t},r){if(!e)return;const M=this._getLine(e,r,"set_color");M&&(I1(t,["color"]),M.color=t.color)}set_style({id:e,style:t},r){if(!e)return;const M=this._getLine(e,r,"set_style");M&&(M.style=t,this._paramVerfiy(t,r,"line.set_style",Object.values(G1),"style"))}set_width({id:e,width:t},r){if(!e)return;const M=this._getLine(e,r,"set_width");M&&(M.width=t)}set_extend({id:e,extend:t},r){if(!e)return;const M=this._getLine(e,r,"set_extend");M&&(M.extend=t,this._paramVerfiy(t,r,"line.set_extend",Object.values(P2),"extend"))}set_first_point({id:e,point:t},r){if(!e)return;const M=this._getLine(e,r,"set_first_point");if(M){const{index:n,time:b,price:z}=t||{},i=M.xloc===w1.bar_index?n:b,c=z;i&&(M.x1=i),c&&(M.y1=c)}}set_second_point({id:e,point:t},r){if(!e)return;const M=this._getLine(e,r,"set_second_point");if(M){const{index:n,time:b,price:z}=t||{},i=M.xloc===w1.bar_index?n:b,c=z;i&&(M.x2=i),c&&(M.y2=c)}}_getLine(e,t,r){return D0(this._errorListener,`line.${r}`,this._variables.__requestName,t),this._variables.line.get(e.id)||e.data}}function V3(o,e){return{type:e1.LINE,id:o,data:e,_suffix:"",preId:"",fillKeys:[],isDraw:!0}}class Lm{constructor(e){C(this,"_variables");this._variables=e}new(e,t){var q,A;const{line1:r,line2:M}=e,{bar_index:n,linefill:b}=this._variables,z=`linefill_${t}_${n}`,i=r==null?void 0:r.data,c=M==null?void 0:M.data,O=`${(i==null?void 0:i.id)||""}${(c==null?void 0:c.id)||""}`;i&&(i.linefills=i.linefills||[],i.linefills.push(z)),c&&(c.linefills=c.linefills||[],c.linefills.push(z)),I1(e,["color"]);const s={line1:i,line2:c,color:e.color,id:z,bar_index:n},u=this._verifyLineKey(O);u?(b.delete(u,n),r&&i&&(i.linefills=(q=i.linefills)==null?void 0:q.filter(h=>h!==u),nt.__updateFillKeys(r,u,z)),M&&c&&(c.linefills=(A=c.linefills)==null?void 0:A.filter(h=>h!==u),nt.__updateFillKeys(M,u,z))):(r&&nt.__setFillKeys(r,z),M&&nt.__setFillKeys(M,z));const l=Nm(z,s,O,r,M);return t.startsWith("export")||(i||c)&&b.add(z,s,l),l}_verifyLineKey(e){for(const[t,r]of this._variables.linefill.__allInstance)if(r.lineKey===e)return t}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables,M=e.id;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const n=e.id.split("_");n.pop(),e.id=`${n.join("_")}_${t}`}return e.line1&&nt.__updateFillKeys(e.line1,M,e.id),e.line2&&nt.__updateFillKeys(e.line2,M,e.id),r||(e.preId=e.id),e.id}delete({id:e}){var r,M;if(!e)return;const t=this._variables.linefill.get(e.id)||e.data;if(t){const{line1:n,line2:b}=t;n&&(n.linefills=(r=n.linefills)==null?void 0:r.filter(z=>z!==e.id)),b&&(b.linefills=(M=b.linefills)==null?void 0:M.filter(z=>z!==e.id))}e.line1=void 0,e.line2=void 0,this._variables.linefill.delete(e.id,this._variables.bar_index,t==null?void 0:t.id)}get_line1({id:e}){return e==null?void 0:e.line1}get_line2({id:e}){return e==null?void 0:e.line2}set_color({id:e,...t}){if(!e)return;const r=this._variables.linefill.get(e.id)||e.data;r&&(I1(t,["color"]),r.color=t.color)}}function Nm(o,e,t,r,M){return{type:e1.LINEFILL,id:o,data:e,_suffix:"",preId:"",line1:r,line2:M,isDraw:!0,lineKey:t}}const ym=["top_left","bottom_right","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"],Bm=["left","top","right","bottom","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"];class wm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultBox",{border_color:xr.blue,border_width:1,bgcolor:xr.blue,xloc:w1.bar_index,extend:P2.none,style:G1.styleSolid,text:"",text_size:f2.auto,text_color:xr.black,text_halign:S0.alignCenter,text_valign:S0.alignCenter,text_wrap:S0.wrapNone});this._variables=e,this._errorListener=t}box({x:e}){return e}new(e,t,r){D0(this._errorListener,"box.new",this._variables.__requestName,t);const{bar_index:M}=this._variables,n=`box_${t}_${M}`;e=this._parameterHandle(e,r);const{top_left:b,bottom_right:z,...i}=e,c={...this._defaultBox,...i,id:n,bar_index:M};I1(c,["border_color","bgcolor","text_color"]);const{left:O,right:s}=c;if(O&&(c.left=O&&Math.floor(O)),s&&(c.right=s&&Math.floor(s)),b){const{price:l,time:q,index:A}=b;c.top=l,c.left=c.xloc===w1.bar_index?A:q}if(z){const{price:l,time:q,index:A}=z;c.bottom=l,c.right=c.xloc===w1.bar_index?A:q}this._verfiyArgs(i,t);const u=K3(n,c);return t.startsWith("export")||this._variables.box.add(n,c,u),u}_parameterHandle(e,t){const{top_left:r,bottom_right:M,top:n,bottom:b,left:z,right:i,...c}=e;if(typeof r=="object"||typeof M=="object"||typeof n=="number"||typeof b=="number"||typeof z=="number"||typeof i=="number")return e;const O=c;if(t[0]===ym[0]&&(typeof r=="number"||typeof M=="number"||this._preVerfiyArgs(e)))for(const[s,u]of t.entries()){const l=O[u];O[u]=void 0,O[Bm[s]]=l}return O}_preVerfiyArgs(e){const{border_style:t,extend:r,xloc:M,text_size:n,text_halign:b,text_valign:z,text_wrap:i,text_font_family:c}=e;return this._paramVerfiyHandle(t,[G1.styleDashed,G1.styleDotted,G1.styleSolid])||this._paramVerfiyHandle(r,Object.values(P2))||this._paramVerfiyHandle(M,Object.values(w1))||this._paramVerfiyHandle(n,Object.values(f2))||this._paramVerfiyHandle(b,[S0.alignLeft,S0.alignCenter,S0.alignRight])||this._paramVerfiyHandle(z,[S0.alignBottom,S0.alignCenter,S0.alignTop])||this._paramVerfiyHandle(i,[S0.wrapAuto,S0.wrapNone])||this._paramVerfiyHandle(c,Object.values(Ue))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{border_style:r,extend:M,xloc:n,text_size:b,text_halign:z,text_valign:i,text_wrap:c,text_font_family:O}=e,s="box.new";this._paramVerfiy(r,t,s,[G1.styleDashed,G1.styleDotted,G1.styleSolid],"border_style"),this._paramVerfiy(M,t,s,Object.values(P2),"extend"),this._paramVerfiy(n,t,s,Object.values(w1),"xloc"),this._paramVerfiy(b,t,s,Object.values(f2),"text_size"),this._paramVerfiy(z,t,s,[S0.alignLeft,S0.alignCenter,S0.alignRight],"text_halign"),this._paramVerfiy(i,t,s,[S0.alignBottom,S0.alignCenter,S0.alignTop],"text_valign"),this._paramVerfiy(c,t,s,[S0.wrapAuto,S0.wrapNone],"text_wrap"),this._paramVerfiy(O,t,s,Object.values(Ue),"text_font_family")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}copy({id:e},t){if(!e)return;D0(this._errorListener,"box.copy",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`box_${t}_${r}`,n=this._getBox(e),b={...n,id:M,bar_index:r},z=K3(M,b);return n&&this._variables.box.add(M,b,z),z}delete({id:e},t){if(!e)return;D0(this._errorListener,"box.delete",this._variables.__requestName,t);const r=this._getBox(e)||e.data;this._variables.box.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_top({id:e},t){if(!e)return;D0(this._errorListener,"box.get_top",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.top}get_bottom({id:e},t){if(!e)return;D0(this._errorListener,"box.get_bottom",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.bottom}get_left({id:e},t){if(!e)return;D0(this._errorListener,"box.get_left",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.left}get_right({id:e},t){if(!e)return;D0(this._errorListener,"box.get_right",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.right}set_top({id:e,top:t},r){if(!e)return;D0(this._errorListener,"box.set_top",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.top=t)}set_bottom({id:e,bottom:t},r){if(!e)return;D0(this._errorListener,"box.set_bottom",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.bottom=t)}set_text({id:e,text:t},r){if(!e)return;D0(this._errorListener,"box.set_text",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text=t)}set_left({id:e,left:t},r){if(!e)return;D0(this._errorListener,"box.set_left",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.left=t&&Math.floor(t))}set_right({id:e,right:t},r){if(!e)return;D0(this._errorListener,"box.set_right",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.right=t&&Math.floor(t))}set_extend({id:e,extend:t},r){if(!e)return;D0(this._errorListener,"box.set_extend",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.extend=t,this._paramVerfiy(t,r,"box.set_extend",Object.values(P2),"extend"))}set_bgcolor({id:e,color:t},r){if(!e)return;D0(this._errorListener,"box.set_bgcolor",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.bgcolor=t,I1(M,["bgcolor"]))}set_border_color({id:e,color:t},r){if(!e)return;D0(this._errorListener,"box.set_border_color",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_color=t,I1(M,["border_color"]))}set_border_width({id:e,width:t},r){if(!e)return;D0(this._errorListener,"box.set_border_width",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_width=t)}set_border_style({id:e,style:t},r){if(!e)return;D0(this._errorListener,"box.set_border_style",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_style=t,this._paramVerfiy(t,r,"box.set_border_style",[G1.styleDashed,G1.styleDotted,G1.styleSolid],"style"))}set_lefttop({id:e,left:t,top:r},M){if(!e)return;D0(this._errorListener,"box.set_lefttop",this._variables.__requestName,M);const n=this._getBox(e);n&&(n.left=t&&Math.floor(t),n.top=r)}set_rightbottom({id:e,right:t,bottom:r},M){if(!e)return;D0(this._errorListener,"box.set_rightbottom",this._variables.__requestName,M);const n=this._getBox(e);n&&(n.right=t&&Math.floor(t),n.bottom=r)}set_text_size({id:e,text_size:t},r){if(!e)return;D0(this._errorListener,"box.set_text_size",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_size=t,this._paramVerfiy(t,r,"box.set_text_size",Object.values(f2),"text_size"))}set_text_wrap({id:e,text_wrap:t},r){if(!e)return;D0(this._errorListener,"box.set_text_wrap",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_wrap=t,this._paramVerfiy(t,r,"box.set_text_wrap",[S0.wrapAuto,S0.wrapNone],"text_wrap"))}set_text_color({id:e,text_color:t},r){if(!e)return;D0(this._errorListener,"box.set_text_color",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_color=t,I1(M,["text_color"]))}set_text_halign({id:e,text_halign:t},r){if(!e)return;D0(this._errorListener,"box.set_text_halign",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_halign=t,this._paramVerfiy(t,r,"box.set_text_halign",[S0.alignLeft,S0.alignCenter,S0.alignRight],"text_halign"))}set_text_valign({id:e,text_valign:t},r){if(!e)return;D0(this._errorListener,"box.set_text_valign",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_valign=t,this._paramVerfiy(t,r,"box.set_text_valign",[S0.alignBottom,S0.alignCenter,S0.alignTop],"text_valign"))}set_top_left_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"box.set_top_left_point",this._variables.__requestName,r);const M=this._getBox(e);if(M){const{index:n,price:b,time:z}=t||{};M.top=b,M.left=M.xloc===w1.bar_index?n:z}}set_bottom_right_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"box.set_bottom_right_point",this._variables.__requestName,r);const M=this._getBox(e);if(M){const{index:n,price:b,time:z}=t||{};M.bottom=b,M.right=M.xloc===w1.bar_index?n:z}}set_text_font_family({id:e,text_font_family:t},r){if(!e)return;D0(this._errorListener,"box.set_text_font_family",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_font_family=t,this._paramVerfiy(t,r,"box.set_text_font_family",Object.values(Ue),"text_font_family"))}_getBox(e){return this._variables.box.get(e.id)||e.data}}function K3(o,e){return{type:e1.BOX,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}class Dm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultCell",{column:0,row:0,text:"",text_color:xr.black,text_halign:S0.alignCenter,text_valign:S0.alignCenter,text_size:f2.normal});C(this,"_defaultTable",{position:k2.topLeft,columns:0,rows:0,frame_width:0,border_width:0});this._variables=e,this._errorListener=t}table({x:e}){return e}new(e,t){D0(this._errorListener,"table.new",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`table_${t}_${r}`,{rows:n}=e;I1(e,["text_color","bgcolor","border_color"]);const b=Array.from(Array(n),()=>[]),z=t.split("_"),i=z.pop(),c=z.pop(),O={...this._defaultTable,...e,cell:b,id:M,bar_index:r,line:c,col:i},s=Xm(M,O);return this._paramVerfiy(e.position,t,"table.new",Object.values(k2),"position"),t.startsWith("export")||this._variables.table.add(M,O,s),s}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}cell({table_id:e,...t},r){if(!e)return;this._verfiyRequestFunc(r,"cell");let{column:M=0,row:n=0}=t;[n,M]=this._rowColToInt(n,M);const b={...this._defaultCell,...t,row:n,column:M},z=this._getTable(e);if(z){const i=z.cell||[],c=i[n]||[];c[M]=b,i[n]=c,z.cell=i}}cell_set_bgcolor({table_id:e,column:t=0,row:r=0,bgcolor:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_bgcolor");const b=this._getTableItem(e,t,r);b&&(b.bgcolor=M)}cell_set_height({table_id:e,column:t=0,row:r=0,height:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_height");const b=this._getTableItem(e,t,r);b&&(b.height=M)}cell_set_text({table_id:e,column:t=0,row:r=0,text:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text");const b=this._getTableItem(e,t,r);b&&(b.text=M)}cell_set_text_color({table_id:e,column:t=0,row:r=0,text_color:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_color");const b=this._getTableItem(e,t,r);b&&(b.text_color=M,I1(b,["text_color"]))}cell_set_text_font_family({table_id:e,column:t=0,row:r=0,text_font_family:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_font_family");const b=this._getTableItem(e,t,r);b&&(b.text_font_family=M)}cell_set_text_halign({table_id:e,column:t=0,row:r=0,text_halign:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_halign");const b=this._getTableItem(e,t,r);b&&(b.text_halign=M)}cell_set_text_valign({table_id:e,column:t=0,row:r=0,text_valign:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_valign");const b=this._getTableItem(e,t,r);b&&(b.text_valign=M)}cell_set_text_size({table_id:e,column:t=0,row:r=0,text_size:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_size");const b=this._getTableItem(e,t,r);b&&(b.text_size=M)}cell_set_tooltip({table_id:e,column:t=0,row:r=0,tooltip:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_tooltip");const b=this._getTableItem(e,t,r);b&&(b.tooltip=M)}cell_set_width({table_id:e,column:t=0,row:r=0,width:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_width");const b=this._getTableItem(e,t,r);b&&(b.width=M)}clear({table_id:e,start_column:t=0,start_row:r=0,end_column:M=0,end_row:n=0},b){if(!e)return;this._verfiyRequestFunc(b,"clear");const z=this._getTable(e);if(z){const i=z.cell;if(i)for(let c=r;c<=n;c++)for(let O=t;O<=M;O++){const s=i[c];s&&(s[O]=void 0)}}}delete({table_id:e},t){if(!e)return;this._verfiyRequestFunc(t,"delete");const r=this._getTable(e);this._variables.table.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}merge_cells({table_id:e,start_column:t=0,start_row:r=0,end_column:M=0,end_row:n=0},b){if(!e)return;if(this._verfiyRequestFunc(b,"merge_cells"),t>M||r>n){this._errorListener.addError(N1.mergeCellErr,b,K0.Error);return}const z=this._getTable(e);if(!z)return;const i=z.merge_cells||[];i.push({start_column:t,start_row:r,end_column:M,end_row:n}),z.merge_cells=i}set_bgcolor({table_id:e,bgcolor:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_bgcolor");const M=this._getTable(e);M&&(M.bgcolor=t,I1(M,["bgcolor"]))}set_border_color({table_id:e,border_color:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_border_color");const M=this._getTable(e);M&&(M.border_color=t,I1(M,["border_color"]))}set_border_width({table_id:e,border_width:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_border_width");const M=this._getTable(e);M&&(M.border_width=t)}set_frame_color({table_id:e,frame_color:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_frame_color");const M=this._getTable(e);M&&(M.frame_color=t)}set_frame_width({table_id:e,frame_width:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_frame_width");const M=this._getTable(e);M&&(M.frame_width=t)}set_position({table_id:e,position:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_position");const M=this._getTable(e);M&&(M.position=t,this._paramVerfiy(t,r,"table.set_position",Object.values(k2),"position"))}_getTableItem(e,t,r){[r,t]=this._rowColToInt(r,t);const M=this._getTable(e);if(M){const n=M.cell;return n?n[r][t]:void 0}}_getTable(e){return this._variables.table.get(e.id)||e.data}_verfiyRequestFunc(e,t){D0(this._errorListener,`table.${t}`,this._variables.__requestName,e)}_rowColToInt(e,t){return[Math.round(e),Math.round(t)]}}function Xm(o,e){return{type:e1.TABLE,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}class Em{constructor(e){C(this,"_strategy");this._strategy=e}commission({trade_num:e},t){return this._verifyTradeNum(e,t)&&this._strategy.historyOrders[e].commission||0}entry_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].in_index}entry_comment({trade_num:e},t){if(!this._verifyTradeNum(e,t))return"";const{comment:r,id:M}=this._strategy.historyOrders[e];return r||M}entry_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].id:""}entry_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].in_price}entry_time({trade_num:e},t){if(!this._verifyTradeNum(e,t))return;const{in_time:r,entry_time:M}=this._strategy.historyOrders[e];return M||r}exit_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_index}exit_comment({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].out_comment:""}exit_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].out_id:""}exit_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_price}exit_time({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_time}max_drawdown({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].trading_loss:0}max_drawdown_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].trading_loss_percent:0}max_runup({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].max_profit:0}max_runup_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].max_profit_percent:0}profit({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].profit:0}profit_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].profit_percent:0}size({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{out_qty:r=0,direction:M}=this._strategy.historyOrders[e];return M===a1.long?r:-r}_verifyTradeNum(e,t){if(this._strategy._verfiyRequestFunc(t,"strategy.closedtrades.*"),typeof e!="number"||e<0)return!1;const r=this._strategy.historyOrders.length;return!(e>=r)}}class Tm{constructor(e){C(this,"_strategy");this._strategy=e}commission({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{qty:r=0,original_qty:M=0,commission:n=0}=this._strategy.orders[e];return n*r/M}entry_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.orders[e].in_index}entry_comment({trade_num:e},t){if(!this._verifyTradeNum(e,t))return"";const{comment:r,id:M}=this._strategy.orders[e];return r||M}entry_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].id:""}entry_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.orders[e].in_price}entry_time({trade_num:e},t){if(!this._verifyTradeNum(e,t))return;const{in_time:r,entry_time:M}=this._strategy.orders[e];return M||r}max_drawdown({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].trading_loss:0}max_drawdown_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].trading_loss_percent:0}max_runup({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].max_profit:0}max_runup_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].max_profit_percent:0}profit({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].profit:0}profit_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].profit_percent:0}size({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{qty:r=0,direction:M}=this._strategy.orders[e];return M===a1.long?r:-r}_verifyTradeNum(e,t){if(this._strategy._verfiyRequestFunc(t,"strategy.opentrades.*"),typeof e!="number"||e<0)return!1;const r=this._strategy.orders.length;return!(e>=r)}}class Cm{constructor(e,t){C(this,"_strategy");C(this,"_errorListener");this._strategy=e,this._errorListener=t}allow_entry_in({value:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._paramVerfiy(e,t,"strategy.risk.allow_entry_in",Object.values(a1),"value"),this._strategy.updateRisk({allow_entry_in:e})}max_cons_loss_days({count:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_cons_loss_days:e})}max_drawdown({value:e,type:t},r){this._strategy._verfiyRequestFunc(r,"strategy.risk.*"),this._paramVerfiy(t,r,"strategy.risk.max_drawdown",[p2.percentOfEquity,p2.cash],"type"),t===p2.percentOfEquity&&(e=e>100?100:e),this._strategy.updateRisk({max_drawdown:e,max_drawdown_type:t})}max_intraday_filled_orders({count:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_intraday_filled_orders:e})}max_intraday_loss({value:e,type:t},r){this._strategy._verfiyRequestFunc(r,"strategy.risk.*"),this._paramVerfiy(t,r,"strategy.risk.max_intraday_loss",[p2.percentOfEquity,p2.cash],"type"),t===p2.percentOfEquity&&(e=e>100?100:e),this._strategy.updateRisk({max_intraday_loss:e,max_intraday_loss_type:t})}max_position_size({contracts:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_position_size:e})}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}}function J3(o,e){return gM(o).plus(e).toNumber()}function tn(o,e){return gM(o).minus(e).toNumber()}function tr(o,e){return gM(o).mul(e).toNumber()}function rn(o,e=5){return Number(o&&gM(o).toFixed(e))}let xm=class{constructor(e,t,r,M,n){C(this,"_variables");C(this,"_options");C(this,"_totalChangeCapital");C(this,"_historyOrder");C(this,"_orders");C(this,"_exitOrders");C(this,"_pendingOrders");C(this,"_mintick");C(this,"_funcOptions");C(this,"_pendingCloseOrders");C(this,"_errorListener");C(this,"_risk");C(this,"_opentrades");C(this,"_closedtrades");C(this,"_riskNamespace");C(this,"_updateOptions",{});C(this,"_id");C(this,"_maxDrawdownVerifyIndex",0);C(this,"calcOnOrderFillsData",{index:-1});this._variables=e,this._errorListener=M,this._options={overlay:!1,format:A1.inherit,pyramiding:1,calc_on_order_fills:!1,calc_on_every_tick:!1,max_bars_back:0,backtest_fill_limits_assumption:0,default_qty_type:p2.fixed,default_qty_value:1,initial_capital:1e6,currency:Y3.NONE,slippage:0,commission_type:O2.percent,commission_value:0,process_orders_on_close:!1,close_entries_rule:"FIFO",margin_long:0,margin_short:0,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,calc_bars_count:0,risk_free_rate:2,use_bar_magnifier:!1,fill_orders_on_standard_ohlc:!1,max_polylines_count:50},this._funcOptions=t,this._totalChangeCapital=0,this._orders=[],this._pendingOrders=[],this._historyOrder=[],this._exitOrders=[],this._pendingCloseOrders=[],this._mintick=r,this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),this._variables.strategy.updateStrategyOptions(this._options),this._risk={intradayOrders:0},this._opentrades=new Tm(this),this._closedtrades=new Em(this),this._riskNamespace=new Cm(this,M),this._id=`strategy_${n}`}get _strategyCacheData(){return{totalChangeCapital:this._totalChangeCapital,orders:this._orders,historyOrders:this._historyOrder,pendingOrders:this._pendingOrders,pendingCloseOrders:this._pendingCloseOrders,exitOrders:this._exitOrders,maxDrawdownVerifyIndex:this._maxDrawdownVerifyIndex}}set _strategyCacheData(e){const{totalChangeCapital:t,orders:r,historyOrders:M,pendingOrders:n,pendingCloseOrders:b,exitOrders:z,maxDrawdownVerifyIndex:i}=e;this._totalChangeCapital=t,this._orders=r,this._historyOrder=M,this._pendingOrders=n,this._pendingCloseOrders=b,this._exitOrders=z,this._maxDrawdownVerifyIndex=i,this._historyOrder.length&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._variables.strategy.updateOrders(this._orders)}get orders(){return[...this._orders]}get historyOrders(){return[...this._historyOrder]}get _freezeCapital(){const{close:e}=this.calcOnOrderFillsData.data||this._variables;return this._orders.reduce((t,r)=>t+e*(r.qty||0),0)}get opentrades(){return this._opentrades}get closedtrades(){return this._closedtrades}get risk(){return this._riskNamespace}get isCalcOnEveryTick(){return this._options.calc_on_every_tick}updateOptions(e){this._updateOptions=e||{},Object.assign(this._options,this._updateOptions)}update(){this._maxConsLossDaysVerify(),this._ordersHandle(),this._pendingOrderHandle(),this._exitOrdersHandle(),this._maxIntradayFilledOrdersVerify(),this._maxDrawdownVerify();const{open:e,high:t,low:r}=this.calcOnOrderFillsData.data||this._variables,M=this._variables.close;this._variables.strategy.update(this.calcOnOrderFillsData.currentData||{open:e,close:M,high:t,low:r}),!this._options.process_orders_on_close&&this._calcLiquidate(),this._calcProfitAndLoss()}calcCurrentOrder(){this._ordersHandle(),this._pendingOrderHandle(),this._calcProfitAndLoss()}updateRisk(e){Object.assign(this._risk,e)}endExecution(){this._maxIntradayLoss(),this._pendingCloseOrderHandle(),this._options.process_orders_on_close&&this._calcLiquidate()}_maxIntradayLoss(){var l;const{max_intraday_loss:e,max_intraday_loss_type:t,isDisabledOpen:r}=this._risk;if(e===void 0||!t||r)return;const{time_tradingday:M,time:n,strategy:{netprofit:b,initial_capital:z}}=this._variables,{high:i,low:c}=this.calcOnOrderFillsData.data||this._variables;let{preNetprofit:O=0}=this._risk;n===M&&(O=b,this._risk.preNetprofit=b,this._risk.isTemporaryBan=!1);let s=O-b;s+=this._orders.reduce((q,A)=>{const{in_price:h,direction:d,qty:m=0,commission:_=0,original_qty:R=0}=A,g=d===a1.long?1:-1,L=(i-h)*m,y=(c-h)*m,D=g===1?y:-L;return q+D+m/R*_},0);let u=!1;switch(t){case p2.cash:u=e<s;break;case p2.percentOfEquity:const q=s/(z+b)*100;u=e<q;break}if(u){this._risk.isTemporaryBan=!0;const q=(l=this._orders[0])==null?void 0:l.direction;this._closeOrders(this._orders,q===a1.long?c:i,"Close Position (Max intraday Loss)",void 0,"close"),this._pendingOrders=[]}}_maxIntradayFilledOrdersVerify(){const{max_intraday_filled_orders:e,intradayOrders:t=0,isDisabledOpen:r}=this._risk;if(e===void 0||r)return;const{time:M,time_tradingday:n}=this._variables,{open:b}=this.calcOnOrderFillsData.data||this._variables;M===n&&(this._risk.intradayOrders=0,this._risk.isTemporaryBan=!1),e<=t&&(this._risk.isTemporaryBan=!0,this._closeOrders(this._orders,b,"Close Position (Max number of filled orders in one day)",void 0,"close"),this._pendingOrders=[])}_maxConsLossDaysVerify(){const{max_cons_loss_days:e,lossDays:t=0,isDisabledOpen:r,totalProfit:M=0}=this._risk;if(e===void 0||r)return;const{time:n,time_tradingday:b,strategy:z}=this._variables,{open:i}=this.calcOnOrderFillsData.data||this._variables;let c=t;if(n===b){const O=z.netprofit+z.openprofit;O<M?c=0:c++,Object.assign(this._risk,{lossDays:c,totalProfit:O})}e<=c&&this._riskTouchOff(i,"Close Position (Max consecutive loss days)")}_maxDrawdownVerify(){const{max_drawdown:e,max_drawdown_type:t,isDisabledOpen:r}=this._risk;if(r)return;const{bar_index:M}=this._variables,{open:n}=this.calcOnOrderFillsData.data||this._variables;if(e!==void 0&&t&&this._maxDrawdownVerifyIndex===M){const{initial_capital:b}=this._options,i=this._orders.reduce((O,s)=>{const{in_price:u,commission:l=0,qty:q=0,original_qty:A=0,direction:h}=s,d=h===a1.long?1:-1,m=(n-u)*d*q;return O+m+l*q/A},0)+this._totalChangeCapital;let c=!1;switch(t){case p2.percentOfEquity:c=i/b*100<=-e;break;case p2.cash:c=i<=-e;break}c&&this._riskTouchOff(n,"Close Position (Max Drawdown)")}}_riskTouchOff(e,t){this._risk.isDisabledOpen=!0,this._orders.length&&this._closeOrders(this._orders,e,t,"close"),this._pendingOrders=[]}strategy(e,t){if(!this._funcOptions.scriptType){this._paramVerfiy(e.format,t,"strategy",[A1.inherit,A1.price,A1.percent,A1.volume],"format"),this._paramVerfiy(e.default_qty_type,t,"strategy",Object.values(p2),"default_qty_type"),this._paramVerfiy(e.commission_type,t,"strategy",Object.values(O2),"commission_type");const r=self==null?void 0:self.workerStorage.get(this._id),M={...this._updateOptions};if(r)for(const n of Object.keys({...r,...e}))e[n]!==r[n]&&delete M[n];this._variables.max_bars_back=e.max_bars_back||0,self==null||self.workerStorage.set(this._id,e),Object.assign(this._options,e,M),this._variables.updateMaxLength(e),Object.assign(this._funcOptions,{strategy:this._options,userSetStrategyConfig:M,scriptType:"strategy"})}}order(e,t){this._verfiyRequestFunc(t,"order"),!this._risk.isDisabledOpen&&(this._paramVerfiy(e.oca_type,t,"strategy.order",Object.values(je),"oca_type"),this._orderHandle(e))}entry(e,t){this._verfiyRequestFunc(t,"entry"),!this._risk.isDisabledOpen&&(this._paramVerfiy(e.oca_type,t,"strategy.entry",Object.values(je),"oca_type"),this._entryHandle(e))}close(e,t){if(this._verfiyRequestFunc(t,"close"),!this._getCloseOrders(e.id).length)return;const{immediately:M}=e;if(M||this._options.process_orders_on_close){const n=this._pendingCloseOrders.find(b=>b.id===e.id&&b.place_order_type==="close");if(n){Object.assign(n,e);return}this._pendingCloseOrders.push({...e,place_order_type:"close"})}else{const n=this._pendingOrders.find(b=>b.id===e.id&&b.place_order_type==="close");if(n){Object.assign(n,e);return}this._pendingOrders.push({...e,place_order_type:"close"})}}close_all(e,t){if(this._verfiyRequestFunc(t,"close_all"),typeof e=="string"&&(e={}),!this._orders.length)return;const{immediately:r}=e;r||this._options.process_orders_on_close?this._pendingCloseOrders.push({...e,place_order_type:"close_all"}):this._pendingOrders.push({...e,place_order_type:"close_all"})}cancel({id:e},t){this._verfiyRequestFunc(t,"cancel"),this._pendingOrders=this._pendingOrders.filter(r=>!(r.id===e&&r.place_order_type!=="close"))}cancel_all(e){this._verfiyRequestFunc(e,"cancel_all"),this._pendingOrders=this._pendingOrders.filter(t=>t.place_order_type==="close_all")}exit(e,t){this._verfiyRequestFunc(t,"exit"),this._options.process_orders_on_close?this._pendingCloseOrders.push({...e,place_order_type:"exit",posStr:t}):this._exit(e,t)}convert_to_account({value:e},t){return this._verfiyRequestFunc(t,"convert_to_account"),e}convert_to_symbol({value:e},t){return this._verfiyRequestFunc(t,"convert_to_symbol"),e}default_entry_qty({fill_price:e},t){return this._verfiyRequestFunc(t,"default_entry_qty"),e?this._calcDefaultQty(e):0}_calcDefaultQty(e){const{default_qty_type:t=p2.fixed,default_qty_value:r=1,initial_capital:M,commission_value:n}=this._options;let b=r;switch(t){case p2.cash:b=r/e;break;case p2.percentOfEquity:const z=this._getOrderProfit(e),i=M+z+this._totalChangeCapital;n?b=this._getCommQty(i,e):b=i*r/100/e;break}return qc(b,this._getLen())}_calcExitQty(e,t="ceil"){if(!String(e).includes("."))return e;const r=this._getLen();return Math[t](tr(e,Math.pow(10,r)))}_getCommQty(e,t){const{commission_type:r,commission_value:M=0,default_qty_value:n=0}=this._options;let b=0;switch(r){case O2.percent:b=e*n/(100*t+M*t);break;case O2.cashPerContract:b=e*n/(100*t+M);break;case O2.cashPerOrder:b=(e-M)*n/100/t}return b}_getLen(){const e=5-(this._variables.precision||5);return e<0?0:e}_getCapital(e,t){const{margin_long:r=0,margin_short:M=0}=this._options;return r<100&&r>0&&e===1?t=t*100/r:M<=100&&M>0&&e===-1&&(t=t*100/M),t}_calcProfitAndLoss(){const{close:e}=this.calcOnOrderFillsData.data||this._variables;for(const t of this._orders){const{in_price:r,qty:M=0,direction:n}=t,b=n===a1.long?1:-1,z=(e-r)*b*M,[i,c]=this._calcProfitAndLossHandle(r,M,b);this._calcOrderPercent(t,z,i,c)}}_calcProfitAndLossHandle(e,t,r,M){const{high:n,low:b}=this.calcOnOrderFillsData.data||this._variables,z=((M||n)-e)*t,i=((M||b)-e)*t;let c=r===1?z:-i,O=r===1?i:-z;return[c,O]}_calcOrderPercent(e,t,r,M){const{commission_value:n}=this._options,{close:b}=this.calcOnOrderFillsData.data||this._variables,{original_qty:z=0,qty:i=0,in_price:c,max_profit:O=0,trading_loss:s=0}=e;let{commission:u=0}=e,l=c*i;if(n){const q=this._getCommission(b,i);u=u*i/z,r-=u,M-=u,l+=u,t=t-q-u}r=Math.max(r,O,0),M=Math.min(M,s,0),Object.assign(e,{profit:t,total_profit:this._totalChangeCapital+t,total_profit_percent:t/(this._options.initial_capital+this._totalChangeCapital)*100,max_profit:r,trading_loss:M,profit_percent:t/l*100,max_profit_percent:r/l*100,trading_loss_percent:M/l*100})}_calcLiquidate(){if(!this._orders.length)return;const{time:e}=this._variables,{high:t,low:r}=this.calcOnOrderFillsData.data||this._variables,{initial_capital:M,margin_long:n=0,margin_short:b=0}=this._options,z=this._orders[0].direction===a1.long?1:-1;let i=z===1?r:t;if(z===1&&n===100)return;const c=(z===1?n:b)/100;if(c<=0)return;let O=!1;const[s,u]=this._orders.reduce((h,d)=>{let[m,_]=h;const{in_price:R,qty:g=0,in_time:L}=d;L===e&&(O=!0);const y=R*g,D=i*g;return m+=y,_+=D,[m,_]},[0,0]);let l=0,q=0;const A=M+this._totalChangeCapital;if(O&&(l=A-s*c,l<0&&(i=this._orders[0].in_price,q=Math.abs(Math.trunc(l/c/i)*4),q=Math.max(q,1))),l>=0){const h=z*(u-s);if(l=A+h-u*c,l>=0)return;q=Math.abs(Math.trunc(l/c/i)*4)}q<=0||this._marginCallOrders(i,q,"Margin Call")}_marginCallOrders(e,t,r){const{close_entries_rule:M="FIFO"}=this._options;if(M==="FIFO"){this._processOrders(this._orders,e,t*this._orders.length,r,r,!0);return}for(const n of this.orders)n.position_close_type=n.place_order_type,n.isTiggerClose=!0,this._processOrder(n,e,t,r,r,!0);this._orders=this._orders.filter(n=>!n.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_orderHandle(e){const{process_orders_on_close:t}=this._options,{isMarketPrice:r,quantities:M,close:n,price:b,activePrice:z,isTouch:i}=this._orderArgsParse(e),c=e.direction===a1.long?1:-1;if(M<=0)return;let O=M;if((r||i)&&t){this._pendingCloseOrders.push({...e,in_price:n,qty:M,place_order_type:"order"});return}this._judgeCapitalEnough(M,b,c)&&this._addPendingOrders(e,b,O,r,z)}_orderOnCloseHandle(e){const t=this._orders.filter(m=>m.direction!==e.direction),{slippage:r=0}=this._options;let{direction:M,qty:n=0,id:b,comment:z,oca_type:i,oca_name:c,in_price:O}=e;const s=M===a1.long?1:-1;if(t.length){const m=this._processOrders(t,O,n,b,z,!1,"order");if(m<=0)return;n=m}const u=O-s*r*this._mintick;if(!this._judgeCapitalEnough(n,u,s))return;this._ocaGroupVerify(n,c,i);const{bar_index:q,time:A}=this._variables,{high:h,low:d}=this.calcOnOrderFillsData.data||this._variables;this._calcCurrentOrder({...e,in_price:u,in_high:h,in_low:d,in_index:q,in_time:A,qty:n,place_order_type:"order"})}_judgeCapitalEnough(e,t,r){let M=this._freezeCapital;if(this._orders.some(O=>(O.direction===a1.long?1:-1)!==r)&&(M=0),e<=0)return!1;const{margin_long:n=0,margin_short:b=0}=this._options;if(n===0&&r===1||b===0&&r===-1)return!0;const z=this._getOrderProfit(t),c=this._getCapital(r,this._options.initial_capital+z+this._totalChangeCapital)-M;return e*t<=c}_getOrderProfit(e){return this._orders.reduce((t,r)=>{const{in_price:M,qty:n=0,direction:b}=r,z=b===a1.long?1:-1;return t+(e-M)*n*z},0)}_ocaGroupVerify(e,t,r){if(!t||!r||r===je.none)return!1;let M=!1;switch(r){case je.cancel:this._pendingOrders=this._pendingOrders.filter(n=>{if(n.oca_name===t)n.isCancel=!0,M=!0;else return!0});break;case je.reduce:this._pendingOrders=this._pendingOrders.filter(n=>{const{qty:b=0,oca_name:z}=n;if(t===z){const i=b-e;return M=!0,i<=0?(n.isCancel=!0,!1):(n.qty=i,!0)}else return!0});break}return M}_processOrders(e,t,r,M,n,b=!1,z,i){if(!e.length)return r;let c=r;for(const O of e)if(O.position_close_type=z||O.place_order_type,O.immediately=i,O.isTiggerClose=(b||O.position_close_type==="close")&&c>=(O.qty||0),c=this._processOrder(O,t,c,M,n,b),c<=0)break;return this._orders=this._orders.filter(O=>!O.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),c}_addPendingOrders(e,t,r,M,n){const b=this._pendingOrders.find(z=>z.id===e.id&&!z.isMarketPrice);if(b)Object.assign(b,{...e,in_price:t,isMarketPrice:M,qty:r,active_price:n});else{const z={...e,in_price:t,isMarketPrice:M,qty:r,active_price:n,entry_time:this._variables.time,place_order_type:"order"};this._pendingOrders.push(z)}}_orderArgsParse(e){var d,m;const{direction:t,qty:r,stop:M}=e;let n=e.limit||0,{close:b}=this.calcOnOrderFillsData.data||this._variables;(m=(d=this.calcOnOrderFillsData)==null?void 0:d.tradeData)!=null&&m.open&&(b=this.calcOnOrderFillsData.tradeData.open);let z=b,i=!1,c;const O=t===a1.long?1:-1,s=M&&(M-b)*O>=0,{backtest_fill_limits_assumption:u=0}=this._options;u>0&&n&&(n-=u*this._mintick*O);const l=n&&(n-b)*O<=0;let q=!1;s&&l?(M!==b&&(c=M),z=n):s?(z=M,q=M===b):l?(z=n,q=n===b):i=!0;const A=r!==void 0?qc(r,this._getLen()):this._calcDefaultQty(z);return{orders:this._orders.filter(_=>_.direction!==t),isMarketPrice:i,activePrice:c,quantities:A,close:b,price:z,isTouch:q}}_entryHandle(e){const{process_orders_on_close:t}=this._options,{isMarketPrice:r,quantities:M,close:n,price:b,activePrice:z,isTouch:i}=this._orderArgsParse(e);if(M<=0)return;if((r||i)&&t){this._pendingCloseOrders.push({...e,in_price:n,qty:M,place_order_type:"entry"});return}this._judgeCapitalEnough(M,n,e.direction===a1.long?1:-1)&&this._addPendingEntry(e,b,M,r,z)}_entryOnCloseHandle(e){const{direction:t,in_price:r,qty:M=0}=e,n=this._orders.filter(b=>b.direction!==t);this._entryOrder(n,r,M,e)}_entryOrder(e,t,r,M){const{time:n,bar_index:b}=this._variables,{high:z,low:i}=this.calcOnOrderFillsData.data||this._variables,{slippage:c=0}=this._options,{oca_name:O,oca_type:s,direction:u,comment:l,id:q}=M,A=u===a1.long?1:-1;if(r=this._getAvailablePositionSize(r,u),r<=0)return;const h=t;if(t=t+c*this._mintick*A,!this._judgeCapitalEnough(r,t,A))return;this._closeOrders(e,h,q,l,"entry",void 0,!0);const m={...M,in_price:t,qty:r,in_index:b,in_high:z,in_low:i,in_time:n,place_order_type:"entry"},{orders:_}=this._getEntryOrders(u),R=_.length;R&&R>=(this._options.pyramiding||1)||(this._ocaGroupVerify(r,O,s),this._calcCurrentOrder(m))}_getAvailablePositionSize(e,t){const{max_position_size:r,allow_entry_in:M}=this._risk;if(M&&M!==a1.all&&M!==t)return 0;if(r===void 0)return e;const n=this._orders.reduce((b,z)=>b+(z.qty||0),0);return n?n+e>r?0:e:e>r?e-r:0}_getEntryOrders(e){const t=this._pendingOrders.filter(M=>["entry","order"].includes(M.place_order_type)&&M.direction===e),r=this._orders.filter(M=>M.direction===e);return{pendingOrders:t,orders:r}}_addPendingEntry(e,t,r,M,n){if(r=this._getAvailablePositionSize(r,e.direction),r<=0)return;const{pendingOrders:b}=this._getEntryOrders(e.direction),z=b.find(i=>i.id===e.id&&i.place_order_type==="entry");if(z)Object.assign(z,{...e,in_price:t,isMarketPrice:M,qty:r,active_price:n});else{const i={...e,in_price:t,isMarketPrice:M,qty:r,active_price:n,entry_time:this._variables.time,place_order_type:"entry"};this._pendingOrders.push(i)}}_closeAllOrders(e,t){const{comment:r,immediately:M}=e,{bar_index:n}=this._variables,b=this._orders.filter(z=>z.in_index!==n);b.length&&(this._closeOrders(b,t,"Close position order",r,"close",M),this._orders=[],this._variables.strategy.updateOrders(this._orders))}_closeOrders(e,t,r,M,n,b,z){if(e.length){for(const i of e)i.position_close_type=n,i.immediately=b,i.isTiggerClose=!0,this._closeOrder(i,t,r,M,z);this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}}_closeOrder(e,t,r,M,n){const{time:b,bar_index:z}=this._variables,{high:i,low:c}=this.calcOnOrderFillsData.data||this._variables,{slippage:O=0}=this._options,{in_price:s,qty:u=0,direction:l}=e,q=l===a1.long?1:-1;t=t-q*O*this._mintick,e.isDeal=!0;const A=(t-s)*q*u,h={...e,out_price:t,out_id:r,out_index:z,out_high:i,out_low:c,out_time:b,out_comment:M,out_qty:u,profit:A};this._calcPercent(h,n)}_exitOrdersHandle(){if(!this._exitOrders.length)return;let{open:e,low:t,high:r,close:M}=this.calcOnOrderFillsData.data||this._variables;const n=[],b=Math.abs(r-e),z=Math.abs(t-e),i=[],c=this._variables.precision;e=Number(e.toFixed(c)),t=Number(t.toFixed(c)),r=Number(r.toFixed(c)),M=Number(M.toFixed(c));for(const O of this._exitOrders){const{directionNum:s,id:u,comment:l,qty:q,comment_loss:A,comment_profit:h,comment_trailing:d,order:m}=O;if(m.isTiggerClose)continue;let _=b<z||b===z&&s===1;if(m.in_time===this._variables.time&&!this._variables._isRepeated){const{in_price:w}=m;_?w<r&&w>=e?e=w:w<=r&&w>=M?r=w:r=M:w<=e&&w>t?e=w:w<=M&&w>=t?t=w:t=M,e=w}const R=[],[g,L]=this._getLimitPrice(O,e,t,r,_);g&&R.push({order:m,price:g,index:L,isHighFront:_,exitInfo:{id:u,comment:h||l,qty:q}});const[y,D]=this._getStopPrice(O,e,t,r,_);y&&R.push({order:m,price:y,index:D,isHighFront:_,exitInfo:{id:u,comment:A||l,qty:q}});const[T,N]=this._getTrailStopPrice(O,e,t,r,M,_);if(T&&R.push({order:m,price:T,index:N,isHighFront:_,exitInfo:{id:u,comment:d||l,qty:q}}),R.length){this._executesSort(R),n.push(R[0]);continue}i.push(O)}this._exitOrders=i,this._executesSort(n);for(const O of n){const{order:s,price:u,exitInfo:l,isHighFront:q,index:A}=O;q?(r=A===1?u:r,t=A===1?e:u):(r=A===1?e:u,t=A===1?u:t),this._variables.strategy.update({open:u,high:r,low:t,close:M}),this._processExitOnClose(s,u,l)}}_executesSort(e){return e.sort(({price:t,index:r,isHighFront:M},{price:n,index:b})=>r!==b?r-b:M?r===1?t-n:n-t:r===1?n-t:t-n),e}_getLimitPrice(e,t,r,M,n){const{limit:b,directionNum:z}=e;let i,c=1;return b&&((t-b)*z>=0?(i=t,c=1):r<=b&&M>=b&&(i=b,n&&b>t||!n&&b<t?c=1:c=2)),[i,c]}_getStopPrice(e,t,r,M,n){const{stop:b,directionNum:z}=e;let i,c=1;return b&&((t-b)*z<=0?(i=t,c=1):r<=b&&M>=b&&(i=b,n&&b>t||!n&&b<t?c=1:c=2)),[i,c]}_getTrailStopPrice(e,t,r,M,n,b){const{trail_stop_price:z,directionNum:i,active_price:c,trail_offset:O=0}=e;let s=z,u,l=1;if(s)if((s-t)*i>=0)u=t,l=1;else{const[q,A,h]=this._calcTrailStopPrice(s,M,r,n,O,i,b);u=A,l=h||1,e.trail_stop_price=q}if(c&&!u&&c<=M&&c>=r)if(O===0)u=c,b&&c>t||!b&&c<t?l=1:l=2;else{s=tn(c,tr(O*i,this._mintick));let q=M,A=r;b?c>=t&&c<=M?(q=M,l=1):(b=!1,q=n,l=2):c<t&&c>=r?(A=r,l=1):(b=!0,A=n,l=2);const[h,d,m=1]=this._calcTrailStopPrice(s,q,A,n,O,i,b);delete e.active_price,l<m&&(l=m),e.trail_stop_price=h,u=d}return[u,l]}_ordersHandle(e){const t=this._orders.filter(b=>b.isMarketPriceLimit||b.isMarketPriceStop);if(!t.length)return;const{open:r,close:M}=this.calcOnOrderFillsData.data||this._variables,n=e?M:r;for(const b of t){const{out_comment:z,out_qty:i,out_id:c}=b;this._processExitOnClose(b,n,{id:c,comment:z,qty:i})}}_calcTrailStopPrice(e,t,r,M,n,b,z){let i=e,c;const O=tn(b===1?t:r,tr(n*b,this._mintick));let s=1;return b===1?z?(i<O&&(i=O),i>=r&&(s=2,c=i)):i>=r?(s=1,c=i):O>i&&(i=O,O>=M&&(s=3,c=O)):z?i<=t?(s=1,c=i):O<i&&(i=O,O<=M&&(s=3,c=O)):(O<i&&(i=O),i<=t&&(s=2,c=i)),[i,c,s]}_pendingOrderHandle(){if(!this._pendingOrders.length)return;const e=[],t=this._pendingOrders.filter(z=>z.place_order_type==="exit");let r=[];for(const z of this._pendingOrders){const{isCancel:i,place_order_type:c,isMarketPrice:O}=z;if(i)continue;let s;switch(c){case"entry":if(!O){r.push(z);continue}this._entryOrderHandle(z);break;case"order":if(!O){r.push(z);continue}this._orderOrderHandle(z);break;case"close":s=this._closeOrderHandle(z);break;case"close_all":const{open:u}=this.calcOnOrderFillsData.data||this._variables;this._closeAllOrders(z,u);break}s&&e.push(s)}const M=this._options.pyramiding||1,n=this._orders.filter(z=>z.direction===a1.long).length<M,b=this._orders.filter(z=>z.direction===a1.short).length<M;r=r.filter(z=>z.direction===a1.long&&n||z.direction===a1.short&&b);for(const z of this._pendingOrderSort(r)){const{place_order_type:i}=z;let c;switch(i){case"entry":c=this._entryOrderHandle(z);break;case"order":c=this._orderOrderHandle(z);break}c&&e.push(c)}for(const z of t){const i=this._exitOrderHandle(z);i&&e.push(i)}this._pendingOrders=e}_pendingOrderSort(e){const{open:t,low:r,high:M}=this.calcOnOrderFillsData.data||this._variables,n=Math.abs(M-t)<=Math.abs(r-t);return e.sort(({in_price:b},{in_price:z})=>{let i=0,c=0;return n?(b>=t&&b<=M?i=1:i=2,z>=t&&z<=M?c=1:c=2):(b<=t&&b>=r?i=1:i=2,z<=t&&z>=r?c=1:c=2),i!==c?i-c:n?i===1?b-z:z-b:i===1?z-b:b-z}),e}_pendingCloseOrderHandle(){if(!this._pendingCloseOrders.length)return;const e=[...this._pendingCloseOrders];this._pendingCloseOrders=[];const t=this._onCloseOrderHandle(e);this._pendingCloseOrders.length&&this._onCloseOrderHandle(this._pendingCloseOrders),this._pendingCloseOrders=t,this._ordersHandle(!0)}_onCloseOrderHandle(e){const{close:t}=this.calcOnOrderFillsData.data||this._variables,r=[];for(const M of e)switch(M.place_order_type){case"close":const n=this._closeOrderHandle(M,!0);n&&r.push(n);break;case"close_all":this._closeAllOrders(M,t);break;case"entry":this._entryOnCloseHandle(M);break;case"order":this._orderOnCloseHandle(M);break;case"exit":const{posStr:b,place_order_type:z,...i}=M;this._exit(i,b);break}return r}_entryOrderHandle(e){const{open:t,low:r,high:M}=this.calcOnOrderFillsData.data||this._variables,{isMarketPrice:n,qty:b=0,in_price:z,direction:i,active_price:c}=e;if(c&&M>=c&&r<=c)return delete e.active_price,e;let O=z;if(n)O=t;else{let{stop:s,limit:u}=e;const l=i===a1.long?1:-1,q=s&&(s-t)*l>=0,{backtest_fill_limits_assumption:A=0}=this._options;A>0&&u&&(u-=A*this._mintick*l);const h=u&&(u-t)*l<=0;q&&h||(s&&!q||u&&!h)&&(O=t)}if(O<=M&&O>=r){const s=this._orders.filter(u=>u.direction!==i);this._entryOrder(s,O,b,e)}else return e}_orderOrderHandle(e){const{time:t,bar_index:r}=this._variables,{open:M,low:n,high:b}=this.calcOnOrderFillsData.data||this._variables,{slippage:z=0}=this._options,{isMarketPrice:i,qty:c=0,in_price:O,direction:s,comment:u,oca_name:l,oca_type:q,active_price:A,id:h}=e;if(A&&b>=A&&n<=A)return delete e.active_price,e;let d=O,m=c;if(i&&(d=M),d<=b&&d>=n){const _=this._orders.filter(g=>g.direction!==s);if(_.length&&(m=this._processOrders(_,d,c,h,u,!1,"order"),m<=0))return;const R=s===a1.long?1:-1;this._ocaGroupVerify(m,l,q),this._calcCurrentOrder({...e,in_price:d-R*z*this._mintick,in_index:r,in_time:t,in_high:b,in_low:n,qty:m});return}else return e}_getCloseOrders(e){const{close_entries_rule:t="FIFO"}=this._options;let r=[];return t==="FIFO"?r=this._orders.filter(M=>M.id===e):r=this._orders.filter(M=>M.id===e&&!M.close_qty),r}_closeOrderHandle(e,t){const{id:r,qty:M,qty_percent:n=100,comment:b,immediately:z}=e,{close_entries_rule:i="FIFO"}=this._options,c=this._getCloseOrders(r);if(!c.length)return;let O=0;if(M?O=M:(O=c.reduce((l,q)=>l+(q.qty||0),O),O=this._calcExitQty(n/100*O,"floor")),O<=0)return;const{open:s,close:u}=this.calcOnOrderFillsData.data||this._variables;if(i==="FIFO")this._processOrders(c,t?u:s,O,`Close entry(s) order ${r}`,b,!1,"close",z);else if(this._processCloseOrders(c,t?u:s,O,`Close entry(s) order ${r}`,b,z))return e}_processCloseOrders(e,t,r,M,n,b){let z=!1;for(const i of e)i.close_qty=r,(i.qty||0)>r&&(z=!0),i.immediately=b,i.position_close_type="close",i.isTiggerClose=!z,this._processOrder(i,t,r,M,n);return this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),z}_exitOrderHandle(e){const{from_entry:t,id:r}=e,M=this._orders.filter(n=>{var b;return(!t||t===n.id)&&!((b=n.exitIds)!=null&&b.includes(r))});if(!(M.length&&!this._ordersToExit(M,e,!0)))return e}_exit(e,t){if(!e.hasOwnProperty("profit")&&!e.hasOwnProperty("loss")&&!e.hasOwnProperty("stop")&&!e.hasOwnProperty("limit")&&(!e.hasOwnProperty("trail_offset")||!e.hasOwnProperty("trail_price")&&!e.hasOwnProperty("trail_points"))){this._errorListener.addError(N1.strategyExitErr,t,K0.Error);return}const{profit:r,loss:M,stop:n,limit:b,trail_offset:z,trail_price:i,trail_points:c,from_entry:O="",id:s}=e;if(this._isNaN(r)&&this._isNaN(M)&&this._isNaN(n)&&this._isNaN(b)&&(this._isNaN(z)||this._isNaN(c)&&this._isNaN(i)))return;const u={...e,place_order_type:"exit"},l=this._orders.filter(d=>{var m;return(!O||O===d.id)&&!((m=d.exitIds)!=null&&m.includes(s))}),q=this._updateExitOrders(u),A=this._pendingOrders.filter(d=>(!O||O===d.id)&&["order","entry"].includes(d.place_order_type||""));if(l.length){if(!this._ordersToExit(l,u,!1))return}else if(!A.length||q)return;const h=this._pendingOrders.find(d=>d.id===s&&d.place_order_type==="exit");h?Object.assign(h,{...e}):this._pendingOrders.push(u)}_updateExitOrders(e){let t=!1;e.qty&&(e.qty=this._calcExitQty(e.qty));const r=this._exitOrders.filter(M=>M.id===e.id&&(M.from_entry===e.from_entry||!e.from_entry));for(const M of r){const{directionNum:n,order:b,qty:z}=M;if(b.isTiggerClose){M.isClose=!0;continue}t=!0;const i={qty:z,...e},c=!0;if(this._stopProfit(b,n,i,c)){M.isClose=!0;continue}if(this._stopLoss(b,n,i,c)){M.isClose=!0;continue}if(this._trailStopLoss(b,n,i,c)){M.isClose=!0;continue}Object.assign(M,i)}return this._exitOrders=this._exitOrders.filter(M=>!M.isClose),t}_ordersToExit(e,t,r){var d;const{qty:M,qty_percent:n=100,id:b,comment:z}=t;let i=M,c=!1;t.comment=z||b;const O=e[0],s={...t},{qty:u=0}=O,l=O.direction===a1.long?1:-1;return i=M?M>=u?u:M:n/100*u,s.qty=this._calcExitQty(i),i<u&&(c=!0),this._stopProfit(O,l,s,r)||this._stopLoss(O,l,s,r)||this._trailStopLoss(O,l,s,r)||(this._exitOrders.push({...s,directionNum:l,order:O}),O.exitIds?(d=O.exitIds)==null||d.push(b):O.exitIds=[b]),c}_addExitPendingCloseOrders(e){const t=this._pendingCloseOrders.find(r=>r.id===e.id);t?Object.assign(t,{...e}):this._pendingCloseOrders.push(e)}_stopProfit(e,t,r,M){var A,h;const{limit:n,profit:b,comment_profit:z,comment:i,id:c,qty:O}=r;let s=n;const{in_price:u}=e,{process_orders_on_close:l}=this._options;if(!this._isNaN(b)&&this._isNaN(n)&&(s=J3(u,tr(b*t,this._mintick))),s=t===1?Wc(s,this._variables.precision):_c(s,this._variables.precision),r.limit=s,M)return;let{close:q}=this.calcOnOrderFillsData.data||this._variables;if((h=(A=this.calcOnOrderFillsData)==null?void 0:A.tradeData)!=null&&h.open&&(q=this.calcOnOrderFillsData.tradeData.open),s!==void 0&&(s-q)*t<=0)return e.isMarketPriceLimit=!0,r.comment=z||i,Object.assign(e,{out_comment:r.comment,out_id:c,out_qty:O}),l&&this._addExitPendingCloseOrders(r),!0}_stopLoss(e,t,r,M){var A,h;const{stop:n,loss:b,comment_loss:z,comment:i,id:c,qty:O}=r;let s=n;const{in_price:u}=e,{process_orders_on_close:l}=this._options;if(!this._isNaN(b)&&this._isNaN(n)&&(s=tn(u,tr(b*t,this._mintick))),s=t===1?_c(s,this._variables.precision):Wc(s,this._variables.precision),r.stop=s,M)return;let{close:q}=this.calcOnOrderFillsData.data||this._variables;if((h=(A=this.calcOnOrderFillsData)==null?void 0:A.tradeData)!=null&&h.open&&(q=this.calcOnOrderFillsData.tradeData.open),s!==void 0&&(s-q)*t>=0)return e.isMarketPriceStop=!0,r.comment=z||i,Object.assign(e,{out_comment:r.comment,out_id:c,out_qty:O}),l&&this._addExitPendingCloseOrders(r),!0}_trailStopLoss(e,t,r,M){var u,l;const{trail_offset:n,trail_price:b,trail_points:z,comment_trailing:i,comment:c,id:O,qty:s}=r;if(!this._isNaN(n)){const{in_price:q}=e,{process_orders_on_close:A}=this._options;let h;if(this._isNaN(b)?this._isNaN(z)||(h=J3(q,tr(z*t,this._mintick))):h=b,r.active_price=h,M)return;let{close:d}=this.calcOnOrderFillsData.data||this._variables;if((l=(u=this.calcOnOrderFillsData)==null?void 0:u.tradeData)!=null&&l.open&&(d=this.calcOnOrderFillsData.tradeData.open),h!==void 0&&(h-d)*t<=0){const m=tn(d,tr(n*t,this._mintick));if((m-d)*t>=0)return e.isMarketPriceStop=!0,r.comment=i||c,Object.assign(e,{out_comment:r.comment,out_id:O,out_qty:s}),A&&this._addExitPendingCloseOrders(r),!0;r.trail_stop_price=m}}}_processExitOnClose(e,t,r){const{qty:M=0,comment:n,id:b}=r,{close_entries_rule:z="FIFO"}=this._options;if(M)if(e.isTiggerClose=!0,z==="FIFO")this._processExitOrders(this._orders,t,M,b,n);else{if(e.isDeal)return;this._processOrders([e],t,M,b,n,!1,"exit")}}_processExitOrders(e,t,r,M,n){let b=r,z;for(const i of e)if(z=i,i.position_close_type="exit",b=this._processOrder(i,t,b,M,n),b<=0)break;return this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),z}_processOrder(e,t,r,M,n,b=!1){const{time:z,bar_index:i}=this._variables,{low:c,high:O}=this.calcOnOrderFillsData.data||this._variables,{slippage:s=0}=this._options,{in_price:u,qty:l=0,max_profit:q,trading_loss:A,direction:h,commission:d=0,original_qty:m=0}=e,_=h===a1.long?1:-1;if(t=t-_*s*this._mintick,r<l){const R=l-r,g=(t-u)*_*r,L=q!==void 0?q/l*r:void 0,y=A!==void 0?A/l*r:void 0,D=d*R/m;this._calcPercent({...e,out_price:t,last_commission:D,out_id:M,out_index:i,out_high:O,out_low:c,out_time:z,out_comment:n,profit:g,out_qty:r,max_profit:L,trading_loss:y});const T=(t-u)*_*R-D;Object.assign(e,{qty:R,profit:T,max_profit:q!==void 0?q-(L||0):void 0,trading_loss:A!==void 0?A-(y||0):void 0,total_profit:this._totalChangeCapital+T}),r=0}else{e.isDeal=!0;const R=(t-u)*_*l;this._calcPercent({...e,out_price:t,out_id:M,out_index:i,out_high:O,out_low:c,out_time:z,out_comment:n,out_qty:l,profit:R}),r-=l}return b&&(_===1?this._variables.strategy.marginCallLong++:this._variables.strategy.marginCallShort++),r}_calcPercent(e,t){const{commission_value:r,process_orders_on_close:M}=this._options,{in_price:n,out_qty:b=0,out_price:z=0,original_qty:i=0,direction:c,last_commission:O=0,immediately:s}=e;let{profit:u=0,max_profit:l,trading_loss:q,commission:A=0}=e,h=n*b,d=this._totalChangeCapital+this._options.initial_capital;if(this._totalChangeCapital+=u,r){const g=this._getCommission(z,b);this._totalChangeCapital-=g;let L=A*b/i;h+=L,L+=g,u=u-L,Object.assign(e,{commission:L});const y=this._orders.reduce((D,T)=>{const{qty:N=0,original_qty:w=0,commission:E=0}=T;return D+E*N/w},0);d+=y-O}const m=c===a1.long?1:-1;let[_,R]=this._calcProfitAndLossHandle(n,b,m,z);if(r){const g=A*b/i;_-=g,R-=g}l=Math.max(_,l||0),q=Math.min(R,q||0),u=parseFloat(String(u)),Object.assign(e,{max_profit:l,profit:u,trading_loss:q,total_profit:this._totalChangeCapital,total_profit_percent:u/d*100,profit_percent:u/h*100,max_profit_percent:l/h*100,trading_loss_percent:q/h*100}),this._maxDrawdownVerifyIndex=this._variables.bar_index+(M?1:0),this._risk.intradayOrders+=1,this._historyOrder.push(e),!t&&this._calcOrderFillsHandle(z,c,s)}_getCommission(e,t){const{commission_value:r=0,commission_type:M}=this._options,n=e*t;let b=0;switch(M){case O2.percent:b=n*r/100;break;case O2.cashPerContract:b=t*r;break;case O2.cashPerOrder:b=r;break}return b}_calcCurrentOrder(e){const{commission_value:t}=this._options,{in_price:r,qty:M=0,max_profit:n=0,trading_loss:b=0,direction:z,immediately:i}=e;let{profit:c=0}=e,O=r*M;const s=this._totalChangeCapital+this._options.initial_capital;if(t){const u=this._getCommission(r,M);this._totalChangeCapital-=u,c=c-u,O+=u,Object.assign(e,{commission:u,total_profit:this._totalChangeCapital})}c=parseFloat(String(c)),Object.assign(e,{original_qty:M,profit:c,total_profit_percent:c/s*100,profit_percent:c/O*100,max_profit_percent:n/O*100,trading_loss_percent:b/O*100,stop:void 0,limit:void 0}),this._risk.intradayOrders+=1,this._orders.push(e),this._variables.strategy.updateOrders(this._orders),t&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._calcOrderFillsHandle(r,z,i)}_calcOrderFillsHandle(e,t,r=!1){const{calc_on_order_fills:M,process_orders_on_close:n,slippage:b=0}=this._options;if(M){const{open:z,high:i,low:c,close:O}=this._variables,s=t===a1.long?1:-1,u=O-s*b*this._mintick;if((r||n)&&e===u)return;const l=z-s*b*this._mintick;let q={open:z,high:i,low:c,close:O},A={open:z,high:i,low:c,close:O},h=this.calcOnOrderFillsData.index;const d=Math.abs(i-z)<=Math.abs(c-z);switch(h){case-1:e===l?(h=0,A={open:z,high:z,low:z,close:z}):e>l?d?(h=1,A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(h=2,A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O}):d?(h=2,A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(h=1,A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O});break;case 0:e===l?(h=1,d?(A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O})):e>l?d?(h=1,A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(h=2,A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O}):d?(h=2,A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(h=1,A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O});break;case 1:h=2,d?(A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O});break;case 2:h=-1,q=void 0;break}this.calcOnOrderFillsData={tradeData:q,index:h,currentData:A}}}_isNaN(e){return e===void 0||isNaN(e)}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}_verfiyRequestFunc(e,t){D0(this._errorListener,`strategy.${t}`,this._variables.__requestName,e)}};class Wp{constructor(e,t,r){C(this,"array");C(this,"color");C(this,"math");C(this,"str");C(this,"map");C(this,"matrix");C(this,"timeframe");C(this,"ta");C(this,"input");C(this,"_variables");C(this,"_cacheData");C(this,"_options");C(this,"_errorListener");C(this,"_plots");C(this,"_plotshapes");C(this,"_plotbars");C(this,"_plotchars");C(this,"_plotarrows");C(this,"_plotcandles");C(this,"_alerts");C(this,"_bgColors");C(this,"_hlines");C(this,"_fills");C(this,"_proxy");C(this,"chart");C(this,"line");C(this,"label");C(this,"polyline");C(this,"box");C(this,"table");C(this,"linefill");C(this,"log");C(this,"runtime");C(this,"strategy");C(this,"request");C(this,"syminfo");C(this,"_count",0);var n;const M=((n=e.toString().split(".")[1])==null?void 0:n.length)||5;this._variables=t,this._errorListener=new km,this.array=new mc(this._errorListener),this.math=new ld(M),this.color=new k6,this.str=new J_(this._errorListener,M),this.map=new Q_,this.timeframe=new k_(t),this.matrix=new P_(this._errorListener),this.ta=new I6(t,this.math,this.timeframe),this._cacheData={},this._options={},this._bgColors={},this._alerts=new Map,this._hlines=new Map,this._fills=new Map,this.input=new P6(t,this._errorListener,r),this._plots=new Map,this._plotshapes=new Map,this._plotbars=new Map,this._plotcandles=new Map,this._plotchars=new Map,this._plotarrows=new Map,this.chart={point:new Z_(t)},this.line=new nt(t,this._errorListener),this.label=new rm(t,this._errorListener),this.polyline=new mm(t,this._errorListener),this.box=new wm(t,this._errorListener),this.table=new Dm(t,this._errorListener),this.linefill=new Lm(t),this.log=new Im(t,this.str),this.runtime=new Pm(this._errorListener),this.strategy=new xm(this._variables,this._options,e,this._errorListener,r),this.request=new Sm(this._variables,r,this,this._errorListener),this.syminfo=new Fm,this._proxy=new Map}getFuncCacheData(){return{funcCacheData:this._cacheData,taCacheData:this.ta._taCacheData,strategyCacheData:this.strategy._strategyCacheData,inputCacheData:this.input._inputCacheData,requestCacheData:this.request._requestCacheData,timeframeCacheData:this.timeframe._timeframeCacheData,logCacheData:this.log._logCacheData,mathCacheData:this.math._mathCacheData}}setFuncCacheData(e){if(!e)return;const{funcCacheData:t,taCacheData:r,strategyCacheData:M,inputCacheData:n,requestCacheData:b,timeframeCacheData:z,mathCacheData:i}=e;this._cacheData=t,this.ta._taCacheData=r,this.strategy._strategyCacheData=M,this.input._inputCacheData=n,this.request._requestCacheData=b,this.timeframe._timeframeCacheData=z,this.log._logCacheData=e.logCacheData,this.math._mathCacheData=i}get errors(){return this._errorListener.errors}get scriptType(){return this._options.scriptType}clearErrors(){this._errorListener.clear()}addErrors(e,t){this._errorListener.setErrors(e,t)}options(e,t){if(!t)return e.length?this._getDataOfBarindex(e):this._options;const r=this.input.getInputs(),M=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const n=Object.keys(this._bgColors);let b;if(n.length){b={};for(const m of n)b[m]=[...this._bgColors[m].values()]}const z=this._hlines.size?[...this._hlines.values()]:void 0,i=this._fills.size?[...this._fills.values()]:void 0,c=this.log.logs.length?this.log.logs:void 0;this.log.clearLogs(),this._options.scriptType==="strategy"&&Object.assign(this._options,{orders:this.strategy.orders,historyOrders:this.strategy.historyOrders,strategySummary:this._variables.strategy.summaryData});const O=this._plots.size>0?[...this._plots.values()]:void 0,s=this._plotbars.size>0?[...this._plotbars.values()]:void 0,u=this._plotshapes.size>0?[...this._plotshapes.values()]:void 0,l=this._plotarrows.size>0?[...this._plotarrows.values()]:void 0,q=this._plotcandles.size>0?[...this._plotcandles.values()]:void 0,A=this._plotchars.size>0?[...this._plotchars.values()]:void 0,h=this._getDraws(),d=this._variables.chart.isUseBgColor;return Object.assign({},this._options,{inputs:r,plots:O,draws:h,alerts:M,colors:b,hlines:z,fills:i,logs:c,plotshapes:u,plotarrows:l,plotcandles:q,plotchars:A,plotbars:s,isUseBgColor:d})}_getDataOfBarindex(e){const t=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const r=Object.keys(this._bgColors);let M;if(r.length){M={};for(const d of r)M[d]=[...this._bgColors[d].values()].map(m=>{const _=[];for(const R of e){const g=m.data[R];g&&_.push(g)}return m.data=_,m})}const n=this._hlines.size?[...this._hlines.values()]:void 0,b=this._fills.size?this._getDataFromBarindex(e,[...this._fills.values()]):void 0,z=this.log.logs.length?this.log.logs:void 0;this.log.clearLogs(),this._options.scriptType==="strategy"&&Object.assign(this._options,{orders:this.strategy.orders,historyOrders:this.strategy.historyOrders});const i=this._getDataFromBarindex(e,[...this._plots.values()]),c=this._plotbars.size>0?this._getDataFromBarindex(e,[...this._plotbars.values()]):void 0,O=this._plotarrows.size>0?this._getDataFromBarindex(e,[...this._plotarrows.values()]):void 0,s=this._plotcandles.size>0?this._getDataFromBarindex(e,[...this._plotcandles.values()]):void 0,u=this._plotchars.size>0?this._getDataFromBarindex(e,[...this._plotchars.values()]):void 0,l=this._plotshapes.size>0?this._getDataFromBarindex(e,[...this._plotshapes.values()]):void 0,q=this._getDrawDeletes(e),A=this._getDrawsFromBarindex(e),h=this._variables.chart.isUseBgColor;return Object.assign({},this._options,{plots:i,plotarrows:O,plotcandles:s,plotchars:u,plotbars:c,draws:A,drawDeletes:q,alerts:t,colors:M,hlines:n,fills:b,logs:z,plotshapes:l,isUseBgColor:h})}_getDataFromBarindex(e,t){return t.map(r=>{const M=[];for(const n of e){const b=r.data[n];b&&M.push(b)}return r.data=M,{...r}})}_getDraws(){const{line:e,linefill:t,table:r,box:M,polyline:n,label:b}=this._variables,z={};return e.size&&(z.lines=e.data),t.size&&(z.linefills=t.data),r.size&&(z.tables=r.data),M.size&&(z.boxes=M.data),n.size&&(z.polylines=n.data),b.size&&(z.labels=b.data),Object.keys(z).length?z:void 0}_getDrawsFromBarindex(e){const{line:t,linefill:r,table:M,box:n,polyline:b,label:z}=this._variables,i={};return t.size&&(i.lines=t.getValOfBarIndex(e)||[]),r.size&&(i.linefills=r.getValOfBarIndex(e)),M.size&&(i.tables=M.getValOfBarIndex(e)),n.size&&(i.boxes=n.getValOfBarIndex(e)),b.size&&(i.polylines=b.getValOfBarIndex(e)),z.size&&(i.labels=z.getValOfBarIndex(e)),Object.keys(i).length?i:void 0}_getDrawDeletes(e){const{line:t,linefill:r,table:M,box:n,polyline:b,label:z}=this._variables,i={},c=t.getDeleteIds(e),O=r.getDeleteIds(e),s=M.getDeleteIds(e),u=n.getDeleteIds(e),l=b.getDeleteIds(e),q=z.getDeleteIds(e);return c.length&&(i.lines=c),O.length&&(i.linefills=O),s.length&&(i.tables=s),u.length&&(i.boxes=u),l.length&&(i.polylines=l),q.length&&(i.labels=q),i}updateOptions(e){var M;const{inputs:t,strategy:r}=e;this.input.update(t),r&&((M=this.strategy)==null||M.updateOptions(r))}update(e){const{barIndex:t}=e;this.strategy.update(),this._proxy.clear(),this.math.update(t)}endExecution(){this.strategy.endExecution()}getProxy(e,t,r){if(!e)return;const M=this;let n=this._proxy.get(t);const{params:b,funcName:z}=r;n||(n=new Proxy(e,{get(c,O,s){const u=O;return typeof c[u]>"u"?M._getProxyFunc(c.type,u):Reflect.get(c,O,s)}}),this._proxy.set(t,n));const i=M._getFirstArgName(e.type,z);return typeof b[0]=="string"&&b.unshift({[i]:e}),n==null?void 0:n[z](...b)}userFuncMiddleware(e,t,r,M,n,b,z){const i=t.split(",");if(typeof e=="string"){if(i.includes("string"))return r(...M);if(i.includes("color")&&(e.startsWith("#")||e.startsWith("rgb")))return r(...M)}else if(typeof e=="number"){if(i.includes("int")||i.includes("float"))return r(...M)}else if(typeof e=="boolean"){if(i.includes("bool"))return r(...M)}else if(typeof e=="object"){if(i.includes(e.typeName))return r(...M);if(e.type===e1.ARRAY&&i.includes(`${e.typeName}[]`))return r(...M);if(e.type===e1.MATRIX&&i.includes(`matrix<${e.typeName}>`))return r(...M);if(e.type===e1.MAP&&i.includes(`map<${e.keyTypeName},${e.typeName}>`))return r(...M)}this._errorListener.addError(l2(N1.methodNotExistErr,{methodName:z,name:b}),n,K0.Error)}_getFirstArgName(e,t){switch(e){case e1.TYPE:return"object";case e1.ARRAY:return["concat","covariance"].includes(t)?"id1":"id";case e1.MATRIX:return["sum","diff","kron","mult","concat"].includes(t)?"id1":"id";case e1.MAP:case e1.BOX:case e1.LABEL:case e1.LINE:case e1.LINEFILL:case e1.POLYLINE:case e1.CHART_POINT:return"id";case e1.TABLE:return"table_id";default:return"id"}}_getProxyFunc(e,t){switch(e){case e1.TYPE:if(t==="copy")return Oi.copy;break;case e1.ARRAY:return this.array[t];case e1.MATRIX:return this.matrix[t];case e1.MAP:return this.map[t];case e1.BOX:return this.box[t];case e1.LABEL:return this.label[t];case e1.LINE:return this.line[t];case e1.LINEFILL:return this.linefill[t];case e1.TABLE:return this.table[t];case e1.POLYLINE:return this.polyline[t];case e1.CHART_POINT:return this.chart.point[t]}}library(e,t){if(!this._variables.bar_index){const r=/^[^\W\d\s][^\W\s]*$/,{title:M}=e;r.test(M)?(Iu.includes(M)||Fu.includes(M))&&this._errorListener.addError(l2(N1.libraryTitleIsKeywordErr,{name:M}),t,K0.Error):this._errorListener.addError(N1.libraryTitleErr,t,K0.Error),this._options.scriptType="library",this._options.library=e}}indicator(e,t){if(!this._options.scriptType){const{format:r,max_bars_back:M=0}=e;this._variables.max_bars_back=M,this._paramVerfiy(r,t,"indicator",[A1.inherit,A1.percent,A1.price,A1.volume]),this._variables.updateMaxLength(e),this._options.scriptType="indicator",this._options.indicator=e}}_paramVerfiy(e="",t,r,M,n="format"){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}_lineWidthVerify(e,t){const{linewidth:r=1}=e;r<1&&(this._errorListener.addError(Su.lineWidthWarning,t,K0.Warning),e.linewidth=1)}plot(e,t){const r=["color"];I1(e,r);const{series:M,color:n,...b}=e,{bar_index:z,time:i}=this._variables,c=`plot_${t}`,O=this._plots.get(c),s=(O==null?void 0:O.data)||[],u=M!==void 0&&isNaN(M)?void 0:M;if(s[z]={value:[i,u],barIndex:z,itemStyle:{color:n}},this._seriesColorHandle(e,r,O),!O){this._count++,this._lineWidthVerify(b,t),this._paramVerfiy(e.format,t,"plot",[A1.percent,A1.price,A1.volume]);const l=n?[n]:void 0;this._plots.set(c,{editable:!0,...b,colors:l,data:s,id:c,zIndex:this._count})}return{type:"plot",offset:e.offset||0,key:c}}plotbar(e,t){const r=["color"];I1(e,r);const{open:M,close:n,low:b,high:z,color:i,...c}=e,{bar_index:O,time:s}=this._variables,u=`plotbar_${t}`,l=this._plotbars.get(u),q=(l==null?void 0:l.data)||[],A=n!==void 0&&isNaN(n)?void 0:n,h=M!==void 0&&isNaN(M)?void 0:M,d=b!==void 0&&isNaN(b)?void 0:b,m=z!==void 0&&isNaN(z)?void 0:z,_=[s,h,A,d,m];if(q[O]={value:_,barIndex:O,itemStyle:{color:i}},this._seriesColorHandle(e,r,l),!l){this._count++,this._paramVerfiy(e.format,t,"plotbar",[A1.percent,A1.price,A1.volume]);const R=i?[i]:void 0;this._plotbars.set(u,{editable:!0,...c,colors:R,data:q,id:u,zIndex:this._count})}}_verfiyArgs(e,t,r){const{size:M,format:n,location:b,style:z}=e;this._paramVerfiy(z,r,t,Object.values(X2),"style"),this._paramVerfiy(b,r,t,Object.values($e),"location"),this._paramVerfiy(M,r,t,Object.values(f2),"size"),this._paramVerfiy(n,r,t,[A1.percent,A1.price,A1.volume],"format")}plotchar(e,t){const r=["color","textcolor"];I1(e,r);const{series:M,color:n,textcolor:b,location:z=$e.abovebar,...i}=e,{bar_index:c,time:O,high:s,low:u}=this._variables,l=`plotchar_${t}`,q=this._plotchars.get(l),A=(q==null?void 0:q.data)||[],h={value:[O,M],barIndex:c,itemStyle:{color:n,textcolor:b},low:u,high:s};A[c]=h,this._seriesColorHandle(e,r,q),q||(this._count++,this._verfiyArgs(e,"plotchar",t),this._plotchars.set(l,{editable:!0,...i,location:z,data:A,id:l,zIndex:this._count}))}plotarrow(e,t){const r=["colorup","colordown"];I1(e,r);const{series:M,colorup:n,colordown:b,...z}=e,{bar_index:i,time:c,low:O,high:s}=this._variables,u=`plotarrow_${t}`,l=this._plotarrows.get(u),q=(l==null?void 0:l.data)||[];q[i]={value:[c,M!==void 0&&isNaN(M)?void 0:M],barIndex:i,itemStyle:{colorup:n,colordown:b},low:O,high:s},this._seriesColorHandle(e,r,l),l||(this._count++,this._paramVerfiy(e.format,t,"plotarrow",[A1.percent,A1.price,A1.volume]),this._plotarrows.set(u,{editable:!0,...z,data:q,id:u,zIndex:this._count}))}plotshape(e,t){const r=["color","textcolor"];I1(e,r);const{series:M,color:n,textcolor:b,location:z=$e.abovebar,...i}=e,{bar_index:c,time:O,low:s,high:u}=this._variables,l=`plotshape_${t}`,q=this._plotshapes.get(l),A=(q==null?void 0:q.data)||[],h={value:M,barIndex:c,color:n,textcolor:b,time:O,low:s,high:u};if(A[c]=h,this._seriesColorHandle(e,r,q),!q){this._count++;const d=n?[n]:void 0;this._verfiyArgs(e,"plotshape",t),this._plotshapes.set(l,{editable:!0,...i,data:A,location:z,id:l,colors:d,zIndex:this._count})}}plotcandle(e,t){const r=["wickcolor","bordercolor","color"];I1(e,r);const{wickcolor:M,bordercolor:n,color:b,close:z,open:i,low:c,high:O,...s}=e,{bar_index:u,time:l}=this._variables,q=`plotcandle_${t}`,A=this._plotcandles.get(q),h=(A==null?void 0:A.data)||[],d=z!==void 0&&isNaN(z)?void 0:z,m=i!==void 0&&isNaN(i)?void 0:i,_=c!==void 0&&isNaN(c)?void 0:c,R=O!==void 0&&isNaN(O)?void 0:O,g=[l,m,d,_,R];h[u]={value:g,barIndex:u,wickcolor:M,bordercolor:n,color:b},this._seriesColorHandle(e,r,A),A||(this._count++,this._paramVerfiy(e.format,t,"plotcandle",[A1.percent,A1.price,A1.volume]),this._plotcandles.set(q,{editable:!0,...s,data:h,id:q,zIndex:this._count}))}hline(e,t){const r=`hline_${t}`;I1(e,["color"]),this._verifyDisplay(e.display,"hline",t);const n=e.display&&!e.display.length?[]:void 0;return this._hlines.has(r)||(this._count++,this._lineWidthVerify(e,t),this._hlines.set(r,{id:r,linewidth:1,editable:!0,display:n,...e,zIndex:this._count})),{type:"hline",key:r}}fill(e,t){var D,T,N,w,E,P,H,Y;const r=["color","top_color","bottom_color"];I1(e,r);const{color:M,top_color:n,bottom_color:b,seriesColors:z,hline1:i,hline2:c,plot1:O,plot2:s,top_value:u,bottom_value:l,...q}=e,{bar_index:A,time:h}=this._variables,d=`fill_${t}`,m=this._fills.get(d),_=(m==null?void 0:m.data)||[];this._verifyDisplay(e.display,"fill",t);const R=e.display&&!e.display.length?[]:void 0;let g,L,y="plot";if(i&&c)g=(D=this._hlines.get(i==null?void 0:i.key))==null?void 0:D.price,L=(T=this._hlines.get(c==null?void 0:c.key))==null?void 0:T.price,y="hline";else{const k=this._plots.get(O==null?void 0:O.key),K=this._plots.get(s==null?void 0:s.key),e0=(k==null?void 0:k.data)||[],b0=(K==null?void 0:K.data)||[];if(g=(w=(N=e0[A])==null?void 0:N.value)==null?void 0:w[1],L=(P=(E=b0[A])==null?void 0:E.value)==null?void 0:P[1],!A){const O0=(k==null?void 0:k.force_overlay)&&(K==null?void 0:K.force_overlay);(k!=null&&k.force_overlay||K!=null&&K.force_overlay)&&!O0?this._errorListener.addError(N1.plotFillForceOverlayErr,t,K0.Error):q.force_overlay=O0}}if(_[A]={time:h,color:M,top_color:n,bottom_color:b,barIndex:A,plot1:g,plot2:L,top_value:u,bottom_value:l},this._seriesColorHandle(e,r,m),!m){this._count++;const k=((H=this._options.indicator)==null?void 0:H.explicit_plot_zorder)||((Y=this._options.strategy)==null?void 0:Y.explicit_plot_zorder),K=M?[M]:void 0,e0=n?[n]:void 0,b0=b?[b]:void 0;this._fills.set(d,{id:d,colors:K,top_colors:e0,bottom_colors:b0,display:R,data:_,type:y,editable:!0,fillgaps:!1,hline1:i,hline2:c,plot1:O,plot2:s,...q,zIndex:k?this._count:void 0})}}alert({message:e,freq:t=fe.freqOncePerBar},r){const{bar_index:M,_isRealTimeBar:n,last_bar_index:b}=this._variables,z=`alert_${r}`,i=this._cacheData[z]||{},c=i.barIndex;if(this._paramVerfiy(t,r,"alert",[fe.freqAll,fe.freqOncePerBar,fe.freqOncePerBarClose]),t===fe.freqOncePerBar&&M===c){this._alerts.delete(z);return}this._cacheData[z]=i;const O={message:e,freq:t,id:z,type:"alert"};if(n){t!==fe.freqOncePerBarClose&&this._alerts.set(z,O),i.barIndex=M;return}if(!n&&t===fe.freqOncePerBarClose&&M===c&&b===M-1){this._alerts.set(z,O),i.barIndex=M;return}this._alerts.delete(z)}alertcondition({condition:e,message:t,title:r},M){const{_isRealTimeBar:n}=this._variables,b=`alertcondition_${M}`;n&&e?this._alerts.set(b,{message:t,title:r,id:b,type:"alertcondition"}):this._alerts.delete(b)}barcolor(e,t){this._setColors(e,"barcolor",t)}bgcolor(e,t){this._setColors(e,"bgcolor",t)}_verifyDisplay(e=G3.all,t,r){e.length&&e.length<4&&this._errorListener.addError(l2(N1.displayErr,{func:t,values:"[display.none, display.all]"}),r,K0.Error)}_setColors(e,t,r){I1(e,["color"]);const{color:n,...b}=e;this._verifyDisplay(b.display,t,r);const z=e.display&&!e.display.length?[]:void 0,{bar_index:i,time:c}=this._variables,O=`${t}_${r}`;this._bgColors[t]||(this._bgColors[t]=new Map);const s=this._bgColors[t].get(O),u=(s==null?void 0:s.data)||[],l=(s==null?void 0:s.setColors)||[];n&&!l.includes(n)&&l.push(n),u[i]={color:n,time:c,barIndex:i},s||this._bgColors[t].set(O,{...b,display:z,data:u,setColors:l,id:O})}max_bars_back({num:e,var_name:t}){this._variables.__setBarsBackOfKey(t,e)}float({x:e}){return e}bool({x:e}){return e||!1}string({x:e}){return e}int({x:e}){return e&&Math.trunc(e)}na({x:e}){return!!(e===void 0||typeof e=="number"&&isNaN(e))}fixnan({source:e},t){return e===void 0||typeof e=="number"&&isNaN(e)?this._cacheData[`fixnan_${t}`]:(this._cacheData[`fixnan_${t}`]=e,e)}nz(e){const t=e.hasOwnProperty("replacement"),{source:r,replacement:M}=e;return r!==void 0&&!(typeof r=="number"&&isNaN(r))?r:t?M:0}time({timeframe:e="",session:t,timezone:r=this._variables.syminfo.timezone,bars_back:M=0},n){return this._timeHandle(this._variables.time,n,e,t,r,M)}time_close({timeframe:e="",session:t,timezone:r=this._variables.syminfo.timezone,bars_back:M=0},n){return this._timeHandle(this._variables.time,n,e,t,r,M,!0)}timestamp(e){const{dateString:t,timezone:r=this._variables.syminfo.timezone,year:M,month:n,day:b,hour:z=0,minute:i=0,second:c=0}=e;if(t)return O1(t).utc(!/GMT|UTC/.test(t)).valueOf();let O=n-1,s=M;if(O<0){const u=Math.ceil(Math.abs(O/12));O=12*u+O,s=M-u}return lc({year:s,month:O,day:b,hour:z,minute:i,second:c},r)}weekofyear({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).week()}year({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).year()}second({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).second()}month({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).month()+1}minute({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).minute()}hour({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).hour()}dayofweek({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).weekday()+1}dayofmonth({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).date()}_calcTimeOffset(e,t){const r=this._variables.getTimeTradingday(e,this._variables.timeframe.period),M=y2(t,e)*1e3;return e-r-Math.floor((e-r)/M)*M}_timeHandle(e,t,r="",M,n,b=0,z=!1){const i=r||this._variables.__period,c=y2(i,e),O=y2(this._variables.__period,e);let s;if(c<=O)s=e,z&&(s+=O*1e3);else{const u=`time_${t}`,l=this._cacheData[u];if(l)switch(l.type){case 1:const{time:q,nextTime:A,unit:h,preNum:d}=l;e>=A?(s=A,this._cacheData[u]={type:1,time:s,nextTime:O1(A).add(d,h).startOf(h).add(this._variables._offsetTime,"hour").valueOf(),unit:h,preNum:d}):s=q;break;case 2:s=O1(e).startOf(l.unit).add(this._variables._offsetTime,"hour").valueOf();break;default:l.currentTime+c*1e3-l.offset<=e?(s=e,this._cacheData[u]={type:3,currentTime:e,offset:0}):s=l.currentTime;break}else{const[q,A]=ht(i);if(/[DWM]/.test(i))if(s=O1(e).startOf(A).add(this._variables._offsetTime,"hour").valueOf(),q>1){const h=O1(s).add(q,A).startOf(A).add(this._variables._offsetTime,"hour").valueOf();this._cacheData[u]={type:1,time:s,nextTime:h,unit:A,preNum:q}}else this._cacheData[u]={type:2,unit:A};else{const h=this._calcTimeOffset(e,i);this._cacheData[u]={type:3,currentTime:e,offset:h},s=e}}z&&(s+=c*1e3)}if(M&&M!==ft.regular&&M!==ft.extended){const{timePeriods:u,weeks:l}=this._parserSession(M,t),q=_e(e,n),A=q.format("YYYY-MM-DD HH:mm"),h=q.format("YYYY-MM-DD");s=void 0;for(const m of u){const[_,R]=m;let g;if((_===R||Number(_==null?void 0:_.replace(":",""))>Number(R==null?void 0:R.replace(":","")))&&(g=q.add(1,"day").format("YYYY-MM-DD")),_e(A,n).isBetween(`${h} ${_}`,`${g||h} ${R}`,"minute","[)")){s=lc(`${h} ${_}`,n);break}}const d=this._variables.dayofweek;s&&!l.includes(d)&&(s=void 0)}return Number(s&&s-b*O*1e3)}_seriesColorHandle(e,t,r){var M;if(r&&t!=null&&t.length)for(const n of t){if((M=r.gradientColorKeys)!=null&&M.includes(n))continue;const b=e[n];if(!b)continue;const z=r[`${n}s`]||[];z.includes(b)||(z.push(b),r[`${n}s`]=z,z.length>5&&(r[`${n}s`]=[],r.gradientColorKeys=r.gradientColorKeys||[],r.gradientColorKeys.push(n)))}}_parserSession(e,t){const r=e.split(":"),M=r[0],b=(r[1]||"1234567").split("").map(i=>{const c=parseInt(i,10);if(c<1||c>7){this._errorListener.addError(`Invalid day of week: ${i}`,t,K0.Error);return}return c});return{timePeriods:M.split(",").map(i=>{i===""||i===ft.regular?i="0930-1500":i===ft.extended&&(i="1500-1830");const c=i.split("-");return c.length!==2?[]:[this._processTime(c[0],t),this._processTime(c[1],t)]}),weeks:b}}_processTime(e,t){const r=e.slice(0,2),M=e.slice(2),n=parseInt(r,10),b=parseInt(M,10);if(!(n>=0&&n<=23)&&b>=0&&b<=59){this._errorListener.addError("Invalid time: Time must be within 00:00 to 23:59",t,K0.Error);return}return`${r}:${M}`}}let Sm=class{constructor(e,t,r,M){C(this,"_variables");C(this,"_scriptId");C(this,"_cacheData");C(this,"_funcs");C(this,"_errorListener");this._variables=e,this._scriptId=t,this._cacheData=Object.create(null),this._funcs=r,this._errorListener=M}get _requestCacheData(){return this._cacheData}set _requestCacheData(e){this._cacheData=e}security(e,t){var q;const r=self.workerStorage.get(`request_${this._scriptId}`),{__requestName:M,__period:n}=this._variables;e.symbol=this._symbolTransform(e.symbol),e.timeframe=e.timeframe||n;let{symbol:b,timeframe:z,paramsExpr:i=[]}=e;z=uM(z);const c=`${b}--${z}`,O=`${M}${t}_${c}`,s=this._getRequestData(e,O);if(r!=null&&r.has(O))return(q=s==null?void 0:s.result)==null?void 0:q[O];const u=this._parseExprCode(e),l=this._runScriptHandle(u,O,i,s,!0);return r==null||r.set(O,{id:O,isRun:!1,strJs:u,dataId:c,interval:z,symbol:b,paramsExpr:i}),l}security_lower_tf(e,t){const r=self.workerStorage.get(`request_${this._scriptId}`),{__period:M,__requestName:n}=this._variables;e.symbol=this._symbolTransform(e.symbol),e.timeframe=e.timeframe||M;let{symbol:b,timeframe:z,paramsExpr:i=[]}=e;z=uM(z);const c=`${b}--${z}`,O=`${n}${t}_${c}`,s=r==null?void 0:r.get(O),u=this._getRequestLowerTfData(e,t,O,s==null?void 0:s.defaultResult),l=p1(0,void 0,N0.FLOAT);if(s!=null&&s.strJs)return s!=null&&s.defaultResult?u!=null&&u.length?u.map(d=>{const m=p1(0,void 0,N0.FLOAT);return m._value=d,m}):s==null?void 0:s.defaultResult:u&&(l._value=u,l);const q=this._parseExprCode(e),A={id:O,strJs:q,isRun:!1,dataId:c,interval:z,symbol:b,paramsExpr:i,defaultResult:void 0};r==null||r.set(O,A);const h=this._runScriptHandle(q,O,i,u,!0);return Array.isArray(h)?(A.defaultResult=h.map(()=>p1(0,void 0,N0.FLOAT)),A.defaultResult):l}_symbolTransform(e){if(!e)return this._variables.syminfo.tickerid;let[t,r]=e.split(":");return r?t=ku[t]||t:(r=t,t="FX"),`${t}:${r}`}_runScriptHandle(e,t,r,M,n){const{result:b,logs:z,errors:i}=this._runScripts(e,t,n,r,M);return this._funcs.log.mergeLogs(z),this._funcs.addErrors(i,t),b}_parseExprCode(e){let{expression:t,paramsExpr:r=[]}=e,M=[];t=dc(t);const n=JSON.parse(t),b=n.pop();let z=(b==null?void 0:b.memberCodes)||{},i=(b==null?void 0:b.depends)||[];if(!i.length)return`return ${b==null?void 0:b.code}`;let c=[],O=[],s=[];if(this._getDependCodes(i,n,M,c,O,s),this._getStmtFuncs(M,n,s,c,O),O.length){const h=r.length;for(let d=h-1;d>=0;d--){const m=r[d];let _=JSON.parse(dc(m));const R=[];_=_.map(y=>{const{type:D,code:T,varNames:N,dependSelf:w}=y;return D===2&&!R.includes(N)&&!w&&(y.code=`let ${T}`),N&&R.push(...N.split(", ")),y.memberCodes&&Object.assign(z,{...y.memberCodes}),y});const g=[];let L=O.map(y=>({...y,isArg:!1,isPreArg:!0}));O=[],this._getDependCodes(L,_,M,c,O,g),this._getStmtFuncs(M,_,g,c,O)}}const u=M.filter(h=>!!h).map((h,d)=>{let m=h.join(`
76
+ `)}}if(typeof e=="string")return e;if(typeof e=="boolean")return String(e);if(typeof e=="number")return String(this._toStringFormat(e,t))}_arrToStr(e,t){return`[${e.map(M=>typeof M=="number"?this._toStringFormat(M,t):M).toString()}]`}substring({source:e="",begin_pos:t=0,end_pos:r}){return u0(t)&&(t=0),u0(r)&&(r=void 0),e==null?void 0:e.substring(t,r)}startswith({source:e="",str:t=""}){return e==null?void 0:e.startsWith(t)}format_time({time:e,format:t="yyyy-MM-dd'T'HH:mm:ssZ",timezone:r}){return u0(e)&&(e=0),_e(e,r).format(t)}replace_all({source:e="",target:t="",replacement:r=""}){return e==null?void 0:e.replace(new RegExp(t,"g"),r)}_toStringFormat(e,t){if(!t)return this._numberDef(e);switch(t){case A1.mintick:return e==null?void 0:e.toFixed(this._precision);case A1.percent:return`${Number(e.toFixed(2))}%`;case A1.volume:return this._intlNumberFormatter.format(Math.round(e));default:return this._formatOthers(e,t)}}_numberDef(e){if(!e)return e;const t=String(Number(e.toFixed(10)));return/[eE]/.test(t)?new gM(t).toFixed():t}_formatOthers(e,t){var z;if(u0(e))return NaN;let[r,M]=t.split(".");t.split("%").length===2&&(e=Number((e*100).toFixed(2)));let[n,b=""]=String(e).split(".");if(r.includes("0")){r=r.replace(/#/g,"");const i=r.split("0");let c=i.length-1;for(;c>n.length;)n=`0${n}`,c--;i.splice(1,0,n),n=i.join("")}else if(r.includes("#")){if(r.includes(",")){const i=r.split(","),c=((z=i[i.length-1])==null?void 0:z.replace(/[^#]/g,"").length)||0;c&&(n=n.replace(new RegExp(`\\B(?=(\\d{${c}})+(?!\\d))`,"g"),",")),r=i.join("")}n=r.replace(/#/,n).replace(/#/g,"")}else n=`${r}${n}`;if(M&&M.includes("0")){M=M.replace(/#/g,"");const i=M.split("0");let c=i.length-1;if(b.length>c)b=b.substring(0,c);else for(;c>b.length;)b=`${b}0`,c--;return i.push(b),b=i.join(""),`${n}.${b}`}else if(M&&M.includes("#")){const i=M.split("#").length-1,c=+`${n}.${b}`;if(!isNaN(c)){const O=`${c.toFixed(i)}${M.replace(/#/g,"")}`,s=Number(O);return isNaN(s)?O:s}b=`${b.substring(0,i)}${M.replace(/#/g,"")}`}else b=M||"";if(b){const i=+`${n}.${b}`;return isNaN(i)?`${n}.${b}`:i}else return n}_formatNumber(e,t){if(!t)return Number(e==null?void 0:e.toFixed(this._precision));switch(t){case"integer":return String(Math.round(e));case"currency":return`$${e}`;case"percent":return`${e*100}%`;default:return this._formatOthers(e,t)}}strformat({formatString:e=""},t,r){return this._strFormat(e,t,r)}_strFormat(e,t,r){return e.replace(/{[^{}]+}/g,M=>{if(!M)return M;const n=M.replace(/[{}]/g,"").split(","),b=Number(n[0]);if(isNaN(b)||t.length<=b)return M;const z=t[b];if(n.length===1)return typeof z=="number"?r?this._intlFormat.format(z):Number(z.toFixed(this._precision)):z===void 0?"":z;if(n.length===2){const i=n[1].trim();return i==="number"?r?this._intlFormat.format(z):Number(z.toFixed(this._precision)):i==="date"?O1(z).format("LL"):M}else{const i=n[1].trim(),c=n[2].trim();if(i==="number")return this._formatNumber(z,c);if(i==="date"||i==="time"){let O="YYYY-MM-DD";switch(c){case"long":O="LL";break;case"short":O="L";break;default:c&&(O=c)}return O1(z).format(O)}return M}})}}class Q_{constructor(){}new({type:e}){const t=e.split(",");return j3(t)}copy({id:e}){if(!e)return;const t=j3([e.keyTypeName,e.typeName]);return t._value=Object.assign(Object.create(null),e._value),t}get({id:e,key:t}){if(e)return e._value[t]}put({id:e,key:t,value:r}){if(!e)return;const M=e._value[t];return e._value[t]=r,M}keys({id:e}){if(!e)return;const t=p1(0,void 0,e.keyTypeName);let r=Object.keys(e._value);return[N0.INT,N0.FLOAT].includes(e.keyTypeName)?r=r.map(M=>M==="undefined"?void 0:parseFloat(M)):e.keyTypeName===N0.BOOL&&(r=r.map(M=>M==="undefined"?void 0:M==="true")),t._value=r,t}size({id:e}){if(e)return Object.keys(e._value).length}clear({id:e}){e&&(e._value=Object.create(null))}remove({id:e,key:t}){if(!e)return;const r=e._value[t];return delete e._value[t],r}values({id:e}){if(!e)return;const t=p1(0,void 0,e.typeName);return t._value=Object.values(e._value),t}put_all({id:e,id2:t}){if(e){if(!t)return e;Object.assign(e._value,t._value)}}contains({id:e,key:t}){if(e)return t in e._value}}function j3(o){return{isMap:!0,keyTypeName:o[0],typeName:o[1],_value:Object.create(null),type:e1.MAP}}class Z_{constructor(e){C(this,"_variables");this._variables=e}new({price:e,time:t,index:r}){return RM(e,r,t)}now({price:e}){const{time:t,bar_index:r}=this._variables;return RM(e,r,t)}copy({id:e}){if(e)return RM(e.price,e.index,e.time)}from_index({price:e,index:t}){return RM(e,t)}from_time({price:e,time:t}){return RM(e,void 0,t)}}function RM(o,e,t){return{price:o,index:e&&Math.floor(e),time:t,type:e1.CHART_POINT,typeName:N0.CHART_POINT}}const em=["point","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"],tm=["x","y","text","xloc","yloc","color","style","textcolor","size","textalign","tooltip","text_font_family","force_overlay"];class rm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultLabel",{text:"",xloc:w1.bar_index,yloc:te.price,size:f2.normal,style:T1.styleLabelDown,textalign:S0.alignCenter});this._variables=e,this._errorListener=t}new(e,t,r){D0(this._errorListener,"label.new",this._variables.__requestName,t);const{time:M,high:n,low:b,bar_index:z}=this._variables,i=`label_${t}_${z}`;e=this._parameterHandle(e,r),I1(e,["color","textcolor"]);const c={...this._defaultLabel,...e,id:i,time:M,high:n,low:b,bar_index:z};e.x&&(c.x=e.x&&Math.floor(e.x)),e.point&&(c.x=c.xloc===w1.bar_index?e.point.index:e.point.time,c.y=e.point.price),c.yloc===te.abovebar?c.y=n:c.yloc===te.belowbar&&(c.y=b),this._verfiyArgs(e,t);const O=H3(i,c);return t.startsWith("export")||this._variables.label.add(i,c,O),O}_parameterHandle(e,t){const{x:r,y:M,point:n,...b}=e;if(typeof n=="object"||typeof r=="number"||typeof M=="number")return e;const z=b;if(t[0]===em[0]&&(typeof n=="number"||this._preVerfiyArgs(e)))for(const[i,c]of t.entries()){const O=z[c];z[c]=void 0,z[tm[i]]=O}return z}_preVerfiyArgs(e){const{xloc:t,yloc:r,style:M,size:n,textalign:b,text_font_family:z}=e;return this._paramVerfiyHandle(M,Object.values(T1))||this._paramVerfiyHandle(t,Object.values(w1))||this._paramVerfiyHandle(r,Object.values(te))||this._paramVerfiyHandle(n,Object.values(f2))||this._paramVerfiyHandle(b,[S0.alignLeft,S0.alignCenter,S0.alignRight])||this._paramVerfiyHandle(z,Object.values(Ue))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{xloc:r,yloc:M,style:n,size:b,textalign:z,text_font_family:i}=e,c="label.new";this._paramVerfiy(n,t,c,Object.values(T1),"style"),this._paramVerfiy(r,t,c,Object.values(w1),"xloc"),this._paramVerfiy(M,t,c,Object.values(te),"yloc"),this._paramVerfiy(b,t,c,Object.values(f2),"size"),this._paramVerfiy(z,t,c,[S0.alignLeft,S0.alignCenter,S0.alignRight],"textalign"),this._paramVerfiy(i,t,c,Object.values(Ue),"text_font_family")}_paramVerfiy(e="",t,r,M,n){this._paramVerfiyHandle(e,M)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}label(e){return e.x}copy({id:e},t){if(!e)return;D0(this._errorListener,"label.copy",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`label_${t}_${r}`,n=this._getLabel(e),b={...n||{},id:M,bar_index:r},z=H3(M,b);return n&&this._variables.label.add(M,b,z),z}get_x({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_x",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.x}get_y({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_y",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.y}set_x({id:e,x:t},r){if(!e)return;D0(this._errorListener,"label.set_x",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.x=t&&Math.floor(t))}set_y({id:e,y:t},r){if(!e)return;D0(this._errorListener,"label.set_y",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.y=t)}delete({id:e},t){if(!e)return;D0(this._errorListener,"label.delete",this._variables.__requestName,t);const r=this._getLabel(e);this._variables.label.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_text({id:e},t){var r;if(e)return D0(this._errorListener,"label.get_text",this._variables.__requestName,t),(r=this._getLabel(e))==null?void 0:r.text}set_xy({id:e,x:t,y:r},M){if(!e)return;D0(this._errorListener,"label.set_xy",this._variables.__requestName,M);const n=this._getLabel(e);n&&(n.x=t&&Math.floor(t),n.y=r)}set_size({id:e,size:t},r){if(!e)return;D0(this._errorListener,"label.set_size",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.size=t),this._paramVerfiy(t,r,"label.set_size",Object.values(f2),"size")}set_xloc({id:e,x:t,xloc:r},M){if(!e)return;D0(this._errorListener,"label.set_xloc",this._variables.__requestName,M);const n=this._getLabel(e);n&&(n.x=t&&Math.floor(t),n.xloc=r,this._paramVerfiy(r,M,"label.set_xloc",Object.values(w1),"xloc"))}set_yloc({id:e,yloc:t},r){if(!e)return;D0(this._errorListener,"label.set_yloc",this._variables.__requestName,r);const M=this._getLabel(e),{high:n,low:b}=this._variables;M&&(M.yloc=t,t===te.abovebar?M.y=n:t===te.belowbar&&(M.y=b),this._paramVerfiy(t,r,"label.set_yloc",Object.values(te),"yloc"))}set_style({id:e,style:t},r){if(!e)return;D0(this._errorListener,"label.set_style",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.style=t),this._paramVerfiy(t,r,"label.set_style",Object.values(T1),"style")}set_color({id:e,...t},r){if(!e)return;D0(this._errorListener,"label.set_color",this._variables.__requestName,r);const M=this._getLabel(e);I1(t,["color"]),M&&(M.color=t.color)}set_tooltip({id:e,tooltip:t},r){if(!e)return;D0(this._errorListener,"label.set_tooltip",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.tooltip=t)}set_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"label.set_point",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.x=M.xloc===w1.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,M.y=t==null?void 0:t.price)}set_text({id:e,text:t},r){if(!e)return;D0(this._errorListener,"label.set_text",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.text=t)}set_textcolor({id:e,...t},r){if(!e)return;D0(this._errorListener,"label.set_textcolor",this._variables.__requestName,r);const M=this._getLabel(e);I1(t,["textcolor"]),M&&(M.textcolor=t.textcolor)}set_textalign({id:e,textalign:t},r){if(!e)return;D0(this._errorListener,"label.set_textalign",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.textalign=t),this._paramVerfiy(t,r,"label.set_textalign",[S0.alignLeft,S0.alignCenter,S0.alignRight],"textalign")}set_text_font_family({id:e,text_font_family:t},r){if(!e)return;D0(this._errorListener,"label.set_text_font_family",this._variables.__requestName,r);const M=this._getLabel(e);M&&(M.text_font_family=t),this._paramVerfiy(t,r,"label.set_text_font_family",Object.values(Ue),"text_font_family")}_getLabel(e){return this._variables.label.get(e.id)||e.data}}function H3(o,e){return{type:e1.LABEL,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}const Mm={freq_all:fe.freqAll,freq_once_per_bar:fe.freqOncePerBar,freq_once_per_bar_close:fe.freqOncePerBarClose},om={gaps_off:ke.gapsOff,gaps_on:ke.gapsOn,lookahead_off:ke.lookaheadOff,lookahead_on:ke.lookaheadOn},xr={aqua:"#00BCD4",black:"#363A45",blue:"#2962ff",fuchsia:"#E040FB",gray:"#787B86",green:"#4CAF50",lime:"#00E676",maroon:"#880E4F",navy:"#311B92",olive:"#808000",orange:"#FF9800",purple:"#9C27B0",red:"#FF5252",silver:"#B2B5BE",teal:"#00897B",white:"#FFFFFF",yellow:"#FFEB3B"},Y3={AUD:"AUD",BTC:"BTC",CAD:"CAD",CHF:"CHF",ETH:"ETH",EUR:"EUR",GBP:"GBP",HKD:"HKD",INR:"INR",JPY:"JPY",KRW:"KRW",MYR:"MYR",NOK:"NOK",NONE:"NONE",NZD:"NZD",RUB:"RUB",SEK:"SEK",SGD:"SGD",TRY:"TRY",USD:"USD",USDT:"USDT",ZAR:"ZAR"},nm={friday:6,monday:2,saturday:7,sunday:1,thursday:5,tuesday:3,wednesday:4},G3={all:[le.dataWindow,le.pane,le.priceScale,le.statusLine],data_window:[le.dataWindow],none:[],pane:[le.pane],price_scale:[le.priceScale],status_line:[le.statusLine]},bm={both:P2.both,left:P2.left,none:P2.none,right:P2.right},pm={inherit:A1.inherit,mintick:A1.mintick,percent:A1.percent,price:A1.price,volume:A1.volume},zm={style_solid:HM.styleSolid,style_dashed:HM.styleDashed,style_dotted:HM.styleDotted},im={style_arrowdown:T1.styleArrowdown,style_arrowup:T1.styleArrowup,style_circle:T1.styleCircle,style_cross:T1.styleCross,style_diamond:T1.styleDiamond,style_flag:T1.styleFlag,style_label_center:T1.styleLabelCenter,style_label_down:T1.styleLabelDown,style_label_left:T1.styleLabelLeft,style_label_lower_left:T1.styleLabelLowerLeft,style_label_lower_right:T1.styleLabelLowerRight,style_label_right:T1.styleLabelRight,style_label_up:T1.styleLabelUp,style_label_upper_left:T1.styleLabelUpperLeft,style_label_upper_right:T1.styleLabelUpperRight,style_none:T1.styleNone,style_square:T1.styleSquare,style_text_outline:T1.styleTextOutline,style_triangledown:T1.styleTriangledown,style_triangleup:T1.styleTriangleup,style_xcross:T1.styleXcross},cm={style_arrow_both:G1.styleArrowBoth,style_arrow_left:G1.styleArrowLeft,style_arrow_right:G1.styleArrowRight,style_dashed:G1.styleDashed,style_dotted:G1.styleDotted,style_solid:G1.styleSolid},am={abovebar:$e.abovebar,absolute:$e.absolute,belowbar:$e.belowbar,bottom:$e.bottom,top:$e.top},sm={e:2.718281828459045,phi:1.618033988749895,pi:3.141592653589793,rphi:.6180339887498948},Om={style_area:ee.styleArea,style_areabr:ee.styleAreabr,style_circles:ee.styleCircles,style_columns:ee.styleColumns,style_cross:ee.styleCross,style_histogram:ee.styleHistogram,style_line:ee.styleLine,style_linebr:ee.styleLinebr,style_stepline:ee.styleStepline,style_stepline_diamond:ee.styleSteplineDiamond,style_steplinebr:ee.styleSteplinebr},um={bottom_center:k2.bottomCenter,bottom_left:k2.bottomLeft,bottom_right:k2.bottomRight,middle_center:k2.middleCenter,middle_left:k2.middleLeft,middle_right:k2.middleRight,top_center:k2.topCenter,top_left:k2.topLeft,top_right:k2.topRight},Am={left:YM.left,none:YM.none,right:YM.right},fm={arrowdown:X2.arrowdown,arrowup:X2.arrowup,circle:X2.circle,cross:X2.cross,diamond:X2.diamond,flag:X2.flag,labeldown:X2.labeldown,labelup:X2.labelup,square:X2.square,triangledown:X2.triangledown,triangleup:X2.triangleup,xcross:X2.xcross},lm={auto:f2.auto,huge:f2.huge,large:f2.large,normal:f2.normal,small:f2.small,tiny:f2.tiny},dm={cash:p2.cash,fixed:p2.fixed,percent_of_equity:p2.percentOfEquity,commission:{cash_per_contract:O2.cashPerContract,cash_per_order:O2.cashPerOrder,percent:O2.percent},direction:{all:a1.all,long:a1.long,short:a1.short},oca:{cancel:je.cancel,none:je.none,reduce:je.reduce}},qm={align_bottom:S0.alignBottom,align_center:S0.alignCenter,align_left:S0.alignLeft,align_right:S0.alignRight,align_top:S0.alignTop,wrap_auto:S0.wrapAuto,wrap_none:S0.wrapNone},hm={bar_index:w1.bar_index,bar_time:w1.bar_time},Wm={abovebar:te.abovebar,belowbar:te.belowbar,price:te.price},_m={actual:GM.actual,estimate:GM.estimate,standardized:GM.standardized};class hp{constructor(){C(this,"adjustment",{dividends:jM.dividends,none:jM.none,splits:jM.splits});C(this,"alert",Mm);C(this,"barmerge",om);C(this,"color",xr);C(this,"currency",Y3);C(this,"dayofweek",nm);C(this,"earnings",_m);C(this,"display",G3);C(this,"extend",bm);C(this,"font",{family_default:Ue.familyDefault,family_monospace:Ue.familyMonospace});C(this,"format",pm);C(this,"hline",zm);C(this,"label",im);C(this,"line",cm);C(this,"location",am);C(this,"math",sm);C(this,"order",{ascending:ur.ascending,descending:ur.descending});C(this,"plot",Om);C(this,"position",um);C(this,"scale",Am);C(this,"session",{extended:ft.extended,regular:ft.regular});C(this,"shape",fm);C(this,"size",lm);C(this,"splits",{denominator:"denominator",numerator:"numerator"});C(this,"strategy",dm);C(this,"text",qm);C(this,"xloc",hm);C(this,"yloc",Wm);C(this,"true",!0);C(this,"false",!1)}updateData(){}}class mm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultPolyline",{curved:!1,closed:!1,xloc:w1.bar_index,line_color:xr.blue,line_style:G1.styleSolid,line_width:1});this._variables=e,this._errorListener=t}new(e,t){var z;D0(this._errorListener,"polyline.new",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`polyline_${t}_${r}`,n=Object.assign({},this._defaultPolyline,e,{id:M,bar_index:r,points:(z=e.points)==null?void 0:z._value.map(i=>({time:i.time,index:i.index,price:i.price}))});I1(n,["line_color","fill_color"]);const b=gm(M,n);return this._verfiyArgs(e,t),t.startsWith("export")||this._variables.polyline.add(M,n,b),b}_verfiyArgs(e,t){const{line_style:r,xloc:M}=e,n="polyline.new";this._paramVerfiy(r,t,n,Object.values(G1),"line_style"),this._paramVerfiy(M,t,n,Object.values(w1),"xloc")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}delete({id:e}){if(!e)return;const t=this._variables.polyline.get(e.id)||e.data;this._variables.polyline.delete(e.id,this._variables.bar_index,t==null?void 0:t.id)}}function gm(o,e){return{type:e1.POLYLINE,id:o,data:e,_suffix:"",isDraw:!0,preId:""}}const Rm=["first_point","second_point","xloc","extend","color","style","width","force_overlay"],vm=["x1","y1","x2","y2","xloc","extend","color","style","width","force_overlay"];class nt{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultLine",{xloc:w1.bar_index,extend:P2.none,style:G1.styleSolid});this._variables=e,this._errorListener=t}new(e,t,r){D0(this._errorListener,"line.new",this._variables.__requestName,t);const{bar_index:M}=this._variables,n=`line_${t}_${M}`;e=this._parameterHandle(e,r);const{first_point:b,second_point:z,...i}=e;I1(i,["color"]);const c={...this._defaultLine,...i,id:n,bar_index:M},{x1:O,x2:s}=c;if(O&&(c.x1=O&&Math.floor(O)),s&&(c.x2=s&&Math.floor(s)),b&&z){const l=c.xloc===w1.bar_index?b==null?void 0:b.index:b==null?void 0:b.time,q=c.xloc===w1.bar_index?z==null?void 0:z.index:z==null?void 0:z.time;Object.assign(c,{x1:l,y1:b==null?void 0:b.price,x2:q,y2:z==null?void 0:z.price})}this._verfiyArgs(i,t);const u=V3(n,c);return t.startsWith("export")||this._variables.line.add(n,c,u),u}_parameterHandle(e,t){const{x1:r,y1:M,x2:n,y2:b,first_point:z,second_point:i,...c}=e;if(typeof z=="object"||typeof i=="object"||typeof r=="number"||typeof M=="number"||typeof n=="number"||typeof b=="number")return e;const O=c;if(t[0]===vm[0]&&(typeof r=="object"||typeof M=="object"||typeof n=="string"||typeof b=="string"||this._preVerfiyArgs(e)))for(const[s,u]of t.entries()){const l=O[u];O[u]=void 0,O[Rm[s]]=l}return O}_preVerfiyArgs(e){const{extend:t,xloc:r,style:M}=e;return this._paramVerfiyHandle(M,Object.values(G1))||this._paramVerfiyHandle(r,Object.values(w1))||this._paramVerfiyHandle(t,Object.values(P2))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{extend:r,xloc:M,style:n}=e,b="line.new";this._paramVerfiy(n,t,b,Object.values(G1),"style"),this._paramVerfiy(r,t,b,Object.values(P2),"extend"),this._paramVerfiy(M,t,b,Object.values(w1),"xloc")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}static __setFillKeys(e,t){e.fillKeys.includes(t)||e.fillKeys.push(t)}static __updateFillKeys(e,t,r){const M=e.fillKeys.findIndex(n=>n===t);M!==-1?e.fillKeys.splice(M,1,r):e.fillKeys.push(r)}line(e){return e.x}copy({id:e},t){if(!e)return;const{bar_index:r}=this._variables,M=`line_${t}_${r}`,n=this._getLine(e,t,"copy"),b={...n,id:M,bar_index:r,isVar:void 0},z=V3(M,b);return n&&this._variables.line.add(M,b,z),z}delete({id:e},t){if(!e)return;for(const M of e.fillKeys)this._variables.linefill.delete(M,this._variables.bar_index);const r=this._getLine(e,t,"delete");this._variables.line.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_x1({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_x1"))==null?void 0:r.x1}get_x2({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_x2"))==null?void 0:r.x2}get_y1({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_y1"))==null?void 0:r.y1}get_y2({id:e},t){var r;if(e)return(r=this._getLine(e,t,"get_y2"))==null?void 0:r.y2}set_x1({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"set_x1");M&&(M.x1=t&&Math.floor(t))}set_x2({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"set_x2");M&&(M.x2=t&&Math.floor(t))}set_y1({id:e,y:t},r){if(!e)return;const M=this._getLine(e,r,"set_y1");M&&(M.y1=t)}set_y2({id:e,y:t},r){if(!e)return;const M=this._getLine(e,r,"set_y2");M&&(M.y2=t)}set_xy1({id:e,x:t,y:r},M){if(!e)return;const n=this._getLine(e,M,"set_xy1");n&&(n.x1=t&&Math.floor(t),n.y1=r)}set_xy2({id:e,x:t,y:r},M){if(!e)return;const n=this._getLine(e,M,"set_xy2");n&&(n.x2=t&&Math.floor(t),n.y2=r)}set_xloc({id:e,xloc:t,x1:r,x2:M},n){if(!e)return;const b=this._getLine(e,n,"set_xloc");b&&(b.xloc=t,b.x1=r&&Math.floor(r),b.x2=M&&Math.floor(M),this._paramVerfiy(t,n,"line.set_xloc",Object.values(w1),"xloc"))}get_price({id:e,x:t},r){if(!e)return;const M=this._getLine(e,r,"get_price");if(t===void 0)return t;if(M&&M.xloc===w1.bar_index){const{x1:n,y1:b,x2:z,y2:i}=M;return n===void 0||z===void 0||b===void 0||i===void 0?void 0:(i-b)/(z-n)*(t-n)+b}}set_color({id:e,...t},r){if(!e)return;const M=this._getLine(e,r,"set_color");M&&(I1(t,["color"]),M.color=t.color)}set_style({id:e,style:t},r){if(!e)return;const M=this._getLine(e,r,"set_style");M&&(M.style=t,this._paramVerfiy(t,r,"line.set_style",Object.values(G1),"style"))}set_width({id:e,width:t},r){if(!e)return;const M=this._getLine(e,r,"set_width");M&&(M.width=t)}set_extend({id:e,extend:t},r){if(!e)return;const M=this._getLine(e,r,"set_extend");M&&(M.extend=t,this._paramVerfiy(t,r,"line.set_extend",Object.values(P2),"extend"))}set_first_point({id:e,point:t},r){if(!e)return;const M=this._getLine(e,r,"set_first_point");if(M){const{index:n,time:b,price:z}=t||{},i=M.xloc===w1.bar_index?n:b,c=z;i&&(M.x1=i),c&&(M.y1=c)}}set_second_point({id:e,point:t},r){if(!e)return;const M=this._getLine(e,r,"set_second_point");if(M){const{index:n,time:b,price:z}=t||{},i=M.xloc===w1.bar_index?n:b,c=z;i&&(M.x2=i),c&&(M.y2=c)}}_getLine(e,t,r){return D0(this._errorListener,`line.${r}`,this._variables.__requestName,t),this._variables.line.get(e.id)||e.data}}function V3(o,e){return{type:e1.LINE,id:o,data:e,_suffix:"",preId:"",fillKeys:[],isDraw:!0}}class Lm{constructor(e){C(this,"_variables");this._variables=e}new(e,t){var q,A;const{line1:r,line2:M}=e,{bar_index:n,linefill:b}=this._variables,z=`linefill_${t}_${n}`,i=r==null?void 0:r.data,c=M==null?void 0:M.data,O=`${(i==null?void 0:i.id)||""}${(c==null?void 0:c.id)||""}`;i&&(i.linefills=i.linefills||[],i.linefills.push(z)),c&&(c.linefills=c.linefills||[],c.linefills.push(z)),I1(e,["color"]);const s={line1:i,line2:c,color:e.color,id:z,bar_index:n},u=this._verifyLineKey(O);u?(b.delete(u,n),r&&i&&(i.linefills=(q=i.linefills)==null?void 0:q.filter(h=>h!==u),nt.__updateFillKeys(r,u,z)),M&&c&&(c.linefills=(A=c.linefills)==null?void 0:A.filter(h=>h!==u),nt.__updateFillKeys(M,u,z))):(r&&nt.__setFillKeys(r,z),M&&nt.__setFillKeys(M,z));const l=Nm(z,s,O,r,M);return t.startsWith("export")||(i||c)&&b.add(z,s,l),l}_verifyLineKey(e){for(const[t,r]of this._variables.linefill.__allInstance)if(r.lineKey===e)return t}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables,M=e.id;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const n=e.id.split("_");n.pop(),e.id=`${n.join("_")}_${t}`}return e.line1&&nt.__updateFillKeys(e.line1,M,e.id),e.line2&&nt.__updateFillKeys(e.line2,M,e.id),r||(e.preId=e.id),e.id}delete({id:e}){var r,M;if(!e)return;const t=this._variables.linefill.get(e.id)||e.data;if(t){const{line1:n,line2:b}=t;n&&(n.linefills=(r=n.linefills)==null?void 0:r.filter(z=>z!==e.id)),b&&(b.linefills=(M=b.linefills)==null?void 0:M.filter(z=>z!==e.id))}e.line1=void 0,e.line2=void 0,this._variables.linefill.delete(e.id,this._variables.bar_index,t==null?void 0:t.id)}get_line1({id:e}){return e==null?void 0:e.line1}get_line2({id:e}){return e==null?void 0:e.line2}set_color({id:e,...t}){if(!e)return;const r=this._variables.linefill.get(e.id)||e.data;r&&(I1(t,["color"]),r.color=t.color)}}function Nm(o,e,t,r,M){return{type:e1.LINEFILL,id:o,data:e,_suffix:"",preId:"",line1:r,line2:M,isDraw:!0,lineKey:t}}const ym=["top_left","bottom_right","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"],Bm=["left","top","right","bottom","border_color","border_width","border_style","extend","xloc","bgcolor","text","text_size","text_color","text_halign","text_valign","text_wrap","text_font_family","force_overlay"];class wm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultBox",{border_color:xr.blue,border_width:1,bgcolor:xr.blue,xloc:w1.bar_index,extend:P2.none,style:G1.styleSolid,text:"",text_size:f2.auto,text_color:xr.black,text_halign:S0.alignCenter,text_valign:S0.alignCenter,text_wrap:S0.wrapNone});this._variables=e,this._errorListener=t}box({x:e}){return e}new(e,t,r){D0(this._errorListener,"box.new",this._variables.__requestName,t);const{bar_index:M}=this._variables,n=`box_${t}_${M}`;e=this._parameterHandle(e,r);const{top_left:b,bottom_right:z,...i}=e,c={...this._defaultBox,...i,id:n,bar_index:M};I1(c,["border_color","bgcolor","text_color"]);const{left:O,right:s}=c;if(O&&(c.left=O&&Math.floor(O)),s&&(c.right=s&&Math.floor(s)),b){const{price:l,time:q,index:A}=b;c.top=l,c.left=c.xloc===w1.bar_index?A:q}if(z){const{price:l,time:q,index:A}=z;c.bottom=l,c.right=c.xloc===w1.bar_index?A:q}this._verfiyArgs(i,t);const u=K3(n,c);return t.startsWith("export")||this._variables.box.add(n,c,u),u}_parameterHandle(e,t){const{top_left:r,bottom_right:M,top:n,bottom:b,left:z,right:i,...c}=e;if(typeof r=="object"||typeof M=="object"||typeof n=="number"||typeof b=="number"||typeof z=="number"||typeof i=="number")return e;const O=c;if(t[0]===ym[0]&&(typeof r=="number"||typeof M=="number"||this._preVerfiyArgs(e)))for(const[s,u]of t.entries()){const l=O[u];O[u]=void 0,O[Bm[s]]=l}return O}_preVerfiyArgs(e){const{border_style:t,extend:r,xloc:M,text_size:n,text_halign:b,text_valign:z,text_wrap:i,text_font_family:c}=e;return this._paramVerfiyHandle(t,[G1.styleDashed,G1.styleDotted,G1.styleSolid])||this._paramVerfiyHandle(r,Object.values(P2))||this._paramVerfiyHandle(M,Object.values(w1))||this._paramVerfiyHandle(n,Object.values(f2))||this._paramVerfiyHandle(b,[S0.alignLeft,S0.alignCenter,S0.alignRight])||this._paramVerfiyHandle(z,[S0.alignBottom,S0.alignCenter,S0.alignTop])||this._paramVerfiyHandle(i,[S0.wrapAuto,S0.wrapNone])||this._paramVerfiyHandle(c,Object.values(Ue))}_paramVerfiyHandle(e="",t){return e&&!t.includes(e)}_verfiyArgs(e,t){const{border_style:r,extend:M,xloc:n,text_size:b,text_halign:z,text_valign:i,text_wrap:c,text_font_family:O}=e,s="box.new";this._paramVerfiy(r,t,s,[G1.styleDashed,G1.styleDotted,G1.styleSolid],"border_style"),this._paramVerfiy(M,t,s,Object.values(P2),"extend"),this._paramVerfiy(n,t,s,Object.values(w1),"xloc"),this._paramVerfiy(b,t,s,Object.values(f2),"text_size"),this._paramVerfiy(z,t,s,[S0.alignLeft,S0.alignCenter,S0.alignRight],"text_halign"),this._paramVerfiy(i,t,s,[S0.alignBottom,S0.alignCenter,S0.alignTop],"text_valign"),this._paramVerfiy(c,t,s,[S0.wrapAuto,S0.wrapNone],"text_wrap"),this._paramVerfiy(O,t,s,Object.values(Ue),"text_font_family")}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}copy({id:e},t){if(!e)return;D0(this._errorListener,"box.copy",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`box_${t}_${r}`,n=this._getBox(e),b={...n,id:M,bar_index:r},z=K3(M,b);return n&&this._variables.box.add(M,b,z),z}delete({id:e},t){if(!e)return;D0(this._errorListener,"box.delete",this._variables.__requestName,t);const r=this._getBox(e)||e.data;this._variables.box.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}get_top({id:e},t){if(!e)return;D0(this._errorListener,"box.get_top",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.top}get_bottom({id:e},t){if(!e)return;D0(this._errorListener,"box.get_bottom",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.bottom}get_left({id:e},t){if(!e)return;D0(this._errorListener,"box.get_left",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.left}get_right({id:e},t){if(!e)return;D0(this._errorListener,"box.get_right",this._variables.__requestName,t);const r=this._getBox(e);return r&&r.right}set_top({id:e,top:t},r){if(!e)return;D0(this._errorListener,"box.set_top",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.top=t)}set_bottom({id:e,bottom:t},r){if(!e)return;D0(this._errorListener,"box.set_bottom",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.bottom=t)}set_text({id:e,text:t},r){if(!e)return;D0(this._errorListener,"box.set_text",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text=t)}set_left({id:e,left:t},r){if(!e)return;D0(this._errorListener,"box.set_left",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.left=t&&Math.floor(t))}set_right({id:e,right:t},r){if(!e)return;D0(this._errorListener,"box.set_right",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.right=t&&Math.floor(t))}set_extend({id:e,extend:t},r){if(!e)return;D0(this._errorListener,"box.set_extend",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.extend=t,this._paramVerfiy(t,r,"box.set_extend",Object.values(P2),"extend"))}set_bgcolor({id:e,color:t},r){if(!e)return;D0(this._errorListener,"box.set_bgcolor",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.bgcolor=t,I1(M,["bgcolor"]))}set_border_color({id:e,color:t},r){if(!e)return;D0(this._errorListener,"box.set_border_color",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_color=t,I1(M,["border_color"]))}set_border_width({id:e,width:t},r){if(!e)return;D0(this._errorListener,"box.set_border_width",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_width=t)}set_border_style({id:e,style:t},r){if(!e)return;D0(this._errorListener,"box.set_border_style",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.border_style=t,this._paramVerfiy(t,r,"box.set_border_style",[G1.styleDashed,G1.styleDotted,G1.styleSolid],"style"))}set_lefttop({id:e,left:t,top:r},M){if(!e)return;D0(this._errorListener,"box.set_lefttop",this._variables.__requestName,M);const n=this._getBox(e);n&&(n.left=t&&Math.floor(t),n.top=r)}set_rightbottom({id:e,right:t,bottom:r},M){if(!e)return;D0(this._errorListener,"box.set_rightbottom",this._variables.__requestName,M);const n=this._getBox(e);n&&(n.right=t&&Math.floor(t),n.bottom=r)}set_text_size({id:e,text_size:t},r){if(!e)return;D0(this._errorListener,"box.set_text_size",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_size=t,this._paramVerfiy(t,r,"box.set_text_size",Object.values(f2),"text_size"))}set_text_wrap({id:e,text_wrap:t},r){if(!e)return;D0(this._errorListener,"box.set_text_wrap",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_wrap=t,this._paramVerfiy(t,r,"box.set_text_wrap",[S0.wrapAuto,S0.wrapNone],"text_wrap"))}set_text_color({id:e,text_color:t},r){if(!e)return;D0(this._errorListener,"box.set_text_color",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_color=t,I1(M,["text_color"]))}set_text_halign({id:e,text_halign:t},r){if(!e)return;D0(this._errorListener,"box.set_text_halign",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_halign=t,this._paramVerfiy(t,r,"box.set_text_halign",[S0.alignLeft,S0.alignCenter,S0.alignRight],"text_halign"))}set_text_valign({id:e,text_valign:t},r){if(!e)return;D0(this._errorListener,"box.set_text_valign",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_valign=t,this._paramVerfiy(t,r,"box.set_text_valign",[S0.alignBottom,S0.alignCenter,S0.alignTop],"text_valign"))}set_top_left_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"box.set_top_left_point",this._variables.__requestName,r);const M=this._getBox(e);if(M){const{index:n,price:b,time:z}=t||{};M.top=b,M.left=M.xloc===w1.bar_index?n:z}}set_bottom_right_point({id:e,point:t},r){if(!e)return;D0(this._errorListener,"box.set_bottom_right_point",this._variables.__requestName,r);const M=this._getBox(e);if(M){const{index:n,price:b,time:z}=t||{};M.bottom=b,M.right=M.xloc===w1.bar_index?n:z}}set_text_font_family({id:e,text_font_family:t},r){if(!e)return;D0(this._errorListener,"box.set_text_font_family",this._variables.__requestName,r);const M=this._getBox(e);M&&(M.text_font_family=t,this._paramVerfiy(t,r,"box.set_text_font_family",Object.values(Ue),"text_font_family"))}_getBox(e){return this._variables.box.get(e.id)||e.data}}function K3(o,e){return{type:e1.BOX,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}class Dm{constructor(e,t){C(this,"_variables");C(this,"_errorListener");C(this,"_defaultCell",{column:0,row:0,text:"",text_color:xr.black,text_halign:S0.alignCenter,text_valign:S0.alignCenter,text_size:f2.normal});C(this,"_defaultTable",{position:k2.topLeft,columns:0,rows:0,frame_width:0,border_width:0});this._variables=e,this._errorListener=t}table({x:e}){return e}new(e,t){D0(this._errorListener,"table.new",this._variables.__requestName,t);const{bar_index:r}=this._variables,M=`table_${t}_${r}`,{rows:n}=e;I1(e,["text_color","bgcolor","border_color"]);const b=Array.from(Array(n),()=>[]),z=t.split("_"),i=z.pop(),c=z.pop(),O={...this._defaultTable,...e,cell:b,id:M,bar_index:r,line:c,col:i},s=Xm(M,O);return this._paramVerfiy(e.position,t,"table.new",Object.values(k2),"position"),t.startsWith("export")||this._variables.table.add(M,O,s),s}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}updateId(e){const{bar_index:t,_isRealTimeBar:r}=this._variables;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const M=e.id.split("_");M.pop(),e.id=`${M.join("_")}_${t}`}return r||(e.preId=e.id),e.id}cell({table_id:e,...t},r){if(!e)return;this._verfiyRequestFunc(r,"cell");let{column:M=0,row:n=0}=t;[n,M]=this._rowColToInt(n,M);const b={...this._defaultCell,...t,row:n,column:M},z=this._getTable(e);if(z){const i=z.cell||[],c=i[n]||[];c[M]=b,i[n]=c,z.cell=i}}cell_set_bgcolor({table_id:e,column:t=0,row:r=0,bgcolor:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_bgcolor");const b=this._getTableItem(e,t,r);b&&(b.bgcolor=M)}cell_set_height({table_id:e,column:t=0,row:r=0,height:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_height");const b=this._getTableItem(e,t,r);b&&(b.height=M)}cell_set_text({table_id:e,column:t=0,row:r=0,text:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text");const b=this._getTableItem(e,t,r);b&&(b.text=M)}cell_set_text_color({table_id:e,column:t=0,row:r=0,text_color:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_color");const b=this._getTableItem(e,t,r);b&&(b.text_color=M,I1(b,["text_color"]))}cell_set_text_font_family({table_id:e,column:t=0,row:r=0,text_font_family:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_font_family");const b=this._getTableItem(e,t,r);b&&(b.text_font_family=M)}cell_set_text_halign({table_id:e,column:t=0,row:r=0,text_halign:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_halign");const b=this._getTableItem(e,t,r);b&&(b.text_halign=M)}cell_set_text_valign({table_id:e,column:t=0,row:r=0,text_valign:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_valign");const b=this._getTableItem(e,t,r);b&&(b.text_valign=M)}cell_set_text_size({table_id:e,column:t=0,row:r=0,text_size:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_text_size");const b=this._getTableItem(e,t,r);b&&(b.text_size=M)}cell_set_tooltip({table_id:e,column:t=0,row:r=0,tooltip:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_tooltip");const b=this._getTableItem(e,t,r);b&&(b.tooltip=M)}cell_set_width({table_id:e,column:t=0,row:r=0,width:M},n){if(!e)return;this._verfiyRequestFunc(n,"cell_set_width");const b=this._getTableItem(e,t,r);b&&(b.width=M)}clear({table_id:e,start_column:t=0,start_row:r=0,end_column:M=0,end_row:n=0},b){if(!e)return;this._verfiyRequestFunc(b,"clear");const z=this._getTable(e);if(z){const i=z.cell;if(i)for(let c=r;c<=n;c++)for(let O=t;O<=M;O++){const s=i[c];s&&(s[O]=void 0)}}}delete({table_id:e},t){if(!e)return;this._verfiyRequestFunc(t,"delete");const r=this._getTable(e);this._variables.table.delete(e.id,this._variables.bar_index,r==null?void 0:r.id)}merge_cells({table_id:e,start_column:t=0,start_row:r=0,end_column:M=0,end_row:n=0},b){if(!e)return;if(this._verfiyRequestFunc(b,"merge_cells"),t>M||r>n){this._errorListener.addError(N1.mergeCellErr,b,K0.Error);return}const z=this._getTable(e);if(!z)return;const i=z.merge_cells||[];i.push({start_column:t,start_row:r,end_column:M,end_row:n}),z.merge_cells=i}set_bgcolor({table_id:e,bgcolor:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_bgcolor");const M=this._getTable(e);M&&(M.bgcolor=t,I1(M,["bgcolor"]))}set_border_color({table_id:e,border_color:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_border_color");const M=this._getTable(e);M&&(M.border_color=t,I1(M,["border_color"]))}set_border_width({table_id:e,border_width:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_border_width");const M=this._getTable(e);M&&(M.border_width=t)}set_frame_color({table_id:e,frame_color:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_frame_color");const M=this._getTable(e);M&&(M.frame_color=t)}set_frame_width({table_id:e,frame_width:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_frame_width");const M=this._getTable(e);M&&(M.frame_width=t)}set_position({table_id:e,position:t},r){if(!e)return;this._verfiyRequestFunc(r,"set_position");const M=this._getTable(e);M&&(M.position=t,this._paramVerfiy(t,r,"table.set_position",Object.values(k2),"position"))}_getTableItem(e,t,r){[r,t]=this._rowColToInt(r,t);const M=this._getTable(e);if(M){const n=M.cell;return n?n[r][t]:void 0}}_getTable(e){return this._variables.table.get(e.id)||e.data}_verfiyRequestFunc(e,t){D0(this._errorListener,`table.${t}`,this._variables.__requestName,e)}_rowColToInt(e,t){return[Math.round(e),Math.round(t)]}}function Xm(o,e){return{type:e1.TABLE,id:o,data:e,_suffix:"",preId:"",isDraw:!0}}class Em{constructor(e){C(this,"_strategy");this._strategy=e}commission({trade_num:e},t){return this._verifyTradeNum(e,t)&&this._strategy.historyOrders[e].commission||0}entry_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].in_index}entry_comment({trade_num:e},t){if(!this._verifyTradeNum(e,t))return"";const{comment:r,id:M}=this._strategy.historyOrders[e];return r||M}entry_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].id:""}entry_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].in_price}entry_time({trade_num:e},t){if(!this._verifyTradeNum(e,t))return;const{in_time:r,entry_time:M}=this._strategy.historyOrders[e];return M||r}exit_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_index}exit_comment({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].out_comment:""}exit_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].out_id:""}exit_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_price}exit_time({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.historyOrders[e].out_time}max_drawdown({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].trading_loss:0}max_drawdown_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].trading_loss_percent:0}max_runup({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].max_profit:0}max_runup_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].max_profit_percent:0}profit({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].profit:0}profit_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.historyOrders[e].profit_percent:0}size({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{out_qty:r=0,direction:M}=this._strategy.historyOrders[e];return M===a1.long?r:-r}_verifyTradeNum(e,t){if(this._strategy._verfiyRequestFunc(t,"strategy.closedtrades.*"),typeof e!="number"||e<0)return!1;const r=this._strategy.historyOrders.length;return!(e>=r)}}class Tm{constructor(e){C(this,"_strategy");this._strategy=e}commission({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{qty:r=0,original_qty:M=0,commission:n=0}=this._strategy.orders[e];return n*r/M}entry_bar_index({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.orders[e].in_index}entry_comment({trade_num:e},t){if(!this._verifyTradeNum(e,t))return"";const{comment:r,id:M}=this._strategy.orders[e];return r||M}entry_id({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].id:""}entry_price({trade_num:e},t){if(this._verifyTradeNum(e,t))return this._strategy.orders[e].in_price}entry_time({trade_num:e},t){if(!this._verifyTradeNum(e,t))return;const{in_time:r,entry_time:M}=this._strategy.orders[e];return M||r}max_drawdown({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].trading_loss:0}max_drawdown_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].trading_loss_percent:0}max_runup({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].max_profit:0}max_runup_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].max_profit_percent:0}profit({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].profit:0}profit_percent({trade_num:e},t){return this._verifyTradeNum(e,t)?this._strategy.orders[e].profit_percent:0}size({trade_num:e},t){if(!this._verifyTradeNum(e,t))return 0;const{qty:r=0,direction:M}=this._strategy.orders[e];return M===a1.long?r:-r}_verifyTradeNum(e,t){if(this._strategy._verfiyRequestFunc(t,"strategy.opentrades.*"),typeof e!="number"||e<0)return!1;const r=this._strategy.orders.length;return!(e>=r)}}class Cm{constructor(e,t){C(this,"_strategy");C(this,"_errorListener");this._strategy=e,this._errorListener=t}allow_entry_in({value:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._paramVerfiy(e,t,"strategy.risk.allow_entry_in",Object.values(a1),"value"),this._strategy.updateRisk({allow_entry_in:e})}max_cons_loss_days({count:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_cons_loss_days:e})}max_drawdown({value:e,type:t},r){this._strategy._verfiyRequestFunc(r,"strategy.risk.*"),this._paramVerfiy(t,r,"strategy.risk.max_drawdown",[p2.percentOfEquity,p2.cash],"type"),t===p2.percentOfEquity&&(e=e>100?100:e),this._strategy.updateRisk({max_drawdown:e,max_drawdown_type:t})}max_intraday_filled_orders({count:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_intraday_filled_orders:e})}max_intraday_loss({value:e,type:t},r){this._strategy._verfiyRequestFunc(r,"strategy.risk.*"),this._paramVerfiy(t,r,"strategy.risk.max_intraday_loss",[p2.percentOfEquity,p2.cash],"type"),t===p2.percentOfEquity&&(e=e>100?100:e),this._strategy.updateRisk({max_intraday_loss:e,max_intraday_loss_type:t})}max_position_size({contracts:e},t){this._strategy._verfiyRequestFunc(t,"strategy.risk.*"),this._strategy.updateRisk({max_position_size:e})}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}}function J3(o,e){return gM(o).plus(e).toNumber()}function tn(o,e){return gM(o).minus(e).toNumber()}function tr(o,e){return gM(o).mul(e).toNumber()}function rn(o,e=5){return Number(o&&gM(o).toFixed(e))}let xm=class{constructor(e,t,r,M,n){C(this,"_variables");C(this,"_options");C(this,"_totalChangeCapital");C(this,"_historyOrder");C(this,"_orders");C(this,"_exitOrders");C(this,"_pendingOrders");C(this,"_mintick");C(this,"_funcOptions");C(this,"_pendingCloseOrders");C(this,"_errorListener");C(this,"_risk");C(this,"_opentrades");C(this,"_closedtrades");C(this,"_riskNamespace");C(this,"_updateOptions",{});C(this,"_id");C(this,"_maxDrawdownVerifyIndex",0);C(this,"calcOnOrderFillsData",{index:-1});C(this,"_cacheArgs",{});C(this,"_useSetArgs",{});this._variables=e,this._errorListener=M,this._options={overlay:!1,format:A1.inherit,pyramiding:1,calc_on_order_fills:!1,calc_on_every_tick:!1,max_bars_back:0,backtest_fill_limits_assumption:0,default_qty_type:p2.fixed,default_qty_value:1,initial_capital:1e6,currency:Y3.NONE,slippage:0,commission_type:O2.percent,commission_value:0,process_orders_on_close:!1,close_entries_rule:"FIFO",margin_long:0,margin_short:0,explicit_plot_zorder:!1,max_lines_count:50,max_labels_count:50,max_boxes_count:50,calc_bars_count:0,risk_free_rate:2,use_bar_magnifier:!1,fill_orders_on_standard_ohlc:!1,max_polylines_count:50,keep_short_long:!1},this._funcOptions=t,this._totalChangeCapital=0,this._orders=[],this._pendingOrders=[],this._historyOrder=[],this._exitOrders=[],this._pendingCloseOrders=[],this._mintick=r,this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),this._variables.strategy.updateStrategyOptions(this._options),this._risk={intradayOrders:0},this._opentrades=new Tm(this),this._closedtrades=new Em(this),this._riskNamespace=new Cm(this,M),this._id=`strategy_${n}`}get _strategyCacheData(){return{totalChangeCapital:this._totalChangeCapital,orders:this._orders,historyOrders:this._historyOrder,pendingOrders:this._pendingOrders,pendingCloseOrders:this._pendingCloseOrders,exitOrders:this._exitOrders,maxDrawdownVerifyIndex:this._maxDrawdownVerifyIndex,useSetArgs:this._useSetArgs,cacheArgs:this._cacheArgs}}set _strategyCacheData(e){const{totalChangeCapital:t,orders:r,historyOrders:M,pendingOrders:n,pendingCloseOrders:b,exitOrders:z,maxDrawdownVerifyIndex:i,cacheArgs:c,useSetArgs:O}=e;this._totalChangeCapital=t,this._orders=r,this._historyOrder=M,this._pendingOrders=n,this._pendingCloseOrders=b,this._exitOrders=z,this._maxDrawdownVerifyIndex=i,this._historyOrder.length&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._variables.strategy.updateOrders(this._orders),this._updateArgToOptions(c,O)}get orders(){return[...this._orders]}get historyOrders(){return[...this._historyOrder]}get _freezeCapital(){const{close:e}=this.calcOnOrderFillsData.data||this._variables;return this._orders.reduce((t,r)=>t+e*(r.qty||0),0)}get opentrades(){return this._opentrades}get closedtrades(){return this._closedtrades}get risk(){return this._riskNamespace}get isCalcOnEveryTick(){return this._options.calc_on_every_tick}updateOptions(e){this._updateOptions=e||{},Object.assign(this._options,this._updateOptions)}update(){this._maxConsLossDaysVerify(),this._ordersHandle(),this._pendingOrderHandle(),this._exitOrdersHandle(),this._maxIntradayFilledOrdersVerify(),this._maxDrawdownVerify();const{open:e,high:t,low:r}=this.calcOnOrderFillsData.data||this._variables,M=this._variables.close;this._variables.strategy.update(this.calcOnOrderFillsData.currentData||{open:e,close:M,high:t,low:r}),!this._options.process_orders_on_close&&this._calcLiquidate(),this._calcProfitAndLoss()}calcCurrentOrder(){this._ordersHandle(),this._pendingOrderHandle(),this._calcProfitAndLoss()}updateRisk(e){Object.assign(this._risk,e)}endExecution(){this._maxIntradayLoss(),this._pendingCloseOrderHandle(),this._options.process_orders_on_close&&this._calcLiquidate()}_maxIntradayLoss(){var l;const{max_intraday_loss:e,max_intraday_loss_type:t,isDisabledOpen:r}=this._risk;if(e===void 0||!t||r)return;const{time_tradingday:M,time:n,strategy:{netprofit:b,initial_capital:z}}=this._variables,{high:i,low:c}=this.calcOnOrderFillsData.data||this._variables;let{preNetprofit:O=0}=this._risk;n===M&&(O=b,this._risk.preNetprofit=b,this._risk.isTemporaryBan=!1);let s=O-b;s+=this._orders.reduce((q,A)=>{const{in_price:h,direction:d,qty:m=0,commission:_=0,original_qty:R=0}=A,g=d===a1.long?1:-1,L=(i-h)*m,y=(c-h)*m,D=g===1?y:-L;return q+D+m/R*_},0);let u=!1;switch(t){case p2.cash:u=e<s;break;case p2.percentOfEquity:const q=s/(z+b)*100;u=e<q;break}if(u){this._risk.isTemporaryBan=!0;const q=(l=this._orders[0])==null?void 0:l.direction;this._closeOrders(this._orders,q===a1.long?c:i,"Close Position (Max intraday Loss)",void 0,"close"),this._pendingOrders=[]}}_maxIntradayFilledOrdersVerify(){const{max_intraday_filled_orders:e,intradayOrders:t=0,isDisabledOpen:r}=this._risk;if(e===void 0||r)return;const{time:M,time_tradingday:n}=this._variables,{open:b}=this.calcOnOrderFillsData.data||this._variables;M===n&&(this._risk.intradayOrders=0,this._risk.isTemporaryBan=!1),e<=t&&(this._risk.isTemporaryBan=!0,this._closeOrders(this._orders,b,"Close Position (Max number of filled orders in one day)",void 0,"close"),this._pendingOrders=[])}_maxConsLossDaysVerify(){const{max_cons_loss_days:e,lossDays:t=0,isDisabledOpen:r,totalProfit:M=0}=this._risk;if(e===void 0||r)return;const{time:n,time_tradingday:b,strategy:z}=this._variables,{open:i}=this.calcOnOrderFillsData.data||this._variables;let c=t;if(n===b){const O=z.netprofit+z.openprofit;O<M?c=0:c++,Object.assign(this._risk,{lossDays:c,totalProfit:O})}e<=c&&this._riskTouchOff(i,"Close Position (Max consecutive loss days)")}_maxDrawdownVerify(){const{max_drawdown:e,max_drawdown_type:t,isDisabledOpen:r}=this._risk;if(r)return;const{bar_index:M}=this._variables,{open:n}=this.calcOnOrderFillsData.data||this._variables;if(e!==void 0&&t&&this._maxDrawdownVerifyIndex===M){const{initial_capital:b}=this._options,i=this._orders.reduce((O,s)=>{const{in_price:u,commission:l=0,qty:q=0,original_qty:A=0,direction:h}=s,d=h===a1.long?1:-1,m=(n-u)*d*q;return O+m+l*q/A},0)+this._totalChangeCapital;let c=!1;switch(t){case p2.percentOfEquity:c=i/b*100<=-e;break;case p2.cash:c=i<=-e;break}c&&this._riskTouchOff(n,"Close Position (Max Drawdown)")}}_riskTouchOff(e,t){this._risk.isDisabledOpen=!0,this._orders.length&&this._closeOrders(this._orders,e,t,"close"),this._pendingOrders=[]}strategy(e,t){if(!this._variables.bar_index){this._paramVerfiy(e.format,t,"strategy",[A1.inherit,A1.price,A1.percent,A1.volume],"format"),this._paramVerfiy(e.default_qty_type,t,"strategy",Object.values(p2),"default_qty_type"),this._paramVerfiy(e.commission_type,t,"strategy",Object.values(O2),"commission_type");const r=this._cacheArgs,M={...this._updateOptions};if(r)for(const n of Object.keys({...r,...e}))e[n]!==r[n]&&delete M[n];this._updateArgToOptions(e,M)}}_updateArgToOptions(e,t){this._cacheArgs=e,this._useSetArgs=t,this._variables.max_bars_back=e.max_bars_back||0,Object.assign(this._options,e,t),this._variables.updateMaxLength(e),Object.assign(this._funcOptions,{strategy:this._options,userSetStrategyConfig:t,scriptType:"strategy"})}order(e,t){this._verfiyRequestFunc(t,"order"),!this._risk.isDisabledOpen&&(this._paramVerfiy(e.oca_type,t,"strategy.order",Object.values(je),"oca_type"),this._orderHandle(e))}entry(e,t){this._verfiyRequestFunc(t,"entry"),!this._risk.isDisabledOpen&&(this._paramVerfiy(e.oca_type,t,"strategy.entry",Object.values(je),"oca_type"),this._entryHandle(e))}close(e,t){if(this._verfiyRequestFunc(t,"close"),!this._getCloseOrders(e.id).length)return;const{immediately:M}=e;if(M||this._options.process_orders_on_close){const n=this._pendingCloseOrders.find(b=>b.id===e.id&&b.place_order_type==="close");if(n){Object.assign(n,e);return}this._pendingCloseOrders.push({...e,place_order_type:"close"})}else{const n=this._pendingOrders.find(b=>b.id===e.id&&b.place_order_type==="close");if(n){Object.assign(n,e);return}this._pendingOrders.push({...e,place_order_type:"close"})}}close_all(e,t){if(this._verfiyRequestFunc(t,"close_all"),typeof e=="string"&&(e={}),!this._orders.length)return;const{immediately:r}=e;r||this._options.process_orders_on_close?this._pendingCloseOrders.push({...e,place_order_type:"close_all"}):this._pendingOrders.push({...e,place_order_type:"close_all"})}cancel({id:e},t){this._verfiyRequestFunc(t,"cancel"),this._pendingOrders=this._pendingOrders.filter(r=>!(r.id===e&&r.place_order_type!=="close"))}cancel_all(e){this._verfiyRequestFunc(e,"cancel_all"),this._pendingOrders=this._pendingOrders.filter(t=>t.place_order_type==="close_all")}exit(e,t){this._verfiyRequestFunc(t,"exit"),this._options.process_orders_on_close?this._pendingCloseOrders.push({...e,place_order_type:"exit",posStr:t}):this._exit(e,t)}convert_to_account({value:e},t){return this._verfiyRequestFunc(t,"convert_to_account"),e}convert_to_symbol({value:e},t){return this._verfiyRequestFunc(t,"convert_to_symbol"),e}default_entry_qty({fill_price:e},t){return this._verfiyRequestFunc(t,"default_entry_qty"),e?this._calcDefaultQty(e):0}_calcDefaultQty(e){const{default_qty_type:t=p2.fixed,default_qty_value:r=1,initial_capital:M,commission_value:n}=this._options;let b=r;switch(t){case p2.cash:b=r/e;break;case p2.percentOfEquity:const z=this._getOrderProfit(e),i=M+z+this._totalChangeCapital;n?b=this._getCommQty(i,e):b=i*r/100/e;break}return qc(b,this._getLen())}_calcExitQty(e,t="ceil"){if(!String(e).includes("."))return e;const r=this._getLen();return Math[t](tr(e,Math.pow(10,r)))}_getCommQty(e,t){const{commission_type:r,commission_value:M=0,default_qty_value:n=0}=this._options;let b=0;switch(r){case O2.percent:b=e*n/(100*t+M*t);break;case O2.cashPerContract:b=e*n/(100*t+M);break;case O2.cashPerOrder:b=(e-M)*n/100/t}return b}_getLen(){const e=5-(this._variables.precision||5);return e<0?0:e}_getCapital(e,t){const{margin_long:r=0,margin_short:M=0}=this._options;return r<100&&r>0&&e===1?t=t*100/r:M<=100&&M>0&&e===-1&&(t=t*100/M),t}_calcProfitAndLoss(){const{close:e}=this.calcOnOrderFillsData.data||this._variables;for(const t of this._orders){const{in_price:r,qty:M=0,direction:n}=t,b=n===a1.long?1:-1,z=(e-r)*b*M,[i,c]=this._calcProfitAndLossHandle(r,M,b);this._calcOrderPercent(t,z,i,c)}}_calcProfitAndLossHandle(e,t,r,M){const{high:n,low:b}=this.calcOnOrderFillsData.data||this._variables,z=((M||n)-e)*t,i=((M||b)-e)*t;let c=r===1?z:-i,O=r===1?i:-z;return[c,O]}_calcOrderPercent(e,t,r,M){const{commission_value:n}=this._options,{close:b}=this.calcOnOrderFillsData.data||this._variables,{original_qty:z=0,qty:i=0,in_price:c,max_profit:O=0,trading_loss:s=0}=e;let{commission:u=0}=e,l=c*i;if(n){const q=this._getCommission(b,i);u=u*i/z,r-=u,M-=u,l+=u,t=t-q-u}r=Math.max(r,O,0),M=Math.min(M,s,0),Object.assign(e,{profit:t,total_profit:this._totalChangeCapital+t,total_profit_percent:t/(this._options.initial_capital+this._totalChangeCapital)*100,max_profit:r,trading_loss:M,profit_percent:t/l*100,max_profit_percent:r/l*100,trading_loss_percent:M/l*100})}_calcLiquidate(){if(!this._orders.length)return;const{time:e}=this._variables,{high:t,low:r}=this.calcOnOrderFillsData.data||this._variables,{initial_capital:M,margin_long:n=0,margin_short:b=0}=this._options,z=this._orders[0].direction===a1.long?1:-1;let i=z===1?r:t;if(z===1&&n===100)return;const c=(z===1?n:b)/100;if(c<=0)return;let O=!1;const[s,u]=this._orders.reduce((h,d)=>{let[m,_]=h;const{in_price:R,qty:g=0,in_time:L}=d;L===e&&(O=!0);const y=R*g,D=i*g;return m+=y,_+=D,[m,_]},[0,0]);let l=0,q=0;const A=M+this._totalChangeCapital;if(O&&(l=A-s*c,l<0&&(i=this._orders[0].in_price,q=Math.abs(Math.trunc(l/c/i)*4),q=Math.max(q,1))),l>=0){const h=z*(u-s);if(l=A+h-u*c,l>=0)return;q=Math.abs(Math.trunc(l/c/i)*4)}q<=0||this._marginCallOrders(i,q,"Margin Call")}_marginCallOrders(e,t,r){const{close_entries_rule:M="FIFO"}=this._options;if(M==="FIFO"){this._processOrders(this._orders,e,t*this._orders.length,r,r,!0);return}for(const n of this.orders)n.position_close_type=n.place_order_type,n.isTiggerClose=!0,this._processOrder(n,e,t,r,r,!0);this._orders=this._orders.filter(n=>!n.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_orderHandle(e){const{process_orders_on_close:t}=this._options,{isMarketPrice:r,quantities:M,close:n,price:b,activePrice:z,isTouch:i}=this._orderArgsParse(e),c=e.direction===a1.long?1:-1;if(M<=0)return;let O=M;if((r||i)&&t){this._pendingCloseOrders.push({...e,in_price:n,qty:M,place_order_type:"order"});return}this._judgeCapitalEnough(M,b,c)&&this._addPendingOrders(e,b,O,r,z)}_orderOnCloseHandle(e){const t=this._orders.filter(m=>m.direction!==e.direction),{slippage:r=0}=this._options;let{direction:M,qty:n=0,id:b,comment:z,oca_type:i,oca_name:c,in_price:O}=e;const s=M===a1.long?1:-1;if(t.length){const m=this._processOrders(t,O,n,b,z,!1,"order");if(m<=0)return;n=m}const u=O-s*r*this._mintick;if(!this._judgeCapitalEnough(n,u,s))return;this._ocaGroupVerify(n,c,i);const{bar_index:q,time:A}=this._variables,{high:h,low:d}=this.calcOnOrderFillsData.data||this._variables;this._calcCurrentOrder({...e,in_price:u,in_high:h,in_low:d,in_index:q,in_time:A,qty:n,place_order_type:"order"})}_judgeCapitalEnough(e,t,r){let M=this._freezeCapital;if(this._orders.some(O=>(O.direction===a1.long?1:-1)!==r)&&(M=0),e<=0)return!1;const{margin_long:n=0,margin_short:b=0}=this._options;if(n===0&&r===1||b===0&&r===-1)return!0;const z=this._getOrderProfit(t),c=this._getCapital(r,this._options.initial_capital+z+this._totalChangeCapital)-M;return e*t<=c}_getOrderProfit(e){return this._orders.reduce((t,r)=>{const{in_price:M,qty:n=0,direction:b}=r,z=b===a1.long?1:-1;return t+(e-M)*n*z},0)}_ocaGroupVerify(e,t,r){if(!t||!r||r===je.none)return!1;let M=!1;switch(r){case je.cancel:this._pendingOrders=this._pendingOrders.filter(n=>{if(n.oca_name===t)n.isCancel=!0,M=!0;else return!0});break;case je.reduce:this._pendingOrders=this._pendingOrders.filter(n=>{const{qty:b=0,oca_name:z}=n;if(t===z){const i=b-e;return M=!0,i<=0?(n.isCancel=!0,!1):(n.qty=i,!0)}else return!0});break}return M}_processOrders(e,t,r,M,n,b=!1,z,i){if(!e.length)return r;let c=r;for(const O of e)if(O.position_close_type=z||O.place_order_type,O.immediately=i,O.isTiggerClose=(b||O.position_close_type==="close")&&c>=(O.qty||0),c=this._processOrder(O,t,c,M,n,b),c<=0)break;return this._orders=this._orders.filter(O=>!O.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),c}_addPendingOrders(e,t,r,M,n){const b=this._pendingOrders.find(z=>z.id===e.id&&!z.isMarketPrice);if(b)Object.assign(b,{...e,in_price:t,isMarketPrice:M,qty:r,active_price:n});else{const z={...e,in_price:t,isMarketPrice:M,qty:r,active_price:n,entry_time:this._variables.time,place_order_type:"order"};this._pendingOrders.push(z)}}_orderArgsParse(e){var h,d;const{direction:t,qty:r,stop:M}=e;let n=e.limit||0,{close:b}=this.calcOnOrderFillsData.data||this._variables;(d=(h=this.calcOnOrderFillsData)==null?void 0:h.tradeData)!=null&&d.open&&(b=this.calcOnOrderFillsData.tradeData.open);let z=b,i=!1,c;const O=t===a1.long?1:-1,s=M&&(M-b)*O>=0,{backtest_fill_limits_assumption:u=0}=this._options;u>0&&n&&(n-=u*this._mintick*O);const l=n&&(n-b)*O<=0;let q=!1;s&&l?(M!==b&&(c=M),z=n):s?(z=M,q=M===b):l?(z=n,q=n===b):i=!0;const A=r!==void 0?qc(r,this._getLen()):this._calcDefaultQty(z);return{isMarketPrice:i,activePrice:c,quantities:A,close:b,price:z,isTouch:q}}_entryHandle(e){const{process_orders_on_close:t}=this._options,{isMarketPrice:r,quantities:M,close:n,price:b,activePrice:z,isTouch:i}=this._orderArgsParse(e);if(M<=0)return;if((r||i)&&t){this._pendingCloseOrders.push({...e,in_price:n,qty:M,place_order_type:"entry"});return}this._judgeCapitalEnough(M,n,e.direction===a1.long?1:-1)&&this._addPendingEntry(e,b,M,r,z)}_entryOnCloseHandle(e){const{direction:t,in_price:r,qty:M=0,id:n}=e,b=this._getOrders(t,n);this._entryOrder(b,r,M,e)}_getOrders(e,t){return this._options.keep_short_long?this._orders.filter(r=>r.direction!==e&&r.id===t):this._orders.filter(r=>r.direction!==e)}_entryOrder(e,t,r,M){const{time:n,bar_index:b}=this._variables,{high:z,low:i}=this.calcOnOrderFillsData.data||this._variables,{slippage:c=0}=this._options,{oca_name:O,oca_type:s,direction:u,comment:l,id:q}=M,A=u===a1.long?1:-1;if(r=this._getAvailablePositionSize(r,u),r<=0)return;const h=t;if(t=t+c*this._mintick*A,!this._judgeCapitalEnough(r,t,A))return;this._closeOrders(e,h,q,l,"entry",void 0,!0);const m={...M,in_price:t,qty:r,in_index:b,in_high:z,in_low:i,in_time:n,place_order_type:"entry"},{orders:_}=this._getEntryOrders(u),R=_.length;R&&R>=(this._options.pyramiding||1)||(this._ocaGroupVerify(r,O,s),this._calcCurrentOrder(m))}_getAvailablePositionSize(e,t){const{max_position_size:r,allow_entry_in:M}=this._risk;if(M&&M!==a1.all&&M!==t)return 0;if(r===void 0)return e;const n=this._orders.reduce((b,z)=>b+(z.qty||0),0);return n?n+e>r?0:e:e>r?e-r:0}_getEntryOrders(e){const t=this._pendingOrders.filter(M=>["entry","order"].includes(M.place_order_type)&&M.direction===e),r=this._orders.filter(M=>M.direction===e);return{pendingOrders:t,orders:r}}_addPendingEntry(e,t,r,M,n){if(r=this._getAvailablePositionSize(r,e.direction),r<=0)return;const{pendingOrders:b}=this._getEntryOrders(e.direction),z=b.find(i=>i.id===e.id&&i.place_order_type==="entry");if(z)Object.assign(z,{...e,in_price:t,isMarketPrice:M,qty:r,active_price:n});else{const i={...e,in_price:t,isMarketPrice:M,qty:r,active_price:n,entry_time:this._variables.time,place_order_type:"entry"};this._pendingOrders.push(i)}}_closeAllOrders(e,t){const{comment:r,immediately:M}=e,{bar_index:n}=this._variables,b=this._orders.filter(z=>z.in_index!==n);b.length&&(this._closeOrders(b,t,"Close position order",r,"close",M),this._orders=[],this._variables.strategy.updateOrders(this._orders))}_closeOrders(e,t,r,M,n,b,z){if(e.length){for(const i of e)i.position_close_type=n,i.immediately=b,i.isTiggerClose=!0,this._closeOrder(i,t,r,M,z);this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}}_closeOrder(e,t,r,M,n){const{time:b,bar_index:z}=this._variables,{high:i,low:c}=this.calcOnOrderFillsData.data||this._variables,{slippage:O=0}=this._options,{in_price:s,qty:u=0,direction:l}=e,q=l===a1.long?1:-1;t=t-q*O*this._mintick,e.isDeal=!0;const A=(t-s)*q*u,h={...e,out_price:t,out_id:r,out_index:z,out_high:i,out_low:c,out_time:b,out_comment:M,out_qty:u,profit:A};this._calcPercent(h,n)}_exitOrdersHandle(){if(!this._exitOrders.length)return;let{open:e,low:t,high:r,close:M}=this.calcOnOrderFillsData.data||this._variables;const n=[],b=Math.abs(r-e),z=Math.abs(t-e),i=[],c=this._variables.precision;e=Number(e.toFixed(c)),t=Number(t.toFixed(c)),r=Number(r.toFixed(c)),M=Number(M.toFixed(c));for(const O of this._exitOrders){const{directionNum:s,id:u,comment:l,qty:q,comment_loss:A,comment_profit:h,comment_trailing:d,order:m}=O;if(m.isTiggerClose)continue;let _=b<z||b===z&&s===1;if(m.in_time===this._variables.time&&!this._variables._isRepeated){const{in_price:w}=m;_?w<r&&w>=e?e=w:w<=r&&w>=M?r=w:r=M:w<=e&&w>t?e=w:w<=M&&w>=t?t=w:t=M,e=w}const R=[],[g,L]=this._getLimitPrice(O,e,t,r,_);g&&R.push({order:m,price:g,index:L,isHighFront:_,exitInfo:{id:u,comment:h||l,qty:q}});const[y,D]=this._getStopPrice(O,e,t,r,_);y&&R.push({order:m,price:y,index:D,isHighFront:_,exitInfo:{id:u,comment:A||l,qty:q}});const[T,N]=this._getTrailStopPrice(O,e,t,r,M,_);if(T&&R.push({order:m,price:T,index:N,isHighFront:_,exitInfo:{id:u,comment:d||l,qty:q}}),R.length){this._executesSort(R),n.push(R[0]);continue}i.push(O)}this._exitOrders=i,this._executesSort(n);for(const O of n){const{order:s,price:u,exitInfo:l,isHighFront:q,index:A}=O;q?(r=A===1?u:r,t=A===1?e:u):(r=A===1?e:u,t=A===1?u:t),this._variables.strategy.update({open:u,high:r,low:t,close:M}),this._processExitOnClose(s,u,l)}}_executesSort(e){return e.sort(({price:t,index:r,isHighFront:M},{price:n,index:b})=>r!==b?r-b:M?r===1?t-n:n-t:r===1?n-t:t-n),e}_getLimitPrice(e,t,r,M,n){const{limit:b,directionNum:z}=e;let i,c=1;return b&&((t-b)*z>=0?(i=t,c=1):r<=b&&M>=b&&(i=b,n&&b>t||!n&&b<t?c=1:c=2)),[i,c]}_getStopPrice(e,t,r,M,n){const{stop:b,directionNum:z}=e;let i,c=1;return b&&((t-b)*z<=0?(i=t,c=1):r<=b&&M>=b&&(i=b,n&&b>t||!n&&b<t?c=1:c=2)),[i,c]}_getTrailStopPrice(e,t,r,M,n,b){const{trail_stop_price:z,directionNum:i,active_price:c,trail_offset:O=0}=e;let s=z,u,l=1;if(s)if((s-t)*i>=0)u=t,l=1;else{const[q,A,h]=this._calcTrailStopPrice(s,M,r,n,O,i,b);u=A,l=h||1,e.trail_stop_price=q}if(c&&!u&&c<=M&&c>=r)if(O===0)u=c,b&&c>t||!b&&c<t?l=1:l=2;else{s=tn(c,tr(O*i,this._mintick));let q=M,A=r;b?c>=t&&c<=M?(q=M,l=1):(b=!1,q=n,l=2):c<t&&c>=r?(A=r,l=1):(b=!0,A=n,l=2);const[h,d,m=1]=this._calcTrailStopPrice(s,q,A,n,O,i,b);delete e.active_price,l<m&&(l=m),e.trail_stop_price=h,u=d}return[u,l]}_ordersHandle(e){const t=this._orders.filter(b=>b.isMarketPriceLimit||b.isMarketPriceStop);if(!t.length)return;const{open:r,close:M}=this.calcOnOrderFillsData.data||this._variables,n=e?M:r;for(const b of t){const{out_comment:z,out_qty:i,out_id:c}=b;this._processExitOnClose(b,n,{id:c,comment:z,qty:i})}}_calcTrailStopPrice(e,t,r,M,n,b,z){let i=e,c;const O=tn(b===1?t:r,tr(n*b,this._mintick));let s=1;return b===1?z?(i<O&&(i=O),i>=r&&(s=2,c=i)):i>=r?(s=1,c=i):O>i&&(i=O,O>=M&&(s=3,c=O)):z?i<=t?(s=1,c=i):O<i&&(i=O,O<=M&&(s=3,c=O)):(O<i&&(i=O),i<=t&&(s=2,c=i)),[i,c,s]}_pendingOrderHandle(){if(!this._pendingOrders.length)return;const e=[],t=this._pendingOrders.filter(z=>z.place_order_type==="exit");let r=[];for(const z of this._pendingOrders){const{isCancel:i,place_order_type:c,isMarketPrice:O}=z;if(i)continue;let s;switch(c){case"entry":if(!O){r.push(z);continue}this._entryOrderHandle(z);break;case"order":if(!O){r.push(z);continue}this._orderOrderHandle(z);break;case"close":s=this._closeOrderHandle(z);break;case"close_all":const{open:u}=this.calcOnOrderFillsData.data||this._variables;this._closeAllOrders(z,u);break}s&&e.push(s)}const M=this._options.pyramiding||1,n=this._orders.filter(z=>z.direction===a1.long).length<M,b=this._orders.filter(z=>z.direction===a1.short).length<M;r=r.filter(z=>z.direction===a1.long&&n||z.direction===a1.short&&b);for(const z of this._pendingOrderSort(r)){const{place_order_type:i}=z;let c;switch(i){case"entry":c=this._entryOrderHandle(z);break;case"order":c=this._orderOrderHandle(z);break}c&&e.push(c)}for(const z of t){const i=this._exitOrderHandle(z);i&&e.push(i)}this._pendingOrders=e}_pendingOrderSort(e){const{open:t,low:r,high:M}=this.calcOnOrderFillsData.data||this._variables,n=Math.abs(M-t)<=Math.abs(r-t);return e.sort(({in_price:b},{in_price:z})=>{let i=0,c=0;return n?(b>=t&&b<=M?i=1:i=2,z>=t&&z<=M?c=1:c=2):(b<=t&&b>=r?i=1:i=2,z<=t&&z>=r?c=1:c=2),i!==c?i-c:n?i===1?b-z:z-b:i===1?z-b:b-z}),e}_pendingCloseOrderHandle(){if(!this._pendingCloseOrders.length)return;const e=[...this._pendingCloseOrders];this._pendingCloseOrders=[];const t=this._onCloseOrderHandle(e);this._pendingCloseOrders.length&&this._onCloseOrderHandle(this._pendingCloseOrders),this._pendingCloseOrders=t,this._ordersHandle(!0)}_onCloseOrderHandle(e){const{close:t}=this.calcOnOrderFillsData.data||this._variables,r=[];for(const M of e)switch(M.place_order_type){case"close":const n=this._closeOrderHandle(M,!0);n&&r.push(n);break;case"close_all":this._closeAllOrders(M,t);break;case"entry":this._entryOnCloseHandle(M);break;case"order":this._orderOnCloseHandle(M);break;case"exit":const{posStr:b,place_order_type:z,...i}=M;this._exit(i,b);break}return r}_entryOrderHandle(e){const{open:t,low:r,high:M}=this.calcOnOrderFillsData.data||this._variables,{isMarketPrice:n,qty:b=0,in_price:z,direction:i,active_price:c,id:O}=e;if(c&&M>=c&&r<=c)return delete e.active_price,e;let s=z;if(n)s=t;else{let{stop:u,limit:l}=e;const q=i===a1.long?1:-1,A=u&&(u-t)*q>=0,{backtest_fill_limits_assumption:h=0}=this._options;h>0&&l&&(l-=h*this._mintick*q);const d=l&&(l-t)*q<=0;A&&d||(u&&!A||l&&!d)&&(s=t)}if(s<=M&&s>=r){const u=this._getOrders(i,O);this._entryOrder(u,s,b,e)}else return e}_orderOrderHandle(e){const{time:t,bar_index:r}=this._variables,{open:M,low:n,high:b}=this.calcOnOrderFillsData.data||this._variables,{slippage:z=0}=this._options,{isMarketPrice:i,qty:c=0,in_price:O,direction:s,comment:u,oca_name:l,oca_type:q,active_price:A,id:h}=e;if(A&&b>=A&&n<=A)return delete e.active_price,e;let d=O,m=c;if(i&&(d=M),d<=b&&d>=n){const _=this._getOrders(s,h);if(_.length&&(m=this._processOrders(_,d,c,h,u,!1,"order"),m<=0))return;const R=s===a1.long?1:-1;this._ocaGroupVerify(m,l,q),this._calcCurrentOrder({...e,in_price:d-R*z*this._mintick,in_index:r,in_time:t,in_high:b,in_low:n,qty:m});return}else return e}_getCloseOrders(e){const{close_entries_rule:t="FIFO"}=this._options;let r=[];return t==="FIFO"?r=this._orders.filter(M=>M.id===e):r=this._orders.filter(M=>M.id===e&&!M.close_qty),r}_closeOrderHandle(e,t){const{id:r,qty:M,qty_percent:n=100,comment:b,immediately:z}=e,{close_entries_rule:i="FIFO"}=this._options,c=this._getCloseOrders(r);if(!c.length)return;let O=0;if(M?O=M:(O=c.reduce((l,q)=>l+(q.qty||0),O),O=this._calcExitQty(n/100*O,"floor")),O<=0)return;const{open:s,close:u}=this.calcOnOrderFillsData.data||this._variables;if(i==="FIFO")this._processOrders(c,t?u:s,O,`Close entry(s) order ${r}`,b,!1,"close",z);else if(this._processCloseOrders(c,t?u:s,O,`Close entry(s) order ${r}`,b,z))return e}_processCloseOrders(e,t,r,M,n,b){let z=!1;for(const i of e)i.close_qty=r,(i.qty||0)>r&&(z=!0),i.immediately=b,i.position_close_type="close",i.isTiggerClose=!z,this._processOrder(i,t,r,M,n);return this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),z}_exitOrderHandle(e){const{from_entry:t,id:r}=e,M=this._orders.filter(n=>{var b;return(!t||t===n.id)&&!((b=n.exitIds)!=null&&b.includes(r))});if(!(M.length&&!this._ordersToExit(M,e,!0)))return e}_exit(e,t){if(!e.hasOwnProperty("profit")&&!e.hasOwnProperty("loss")&&!e.hasOwnProperty("stop")&&!e.hasOwnProperty("limit")&&(!e.hasOwnProperty("trail_offset")||!e.hasOwnProperty("trail_price")&&!e.hasOwnProperty("trail_points"))){this._errorListener.addError(N1.strategyExitErr,t,K0.Error);return}const{profit:r,loss:M,stop:n,limit:b,trail_offset:z,trail_price:i,trail_points:c,from_entry:O="",id:s}=e;if(this._isNaN(r)&&this._isNaN(M)&&this._isNaN(n)&&this._isNaN(b)&&(this._isNaN(z)||this._isNaN(c)&&this._isNaN(i)))return;const u={...e,place_order_type:"exit"},l=this._orders.filter(d=>{var m;return(!O||O===d.id)&&!((m=d.exitIds)!=null&&m.includes(s))}),q=this._updateExitOrders(u),A=this._pendingOrders.filter(d=>(!O||O===d.id)&&["order","entry"].includes(d.place_order_type||""));if(l.length){if(!this._ordersToExit(l,u,!1))return}else if(!A.length||q)return;const h=this._pendingOrders.find(d=>d.id===s&&d.place_order_type==="exit");h?Object.assign(h,{...e}):this._pendingOrders.push(u)}_updateExitOrders(e){let t=!1;e.qty&&(e.qty=this._calcExitQty(e.qty));const r=this._exitOrders.filter(M=>M.id===e.id&&(M.from_entry===e.from_entry||!e.from_entry));for(const M of r){const{directionNum:n,order:b,qty:z}=M;if(b.isTiggerClose){M.isClose=!0;continue}t=!0;const i={qty:z,...e},c=!0;if(this._stopProfit(b,n,i,c)){M.isClose=!0;continue}if(this._stopLoss(b,n,i,c)){M.isClose=!0;continue}if(this._trailStopLoss(b,n,i,c)){M.isClose=!0;continue}Object.assign(M,i)}return this._exitOrders=this._exitOrders.filter(M=>!M.isClose),t}_ordersToExit(e,t,r){var d;const{qty:M,qty_percent:n=100,id:b,comment:z}=t;let i=M,c=!1;t.comment=z||b;const O=e[0],s={...t},{qty:u=0}=O,l=O.direction===a1.long?1:-1;return i=M?M>=u?u:M:n/100*u,s.qty=this._calcExitQty(i),i<u&&(c=!0),this._stopProfit(O,l,s,r)||this._stopLoss(O,l,s,r)||this._trailStopLoss(O,l,s,r)||(this._exitOrders.push({...s,directionNum:l,order:O}),O.exitIds?(d=O.exitIds)==null||d.push(b):O.exitIds=[b]),c}_addExitPendingCloseOrders(e){const t=this._pendingCloseOrders.find(r=>r.id===e.id);t?Object.assign(t,{...e}):this._pendingCloseOrders.push(e)}_stopProfit(e,t,r,M){var A,h;const{limit:n,profit:b,comment_profit:z,comment:i,id:c,qty:O}=r;let s=n;const{in_price:u}=e,{process_orders_on_close:l}=this._options;if(!this._isNaN(b)&&this._isNaN(n)&&(s=J3(u,tr(b*t,this._mintick))),s=t===1?Wc(s,this._variables.precision):_c(s,this._variables.precision),r.limit=s,M)return;let{close:q}=this.calcOnOrderFillsData.data||this._variables;if((h=(A=this.calcOnOrderFillsData)==null?void 0:A.tradeData)!=null&&h.open&&(q=this.calcOnOrderFillsData.tradeData.open),s!==void 0&&(s-q)*t<=0)return e.isMarketPriceLimit=!0,r.comment=z||i,Object.assign(e,{out_comment:r.comment,out_id:c,out_qty:O}),l&&this._addExitPendingCloseOrders(r),!0}_stopLoss(e,t,r,M){var A,h;const{stop:n,loss:b,comment_loss:z,comment:i,id:c,qty:O}=r;let s=n;const{in_price:u}=e,{process_orders_on_close:l}=this._options;if(!this._isNaN(b)&&this._isNaN(n)&&(s=tn(u,tr(b*t,this._mintick))),s=t===1?_c(s,this._variables.precision):Wc(s,this._variables.precision),r.stop=s,M)return;let{close:q}=this.calcOnOrderFillsData.data||this._variables;if((h=(A=this.calcOnOrderFillsData)==null?void 0:A.tradeData)!=null&&h.open&&(q=this.calcOnOrderFillsData.tradeData.open),s!==void 0&&(s-q)*t>=0)return e.isMarketPriceStop=!0,r.comment=z||i,Object.assign(e,{out_comment:r.comment,out_id:c,out_qty:O}),l&&this._addExitPendingCloseOrders(r),!0}_trailStopLoss(e,t,r,M){var u,l;const{trail_offset:n,trail_price:b,trail_points:z,comment_trailing:i,comment:c,id:O,qty:s}=r;if(!this._isNaN(n)){const{in_price:q}=e,{process_orders_on_close:A}=this._options;let h;if(this._isNaN(b)?this._isNaN(z)||(h=J3(q,tr(z*t,this._mintick))):h=b,r.active_price=h,M)return;let{close:d}=this.calcOnOrderFillsData.data||this._variables;if((l=(u=this.calcOnOrderFillsData)==null?void 0:u.tradeData)!=null&&l.open&&(d=this.calcOnOrderFillsData.tradeData.open),h!==void 0&&(h-d)*t<=0){const m=tn(d,tr(n*t,this._mintick));if((m-d)*t>=0)return e.isMarketPriceStop=!0,r.comment=i||c,Object.assign(e,{out_comment:r.comment,out_id:O,out_qty:s}),A&&this._addExitPendingCloseOrders(r),!0;r.trail_stop_price=m}}}_processExitOnClose(e,t,r){const{qty:M=0,comment:n,id:b}=r,{close_entries_rule:z="FIFO"}=this._options;if(M)if(e.isTiggerClose=!0,z==="FIFO")this._processExitOrders(this._orders,t,M,b,n);else{if(e.isDeal)return;this._processOrders([e],t,M,b,n,!1,"exit")}}_processExitOrders(e,t,r,M,n){let b=r,z;for(const i of e)if(z=i,i.position_close_type="exit",b=this._processOrder(i,t,b,M,n),b<=0)break;return this._orders=this._orders.filter(i=>!i.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),z}_processOrder(e,t,r,M,n,b=!1){const{time:z,bar_index:i}=this._variables,{low:c,high:O}=this.calcOnOrderFillsData.data||this._variables,{slippage:s=0}=this._options,{in_price:u,qty:l=0,max_profit:q,trading_loss:A,direction:h,commission:d=0,original_qty:m=0}=e,_=h===a1.long?1:-1;if(t=t-_*s*this._mintick,r<l){const R=l-r,g=(t-u)*_*r,L=q!==void 0?q/l*r:void 0,y=A!==void 0?A/l*r:void 0,D=d*R/m;this._calcPercent({...e,out_price:t,last_commission:D,out_id:M,out_index:i,out_high:O,out_low:c,out_time:z,out_comment:n,profit:g,out_qty:r,max_profit:L,trading_loss:y});const T=(t-u)*_*R-D;Object.assign(e,{qty:R,profit:T,max_profit:q!==void 0?q-(L||0):void 0,trading_loss:A!==void 0?A-(y||0):void 0,total_profit:this._totalChangeCapital+T}),r=0}else{e.isDeal=!0;const R=(t-u)*_*l;this._calcPercent({...e,out_price:t,out_id:M,out_index:i,out_high:O,out_low:c,out_time:z,out_comment:n,out_qty:l,profit:R}),r-=l}return b&&(_===1?this._variables.strategy.marginCallLong++:this._variables.strategy.marginCallShort++),r}_calcPercent(e,t){const{commission_value:r,process_orders_on_close:M}=this._options,{in_price:n,out_qty:b=0,out_price:z=0,original_qty:i=0,direction:c,last_commission:O=0,immediately:s}=e;let{profit:u=0,max_profit:l,trading_loss:q,commission:A=0}=e,h=n*b,d=this._totalChangeCapital+this._options.initial_capital;if(this._totalChangeCapital+=u,r){const g=this._getCommission(z,b);this._totalChangeCapital-=g;let L=A*b/i;h+=L,L+=g,u=u-L,Object.assign(e,{commission:L});const y=this._orders.reduce((D,T)=>{const{qty:N=0,original_qty:w=0,commission:E=0}=T;return D+E*N/w},0);d+=y-O}const m=c===a1.long?1:-1;let[_,R]=this._calcProfitAndLossHandle(n,b,m,z);if(r){const g=A*b/i;_-=g,R-=g}l=Math.max(_,l||0),q=Math.min(R,q||0),u=parseFloat(String(u)),Object.assign(e,{max_profit:l,profit:u,trading_loss:q,total_profit:this._totalChangeCapital,total_profit_percent:u/d*100,profit_percent:u/h*100,max_profit_percent:l/h*100,trading_loss_percent:q/h*100}),this._maxDrawdownVerifyIndex=this._variables.bar_index+(M?1:0),this._risk.intradayOrders+=1,this._historyOrder.push(e),!t&&this._calcOrderFillsHandle(z,c,s)}_getCommission(e,t){const{commission_value:r=0,commission_type:M}=this._options,n=e*t;let b=0;switch(M){case O2.percent:b=n*r/100;break;case O2.cashPerContract:b=t*r;break;case O2.cashPerOrder:b=r;break}return b}_calcCurrentOrder(e){const{commission_value:t}=this._options,{in_price:r,qty:M=0,max_profit:n=0,trading_loss:b=0,direction:z,immediately:i}=e;let{profit:c=0}=e,O=r*M;const s=this._totalChangeCapital+this._options.initial_capital;if(t){const u=this._getCommission(r,M);this._totalChangeCapital-=u,c=c-u,O+=u,Object.assign(e,{commission:u,total_profit:this._totalChangeCapital})}c=parseFloat(String(c)),Object.assign(e,{original_qty:M,profit:c,total_profit_percent:c/s*100,profit_percent:c/O*100,max_profit_percent:n/O*100,trading_loss_percent:b/O*100,stop:void 0,limit:void 0}),this._risk.intradayOrders+=1,this._orders.push(e),this._variables.strategy.updateOrders(this._orders),t&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._calcOrderFillsHandle(r,z,i)}_calcOrderFillsHandle(e,t,r=!1){const{calc_on_order_fills:M,process_orders_on_close:n,slippage:b=0}=this._options;if(M){const{open:z,high:i,low:c,close:O}=this._variables,s=t===a1.long?1:-1,u=O-s*b*this._mintick;if((r||n)&&e===u)return;const l=z-s*b*this._mintick;let q={open:z,high:i,low:c,close:O},A={open:z,high:i,low:c,close:O},h=this.calcOnOrderFillsData.index;const d=Math.abs(i-z)<=Math.abs(c-z);switch(h){case-1:e===l?(h=0,A={open:z,high:z,low:z,close:z}):e>l?d?(h=1,A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(h=2,A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O}):d?(h=2,A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(h=1,A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O});break;case 0:e===l?(h=1,d?(A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O})):e>l?d?(h=1,A={open:z,high:i,low:z,close:i},q={open:i,high:i,low:c,close:O}):(h=2,A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O}):d?(h=2,A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(h=1,A={open:z,high:z,low:c,close:c},q={open:c,high:i,low:c,close:O});break;case 1:h=2,d?(A={open:z,high:i,low:c,close:c},q={open:c,high:O,low:c,close:O}):(A={open:z,high:i,low:c,close:i},q={open:i,high:i,low:O,close:O});break;case 2:h=-1,q=void 0;break}this.calcOnOrderFillsData={tradeData:q,index:h,currentData:A}}}_isNaN(e){return e===void 0||isNaN(e)}_paramVerfiy(e="",t,r,M,n){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}_verfiyRequestFunc(e,t){D0(this._errorListener,`strategy.${t}`,this._variables.__requestName,e)}};class Wp{constructor(e,t,r){C(this,"array");C(this,"color");C(this,"math");C(this,"str");C(this,"map");C(this,"matrix");C(this,"timeframe");C(this,"ta");C(this,"input");C(this,"_variables");C(this,"_cacheData");C(this,"_options");C(this,"_errorListener");C(this,"_plots");C(this,"_plotshapes");C(this,"_plotbars");C(this,"_plotchars");C(this,"_plotarrows");C(this,"_plotcandles");C(this,"_alerts");C(this,"_bgColors");C(this,"_hlines");C(this,"_fills");C(this,"_proxy");C(this,"chart");C(this,"line");C(this,"label");C(this,"polyline");C(this,"box");C(this,"table");C(this,"linefill");C(this,"log");C(this,"runtime");C(this,"strategy");C(this,"request");C(this,"syminfo");C(this,"_count",0);var n;const M=((n=e.toString().split(".")[1])==null?void 0:n.length)||5;this._variables=t,this._errorListener=new km,this.array=new mc(this._errorListener),this.math=new ld(M),this.color=new k6,this.str=new J_(this._errorListener,M),this.map=new Q_,this.timeframe=new k_(t),this.matrix=new P_(this._errorListener),this.ta=new I6(t,this.math,this.timeframe),this._cacheData={},this._options={},this._bgColors={},this._alerts=new Map,this._hlines=new Map,this._fills=new Map,this.input=new P6(t,this._errorListener,r),this._plots=new Map,this._plotshapes=new Map,this._plotbars=new Map,this._plotcandles=new Map,this._plotchars=new Map,this._plotarrows=new Map,this.chart={point:new Z_(t)},this.line=new nt(t,this._errorListener),this.label=new rm(t,this._errorListener),this.polyline=new mm(t,this._errorListener),this.box=new wm(t,this._errorListener),this.table=new Dm(t,this._errorListener),this.linefill=new Lm(t),this.log=new Im(t,this.str),this.runtime=new Pm(this._errorListener),this.strategy=new xm(this._variables,this._options,e,this._errorListener,r),this.request=new Sm(this._variables,r,this,this._errorListener),this.syminfo=new Fm,this._proxy=new Map}getFuncCacheData(){return{funcCacheData:this._cacheData,taCacheData:this.ta._taCacheData,strategyCacheData:this.strategy._strategyCacheData,inputCacheData:this.input._inputCacheData,requestCacheData:this.request._requestCacheData,timeframeCacheData:this.timeframe._timeframeCacheData,logCacheData:this.log._logCacheData,mathCacheData:this.math._mathCacheData}}setFuncCacheData(e){if(!e)return;const{funcCacheData:t,taCacheData:r,strategyCacheData:M,inputCacheData:n,requestCacheData:b,timeframeCacheData:z,mathCacheData:i}=e;this._cacheData=t,this.ta._taCacheData=r,this.strategy._strategyCacheData=M,this.input._inputCacheData=n,this.request._requestCacheData=b,this.timeframe._timeframeCacheData=z,this.log._logCacheData=e.logCacheData,this.math._mathCacheData=i}get errors(){return this._errorListener.errors}get scriptType(){return this._options.scriptType}clearErrors(){this._errorListener.clear()}addErrors(e,t){this._errorListener.setErrors(e,t)}options(e,t){if(!t)return e.length?this._getDataOfBarindex(e):this._options;const r=this.input.getInputs(),M=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const n=Object.keys(this._bgColors);let b;if(n.length){b={};for(const m of n)b[m]=[...this._bgColors[m].values()]}const z=this._hlines.size?[...this._hlines.values()]:void 0,i=this._fills.size?[...this._fills.values()]:void 0,c=this.log.logs.length?this.log.logs:void 0;this.log.clearLogs(),this._options.scriptType==="strategy"&&Object.assign(this._options,{orders:this.strategy.orders,historyOrders:this.strategy.historyOrders,strategySummary:this._variables.strategy.summaryData});const O=this._plots.size>0?[...this._plots.values()]:void 0,s=this._plotbars.size>0?[...this._plotbars.values()]:void 0,u=this._plotshapes.size>0?[...this._plotshapes.values()]:void 0,l=this._plotarrows.size>0?[...this._plotarrows.values()]:void 0,q=this._plotcandles.size>0?[...this._plotcandles.values()]:void 0,A=this._plotchars.size>0?[...this._plotchars.values()]:void 0,h=this._getDraws(),d=this._variables.chart.isUseBgColor;return Object.assign({},this._options,{inputs:r,plots:O,draws:h,alerts:M,colors:b,hlines:z,fills:i,logs:c,plotshapes:u,plotarrows:l,plotcandles:q,plotchars:A,plotbars:s,isUseBgColor:d})}_getDataOfBarindex(e){const t=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const r=Object.keys(this._bgColors);let M;if(r.length){M={};for(const d of r)M[d]=[...this._bgColors[d].values()].map(m=>{const _=[];for(const R of e){const g=m.data[R];g&&_.push(g)}return m.data=_,m})}const n=this._hlines.size?[...this._hlines.values()]:void 0,b=this._fills.size?this._getDataFromBarindex(e,[...this._fills.values()]):void 0,z=this.log.logs.length?this.log.logs:void 0;this.log.clearLogs(),this._options.scriptType==="strategy"&&Object.assign(this._options,{orders:this.strategy.orders,historyOrders:this.strategy.historyOrders});const i=this._getDataFromBarindex(e,[...this._plots.values()]),c=this._plotbars.size>0?this._getDataFromBarindex(e,[...this._plotbars.values()]):void 0,O=this._plotarrows.size>0?this._getDataFromBarindex(e,[...this._plotarrows.values()]):void 0,s=this._plotcandles.size>0?this._getDataFromBarindex(e,[...this._plotcandles.values()]):void 0,u=this._plotchars.size>0?this._getDataFromBarindex(e,[...this._plotchars.values()]):void 0,l=this._plotshapes.size>0?this._getDataFromBarindex(e,[...this._plotshapes.values()]):void 0,q=this._getDrawDeletes(e),A=this._getDrawsFromBarindex(e),h=this._variables.chart.isUseBgColor;return Object.assign({},this._options,{plots:i,plotarrows:O,plotcandles:s,plotchars:u,plotbars:c,draws:A,drawDeletes:q,alerts:t,colors:M,hlines:n,fills:b,logs:z,plotshapes:l,isUseBgColor:h})}_getDataFromBarindex(e,t){return t.map(r=>{const M=[];for(const n of e){const b=r.data[n];b&&M.push(b)}return r.data=M,{...r}})}_getDraws(){const{line:e,linefill:t,table:r,box:M,polyline:n,label:b}=this._variables,z={};return e.size&&(z.lines=e.data),t.size&&(z.linefills=t.data),r.size&&(z.tables=r.data),M.size&&(z.boxes=M.data),n.size&&(z.polylines=n.data),b.size&&(z.labels=b.data),Object.keys(z).length?z:void 0}_getDrawsFromBarindex(e){const{line:t,linefill:r,table:M,box:n,polyline:b,label:z}=this._variables,i={};return t.size&&(i.lines=t.getValOfBarIndex(e)||[]),r.size&&(i.linefills=r.getValOfBarIndex(e)),M.size&&(i.tables=M.getValOfBarIndex(e)),n.size&&(i.boxes=n.getValOfBarIndex(e)),b.size&&(i.polylines=b.getValOfBarIndex(e)),z.size&&(i.labels=z.getValOfBarIndex(e)),Object.keys(i).length?i:void 0}_getDrawDeletes(e){const{line:t,linefill:r,table:M,box:n,polyline:b,label:z}=this._variables,i={},c=t.getDeleteIds(e),O=r.getDeleteIds(e),s=M.getDeleteIds(e),u=n.getDeleteIds(e),l=b.getDeleteIds(e),q=z.getDeleteIds(e);return c.length&&(i.lines=c),O.length&&(i.linefills=O),s.length&&(i.tables=s),u.length&&(i.boxes=u),l.length&&(i.polylines=l),q.length&&(i.labels=q),i}updateOptions(e){var M;const{inputs:t,strategy:r}=e;this.input.update(t),r&&((M=this.strategy)==null||M.updateOptions(r))}update(e){const{barIndex:t}=e;this.strategy.update(),this._proxy.clear(),this.math.update(t)}endExecution(){this.strategy.endExecution()}getProxy(e,t,r){if(!e)return;const M=this;let n=this._proxy.get(t);const{params:b,funcName:z}=r;n||(n=new Proxy(e,{get(c,O,s){const u=O;return typeof c[u]>"u"?M._getProxyFunc(c.type,u):Reflect.get(c,O,s)}}),this._proxy.set(t,n));const i=M._getFirstArgName(e.type,z);return typeof b[0]=="string"&&b.unshift({[i]:e}),n==null?void 0:n[z](...b)}userFuncMiddleware(e,t,r,M,n,b,z){const i=t.split(",");if(typeof e=="string"){if(i.includes("string"))return r(...M);if(i.includes("color")&&(e.startsWith("#")||e.startsWith("rgb")))return r(...M)}else if(typeof e=="number"){if(i.includes("int")||i.includes("float"))return r(...M)}else if(typeof e=="boolean"){if(i.includes("bool"))return r(...M)}else if(typeof e=="object"){if(i.includes(e.typeName))return r(...M);if(e.type===e1.ARRAY&&i.includes(`${e.typeName}[]`))return r(...M);if(e.type===e1.MATRIX&&i.includes(`matrix<${e.typeName}>`))return r(...M);if(e.type===e1.MAP&&i.includes(`map<${e.keyTypeName},${e.typeName}>`))return r(...M)}this._errorListener.addError(l2(N1.methodNotExistErr,{methodName:z,name:b}),n,K0.Error)}_getFirstArgName(e,t){switch(e){case e1.TYPE:return"object";case e1.ARRAY:return["concat","covariance"].includes(t)?"id1":"id";case e1.MATRIX:return["sum","diff","kron","mult","concat"].includes(t)?"id1":"id";case e1.MAP:case e1.BOX:case e1.LABEL:case e1.LINE:case e1.LINEFILL:case e1.POLYLINE:case e1.CHART_POINT:return"id";case e1.TABLE:return"table_id";default:return"id"}}_getProxyFunc(e,t){switch(e){case e1.TYPE:if(t==="copy")return Oi.copy;break;case e1.ARRAY:return this.array[t];case e1.MATRIX:return this.matrix[t];case e1.MAP:return this.map[t];case e1.BOX:return this.box[t];case e1.LABEL:return this.label[t];case e1.LINE:return this.line[t];case e1.LINEFILL:return this.linefill[t];case e1.TABLE:return this.table[t];case e1.POLYLINE:return this.polyline[t];case e1.CHART_POINT:return this.chart.point[t]}}library(e,t){if(!this._variables.bar_index){const r=/^[^\W\d\s][^\W\s]*$/,{title:M}=e;r.test(M)?(Iu.includes(M)||Fu.includes(M))&&this._errorListener.addError(l2(N1.libraryTitleIsKeywordErr,{name:M}),t,K0.Error):this._errorListener.addError(N1.libraryTitleErr,t,K0.Error),this._options.scriptType="library",this._options.library=e}}indicator(e,t){if(!this._options.scriptType){const{format:r,max_bars_back:M=0}=e;this._variables.max_bars_back=M,this._paramVerfiy(r,t,"indicator",[A1.inherit,A1.percent,A1.price,A1.volume]),this._variables.updateMaxLength(e),this._options.scriptType="indicator",this._options.indicator=e}}_paramVerfiy(e="",t,r,M,n="format"){e&&!M.includes(e)&&this._errorListener.addError(l2(N1.paramsErr,{value:e,func:r,param:n,targetVal:`[${M.join(", ")}]`}),t,K0.Error)}_lineWidthVerify(e,t){const{linewidth:r=1}=e;r<1&&(this._errorListener.addError(Su.lineWidthWarning,t,K0.Warning),e.linewidth=1)}plot(e,t){const r=["color"];I1(e,r);const{series:M,color:n,...b}=e,{bar_index:z,time:i}=this._variables,c=`plot_${t}`,O=this._plots.get(c),s=(O==null?void 0:O.data)||[],u=M!==void 0&&isNaN(M)?void 0:M;if(s[z]={value:[i,u],barIndex:z,itemStyle:{color:n}},this._seriesColorHandle(e,r,O),!O){this._count++,this._lineWidthVerify(b,t),this._paramVerfiy(e.format,t,"plot",[A1.percent,A1.price,A1.volume]);const l=n?[n]:void 0;this._plots.set(c,{editable:!0,...b,colors:l,data:s,id:c,zIndex:this._count})}return{type:"plot",offset:e.offset||0,key:c}}plotbar(e,t){const r=["color"];I1(e,r);const{open:M,close:n,low:b,high:z,color:i,...c}=e,{bar_index:O,time:s}=this._variables,u=`plotbar_${t}`,l=this._plotbars.get(u),q=(l==null?void 0:l.data)||[],A=n!==void 0&&isNaN(n)?void 0:n,h=M!==void 0&&isNaN(M)?void 0:M,d=b!==void 0&&isNaN(b)?void 0:b,m=z!==void 0&&isNaN(z)?void 0:z,_=[s,h,A,d,m];if(q[O]={value:_,barIndex:O,itemStyle:{color:i}},this._seriesColorHandle(e,r,l),!l){this._count++,this._paramVerfiy(e.format,t,"plotbar",[A1.percent,A1.price,A1.volume]);const R=i?[i]:void 0;this._plotbars.set(u,{editable:!0,...c,colors:R,data:q,id:u,zIndex:this._count})}}_verfiyArgs(e,t,r){const{size:M,format:n,location:b,style:z}=e;this._paramVerfiy(z,r,t,Object.values(X2),"style"),this._paramVerfiy(b,r,t,Object.values($e),"location"),this._paramVerfiy(M,r,t,Object.values(f2),"size"),this._paramVerfiy(n,r,t,[A1.percent,A1.price,A1.volume],"format")}plotchar(e,t){const r=["color","textcolor"];I1(e,r);const{series:M,color:n,textcolor:b,location:z=$e.abovebar,...i}=e,{bar_index:c,time:O,high:s,low:u}=this._variables,l=`plotchar_${t}`,q=this._plotchars.get(l),A=(q==null?void 0:q.data)||[],h={value:[O,M],barIndex:c,itemStyle:{color:n,textcolor:b},low:u,high:s};A[c]=h,this._seriesColorHandle(e,r,q),q||(this._count++,this._verfiyArgs(e,"plotchar",t),this._plotchars.set(l,{editable:!0,...i,location:z,data:A,id:l,zIndex:this._count}))}plotarrow(e,t){const r=["colorup","colordown"];I1(e,r);const{series:M,colorup:n,colordown:b,...z}=e,{bar_index:i,time:c,low:O,high:s}=this._variables,u=`plotarrow_${t}`,l=this._plotarrows.get(u),q=(l==null?void 0:l.data)||[];q[i]={value:[c,M!==void 0&&isNaN(M)?void 0:M],barIndex:i,itemStyle:{colorup:n,colordown:b},low:O,high:s},this._seriesColorHandle(e,r,l),l||(this._count++,this._paramVerfiy(e.format,t,"plotarrow",[A1.percent,A1.price,A1.volume]),this._plotarrows.set(u,{editable:!0,...z,data:q,id:u,zIndex:this._count}))}plotshape(e,t){const r=["color","textcolor"];I1(e,r);const{series:M,color:n,textcolor:b,location:z=$e.abovebar,...i}=e,{bar_index:c,time:O,low:s,high:u}=this._variables,l=`plotshape_${t}`,q=this._plotshapes.get(l),A=(q==null?void 0:q.data)||[],h={value:M,barIndex:c,color:n,textcolor:b,time:O,low:s,high:u};if(A[c]=h,this._seriesColorHandle(e,r,q),!q){this._count++;const d=n?[n]:void 0;this._verfiyArgs(e,"plotshape",t),this._plotshapes.set(l,{editable:!0,...i,data:A,location:z,id:l,colors:d,zIndex:this._count})}}plotcandle(e,t){const r=["wickcolor","bordercolor","color"];I1(e,r);const{wickcolor:M,bordercolor:n,color:b,close:z,open:i,low:c,high:O,...s}=e,{bar_index:u,time:l}=this._variables,q=`plotcandle_${t}`,A=this._plotcandles.get(q),h=(A==null?void 0:A.data)||[],d=z!==void 0&&isNaN(z)?void 0:z,m=i!==void 0&&isNaN(i)?void 0:i,_=c!==void 0&&isNaN(c)?void 0:c,R=O!==void 0&&isNaN(O)?void 0:O,g=[l,m,d,_,R];h[u]={value:g,barIndex:u,wickcolor:M,bordercolor:n,color:b},this._seriesColorHandle(e,r,A),A||(this._count++,this._paramVerfiy(e.format,t,"plotcandle",[A1.percent,A1.price,A1.volume]),this._plotcandles.set(q,{editable:!0,...s,data:h,id:q,zIndex:this._count}))}hline(e,t){const r=`hline_${t}`;I1(e,["color"]),this._verifyDisplay(e.display,"hline",t);const n=e.display&&!e.display.length?[]:void 0;return this._hlines.has(r)||(this._count++,this._lineWidthVerify(e,t),this._hlines.set(r,{id:r,linewidth:1,editable:!0,display:n,...e,zIndex:this._count})),{type:"hline",key:r}}fill(e,t){var D,T,N,w,E,P,H,Y;const r=["color","top_color","bottom_color"];I1(e,r);const{color:M,top_color:n,bottom_color:b,seriesColors:z,hline1:i,hline2:c,plot1:O,plot2:s,top_value:u,bottom_value:l,...q}=e,{bar_index:A,time:h}=this._variables,d=`fill_${t}`,m=this._fills.get(d),_=(m==null?void 0:m.data)||[];this._verifyDisplay(e.display,"fill",t);const R=e.display&&!e.display.length?[]:void 0;let g,L,y="plot";if(i&&c)g=(D=this._hlines.get(i==null?void 0:i.key))==null?void 0:D.price,L=(T=this._hlines.get(c==null?void 0:c.key))==null?void 0:T.price,y="hline";else{const k=this._plots.get(O==null?void 0:O.key),K=this._plots.get(s==null?void 0:s.key),e0=(k==null?void 0:k.data)||[],b0=(K==null?void 0:K.data)||[];if(g=(w=(N=e0[A])==null?void 0:N.value)==null?void 0:w[1],L=(P=(E=b0[A])==null?void 0:E.value)==null?void 0:P[1],!A){const O0=(k==null?void 0:k.force_overlay)&&(K==null?void 0:K.force_overlay);(k!=null&&k.force_overlay||K!=null&&K.force_overlay)&&!O0?this._errorListener.addError(N1.plotFillForceOverlayErr,t,K0.Error):q.force_overlay=O0}}if(_[A]={time:h,color:M,top_color:n,bottom_color:b,barIndex:A,plot1:g,plot2:L,top_value:u,bottom_value:l},this._seriesColorHandle(e,r,m),!m){this._count++;const k=((H=this._options.indicator)==null?void 0:H.explicit_plot_zorder)||((Y=this._options.strategy)==null?void 0:Y.explicit_plot_zorder),K=M?[M]:void 0,e0=n?[n]:void 0,b0=b?[b]:void 0;this._fills.set(d,{id:d,colors:K,top_colors:e0,bottom_colors:b0,display:R,data:_,type:y,editable:!0,fillgaps:!1,hline1:i,hline2:c,plot1:O,plot2:s,...q,zIndex:k?this._count:void 0})}}alert({message:e,freq:t=fe.freqOncePerBar},r){const{bar_index:M,_isRealTimeBar:n,last_bar_index:b}=this._variables,z=`alert_${r}`,i=this._cacheData[z]||{},c=i.barIndex;if(this._paramVerfiy(t,r,"alert",[fe.freqAll,fe.freqOncePerBar,fe.freqOncePerBarClose]),t===fe.freqOncePerBar&&M===c){this._alerts.delete(z);return}this._cacheData[z]=i;const O={message:e,freq:t,id:z,type:"alert"};if(n){t!==fe.freqOncePerBarClose&&this._alerts.set(z,O),i.barIndex=M;return}if(!n&&t===fe.freqOncePerBarClose&&M===c&&b===M-1){this._alerts.set(z,O),i.barIndex=M;return}this._alerts.delete(z)}alertcondition({condition:e,message:t,title:r},M){const{_isRealTimeBar:n}=this._variables,b=`alertcondition_${M}`;n&&e?this._alerts.set(b,{message:t,title:r,id:b,type:"alertcondition"}):this._alerts.delete(b)}barcolor(e,t){this._setColors(e,"barcolor",t)}bgcolor(e,t){this._setColors(e,"bgcolor",t)}_verifyDisplay(e=G3.all,t,r){e.length&&e.length<4&&this._errorListener.addError(l2(N1.displayErr,{func:t,values:"[display.none, display.all]"}),r,K0.Error)}_setColors(e,t,r){I1(e,["color"]);const{color:n,...b}=e;this._verifyDisplay(b.display,t,r);const z=e.display&&!e.display.length?[]:void 0,{bar_index:i,time:c}=this._variables,O=`${t}_${r}`;this._bgColors[t]||(this._bgColors[t]=new Map);const s=this._bgColors[t].get(O),u=(s==null?void 0:s.data)||[],l=(s==null?void 0:s.setColors)||[];n&&!l.includes(n)&&l.push(n),u[i]={color:n,time:c,barIndex:i},s||this._bgColors[t].set(O,{...b,display:z,data:u,setColors:l,id:O})}max_bars_back({num:e,var_name:t}){this._variables.__setBarsBackOfKey(t,e)}float({x:e}){return e}bool({x:e}){return e||!1}string({x:e}){return e}int({x:e}){return e&&Math.trunc(e)}na({x:e}){return!!(e===void 0||typeof e=="number"&&isNaN(e))}fixnan({source:e},t){return e===void 0||typeof e=="number"&&isNaN(e)?this._cacheData[`fixnan_${t}`]:(this._cacheData[`fixnan_${t}`]=e,e)}nz(e){const t=e.hasOwnProperty("replacement"),{source:r,replacement:M}=e;return r!==void 0&&!(typeof r=="number"&&isNaN(r))?r:t?M:0}time({timeframe:e="",session:t,timezone:r=this._variables.syminfo.timezone,bars_back:M=0},n){return this._timeHandle(this._variables.time,n,e,t,r,M)}time_close({timeframe:e="",session:t,timezone:r=this._variables.syminfo.timezone,bars_back:M=0},n){return this._timeHandle(this._variables.time,n,e,t,r,M,!0)}timestamp(e){const{dateString:t,timezone:r=this._variables.syminfo.timezone,year:M,month:n,day:b,hour:z=0,minute:i=0,second:c=0}=e;if(t)return O1(t).utc(!/GMT|UTC/.test(t)).valueOf();let O=n-1,s=M;if(O<0){const u=Math.ceil(Math.abs(O/12));O=12*u+O,s=M-u}return lc({year:s,month:O,day:b,hour:z,minute:i,second:c},r)}weekofyear({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).week()}year({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).year()}second({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).second()}month({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).month()+1}minute({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).minute()}hour({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).hour()}dayofweek({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).weekday()+1}dayofmonth({time:e,timezone:t=this._variables.syminfo.timezone}){return _e(e,t).date()}_calcTimeOffset(e,t){const r=this._variables.getTimeTradingday(e,this._variables.timeframe.period),M=y2(t,e)*1e3;return e-r-Math.floor((e-r)/M)*M}_timeHandle(e,t,r="",M,n,b=0,z=!1){const i=r||this._variables.__period,c=y2(i,e),O=y2(this._variables.__period,e);let s;if(c<=O)s=e,z&&(s+=O*1e3);else{const u=`time_${t}`,l=this._cacheData[u];if(l)switch(l.type){case 1:const{time:q,nextTime:A,unit:h,preNum:d}=l;e>=A?(s=A,this._cacheData[u]={type:1,time:s,nextTime:O1(A).add(d,h).startOf(h).add(this._variables._offsetTime,"hour").valueOf(),unit:h,preNum:d}):s=q;break;case 2:s=O1(e).startOf(l.unit).add(this._variables._offsetTime,"hour").valueOf();break;default:l.currentTime+c*1e3-l.offset<=e?(s=e,this._cacheData[u]={type:3,currentTime:e,offset:0}):s=l.currentTime;break}else{const[q,A]=ht(i);if(/[DWM]/.test(i))if(s=O1(e).startOf(A).add(this._variables._offsetTime,"hour").valueOf(),q>1){const h=O1(s).add(q,A).startOf(A).add(this._variables._offsetTime,"hour").valueOf();this._cacheData[u]={type:1,time:s,nextTime:h,unit:A,preNum:q}}else this._cacheData[u]={type:2,unit:A};else{const h=this._calcTimeOffset(e,i);this._cacheData[u]={type:3,currentTime:e,offset:h},s=e}}z&&(s+=c*1e3)}if(M&&M!==ft.regular&&M!==ft.extended){const{timePeriods:u,weeks:l}=this._parserSession(M,t),q=_e(e,n),A=q.format("YYYY-MM-DD HH:mm"),h=q.format("YYYY-MM-DD");s=void 0;for(const m of u){const[_,R]=m;let g;if((_===R||Number(_==null?void 0:_.replace(":",""))>Number(R==null?void 0:R.replace(":","")))&&(g=q.add(1,"day").format("YYYY-MM-DD")),_e(A,n).isBetween(`${h} ${_}`,`${g||h} ${R}`,"minute","[)")){s=lc(`${h} ${_}`,n);break}}const d=this._variables.dayofweek;s&&!l.includes(d)&&(s=void 0)}return Number(s&&s-b*O*1e3)}_seriesColorHandle(e,t,r){var M;if(r&&t!=null&&t.length)for(const n of t){if((M=r.gradientColorKeys)!=null&&M.includes(n))continue;const b=e[n];if(!b)continue;const z=r[`${n}s`]||[];z.includes(b)||(z.push(b),r[`${n}s`]=z,z.length>5&&(r[`${n}s`]=[],r.gradientColorKeys=r.gradientColorKeys||[],r.gradientColorKeys.push(n)))}}_parserSession(e,t){const r=e.split(":"),M=r[0],b=(r[1]||"1234567").split("").map(i=>{const c=parseInt(i,10);if(c<1||c>7){this._errorListener.addError(`Invalid day of week: ${i}`,t,K0.Error);return}return c});return{timePeriods:M.split(",").map(i=>{i===""||i===ft.regular?i="0930-1500":i===ft.extended&&(i="1500-1830");const c=i.split("-");return c.length!==2?[]:[this._processTime(c[0],t),this._processTime(c[1],t)]}),weeks:b}}_processTime(e,t){const r=e.slice(0,2),M=e.slice(2),n=parseInt(r,10),b=parseInt(M,10);if(!(n>=0&&n<=23)&&b>=0&&b<=59){this._errorListener.addError("Invalid time: Time must be within 00:00 to 23:59",t,K0.Error);return}return`${r}:${M}`}}let Sm=class{constructor(e,t,r,M){C(this,"_variables");C(this,"_scriptId");C(this,"_cacheData");C(this,"_funcs");C(this,"_errorListener");this._variables=e,this._scriptId=t,this._cacheData=Object.create(null),this._funcs=r,this._errorListener=M}get _requestCacheData(){return this._cacheData}set _requestCacheData(e){this._cacheData=e}security(e,t){var q;const r=self.workerStorage.get(`request_${this._scriptId}`),{__requestName:M,__period:n}=this._variables;e.symbol=this._symbolTransform(e.symbol),e.timeframe=e.timeframe||n;let{symbol:b,timeframe:z,paramsExpr:i=[]}=e;z=uM(z);const c=`${b}--${z}`,O=`${M}${t}_${c}`,s=this._getRequestData(e,O);if(r!=null&&r.has(O))return(q=s==null?void 0:s.result)==null?void 0:q[O];const u=this._parseExprCode(e),l=this._runScriptHandle(u,O,i,s,!0);return r==null||r.set(O,{id:O,isRun:!1,strJs:u,dataId:c,interval:z,symbol:b,paramsExpr:i}),l}security_lower_tf(e,t){const r=self.workerStorage.get(`request_${this._scriptId}`),{__period:M,__requestName:n}=this._variables;e.symbol=this._symbolTransform(e.symbol),e.timeframe=e.timeframe||M;let{symbol:b,timeframe:z,paramsExpr:i=[]}=e;z=uM(z);const c=`${b}--${z}`,O=`${n}${t}_${c}`,s=r==null?void 0:r.get(O),u=this._getRequestLowerTfData(e,t,O,s==null?void 0:s.defaultResult),l=p1(0,void 0,N0.FLOAT);if(s!=null&&s.strJs)return s!=null&&s.defaultResult?u!=null&&u.length?u.map(d=>{const m=p1(0,void 0,N0.FLOAT);return m._value=d,m}):s==null?void 0:s.defaultResult:u&&(l._value=u,l);const q=this._parseExprCode(e),A={id:O,strJs:q,isRun:!1,dataId:c,interval:z,symbol:b,paramsExpr:i,defaultResult:void 0};r==null||r.set(O,A);const h=this._runScriptHandle(q,O,i,u,!0);return Array.isArray(h)?(A.defaultResult=h.map(()=>p1(0,void 0,N0.FLOAT)),A.defaultResult):l}_symbolTransform(e){if(!e)return this._variables.syminfo.tickerid;let[t,r]=e.split(":");return r?t=ku[t]||t:(r=t,t="FX"),`${t}:${r}`}_runScriptHandle(e,t,r,M,n){const{result:b,logs:z,errors:i}=this._runScripts(e,t,n,r,M);return this._funcs.log.mergeLogs(z),this._funcs.addErrors(i,t),b}_parseExprCode(e){let{expression:t,paramsExpr:r=[]}=e,M=[];t=dc(t);const n=JSON.parse(t),b=n.pop();let z=(b==null?void 0:b.memberCodes)||{},i=(b==null?void 0:b.depends)||[];if(!i.length)return`return ${b==null?void 0:b.code}`;let c=[],O=[],s=[];if(this._getDependCodes(i,n,M,c,O,s),this._getStmtFuncs(M,n,s,c,O),O.length){const h=r.length;for(let d=h-1;d>=0;d--){const m=r[d];let _=JSON.parse(dc(m));const R=[];_=_.map(y=>{const{type:D,code:T,varNames:N,dependSelf:w}=y;return D===2&&!R.includes(N)&&!w&&(y.code=`let ${T}`),N&&R.push(...N.split(", ")),y.memberCodes&&Object.assign(z,{...y.memberCodes}),y});const g=[];let L=O.map(y=>({...y,isArg:!1,isPreArg:!0}));O=[],this._getDependCodes(L,_,M,c,O,g),this._getStmtFuncs(M,_,g,c,O)}}const u=M.filter(h=>!!h).map((h,d)=>{let m=h.join(`
77
77
  `);return d===0&&(m=`${m}
78
78
  ${c.join(`
79
79
  `)}`),m});let l=u.join(`
@@ -82,7 +82,7 @@ ${s.join(`
82
82
  `)}
83
83
  return ${b==null?void 0:b.code}`;q>1;)l=`${l}}`,q--;const A=[];for(const h of Object.keys(z))l.includes(`$_var.getCacheData("${h}"`)&&A.push(z[h]);return A.length&&(l=`${A.join(`
84
84
  `)}
85
- ${l}`),l}_getRequestLowerTfData(e,t,r,M){var R;let{symbol:n,timeframe:b,calc_bars_count:z,ignore_invalid_symbol:i,ignore_invalid_timeframe:c}=e;const{__period:O,time:s,_isRealTimeBar:u}=this._variables;b=uM(b);let l=y2(b,s)*1e3;const q=y2(O,s)*1e3;if(l>q)return!c&&this._errorListener.addError(l2(N1.requestLowerTfPeriodErr,{period:b}),t,K0.Error,25),[];const A=`${n}--${b}`,h=self.workerStorage.get(`request_${this._scriptId}_data`),d=self.workerStorage.get(`request_${this._scriptId}_list`),m=self.workerStorage.get(`request_${this._scriptId}_tmp`),_={id:A,calc_bars_count:z,ignore_invalid_symbol:i,symbol:n,originTimeframe:b,timeframe:Ai[b]||Ac(b)};if(h!=null&&h.has(A)){m==null||m.delete(A);const{index:g=0,periodStamp:L=q}=this._cacheData[r]||{},y=h==null?void 0:h.get(A);if(!y.length)return[];if(y.length-1<0)return[];const T=y.slice(g);let N=s,w=L+N;const E=[];for(const[P,H]of T.entries()){let{time:Y}=H;Y=Y*1e3;let k=g+P;if(Y>=w)return!u&&(this._cacheData[r]={index:k,periodStamp:L}),E;if(N<=Y&&Y<w){const K=(R=H==null?void 0:H.result)==null?void 0:R[r];if(Array.isArray(K))for(const[e0,b0]of K.entries())E[e0]||(E[e0]=[]),E[e0].push(b0);else M||E.push(K)}}return!u&&(this._cacheData[r]={index:y.length,periodStamp:L}),E}else(d==null?void 0:d.get(A))||m==null||m.set(A,_);d==null||d.set(A,_)}_getRequestData(e,t){var m,_,R,g,L;let{symbol:r,timeframe:M,calc_bars_count:n,gaps:b,lookahead:z,ignore_invalid_symbol:i}=e;const{__period:c,mintick:O,time:s,nextBarTime:u}=this._variables;M=uM(M),r=r;const l=`${r}--${M}`,q=self.workerStorage.get(`request_${this._scriptId}_data`),A=self.workerStorage.get(`request_${this._scriptId}_list`),h=self.workerStorage.get(`request_${this._scriptId}_tmp`),d={id:l,calc_bars_count:n,ignore_invalid_symbol:i,symbol:r,originTimeframe:M,timeframe:Ai[M]||Ac(M)};if(q!=null&&q.has(l)){let y=y2(M,s)*1e3;const D=y2(c,s)*1e3;h==null||h.delete(l);const{index:T=0,periodStamp:N=D}=this._cacheData[t]||{},w=q==null?void 0:q.get(l);if(!w.length)return;const E=w.slice(T);let P=s,H=N+P;const Y=w.length-1;if(Y<0)return;const k={lastBarIndex:w[Y].barindex||Y,lastBarTime:w[Y].time,interval:M,mintick:O};if(y>N){let K;if(z===ke.lookaheadOn?K=this._lookaheadOnHandle(E,M,H,y,k,T,N,t,P,b):K=this._lookaheadOffHandle(E,M,H,y,k,T,N,t,P,u||H,b),K)return K;if(K===null)return}else if(z===ke.lookaheadOn)for(const[K,e0]of E.entries()){let{time:b0,barindex:O0}=e0;b0=b0*1e3;const v0=((m=E[K+1])==null?void 0:m.time)*1e3||b0+y;let B0=T+K;if(b0>=H){this._cacheData[t]={index:B0,periodStamp:N};return}if(b0<=P&&v0>P){const A0=T+K;return this._cacheData[t]={index:A0,periodStamp:N},{...e0,barIndex:O0||A0,nextBarTime:(_=E[K+1])==null?void 0:_.time,...k}}}else for(const[K,e0]of E.entries()){let{time:b0,barindex:O0}=e0;b0=b0*1e3;const v0=((R=E[K+1])==null?void 0:R.time)*1e3||b0+y;let B0=T+K;if(b0>H){this._cacheData[t]={index:B0,periodStamp:N};return}if(b0<H&&H<=v0)return this._cacheData[t]={index:B0,periodStamp:N},{...e0,barIndex:O0||B0,nextBarTime:(g=E[K+1])==null?void 0:g.time,...k};if(b0>=P&&b0<=H&&(O0||B0)===k.lastBarIndex)return this._cacheData[t]={index:B0,periodStamp:N},{...e0,barIndex:O0||B0,nextBarTime:(L=E[K+1])==null?void 0:L.time,...k}}this._cacheData[t]={index:w.length,periodStamp:N};return}else(A==null?void 0:A.get(l))||h==null||h.set(l,d);A==null||A.set(l,d)}_lookaheadOnHandle(e,t,r,M,n,b,z,i,c,O){var s;for(const[u,l]of e.entries()){let{time:q,barindex:A}=l;q=q*1e3,t.includes("M")&&(M=y2(t,q)*1e3-(O1(q).date()-1)*864e5);const h=q,d=M+h;let m=b+u;if(r<=h)return this._cacheData[i]={index:m,periodStamp:z},null;let _={...l,barIndex:A||m,nextBarTime:(s=e[u+1])==null?void 0:s.time,...n};if(O===ke.gapsOn){if(r>h&&c<=h)return this._cacheData[i]={index:m,periodStamp:z},_}else{if(r>d)continue;if(r>h)return this._cacheData[i]={index:m,periodStamp:z},_}}}_lookaheadOffHandle(e,t,r,M,n,b,z,i,c,O,s){var u,l;for(const[q,A]of e.entries()){let{time:h,barindex:d}=A;h=h*1e3,t.includes("M")&&(M=y2(t,h)*1e3-(O1(h).date()-1)*864e5);const m=h,_=M+m,R=b+q;if(r<m)return this._cacheData[i]={index:R,periodStamp:z},null;const g={...A,barIndex:d||R,nextBarTime:(u=e[q+1])==null?void 0:u.time,...n};if(r>=_&&c<_||r<_&&O>=_)return s===ke.gapsOn?(this._cacheData[i]={index:R,periodStamp:z},g):(this._cacheData[i]={index:R,data:g,periodStamp:z},g);if(!(c>_)&&c>=m){let L=(l=this._cacheData[i])==null?void 0:l.data;if(!L){const y=e[R-1];if(!y)return null;L={...y,barIndex:y.barindex||R-1,nextBarTime:g.time,...n},this._cacheData[i]={index:R,data:L,periodStamp:z}}return L}}}_getDependCodes(e,t,r,M,n,b){for(const z of e){if(!z.isArg){const i=t.filter(O=>{var s;return(s=O==null?void 0:O.depends)==null?void 0:s.some(u=>u.name===z.name&&u.scope===z.scope&&u.isAgainAssign!==!1)});for(const O of i){const{code:s,depends:u,scope:l,funcName:q}=O;r[l]=r[l]||[];const A=r[l];let h=l===0&&q;if(!A.includes(s)){if(h){if(M.includes(s))continue;M.unshift(s)}else A.unshift(s);if(u!=null&&u.length){for(const d of u)d.memberCode&&!h&&b.push(d.memberCode);this._getDependCodes(u,t,r,M,n,b)}}}const c=t.find(O=>{var s;return((s=O.varNames)==null?void 0:s.split(", ").includes(z.name))&&(!z.isPreArg||z.isPreArg&&O.methodName===z.functionName)||O.funcName===z.name});if(c){const{code:O,depends:s,scope:u}=c;r[u]=r[u]||[];const l=r[u],q=l.findIndex(A=>A===O);if(q!==-1){if(z.isFunc)continue;l.splice(q,1)}if(l.unshift(O),s!=null&&s.length){for(const A of s)A.memberCode&&b.push(A.memberCode);this._getDependCodes(s,t,r,M,n,b)}continue}}n.some(i=>i.name===z.name)||n.push(z)}}_getStmtFuncs(e,t,r,M,n){const b=t.filter(z=>z.isStmtFunc);for(const z of b){const{code:i,depends:c,scope:O=0}=z;e[O]=e[O]||[];const s=e[O];if(!s.includes(i)&&(s.push(i),c!=null&&c.length)){for(const u of c)u.memberCode&&r.push(u.memberCode);this._getDependCodes(c.filter(u=>!(u.isFunc&&i.startsWith(u.name))),t,e,M,n,r)}}}runScripts(e,t,r,M,n,b){var u,l;const z=`${this._scriptId}_${t}`,i=new _p(z),c=new hp,O=new Wp(this._variables.mintick||1e-5,i,this._scriptId),s=new Function("_$_var","_$_const","_$_func","$paramsExpr","$posStr",e);if(!r){const{varCacheData:q,funcCacheData:A}=n;i.setVarCacheData(q),O.setFuncCacheData(A)}if(i.__requestName=t,M&&M.length){const q=M.length-1,{interval:A,symbol:h=""}=n;let{mintick:d,syminfo:m}=this._variables;const[_,R]=h.split(":");d||(d=Math.pow(10,-(((u=String(M[0].o).split(".")[1])==null?void 0:u.length)||0))),i.updateOptions({interval:A,mintick:d,syminfo:{...m.__syminfo,mintick:d,tickerid:h||m.tickerid,ticker:R||_||m.ticker}});for(const[y,D]of M.entries()){const{barindex:T}=D,N=Object.assign(D,{barIndex:T||y,lastBarIndex:M[q].barindex||q,lastBarTime:M[q].time,nextBarTime:(l=M[y+1])==null?void 0:l.time});if(i.updateData(N),O.update({barIndex:(N==null?void 0:N.barindex)||0}),D.result=Object.assign(D.result||{},{[t]:s(i,c,O,b||[],t)}),O.endExecution(),O.errors.length&&O.errors.some(w=>w.type===K0.Error))return{logs:[],errors:O.errors}}const g=O.log.logs,L=O.errors;return O.log.clearLogs(),O.clearErrors(),{logs:g,errors:L,cacheData:{varCacheData:i.getVarCacheData(),funcCacheData:O.getFuncCacheData()}}}}_runScripts(e,t,r,M,n){const b=`${this._scriptId}_${t}`;let{builtInGather:z,buildinConstants:i,buildInFunctions:c,tradingvueFunc:O}=self.workerStorage.get(b)||{};const{interval:s,...u}=n||{};if(r){z=new _p(b),i=new hp,c=new Wp(this._variables.mintick||1e-5,z,this._scriptId),O=new Function("_$_var","_$_const","_$_func","$paramsExpr","$posStr",e);const{mintick:h,syminfo:d}=this._variables;z.updateOptions({interval:s,mintick:h||1e-5,syminfo:{...d.__syminfo}}),z.__requestName=t,self.workerStorage.set(b,{builtInGather:z,buildinConstants:i,buildInFunctions:c,tradingvueFunc:O})}z.updateData(u),c.update({barIndex:(u==null?void 0:u.barindex)||0});const l=O(z,i,c,M||[],t),q=c.log.logs,A=c.errors;return c.log.clearLogs(),c.clearErrors(),c.endExecution(),{result:l,logs:q,errors:A}}},Fm=class{constructor(){}prefix(e){var r;const{symbol:t}=e;return((r=t==null?void 0:t.split("."))==null?void 0:r[0])||""}ticker(e){var r;const{symbol:t}=e;return((r=t==null?void 0:t.split("."))==null?void 0:r[1])||""}};class Im{constructor(e,t){C(this,"_logs");C(this,"_variables");C(this,"_str");C(this,"_preBar",{barIndex:-1,isrealtime:!1});this._variables=e,this._logs=[],this._str=t}get _logCacheData(){return this._preBar}set _logCacheData(e){this._preBar=e}get logs(){return this._logs}clearLogForIndex(e){this._logs=this._logs.filter(t=>t.barIndex!==e)}clearLogs(){this._logs=[]}info(e,t,r){this._addLog(e,t,"info",r)}error(e,t,r){this._addLog(e,t,"error",r)}warning(e,t,r){this._addLog(e,t,"warning",r)}mergeLogs(e){this._logs=this._logs.concat(e)}_addLog(e,t,r,M){if(typeof t=="string"&&(M=t),M.startsWith("export"))return;const{message:n,formatString:b}=e,{time:z,bar_index:i,_isRealTimeBar:c,__isReqRepeated:O}=this._variables;let s=n;b&&Array.isArray(t)&&t.length&&(t=t.map(A=>{if(typeof A=="object"){if(A===null)return"null";A!=null&&A.isArray?A=`[${A._value.toString()}]`:A=A.toString()}return A!==void 0?A:"na"}),s=this._str.strformat({formatString:b},t,!0));const{isrealtime:u,barIndex:l}=this._preBar;i!==l&&(this._preBar={barIndex:i,isrealtime:c});const q=Date.now();s!==void 0&&this._logs.push({message:`[${O1(u&&!O?q:z).format("YYYY-MM-DDTHH:mm:ss.SSSZ")}]: ${s}`,time:z,id:K4(6),barIndex:i,type:r})}}class Pm{constructor(e){C(this,"_errorListener");this._errorListener=e}error({message:e},t){t.startsWith("export")||this._errorListener.addError(e,t,K0.Error)}}class km{constructor(){C(this,"_errors");this._errors=new Map}clear(){this._errors.clear()}get errors(){return b2.flatMap([...this._errors.values()])}setErrors(e,t){this._errors.set(t,e)}addError(e,t,r,M=0){const[n,b]=t.split("_").slice(-2),z=this._errors.get(t),i={message:e,endLineNumber:Number(n),startColumn:Number(b)+1,endColumn:Number(b)+M+1,startLineNumber:Number(n),type:r};z?z.push(i):this._errors.set(t,[i])}}class $m{constructor(){C(this,"_isMarketOpen");C(this,"_currentBarIndex");C(this,"_totalBarIndex");C(this,"_isRealTimeBar");C(this,"_preBarIndex");C(this,"_preIsRealTimeBar");C(this,"_isFirstRun",!1);this._currentBarIndex=0,this._totalBarIndex=0,this._isRealTimeBar=!1,this._preBarIndex=0,this._isMarketOpen=!0,this._preIsRealTimeBar=!1}update(e,t,r,M){this._preBarIndex=this._currentBarIndex,this._preIsRealTimeBar=this._isRealTimeBar,this._currentBarIndex=e,this._totalBarIndex=t,this._isRealTimeBar=r,this._isMarketOpen=M}get _barstateCacheData(){return{currentBarIndex:this._currentBarIndex,isRealTimeBar:this._isRealTimeBar}}set _barstateCacheData(e){this._currentBarIndex=e.currentBarIndex,this._isRealTimeBar=e.isRealTimeBar}set isFirstRun(e){this._isFirstRun=e}get isnew(){return this._preBarIndex!==this._currentBarIndex}get islast(){return this._currentBarIndex===this._totalBarIndex||!this._isFirstRun}get isfirst(){return this._currentBarIndex===0}get ishistory(){return!this._isRealTimeBar||this._isFirstRun}get isrealtime(){return this._isRealTimeBar}get isconfirmed(){return!this._isRealTimeBar}get islastconfirmedhistory(){return this._isMarketOpen?this._currentBarIndex===this._totalBarIndex-1&&!this._preIsRealTimeBar||this._currentBarIndex===this._totalBarIndex&&!this._isRealTimeBar:this._currentBarIndex===this._totalBarIndex}}class Um{constructor(e){C(this,"_variables");this._variables=e}get isfirstbar(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday||this._variables.bar_index===0}get isfirstbar_regular(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday}get islastbar(){if(this._variables.timeframe.isdwm)return!0;const{time:e,__period:t}=this._variables,r=y2(t,e);return this._variables.time+r===this._variables.time_tradingday+24*60*60*1e3}get islastbar_regular(){if(this._variables.timeframe.isdwm)return!0;const{time:e,__period:t}=this._variables,r=y2(t,e);return this._variables.time+r===this._variables.time_tradingday+24*60*60*1e3}get ismarket(){return!0}get ispostmarket(){return!1}get ispremarket(){return!1}}class jm{constructor(e){C(this,"_orders");C(this,"_historyOrders");C(this,"_options");C(this,"_max_contracts_held_all",0);C(this,"_max_contracts_held_long",0);C(this,"_max_contracts_held_short",0);C(this,"_max_drawdown",0);C(this,"_max_runup",0);C(this,"_max_runup_percent",0);C(this,"_max_drawdown_percent",0);C(this,"_variables");C(this,"_netprofit",0);C(this,"_eventrades",0);C(this,"_avg_trade_percent");C(this,"_avg_losing_trade_percent");C(this,"_avg_winning_trade_percent");C(this,"_closedtrades",0);C(this,"_losstrades",0);C(this,"_grossloss",0);C(this,"_grossprofit",0);C(this,"_wintrades",0);C(this,"_opentrades_capital_held",0);C(this,"_position_avg_price",0);C(this,"_position_size",0);C(this,"_openprofit",0);C(this,"_preMaxNetValue",0);C(this,"_preMinNetValue",0);C(this,"marginCallLong",0);C(this,"marginCallShort",0);this._orders=[],this._historyOrders=[],this._variables=e}update(e){this._calcMaxDrawdownAndMaxRunup(e)}_calcMaxDrawdownAndMaxRunup(e){if(!this._orders.length&&!this._historyOrders.length)return;let t=0,r=0;const{high:M,low:n,close:b}=e;let z=0;for(const[O,s]of this._orders.entries()){const{in_price:u,qty:l=0,direction:q,commission:A,original_qty:h=1}=s,d=q===a1.long?1:-1,m=(M-u)*l,_=(n-u)*l,R=d===1?m:-_,g=d===1?-_:m;z+=(b-u)*d*l,t+=g,O>0&&A&&(r-=A*l/h),r+=R}this._openprofit=z;const i=this.initial_capital,c=i+this._netprofit;this._preMinNetValue=this._preMinNetValue||i,this._preMaxNetValue=this._preMaxNetValue||i,t=this._preMaxNetValue-c+Math.max(t,0),r=c-this._preMinNetValue+r,this._max_drawdown<t&&(this._max_drawdown=t,this._max_drawdown_percent=t/this._preMaxNetValue*100),r>this._max_runup&&(this._max_runup=r,this._max_runup_percent=r/(this._preMinNetValue+r)*100)}updateOrders(e){this._orders=e,this._calcMaxContracts()}_calcMaxContracts(){if(!this._orders.length){this._position_size=0,this._position_avg_price=void 0,this._opentrades_capital_held=0;return}const[t,r,M,n,b,z]=this._orders.reduce(([i,c,O,s,u,l],q)=>{const{direction:A,qty:h=0,in_price:d,commission:m=0}=q;return A===a1.long?(i+=h,c+=h,u+=h):(i+=h,O+=h,u-=h),s+=h*d,l+=m,[i,c,O,s,u,l]},[0,0,0,0,0,0]);this._historyOrders.length||(this._netprofit=-z,this._grossloss=z),this._position_size=b,this._position_avg_price=n/t,this._opentrades_capital_held=n,this._max_contracts_held_all=Math.max(t,this._max_contracts_held_all),this._max_contracts_held_long=Math.max(r,this._max_contracts_held_long),this._max_contracts_held_short=Math.max(M,this._max_contracts_held_short)}updateHistoryOrders(e){this._historyOrders=e;const t=this._historyOrders.length;this._closedtrades=t;const[r,M,n,b,z,i,c,O]=this._historyOrders.reduce((l,q)=>{let[A,h,d,m,_,R,g,L]=l;const{profit:y=0,profit_percent:D=0}=q;return A+=y,h+=D,y<0?(d+=y,m+=D,g+=1):y>0&&(_+=y,R+=D,L+=1),[A,h,d,m,_,R,g,L]},[0,0,0,0,0,0,0,0]),s=this._orders.reduce((l,q)=>{const{commission:A=0,qty:h=0,original_qty:d=0}=q,m=A*h/d;return l+m},0);this._avg_trade_percent=t?M/t:void 0,this._avg_losing_trade_percent=t?Math.abs(b)/c:void 0,this._avg_winning_trade_percent=t?i/O:void 0,this._netprofit=r-s;const u=this.initial_capital+this._netprofit;this._preMaxNetValue=Math.max(this._preMaxNetValue||this.initial_capital,u),this._preMinNetValue=Math.min(this._preMinNetValue||this.initial_capital,u),this._grossloss=Math.abs(n-s),this._grossprofit=z,this._eventrades=t-c-O,this._losstrades=c,this._wintrades=O}updateStrategyOptions(e){this._options=e}get long(){return"long"}get short(){return"short"}get account_currency(){return"USD"}get closedtrades(){return this._closedtrades}get opentrades(){return{opentrades:this._orders.length,capital_held:this._opentrades_capital_held}}get avg_losing_trade(){const e=this._losstrades;return e?Math.abs(this._grossloss/e):void 0}get avg_losing_trade_percent(){return this._avg_losing_trade_percent}get avg_trade(){if(this._closedtrades)return this._netprofit/this._closedtrades}get equity(){return this.initial_capital+this._netprofit+this._openprofit}get netprofit(){return this._netprofit}get eventrades(){return this._eventrades}get openprofit(){return this._openprofit}get avg_trade_percent(){return this._avg_trade_percent}get avg_winning_trade(){const e=this._wintrades;return e?Math.abs(this._grossprofit/e):void 0}get avg_winning_trade_percent(){return this._avg_winning_trade_percent}get initial_capital(){var e;return((e=this._options)==null?void 0:e.initial_capital)||0}get losstrades(){return this._losstrades}get grossloss(){return this._grossloss}get grossloss_percent(){return this._grossloss/this.initial_capital*100}get grossprofit(){return this._grossprofit}get grossprofit_percent(){return this._grossprofit/this.initial_capital*100}get wintrades(){return this._wintrades}get margin_liquidation_price(){if(!this._options)return;const{initial_capital:e,margin_long:t=0,margin_short:r=0,commission_type:M,commission_value:n=0}=this._options,b=this._orders[0].direction===a1.long?1:-1,z=(b===1?t:r)/100;if(z<=0)return;const{close:i}=this._variables,[c,O]=this._orders.reduce((s,u)=>{let[l,q]=s;const{in_price:A,qty:h=0,original_qty:d=0}=u,m=A*h;if(l+=m,n){let _=0;switch(M){case O2.percent:_=(m+h*i)*n/100;break;case O2.cashPerContract:_=h*n*2;break;case O2.cashPerOrder:_=h/d*n+n;break}q+=_}return[l,q]},[0,0]);return(c-(e+this._netprofit-O))*b/this._position_size/(1-b*z)}get max_contracts_held_all(){return this._max_contracts_held_all}get max_contracts_held_long(){return this._max_contracts_held_long}get max_contracts_held_short(){return this._max_contracts_held_short}get max_drawdown(){return this._max_drawdown}get max_runup(){return this._max_runup}get max_runup_percent(){return this._max_runup_percent}get max_drawdown_percent(){return this._max_drawdown_percent}get netprofit_percent(){return this._netprofit/this.initial_capital*100}get openprofit_percent(){return this._openprofit/(this.initial_capital+this._netprofit)*100}get position_avg_price(){return this._position_avg_price}get position_entry_name(){if(this._orders.length)return this._orders[0].id}get position_size(){return this._position_size}get summaryData(){return{position_size:this.position_size,position_avg_price:this.position_avg_price,position_entry_name:this.position_entry_name,openprofit_percent:this.openprofit_percent,netprofit_percent:this.netprofit_percent,max_drawdown_percent:this.max_drawdown_percent,max_runup_percent:this.max_runup_percent,max_drawdown:this.max_drawdown,max_runup:this.max_runup,max_contracts_held_long:this.max_contracts_held_long,max_contracts_held_short:this.max_contracts_held_short,max_contracts_held_all:this.max_contracts_held_all,avg_winning_trade_percent:this.avg_winning_trade_percent,avg_winning_trade:this.avg_winning_trade,avg_trade_percent:this.avg_trade_percent,avg_trade:this.avg_trade,avg_losing_trade:this.avg_losing_trade,avg_losing_trade_percent:this.avg_losing_trade_percent,wintrades:this.wintrades,losstrades:this.losstrades,eventrades:this.eventrades,grossprofit:this.grossprofit,grossprofit_percent:this.grossprofit_percent,grossloss:this.grossloss,grossloss_percent:this.grossloss_percent,openprofit:this.openprofit,initial_capital:this.initial_capital,netprofit:this.netprofit,closedtrades:this.closedtrades,opentrades:this.opentrades,equity:this.equity,margin_call_long:this.marginCallLong,margin_call_short:this.marginCallShort}}_getCommission(e,t){if(!this._options)return 0;const{commission_value:r=0,commission_type:M}=this._options,n=e*t;let b=0;switch(M){case O2.percent:b=n*r/100;break;case O2.cashPerContract:b=t*r;break;case O2.cashPerOrder:b=r;break}return b}}class Hm{constructor(e){C(this,"_preAccdist");C(this,"_preNvi");C(this,"_prePvi");C(this,"_preObv");C(this,"_prePvt");C(this,"_preWad");C(this,"_preVwap");C(this,"_preValue");C(this,"_currentData");C(this,"_preData");C(this,"_id");this._preAccdist=0,this._preNvi=0,this._prePvi=0,this._preObv=0,this._prePvt=0,this._preWad=0,this._preVwap={},this._preValue={},this._currentData={},this._preData={},this._id=e}get _varTaCacheData(){return{preAccdist:this._preAccdist,preNvi:this._preNvi,prePvi:this._prePvi,preObv:this._preObv,prePvt:this._prePvt,preWad:this._preWad,preVwap:this._preVwap,currentData:this._currentData,preData:this._preData}}set _varTaCacheData(e){const{preAccdist:t,preNvi:r,prePvi:M,preObv:n,prePvt:b,preWad:z,preVwap:i,currentData:c,preData:O}=e;this._preAccdist=t,this._preNvi=r,this._prePvi=M,this._preObv=n,this._prePvt=b,this._preWad=z,this._preVwap=i,this._currentData=c,this._preData=O}update(e){this._preValue={},e.barIndex!==this._currentData.barIndex&&(this._preData={...this._currentData}),this._currentData={...e}}get isRealTime(){return this._preData.barIndex===this._currentData.barIndex}get accdist(){if(this._preValue.accdist)return this._preValue.accdist;const{close:e,low:t,high:r,volume:M}=this._currentData;if(r===t)return this._preAccdist;const n=(e-t-(r-e))/(r-t)*M+this._preAccdist;return!this.isRealTime&&(this._preAccdist=n),this._preValue.accdist=n,n}get iii(){if(this._preValue.iii)return this._preValue.iii;const{close:e,low:t,high:r,volume:M}=this._currentData,n=(2*e-r-t)/((r-t)*M);return this._preValue.iii=n,n}get nvi(){return this._preValue.nvi?this._preValue.nvi:this._getNvi()}get wvad(){if(this._preValue.wvad)return this._preValue.wvad;const{close:e,low:t,high:r,volume:M,open:n}=this._currentData,b=(e-n)/(r-t)*M;return this._preValue.wvad=b,b}get obv(){if(this._preValue.obv)return this._preValue.obv;const{close:e,volume:t}=this._currentData,{close:r}=this._preData;if(r===void 0){this._preObv=0;return}const M=Math.sign(e-r)*t+this._preObv;return!this.isRealTime&&(this._preObv=M),this._preValue.obv=M,M}get pvi(){return this._preValue.pvi?this._preValue.pvi:this._getPvi()}get tr(){if(this._preValue.tr)return this._preValue.tr;const{low:e,high:t}=this._currentData,{close:r}=this._preData;if(r===void 0)return;const M=Math.max(t-e,Math.abs(t-r),Math.abs(e-r));return this._preValue.tr=M,M}get pvt(){if(this._preValue.pvt)return this._preValue.pvt;const{close:e,volume:t}=this._currentData,{close:r}=this._preData;if(r===void 0){this._prePvt=0;return}const M=(e-r)/r*t+this._prePvt;return!this.isRealTime&&(this._prePvt=M),this._preValue.pvt=M,M}get wad(){if(this._preValue.wad)return this._preValue.wad;const{close:e,high:t,low:r}=this._currentData,{close:M}=this._preData;if(M===void 0)return this._preWad=0,0;const n=Math.max(t,M),b=Math.min(r,M),z=e-M,c=(z>0?e-b:z<0?e-n:0)+this._preWad;return!this.isRealTime&&(this._preWad=c),this._preValue.wad=c,c}get vwap(){var O,s;if(this._preValue.vwap)return this._preValue.vwap;const{hlc3:e,volume:t}=this._currentData;let{sum:r=0,sumV:M=0,isReset:n}=this._preVwap;if(((s=(O=self.workerStorage)==null?void 0:O.get(this._id))==null?void 0:s.buildInFunctions.timeframe.change({timeframe:"1D"},"vwap_buildin"))&&(n=!0,r=M=0),!n)return;const z=e*t+r,i=t+M;!this.isRealTime&&(this._preVwap={sum:z,sumV:i,isReset:n});const c=z/i;return this._preValue.vwap=c,c}_getNvi(){const e=this._preNvi||1,{close:t=0,volume:r=0}=this._preData,{close:M,volume:n}=this._currentData;let b=1;const z=e||1;return M&&t?b=n<r?z+(M-t)/t*z:z:b=z,!this.isRealTime&&(this._preNvi=b),this._preValue.nvi=b,b}_getPvi(){const e=this._prePvi||1,{close:t=0,volume:r=0}=this._preData,{close:M,volume:n}=this._currentData;let b=1;const z=e||1;return M&&t?b=n>r?z+(M-t)/t*z:z:b=z,!this.isRealTime&&(this._prePvi=b),this._preValue.pvi=b,b}}class Ym{constructor(){C(this,"_period");C(this,"_multiplier");C(this,"_unit");this._period="1",this._multiplier=1,this._unit="m"}update(e){if(!e)return;this._period=e;const[t,r]=ht(e);this._multiplier=t,this._unit=r}get isdaily(){return this._unit==="d"}get isdwm(){return["d","w","M"].includes(this._unit)}get isintraday(){return["s","m","h"].includes(this._unit)}get isminutes(){return this._unit==="m"}get ismonthly(){return this._unit==="M"}get isseconds(){return this._unit==="s"}get isweekly(){return this._unit==="w"}get multiplier(){return this._multiplier}get period(){return this._period}}class Gm{constructor(){C(this,"_bgColor");C(this,"_fgColor");C(this,"isUseBgColor",!1)}updateOptions(e){e!=null&&e.bg_color&&(this._bgColor=e.bg_color,this._fgColor=this._contrastColor(e.bg_color))}get bg_color(){return this.isUseBgColor=!0,this._bgColor}get fg_color(){return this.isUseBgColor=!0,this._fgColor}get is_heikinashi(){return!1}get is_kagi(){return!1}get is_linebreak(){return!1}get is_pnf(){return!1}get is_range(){return!1}get is_renko(){return!1}get is_standard(){return!0}get left_visible_bar_time(){}get right_visible_bar_time(){}_parseColor(e){let t,r,M,n;if(e.startsWith("#")){t=parseInt(e.substring(1,3),16),r=parseInt(e.substring(3,5),16),M=parseInt(e.substring(5,7),16);const b=e.substring(7);b?n=parseInt(b,16)/255:n=1}else{const b=this._parserRgbColor(e);t=b[0]||0,r=b[1]||0,M=b[2]||0,n=b[3]||1}return{r:t,g:r,b:M,a:n}}_parserRgbColor(e){var t;return((t=e.match(/\d+/g))==null?void 0:t.map(Number))||[]}_contrastColor(e){const{r:t,g:r,b:M}=this._parseColor(e);return(299*t+587*r+114*M)/1e3>128?"#000000":"#ffffff"}}class Vm{constructor(){C(this,"_syminfo",{})}update(e){this._syminfo=e}get __syminfo(){return this._syminfo}get basecurrency(){return this._syminfo.basecurrency||""}get country(){return this._syminfo.country}get currency(){return this._syminfo.currency||"USD"}get description(){return this._syminfo.description||""}get employees(){return this._syminfo.employees||100}get expiration_date(){return this._syminfo.expiration_date}get industry(){return this._syminfo.industry}get minmove(){return this._syminfo.minmove&&Number(this._syminfo.minmove)}get mintick(){return this._syminfo.mintick}get pointvalue(){return this._syminfo.pointvalue&&Number(this._syminfo.pointvalue)}get prefix(){return this.tickerid.replace(`:${this.ticker}`,"")}get pricescale(){return this._syminfo.pricescale&&Number(this._syminfo.pricescale)}get recommendations_buy(){return this._syminfo.recommendations_buy}get recommendations_buy_strong(){return this._syminfo.recommendations_buy_strong}get recommendations_date(){return this._syminfo.recommendations_date}get recommendations_hold(){return this._syminfo.recommendations_hold}get recommendations_sell(){return this._syminfo.recommendations_sell}get recommendations_sell_strong(){return this._syminfo.recommendations_sell_strong}get recommendations_total(){return this._syminfo.recommendations_total}get root(){return this._syminfo.root||""}get sector(){return this._syminfo.sector}get session(){return this._syminfo.session||ft.regular}get shareholders(){return this._syminfo.shareholders}get shares_outstanding_float(){return this._syminfo.shares_outstanding_float}get shares_outstanding_total(){return this._syminfo.shares_outstanding_total}get target_price_average(){return this._syminfo.target_price_average}get target_price_date(){return this._syminfo.target_price_date}get target_price_estimates(){return this._syminfo.pricescale}get target_price_high(){return this._syminfo.target_price_high}get target_price_low(){return this._syminfo.target_price_low}get target_price_median(){return this._syminfo.target_price_median}get ticker(){return this._syminfo.ticker||""}get tickerid(){return this._syminfo.tickerid||""}get timezone(){return this._syminfo.timezone||"UTC+8"}get type(){return this._syminfo.type||"forex"}get volumetype(){return this._syminfo.volumetype||"n/a"}}class Km{constructor(e){C(this,"_variables");this._variables=e}get future_amount(){}get future_ex_date(){}get future_pay_date(){}}class Jm{constructor(e){C(this,"_variables");this._variables=e}get future_eps(){}get future_period_end_time(){}get future_revenue(){}get future_time(){}}class _p{constructor(e){C(this,"_cacheData");C(this,"_barIndex");C(this,"_isRealTimeBar");C(this,"_barstate");C(this,"_priceVariables");C(this,"_lastBarIndex");C(this,"_currentBarTime");C(this,"_lastBarTime");C(this,"_period");C(this,"_offsetTime");C(this,"_timeframe");C(this,"_ta");C(this,"_polyline");C(this,"_label");C(this,"_line");C(this,"_linefill");C(this,"_box");C(this,"_table");C(this,"_strategy");C(this,"_session");C(this,"syminfo");C(this,"chart");C(this,"earnings");C(this,"dividends");C(this,"_timeTradingday");C(this,"_mintick");C(this,"_cacheSpace");C(this,"_precision");C(this,"_nextBarTime");C(this,"_isRepeated");C(this,"_preCacheData");C(this,"__requestName","");C(this,"__isFirstRun",!1);C(this,"_maxBarsBack",0);C(this,"_maxBarsBackOfKey");C(this,"__isReqRepeated");C(this,"_newCacheData",{});this._cacheData={varData:{},varipData:{}},this._preCacheData={varData:{},varipData:{}},this._barIndex=0,this._lastBarIndex=0,this._currentBarTime=0,this._lastBarTime=0,this._offsetTime=0,this._period="",this._isRealTimeBar=!1,this._barstate=new $m,this._timeframe=new Ym,this._priceVariables={close:0,open:0,low:0,high:0,volume:0},this._ta=new Hm(e),this._polyline=new Sr(this,N0.POLYLINE),this._label=new Sr(this,N0.LABEL),this._line=new Sr(this,N0.LINE),this._linefill=new Sr(this,N0.LINEFILL),this._box=new Sr(this,N0.BOX),this._table=new Sr(this,N0.TABLE),this._strategy=new jm(this),this._session=new Um(this),this.syminfo=new Vm,this.chart=new Gm,this.earnings=new Jm(this),this.dividends=new Km(this),this._cacheSpace=Object.create(null),this._maxBarsBackOfKey=Object.create(null)}getVarCacheData(){return{cacheData:this._cacheData,preCacheData:this._preCacheData,cacheSpace:this._cacheSpace,taCacheData:this._ta._varTaCacheData,polylineCacheData:this._polyline._cacheData,labelCacheData:this._label._cacheData,lineCacheData:this._line._cacheData,linefillCacheData:this._linefill._cacheData,boxCacheData:this._box._cacheData,tableCacheData:this._table._cacheData,barstateCacheData:this.barstate._barstateCacheData}}setVarCacheData(e){if(!e)return;const{cacheData:t,preCacheData:r,cacheSpace:M,taCacheData:n,polylineCacheData:b,labelCacheData:z,lineCacheData:i,linefillCacheData:c,boxCacheData:O,tableCacheData:s,barstateCacheData:u}=e;this._cacheData=t,this._preCacheData=r,this._cacheSpace=M,this._ta._varTaCacheData=n,this._polyline._cacheData=b,this._label._cacheData=z,this._line._cacheData=i,this._linefill._cacheData=c,this._box._cacheData=O,this._table._cacheData=s,this.barstate._barstateCacheData=u}get table(){return this._table}get box(){return this._box}get linefill(){return this._linefill}get line(){return this._line}get polyline(){return this._polyline}get label(){return this._label}get ta(){return this._ta}get strategy(){return this._strategy}get session(){return this._session}get na(){}get last_bar_index(){return this._lastBarIndex}get bar_index(){return this._barIndex}get barstate(){return this._barstate}get close(){return this._priceVariables.close}get low(){return this._priceVariables.low}get open(){return this._priceVariables.open}get high(){return this._priceVariables.high}get volume(){return this._priceVariables.volume}get ohlc4(){const{close:e,open:t,high:r,low:M}=this._priceVariables;return(e+t+r+M)/4}get hl2(){const{high:e,low:t}=this._priceVariables;return(e+t)/2}get hlc3(){const{close:e,high:t,low:r}=this._priceVariables;return(e+t+r)/3}get hlcc4(){const{close:e,high:t,low:r}=this._priceVariables;return(e*2+t+r)/4}get hour(){return O1(this._currentBarTime).hour()}get minute(){return O1(this._currentBarTime).minute()}get second(){return O1(this._currentBarTime).second()}get month(){return O1(this._currentBarTime).month()+1}get year(){return O1(this._currentBarTime).year()}get dayofweek(){return O1(this.time_tradingday).weekday()}get dayofmonth(){return O1(this.time_tradingday).date()}get weekofyear(){return O1(this._currentBarTime).week()}get last_bar_time(){return this._lastBarTime}get time(){return this._currentBarTime}get time_close(){const[e,t]=ht(this._period);return O1(this._currentBarTime).add(e,t).valueOf()}get timenow(){return Date.now()}get time_tradingday(){return this._timeTradingday||this._getTimeTradingday(this._currentBarTime,this._period)}get timeframe(){return this._timeframe}get mintick(){return this._mintick}get __period(){return this._period}get precision(){return this._precision}get nextBarTime(){return this._nextBarTime}set max_bars_back(e){this._maxBarsBack=e}updateMaxLength(e){const{max_lines_count:t,max_labels_count:r,max_boxes_count:M,max_polylines_count:n}=e;M&&this._box.setMaxLen(M),r&&this._label.setMaxLen(r),t&&this._line.setMaxLen(t),n&&this._polyline.setMaxLen(n)}getTimeTradingday(e,t){const[r,M]=ht(t),n=O1(e);return["M","w","y","d"].includes(M)?n.valueOf():(n.subtract(this._offsetTime,"h"),n.startOf("d").add(this._offsetTime,"h").valueOf())}_getTimeTradingday(e,t){const[r,M]=ht(t),n=O1(e).utc(!0);return["M","w","y","d"].includes(M)?n.valueOf():n.startOf("d").valueOf()}updateOptions(e){var c;const{interval:t="1D",offsetTime:r=5,mintick:M,chart:n,syminfo:b}=e,z=((c=M.toString().split(".")[1])==null?void 0:c.length)||5;this._precision=z;const i=Q4(t);this._period=i,this._mintick=M,this._offsetTime=r,this._timeframe.update(i),this.chart.updateOptions(n),this.syminfo.update(b),this._barstate.isFirstRun=this.__isFirstRun}updateData(e,t){const{barIndex:r,c:M,o:n,h:b,l:z,volume:i,time:c,lastBarIndex:O,lastBarTime:s,isrealtime:u,time_tradingday:l,nextBarTime:q}=e;if(this._priceVariables={close:rn(M,this._precision),open:rn(n,this._precision),high:rn(b,this._precision),low:rn(z,this._precision),volume:Number(i)},this._isRealTimeBar=u,this._newCacheData={},r>this._barIndex){const{varData:A,varipData:h}=this._cacheData;this._preCacheData={varData:{},varipData:{}},u?(this._preCacheData.varData=b2.cloneDeep(A),this._preCacheData.varipData=b2.cloneDeep(h)):this._preCacheData={varData:{...A},varipData:{...h}}}this._isRepeated=t,this._timeTradingday=l,this._currentBarTime=c*1e3,this._lastBarIndex=O,this._barIndex=r,this._lastBarTime=s*1e3,this._nextBarTime=q*1e3,this._barstate.update(r,O,u,!0),this.ta.update({...this._priceVariables,hlc3:this.hlc3,barIndex:r})}getCacheData(e,t,r){let M=this._cacheData[e],n=1;M?(M.barIndex<this._barIndex&&(n=0),M=M.data):M=this.setCacheData(e,r);const b=this._cacheSpace[e]||0;return t=Math.floor(t),b<t&&(this._cacheSpace[e]=t),M[M.length-n-t]}setCacheData(e,t){let r=this._cacheData[e]||{barIndex:-1,data:[]};if(r.barIndex>this._barIndex)return r.data;t=this._cacheCopy(t),r.barIndex===this._barIndex?r.data[r.data.length-1]=t:r.data.push(t);const M=this._cacheSpace[e]||0,n=ui.includes(e)?500:50;return M&&r.data.length>(this._maxBarsBackOfKey[e]||this._maxBarsBack||M+n)&&r.data.shift(),r.barIndex=this._barIndex,this._cacheData[e]=r,r.data}__setBarsBackOfKey(e,t){this._maxBarsBackOfKey[e]=t}__getBarsBackOfKey(e){return this._maxBarsBackOfKey[e]}getTypeInstance(e,t,r){return new Oi(e,t,r)}verifyVarAndVarip(e,t,r){const M=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`,n=this._isRepeated||this.__isReqRepeated?this._preCacheData:this._cacheData;if(r==="var"&&n.varData.hasOwnProperty(M))return this._upadteChartDraws(n.varData,M),!0;const b=this.__isReqRepeated?this._preCacheData.varipData:this._cacheData.varipData;return r==="varip"&&b.hasOwnProperty(M)?(this._upadteChartDraws(b,M),!0):!1}getVarValue(e,t,r){const M=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`;(this._isRepeated||this.__isReqRepeated)&&(this._cacheData.varData[M]=this._preCacheData.varData[M],this.__isReqRepeated&&(this._cacheData.varipData[M]=this._preCacheData.varipData[M]));const n=this._cacheData;if(r==="var"){const b=n.varData[M];return this._isRealTimeBar?this._newCacheData.hasOwnProperty(M)?this._newCacheData[M]:this._cacheCopy(b):b}return this._cacheData.varipData[M]}setVarValue(e,t,r,M){var z;const n=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`;let b;switch(typeof r=="object"&&((z=r==null?void 0:r.varipKeys)!=null&&z.length)&&M!=="varip"&&(M="var",b=r.varipKeys),M){case"var":if(this._isRealTimeBar){if(b&&b.length)for(const i of b)this._cacheData.varData[n][i]=r[i];this._newCacheData[n]=r}else this._chartDrawsHandle(r,this._cacheData.varData[n]),this._cacheData.varData[n]=r;break;case"varip":this._chartDrawsHandle(r,this._cacheData.varipData[n]),this._cacheData.varipData[n]=r;break}return r}_upadteChartDraws(e,t){const r=e[t],M=this._isRealTimeBar?r==null?void 0:r.preId:r==null?void 0:r.id;if(!M)return;let n;switch(r==null?void 0:r.type){case N0.BOX:n=this._setChartDraw(M,this._box);break;case N0.LINE:n=this._setChartDraw(M,this._line);break;case N0.POLYLINE:n=this._setChartDraw(M,this._polyline);break;case N0.LABEL:n=this._setChartDraw(M,this._label);break;case N0.LINEFILL:n=this._setChartDraw(M,this._linefill);break;case N0.TABLE:n=this._setChartDraw(M,this._table);break}n&&(e[t]=n)}_cacheCopy(e){return typeof e!="object"||!e||e.isDraw?e:b2.cloneDeep(e)}_updateId(e){const{bar_index:t,_isRealTimeBar:r}=this,M=e.id;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const n=e.id.split("_");n.pop(),e.id=`${n.join("_")}_${t}`}return e.line1&&nt.__updateFillKeys(e.line1,M,e.id),e.line2&&nt.__updateFillKeys(e.line2,M,e.id),r||(e.preId=e.id),e.id}_setChartDraw(e,t){const r=t.getInstance(e);let M=t.get(e);if(!M||!r)return;const n=this._updateId(r)||e;return n===e&&!this._isRealTimeBar||(M=JSON.parse(JSON.stringify(M)),this._isRealTimeBar||(r.data=M),t.deleteHandle(e,!1),t.set(n,M,r)),r}_chartDrawsHandle(e,t){if(typeof e!="object")return;const r=t==null?void 0:t.id;let M=e==null?void 0:e.id;M&&e.data&&(e.data.isVar=!0),r!==M&&r&&t.data&&(t.data.isVar=!1)}add(e,t){return Array.isArray(e)&&Array.isArray(t)?b2.uniq([...e,...t]):typeof e=="number"||typeof t=="number"?Number(e)+Number(t):(e||"")+(t||"")}sub(e,t){return Array.isArray(e)&&Array.isArray(t)?e.filter(r=>!t.includes(r)):Number(e)-Number(t)}div(e,t){if(t)return e/t}notEqual(e,t,r,M){return e===void 0&&typeof t=="number"||t===void 0&&typeof e=="number"||e===void 0&&t===void 0?!1:!this.equal(e,t,r,M)}equal(e,t,r,M){if(typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t))return!0;if(e!==void 0&&t!==void 0)return e==t;if(e===void 0&&typeof t=="number"||t===void 0&&typeof e=="number")return!1;if(!(r.endsWith(N0.BOOL)&&e===void 0))return(r.endsWith(N0.FLOAT)||r.endsWith(N0.INT)||M.endsWith(N0.FLOAT)||M.endsWith(N0.INT))&&e===void 0&&t===void 0?!1:r.endsWith(N0.STRING)&&e===""&&t===void 0||M.endsWith(N0.STRING)&&t===""&&e===void 0?!0:r.endsWith(N0.NA)&&M.endsWith(N0.NA)?!1:e==t}compareDataHandle(e){if(typeof e!="number"||!e)return e;const t=String(e);if(!t.includes(".")&&!/[eE]/.test(t))return e;const[r,M]=e.toFixed(11).split(".");return+`${r}.${M.slice(0,10)}`}}class Sr{constructor(e,t,r=50){C(this,"_all");C(this,"_allInstance");C(this,"_pseudoArrayAll");C(this,"_maxLength");C(this,"_deleteIds");C(this,"_variables");C(this,"_preDeleteIds");C(this,"_againAddItems");C(this,"_tmpData");C(this,"_tmpInstance");C(this,"_type");C(this,"_tmpIds",[]);this._all=new Map,this._allInstance=new Map,this._pseudoArrayAll=p1(0,void 0,t),this._maxLength=r,this._deleteIds=new Map,this._variables=e,this._preDeleteIds=new Map,this._againAddItems=[],this._tmpData=new Map,this._tmpInstance=new Map,this._type=t}get _cacheData(){return{allInstance:Array.from(this._allInstance),tmpIds:this._tmpIds,preDeleteIds:Array.from(this._preDeleteIds)}}set _cacheData(e){this._allInstance=new Map(e.allInstance),this._all=new Map(e.allInstance.map(([t,r])=>[t,r.data])),this._tmpIds=e.tmpIds,this._preDeleteIds=new Map(e.preDeleteIds)}setMaxLen(e){this._maxLength=e}get size(){return this._all.size+this._tmpData.size}get __allInstance(){return this._allInstance}get data(){const e=[],t=b2.flatMap([...this._deleteIds.values()]),r=b2.uniq([...this._tmpData.keys(),...this._all.keys()]),M=[];for(const n of r)if(!t.some(b=>b.key===n)){const b=this._tmpData.get(n)||this._all.get(n),z=b==null?void 0:b.id;b&&!M.includes(z)&&(M.push(z),e.push(b))}return this._variables._isRealTimeBar&&this._preDeleteIds.set(this._variables.last_bar_index,this._deleteIds.get(this._variables.last_bar_index)||[]),this._tmpDataHandle(),this._type===N0.LINEFILL?e:e.slice(-this._maxLength)}get all(){return this._pseudoArrayAll._value=[...this._allInstance.values(),...this._tmpInstance.values()],this._pseudoArrayAll}add(e,t,r){if(this.set(e,t,r),!this._variables._isRealTimeBar&&this._type!==N0.LINEFILL&&this._all.size>this._maxLength){const{bar_index:M}=t;for(const[n,b]of this._all){const{isVar:z,id:i,bar_index:c}=b;if(c===M)break;if(z)continue;this.deleteHandle(i);break}}}getValOfBarIndex(e){let t=[];const r=b2.uniq([...this._all.keys(),...this._tmpData.keys()]),M=b2.flatMap([...this._deleteIds.values()]);for(const n of e){const b=r.filter(z=>z.endsWith(`_${n}`));for(const z of b){if(M.some(c=>c.key===z))continue;const i=this._tmpData.get(z)||this._all.get(z);i&&t.push(i)}}return this._againAddItems.length&&(t=this._againAddItems.concat(t),this._againAddItems=[]),this._tmpDataHandle(),t.length?this._type===N0.LINEFILL?t:t.slice(-this._maxLength):void 0}getDeleteIds(e){let t=[];const{bar_index:r,_isRealTimeBar:M}=this._variables,n=[];for(const z of e){let i=[...this._deleteIds.get(z)||[]];const c=this._preDeleteIds.get(z)||[];if(z===r&&M){let O=[];for(const s of c){const u=i.findIndex(l=>l.id===s.id);if(u===-1){const l=this._all.get(s.key);l&&n.push(l)}else O.push(s),i.splice(u,1)}this._preDeleteIds.set(r,b2.uniqBy([...i,...O],"id"))}else{const O=[];for(const s of i)c.some(u=>u.id===s.id)||O.push(s);i=O,this._preDeleteIds.delete(z)}t=t.concat(i)}const b=[...this._all.values(),...this._tmpData.values()];for(const z of this._tmpIds)b.some(i=>i.id===z.id)||t.push(z);return this._againAddItems=n,b2.uniq(t.map(z=>z.id))}set(e,t,r){this._variables._isRealTimeBar?(this._tmpData.set(e,t),this._tmpInstance.set(e,r)):(this._all.set(e,t),this._allInstance.set(e,r))}get(e){const t=this._all.get(e);let r=this._tmpData.get(e);return this._variables._isRealTimeBar?(r||(r=t?{...t}:void 0,r&&this._tmpData.set(e,r)),r):(this._tmpData.clear(),this._tmpInstance.clear(),t)}getInstance(e){return this._allInstance.get(e)}deleteHandle(e,t=!0,r=!1){var M;if(this._type===N0.LINE&&t){const n=(M=this._allInstance.get(e))==null?void 0:M.fillKeys;if(n&&n.length)for(const b of n)this._variables.linefill.deleteHandle(b)}if(this._variables._isRealTimeBar){if(r){const n=this._tmpInstance.get(e);n&&(n.data=void 0)}this._tmpData.delete(e),this._tmpInstance.delete(e)}else{if(r){const n=this._allInstance.get(e);n&&(n.data=void 0)}this._all.delete(e),this._allInstance.delete(e)}}delete(e,t,r){const M=this._all.get(e);if(this._variables._isRealTimeBar||this.deleteHandle(e,!1,!0),!(this._variables.__isFirstRun&&!this._variables._isRealTimeBar)&&typeof t=="number"){const n=this._deleteIds.get(t)||[];n.push({key:e,id:(M==null?void 0:M.id)||r}),this._deleteIds.set(t,n)}}_tmpDataHandle(){var e;this._tmpIds=[];for(const[t]of this._tmpInstance){const r=(e=this._tmpData.get(t))==null?void 0:e.id;r&&this._tmpIds.push({id:r,key:t})}this._tmpData.clear(),this._tmpInstance.clear(),this._deleteIds.clear()}}/**
85
+ ${l}`),l}_getRequestLowerTfData(e,t,r,M){var R;let{symbol:n,timeframe:b,calc_bars_count:z,ignore_invalid_symbol:i,ignore_invalid_timeframe:c}=e;const{__period:O,time:s,_isRealTimeBar:u}=this._variables;b=uM(b);let l=y2(b,s)*1e3;const q=y2(O,s)*1e3;if(l>q)return!c&&this._errorListener.addError(l2(N1.requestLowerTfPeriodErr,{period:b}),t,K0.Error,25),[];const A=`${n}--${b}`,h=self.workerStorage.get(`request_${this._scriptId}_data`),d=self.workerStorage.get(`request_${this._scriptId}_list`),m=self.workerStorage.get(`request_${this._scriptId}_tmp`),_={id:A,calc_bars_count:z,ignore_invalid_symbol:i,symbol:n,originTimeframe:b,timeframe:Ai[b]||Ac(b)};if(h!=null&&h.has(A)){m==null||m.delete(A);const{index:g=0,periodStamp:L=q}=this._cacheData[r]||{},y=h==null?void 0:h.get(A);if(!y.length)return[];if(y.length-1<0)return[];const T=y.slice(g);let N=s,w=L+N;const E=[];for(const[P,H]of T.entries()){let{time:Y}=H;Y=Y*1e3;let k=g+P;if(Y>=w)return!u&&(this._cacheData[r]={index:k,periodStamp:L}),E;if(N<=Y&&Y<w){const K=(R=H==null?void 0:H.result)==null?void 0:R[r];if(Array.isArray(K))for(const[e0,b0]of K.entries())E[e0]||(E[e0]=[]),E[e0].push(b0);else M||E.push(K)}}return!u&&(this._cacheData[r]={index:y.length,periodStamp:L}),E}else(d==null?void 0:d.get(A))||m==null||m.set(A,_);d==null||d.set(A,_)}_getRequestData(e,t){var m,_,R,g,L;let{symbol:r,timeframe:M,calc_bars_count:n,gaps:b,lookahead:z,ignore_invalid_symbol:i}=e;const{__period:c,mintick:O,time:s,nextBarTime:u}=this._variables;M=uM(M),r=r;const l=`${r}--${M}`,q=self.workerStorage.get(`request_${this._scriptId}_data`),A=self.workerStorage.get(`request_${this._scriptId}_list`),h=self.workerStorage.get(`request_${this._scriptId}_tmp`),d={id:l,calc_bars_count:n,ignore_invalid_symbol:i,symbol:r,originTimeframe:M,timeframe:Ai[M]||Ac(M)};if(q!=null&&q.has(l)){let y=y2(M,s)*1e3;const D=y2(c,s)*1e3;h==null||h.delete(l);const{index:T=0,periodStamp:N=D}=this._cacheData[t]||{},w=q==null?void 0:q.get(l);if(!w.length)return;const E=w.slice(T);let P=s,H=N+P;const Y=w.length-1;if(Y<0)return;const k={lastBarIndex:w[Y].barindex||Y,lastBarTime:w[Y].time,interval:M,mintick:O};if(y>N){let K;if(z===ke.lookaheadOn?K=this._lookaheadOnHandle(E,M,H,y,k,T,N,t,P,b):K=this._lookaheadOffHandle(E,M,H,y,k,T,N,t,P,u||H,b),K)return K;if(K===null)return}else if(z===ke.lookaheadOn)for(const[K,e0]of E.entries()){let{time:b0,barindex:O0}=e0;b0=b0*1e3;const v0=((m=E[K+1])==null?void 0:m.time)*1e3||b0+y;let B0=T+K;if(b0>=H){this._cacheData[t]={index:B0,periodStamp:N};return}if(b0<=P&&v0>P){const A0=T+K;return this._cacheData[t]={index:A0,periodStamp:N},{...e0,barIndex:O0||A0,nextBarTime:(_=E[K+1])==null?void 0:_.time,...k}}}else for(const[K,e0]of E.entries()){let{time:b0,barindex:O0}=e0;b0=b0*1e3;const v0=((R=E[K+1])==null?void 0:R.time)*1e3||b0+y;let B0=T+K;if(b0>H){this._cacheData[t]={index:B0,periodStamp:N};return}if(b0<H&&H<=v0)return this._cacheData[t]={index:B0,periodStamp:N},{...e0,barIndex:O0||B0,nextBarTime:(g=E[K+1])==null?void 0:g.time,...k};if(b0>=P&&b0<=H&&(O0||B0)===k.lastBarIndex)return this._cacheData[t]={index:B0,periodStamp:N},{...e0,barIndex:O0||B0,nextBarTime:(L=E[K+1])==null?void 0:L.time,...k}}this._cacheData[t]={index:w.length,periodStamp:N};return}else(A==null?void 0:A.get(l))||h==null||h.set(l,d);A==null||A.set(l,d)}_lookaheadOnHandle(e,t,r,M,n,b,z,i,c,O){var s;for(const[u,l]of e.entries()){let{time:q,barindex:A}=l;q=q*1e3,t.includes("M")&&(M=y2(t,q)*1e3-(O1(q).date()-1)*864e5);const h=q,d=M+h;let m=b+u;if(r<=h)return this._cacheData[i]={index:m,periodStamp:z},null;let _={...l,barIndex:A||m,nextBarTime:(s=e[u+1])==null?void 0:s.time,...n};if(O===ke.gapsOn){if(r>h&&c<=h)return this._cacheData[i]={index:m,periodStamp:z},_}else{if(r>d)continue;if(r>h)return this._cacheData[i]={index:m,periodStamp:z},_}}}_lookaheadOffHandle(e,t,r,M,n,b,z,i,c,O,s){var u,l;for(const[q,A]of e.entries()){let{time:h,barindex:d}=A;h=h*1e3,t.includes("M")&&(M=y2(t,h)*1e3-(O1(h).date()-1)*864e5);const m=h,_=M+m,R=b+q;if(r<m)return this._cacheData[i]={index:R,periodStamp:z},null;const g={...A,barIndex:d||R,nextBarTime:(u=e[q+1])==null?void 0:u.time,...n};if(r>=_&&c<_||r<_&&O>=_)return s===ke.gapsOn?(this._cacheData[i]={index:R,periodStamp:z},g):(this._cacheData[i]={index:R,data:g,periodStamp:z},g);if(!(c>_)&&c>=m){let L=(l=this._cacheData[i])==null?void 0:l.data;if(!L){const y=e[R-1];if(!y)return null;L={...y,barIndex:y.barindex||R-1,nextBarTime:g.time,...n},this._cacheData[i]={index:R,data:L,periodStamp:z}}return L}}}_getDependCodes(e,t,r,M,n,b){for(const z of e){if(!z.isArg){const i=t.filter(O=>{var s;return(s=O==null?void 0:O.depends)==null?void 0:s.some(u=>u.name===z.name&&u.scope===z.scope&&u.isAgainAssign!==!1)});for(const O of i){const{code:s,depends:u,scope:l,funcName:q}=O;r[l]=r[l]||[];const A=r[l];let h=l===0&&q;if(!A.includes(s)){if(h){if(M.includes(s))continue;M.unshift(s)}else A.unshift(s);if(u!=null&&u.length){for(const d of u)d.memberCode&&!h&&b.push(d.memberCode);this._getDependCodes(u,t,r,M,n,b)}}}const c=t.find(O=>{var s;return((s=O.varNames)==null?void 0:s.split(", ").includes(z.name))&&(!z.isPreArg||z.isPreArg&&O.methodName===z.functionName)||O.funcName===z.name});if(c){const{code:O,depends:s,scope:u}=c;r[u]=r[u]||[];const l=r[u],q=l.findIndex(A=>A===O);if(q!==-1){if(z.isFunc)continue;l.splice(q,1)}if(l.unshift(O),s!=null&&s.length){for(const A of s)A.memberCode&&b.push(A.memberCode);this._getDependCodes(s,t,r,M,n,b)}continue}}n.some(i=>i.name===z.name)||n.push(z)}}_getStmtFuncs(e,t,r,M,n){const b=t.filter(z=>z.isStmtFunc);for(const z of b){const{code:i,depends:c,scope:O=0}=z;e[O]=e[O]||[];const s=e[O];if(!s.includes(i)&&(s.push(i),c!=null&&c.length)){for(const u of c)u.memberCode&&r.push(u.memberCode);this._getDependCodes(c.filter(u=>!(u.isFunc&&i.startsWith(u.name))),t,e,M,n,r)}}}runScripts(e,t,r,M,n,b){var u,l;const z=`${this._scriptId}_${t}`,i=new _p(z),c=new hp,O=new Wp(this._variables.mintick||1e-5,i,this._scriptId),s=new Function("_$_var","_$_const","_$_func","$paramsExpr","$posStr",e);if(!r){const{varCacheData:q,funcCacheData:A}=n;i.setVarCacheData(q),O.setFuncCacheData(A)}if(i.__requestName=t,M&&M.length){const q=M.length-1,{interval:A,symbol:h=""}=n;let{mintick:d,syminfo:m}=this._variables;const[_,R]=h.split(":");d||(d=Math.pow(10,-(((u=String(M[0].o).split(".")[1])==null?void 0:u.length)||0))),i.updateOptions({interval:A,mintick:d,syminfo:{...m.__syminfo,mintick:d,tickerid:h||m.tickerid,ticker:R||_||m.ticker}});for(const[y,D]of M.entries()){const{barindex:T}=D,N=Object.assign(D,{barIndex:T||y,lastBarIndex:M[q].barindex||q,lastBarTime:M[q].time,nextBarTime:(l=M[y+1])==null?void 0:l.time});if(i.updateData(N),O.update({barIndex:(N==null?void 0:N.barindex)||0}),D.result=Object.assign(D.result||{},{[t]:s(i,c,O,b||[],t)}),O.endExecution(),O.errors.length&&O.errors.some(w=>w.type===K0.Error))return{logs:[],errors:O.errors}}const g=O.log.logs,L=O.errors;return O.log.clearLogs(),O.clearErrors(),{logs:g,errors:L,cacheData:{varCacheData:i.getVarCacheData(),funcCacheData:O.getFuncCacheData()}}}}_runScripts(e,t,r,M,n){const b=`${this._scriptId}_${t}`;let{builtInGather:z,buildinConstants:i,buildInFunctions:c,tradingvueFunc:O}=self.workerStorage.get(b)||{};const{interval:s,...u}=n||{};if(r){z=new _p(b),i=new hp,c=new Wp(this._variables.mintick||1e-5,z,this._scriptId),O=new Function("_$_var","_$_const","_$_func","$paramsExpr","$posStr",e);const{mintick:h,syminfo:d}=this._variables;z.updateOptions({interval:s,mintick:h||1e-5,syminfo:{...d.__syminfo}}),z.__requestName=t,self.workerStorage.set(b,{builtInGather:z,buildinConstants:i,buildInFunctions:c,tradingvueFunc:O})}z.updateData(u),c.update({barIndex:(u==null?void 0:u.barindex)||0});const l=O(z,i,c,M||[],t),q=c.log.logs,A=c.errors;return c.log.clearLogs(),c.clearErrors(),c.endExecution(),{result:l,logs:q,errors:A}}},Fm=class{constructor(){}prefix(e){var r;const{symbol:t}=e;return((r=t==null?void 0:t.split("."))==null?void 0:r[0])||""}ticker(e){var r;const{symbol:t}=e;return((r=t==null?void 0:t.split("."))==null?void 0:r[1])||""}};class Im{constructor(e,t){C(this,"_logs");C(this,"_variables");C(this,"_str");C(this,"_preBar",{barIndex:-1,isrealtime:!1});this._variables=e,this._logs=[],this._str=t}get _logCacheData(){return this._preBar}set _logCacheData(e){this._preBar=e}get logs(){return this._logs}clearLogForIndex(e){this._logs=this._logs.filter(t=>t.barIndex!==e)}clearLogs(){this._logs=[]}info(e,t,r){this._addLog(e,t,"info",r)}error(e,t,r){this._addLog(e,t,"error",r)}warning(e,t,r){this._addLog(e,t,"warning",r)}mergeLogs(e){this._logs=this._logs.concat(e)}_addLog(e,t,r,M){if(typeof t=="string"&&(M=t),M.startsWith("export"))return;const{message:n,formatString:b}=e,{time:z,bar_index:i,_isRealTimeBar:c,__isReqRepeated:O}=this._variables;let s=n;b&&Array.isArray(t)&&t.length&&(t=t.map(A=>{if(typeof A=="object"){if(A===null)return"null";A!=null&&A.isArray?A=`[${A._value.toString()}]`:A=A.toString()}return A!==void 0?A:"na"}),s=this._str.strformat({formatString:b},t,!0));const{isrealtime:u,barIndex:l}=this._preBar;i!==l&&(this._preBar={barIndex:i,isrealtime:c});const q=Date.now();s!==void 0&&this._logs.push({message:`[${O1(u&&!O?q:z).format("YYYY-MM-DDTHH:mm:ss.SSSZ")}]: ${s}`,time:z,id:K4(6),barIndex:i,type:r})}}class Pm{constructor(e){C(this,"_errorListener");this._errorListener=e}error({message:e},t){t.startsWith("export")||this._errorListener.addError(e,t,K0.Error)}}class km{constructor(){C(this,"_errors");this._errors=new Map}clear(){this._errors.clear()}get errors(){return b2.flatMap([...this._errors.values()])}setErrors(e,t){this._errors.set(t,e)}addError(e,t,r,M=0){const[n,b]=t.split("_").slice(-2),z=this._errors.get(t),i={message:e,endLineNumber:Number(n),startColumn:Number(b)+1,endColumn:Number(b)+M+1,startLineNumber:Number(n),type:r};z?z.push(i):this._errors.set(t,[i])}}class $m{constructor(){C(this,"_isMarketOpen");C(this,"_currentBarIndex");C(this,"_totalBarIndex");C(this,"_isRealTimeBar");C(this,"_preBarIndex");C(this,"_preIsRealTimeBar");C(this,"_isFirstRun",!1);this._currentBarIndex=0,this._totalBarIndex=0,this._isRealTimeBar=!1,this._preBarIndex=0,this._isMarketOpen=!0,this._preIsRealTimeBar=!1}update(e,t,r,M){this._preBarIndex=this._currentBarIndex,this._preIsRealTimeBar=this._isRealTimeBar,this._currentBarIndex=e,this._totalBarIndex=t,this._isRealTimeBar=r,this._isMarketOpen=M}get _barstateCacheData(){return{currentBarIndex:this._currentBarIndex,isRealTimeBar:this._isRealTimeBar}}set _barstateCacheData(e){this._currentBarIndex=e.currentBarIndex,this._isRealTimeBar=e.isRealTimeBar}set isFirstRun(e){this._isFirstRun=e}get isnew(){return this._preBarIndex!==this._currentBarIndex}get islast(){return this._currentBarIndex===this._totalBarIndex||!this._isFirstRun}get isfirst(){return this._currentBarIndex===0}get ishistory(){return!this._isRealTimeBar||this._isFirstRun}get isrealtime(){return this._isRealTimeBar}get isconfirmed(){return!this._isRealTimeBar}get islastconfirmedhistory(){return this._isMarketOpen?this._currentBarIndex===this._totalBarIndex-1&&!this._preIsRealTimeBar||this._currentBarIndex===this._totalBarIndex&&!this._isRealTimeBar:this._currentBarIndex===this._totalBarIndex}}class Um{constructor(e){C(this,"_variables");this._variables=e}get isfirstbar(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday||this._variables.bar_index===0}get isfirstbar_regular(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday}get islastbar(){if(this._variables.timeframe.isdwm)return!0;const{time:e,__period:t}=this._variables,r=y2(t,e);return this._variables.time+r===this._variables.time_tradingday+24*60*60*1e3}get islastbar_regular(){if(this._variables.timeframe.isdwm)return!0;const{time:e,__period:t}=this._variables,r=y2(t,e);return this._variables.time+r===this._variables.time_tradingday+24*60*60*1e3}get ismarket(){return!0}get ispostmarket(){return!1}get ispremarket(){return!1}}class jm{constructor(e){C(this,"_orders");C(this,"_historyOrders");C(this,"_options");C(this,"_max_contracts_held_all",0);C(this,"_max_contracts_held_long",0);C(this,"_max_contracts_held_short",0);C(this,"_max_drawdown",0);C(this,"_max_runup",0);C(this,"_max_runup_percent",0);C(this,"_max_drawdown_percent",0);C(this,"_variables");C(this,"_netprofit",0);C(this,"_eventrades",0);C(this,"_avg_trade_percent");C(this,"_avg_losing_trade_percent");C(this,"_avg_winning_trade_percent");C(this,"_closedtrades",0);C(this,"_losstrades",0);C(this,"_grossloss",0);C(this,"_grossprofit",0);C(this,"_wintrades",0);C(this,"_opentrades_capital_held",0);C(this,"_position_avg_price",0);C(this,"_position_size",0);C(this,"_openprofit",0);C(this,"_preMaxNetValue",0);C(this,"_preMinNetValue",0);C(this,"marginCallLong",0);C(this,"marginCallShort",0);this._orders=[],this._historyOrders=[],this._variables=e}update(e){this._calcMaxDrawdownAndMaxRunup(e)}_calcMaxDrawdownAndMaxRunup(e){if(!this._orders.length&&!this._historyOrders.length)return;let t=0,r=0;const{high:M,low:n,close:b}=e;let z=0;for(const[O,s]of this._orders.entries()){const{in_price:u,qty:l=0,direction:q,commission:A,original_qty:h=1}=s,d=q===a1.long?1:-1,m=(M-u)*l,_=(n-u)*l,R=d===1?m:-_,g=d===1?-_:m;z+=(b-u)*d*l,t+=g,O>0&&A&&(r-=A*l/h),r+=R}this._openprofit=z;const i=this.initial_capital,c=i+this._netprofit;this._preMinNetValue=this._preMinNetValue||i,this._preMaxNetValue=this._preMaxNetValue||i,t=this._preMaxNetValue-c+Math.max(t,0),r=c-this._preMinNetValue+r,this._max_drawdown<t&&(this._max_drawdown=t,this._max_drawdown_percent=t/this._preMaxNetValue*100),r>this._max_runup&&(this._max_runup=r,this._max_runup_percent=r/(this._preMinNetValue+r)*100)}updateOrders(e){this._orders=e,this._calcMaxContracts()}_calcMaxContracts(){if(!this._orders.length){this._position_size=0,this._position_avg_price=void 0,this._opentrades_capital_held=0;return}const[t,r,M,n,b,z]=this._orders.reduce(([i,c,O,s,u,l],q)=>{const{direction:A,qty:h=0,in_price:d,commission:m=0}=q;return A===a1.long?(i+=h,c+=h,u+=h):(i+=h,O+=h,u-=h),s+=h*d,l+=m,[i,c,O,s,u,l]},[0,0,0,0,0,0]);this._historyOrders.length||(this._netprofit=-z,this._grossloss=z),this._position_size=b,this._position_avg_price=n/t,this._opentrades_capital_held=n,this._max_contracts_held_all=Math.max(t,this._max_contracts_held_all),this._max_contracts_held_long=Math.max(r,this._max_contracts_held_long),this._max_contracts_held_short=Math.max(M,this._max_contracts_held_short)}updateHistoryOrders(e){this._historyOrders=e;const t=this._historyOrders.length;this._closedtrades=t;const[r,M,n,b,z,i,c,O]=this._historyOrders.reduce((l,q)=>{let[A,h,d,m,_,R,g,L]=l;const{profit:y=0,profit_percent:D=0}=q;return A+=y,h+=D,y<0?(d+=y,m+=D,g+=1):y>0&&(_+=y,R+=D,L+=1),[A,h,d,m,_,R,g,L]},[0,0,0,0,0,0,0,0]),s=this._orders.reduce((l,q)=>{const{commission:A=0,qty:h=0,original_qty:d=0}=q,m=A*h/d;return l+m},0);this._avg_trade_percent=t?M/t:void 0,this._avg_losing_trade_percent=t?Math.abs(b)/c:void 0,this._avg_winning_trade_percent=t?i/O:void 0,this._netprofit=r-s;const u=this.initial_capital+this._netprofit;this._preMaxNetValue=Math.max(this._preMaxNetValue||this.initial_capital,u),this._preMinNetValue=Math.min(this._preMinNetValue||this.initial_capital,u),this._grossloss=Math.abs(n-s),this._grossprofit=z,this._eventrades=t-c-O,this._losstrades=c,this._wintrades=O}updateStrategyOptions(e){this._options=e}get long(){return"long"}get short(){return"short"}get account_currency(){return"USD"}get closedtrades(){return this._closedtrades}get opentrades(){return{opentrades:this._orders.length,capital_held:this._opentrades_capital_held}}get avg_losing_trade(){const e=this._losstrades;return e?Math.abs(this._grossloss/e):void 0}get avg_losing_trade_percent(){return this._avg_losing_trade_percent}get avg_trade(){if(this._closedtrades)return this._netprofit/this._closedtrades}get equity(){return this.initial_capital+this._netprofit+this._openprofit}get netprofit(){return this._netprofit}get eventrades(){return this._eventrades}get openprofit(){return this._openprofit}get avg_trade_percent(){return this._avg_trade_percent}get avg_winning_trade(){const e=this._wintrades;return e?Math.abs(this._grossprofit/e):void 0}get avg_winning_trade_percent(){return this._avg_winning_trade_percent}get initial_capital(){var e;return((e=this._options)==null?void 0:e.initial_capital)||0}get losstrades(){return this._losstrades}get grossloss(){return this._grossloss}get grossloss_percent(){return this._grossloss/this.initial_capital*100}get grossprofit(){return this._grossprofit}get grossprofit_percent(){return this._grossprofit/this.initial_capital*100}get wintrades(){return this._wintrades}get margin_liquidation_price(){if(!this._options)return;const{initial_capital:e,margin_long:t=0,margin_short:r=0,commission_type:M,commission_value:n=0}=this._options,b=this._orders[0].direction===a1.long?1:-1,z=(b===1?t:r)/100;if(z<=0)return;const{close:i}=this._variables,[c,O]=this._orders.reduce((s,u)=>{let[l,q]=s;const{in_price:A,qty:h=0,original_qty:d=0}=u,m=A*h;if(l+=m,n){let _=0;switch(M){case O2.percent:_=(m+h*i)*n/100;break;case O2.cashPerContract:_=h*n*2;break;case O2.cashPerOrder:_=h/d*n+n;break}q+=_}return[l,q]},[0,0]);return(c-(e+this._netprofit-O))*b/this._position_size/(1-b*z)}get max_contracts_held_all(){return this._max_contracts_held_all}get max_contracts_held_long(){return this._max_contracts_held_long}get max_contracts_held_short(){return this._max_contracts_held_short}get max_drawdown(){return this._max_drawdown}get max_runup(){return this._max_runup}get max_runup_percent(){return this._max_runup_percent}get max_drawdown_percent(){return this._max_drawdown_percent}get netprofit_percent(){return this._netprofit/this.initial_capital*100}get openprofit_percent(){return this._openprofit/(this.initial_capital+this._netprofit)*100}get position_avg_price(){return this._position_avg_price}get position_entry_name(){if(this._orders.length)return this._orders[0].id}get position_size(){return this._position_size}get summaryData(){return{position_size:this.position_size,position_avg_price:this.position_avg_price,position_entry_name:this.position_entry_name,openprofit_percent:this.openprofit_percent,netprofit_percent:this.netprofit_percent,max_drawdown_percent:this.max_drawdown_percent,max_runup_percent:this.max_runup_percent,max_drawdown:this.max_drawdown,max_runup:this.max_runup,max_contracts_held_long:this.max_contracts_held_long,max_contracts_held_short:this.max_contracts_held_short,max_contracts_held_all:this.max_contracts_held_all,avg_winning_trade_percent:this.avg_winning_trade_percent,avg_winning_trade:this.avg_winning_trade,avg_trade_percent:this.avg_trade_percent,avg_trade:this.avg_trade,avg_losing_trade:this.avg_losing_trade,avg_losing_trade_percent:this.avg_losing_trade_percent,wintrades:this.wintrades,losstrades:this.losstrades,eventrades:this.eventrades,grossprofit:this.grossprofit,grossprofit_percent:this.grossprofit_percent,grossloss:this.grossloss,grossloss_percent:this.grossloss_percent,openprofit:this.openprofit,initial_capital:this.initial_capital,netprofit:this.netprofit,closedtrades:this.closedtrades,opentrades:this.opentrades,equity:this.equity,margin_call_long:this.marginCallLong,margin_call_short:this.marginCallShort}}_getCommission(e,t){if(!this._options)return 0;const{commission_value:r=0,commission_type:M}=this._options,n=e*t;let b=0;switch(M){case O2.percent:b=n*r/100;break;case O2.cashPerContract:b=t*r;break;case O2.cashPerOrder:b=r;break}return b}}class Hm{constructor(e){C(this,"_preAccdist");C(this,"_preNvi");C(this,"_prePvi");C(this,"_preObv");C(this,"_prePvt");C(this,"_preWad");C(this,"_preVwap");C(this,"_preValue");C(this,"_currentData");C(this,"_preData");C(this,"_id");this._preAccdist=0,this._preNvi=0,this._prePvi=0,this._preObv=0,this._prePvt=0,this._preWad=0,this._preVwap={},this._preValue={},this._currentData={},this._preData={},this._id=e}get _varTaCacheData(){return{preAccdist:this._preAccdist,preNvi:this._preNvi,prePvi:this._prePvi,preObv:this._preObv,prePvt:this._prePvt,preWad:this._preWad,preVwap:this._preVwap,currentData:this._currentData,preData:this._preData}}set _varTaCacheData(e){const{preAccdist:t,preNvi:r,prePvi:M,preObv:n,prePvt:b,preWad:z,preVwap:i,currentData:c,preData:O}=e;this._preAccdist=t,this._preNvi=r,this._prePvi=M,this._preObv=n,this._prePvt=b,this._preWad=z,this._preVwap=i,this._currentData=c,this._preData=O}update(e){this._preValue={},e.barIndex!==this._currentData.barIndex&&(this._preData={...this._currentData}),this._currentData={...e}}get isRealTime(){return this._preData.barIndex===this._currentData.barIndex}get accdist(){if(this._preValue.accdist)return this._preValue.accdist;const{close:e,low:t,high:r,volume:M}=this._currentData;if(r===t)return this._preAccdist;const n=(e-t-(r-e))/(r-t)*M+this._preAccdist;return!this.isRealTime&&(this._preAccdist=n),this._preValue.accdist=n,n}get iii(){if(this._preValue.iii)return this._preValue.iii;const{close:e,low:t,high:r,volume:M}=this._currentData,n=(2*e-r-t)/((r-t)*M);return this._preValue.iii=n,n}get nvi(){return this._preValue.nvi?this._preValue.nvi:this._getNvi()}get wvad(){if(this._preValue.wvad)return this._preValue.wvad;const{close:e,low:t,high:r,volume:M,open:n}=this._currentData,b=(e-n)/(r-t)*M;return this._preValue.wvad=b,b}get obv(){if(this._preValue.obv)return this._preValue.obv;const{close:e,volume:t}=this._currentData,{close:r}=this._preData;if(r===void 0){this._preObv=0;return}const M=Math.sign(e-r)*t+this._preObv;return!this.isRealTime&&(this._preObv=M),this._preValue.obv=M,M}get pvi(){return this._preValue.pvi?this._preValue.pvi:this._getPvi()}get tr(){if(this._preValue.tr)return this._preValue.tr;const{low:e,high:t}=this._currentData,{close:r}=this._preData;if(r===void 0)return;const M=Math.max(t-e,Math.abs(t-r),Math.abs(e-r));return this._preValue.tr=M,M}get pvt(){if(this._preValue.pvt)return this._preValue.pvt;const{close:e,volume:t}=this._currentData,{close:r}=this._preData;if(r===void 0){this._prePvt=0;return}const M=(e-r)/r*t+this._prePvt;return!this.isRealTime&&(this._prePvt=M),this._preValue.pvt=M,M}get wad(){if(this._preValue.wad)return this._preValue.wad;const{close:e,high:t,low:r}=this._currentData,{close:M}=this._preData;if(M===void 0)return this._preWad=0,0;const n=Math.max(t,M),b=Math.min(r,M),z=e-M,c=(z>0?e-b:z<0?e-n:0)+this._preWad;return!this.isRealTime&&(this._preWad=c),this._preValue.wad=c,c}get vwap(){var O,s;if(this._preValue.vwap)return this._preValue.vwap;const{hlc3:e,volume:t}=this._currentData;let{sum:r=0,sumV:M=0,isReset:n}=this._preVwap;if(((s=(O=self.workerStorage)==null?void 0:O.get(this._id))==null?void 0:s.buildInFunctions.timeframe.change({timeframe:"1D"},"vwap_buildin"))&&(n=!0,r=M=0),!n)return;const z=e*t+r,i=t+M;!this.isRealTime&&(this._preVwap={sum:z,sumV:i,isReset:n});const c=z/i;return this._preValue.vwap=c,c}_getNvi(){const e=this._preNvi||1,{close:t=0,volume:r=0}=this._preData,{close:M,volume:n}=this._currentData;let b=1;const z=e||1;return M&&t?b=n<r?z+(M-t)/t*z:z:b=z,!this.isRealTime&&(this._preNvi=b),this._preValue.nvi=b,b}_getPvi(){const e=this._prePvi||1,{close:t=0,volume:r=0}=this._preData,{close:M,volume:n}=this._currentData;let b=1;const z=e||1;return M&&t?b=n>r?z+(M-t)/t*z:z:b=z,!this.isRealTime&&(this._prePvi=b),this._preValue.pvi=b,b}}class Ym{constructor(){C(this,"_period");C(this,"_multiplier");C(this,"_unit");this._period="1",this._multiplier=1,this._unit="m"}update(e){if(!e)return;this._period=e;const[t,r]=ht(e);this._multiplier=t,this._unit=r}get isdaily(){return this._unit==="d"}get isdwm(){return["d","w","M"].includes(this._unit)}get isintraday(){return["s","m","h"].includes(this._unit)}get isminutes(){return this._unit==="m"}get ismonthly(){return this._unit==="M"}get isseconds(){return this._unit==="s"}get isweekly(){return this._unit==="w"}get multiplier(){return this._multiplier}get period(){return this._period}}class Gm{constructor(){C(this,"_bgColor");C(this,"_fgColor");C(this,"isUseBgColor",!1)}updateOptions(e){e!=null&&e.bg_color&&(this._bgColor=e.bg_color,this._fgColor=this._contrastColor(e.bg_color))}get bg_color(){return this.isUseBgColor=!0,this._bgColor}get fg_color(){return this.isUseBgColor=!0,this._fgColor}get is_heikinashi(){return!1}get is_kagi(){return!1}get is_linebreak(){return!1}get is_pnf(){return!1}get is_range(){return!1}get is_renko(){return!1}get is_standard(){return!0}get left_visible_bar_time(){}get right_visible_bar_time(){}_parseColor(e){let t,r,M,n;if(e.startsWith("#")){t=parseInt(e.substring(1,3),16),r=parseInt(e.substring(3,5),16),M=parseInt(e.substring(5,7),16);const b=e.substring(7);b?n=parseInt(b,16)/255:n=1}else{const b=this._parserRgbColor(e);t=b[0]||0,r=b[1]||0,M=b[2]||0,n=b[3]||1}return{r:t,g:r,b:M,a:n}}_parserRgbColor(e){var t;return((t=e.match(/\d+/g))==null?void 0:t.map(Number))||[]}_contrastColor(e){const{r:t,g:r,b:M}=this._parseColor(e);return(299*t+587*r+114*M)/1e3>128?"#000000":"#ffffff"}}class Vm{constructor(){C(this,"_syminfo",{})}update(e){this._syminfo=e}get __syminfo(){return this._syminfo}get basecurrency(){return this._syminfo.basecurrency||""}get country(){return this._syminfo.country}get currency(){return this._syminfo.currency||"USD"}get description(){return this._syminfo.description||""}get employees(){return this._syminfo.employees||100}get expiration_date(){return this._syminfo.expiration_date}get industry(){return this._syminfo.industry}get minmove(){return this._syminfo.minmove&&Number(this._syminfo.minmove)}get mintick(){return this._syminfo.mintick}get pointvalue(){return this._syminfo.pointvalue&&Number(this._syminfo.pointvalue)}get prefix(){return this.tickerid.replace(`:${this.ticker}`,"")}get pricescale(){return this._syminfo.pricescale&&Number(this._syminfo.pricescale)}get recommendations_buy(){return this._syminfo.recommendations_buy}get recommendations_buy_strong(){return this._syminfo.recommendations_buy_strong}get recommendations_date(){return this._syminfo.recommendations_date}get recommendations_hold(){return this._syminfo.recommendations_hold}get recommendations_sell(){return this._syminfo.recommendations_sell}get recommendations_sell_strong(){return this._syminfo.recommendations_sell_strong}get recommendations_total(){return this._syminfo.recommendations_total}get root(){return this._syminfo.root||""}get sector(){return this._syminfo.sector}get session(){return this._syminfo.session||ft.regular}get shareholders(){return this._syminfo.shareholders}get shares_outstanding_float(){return this._syminfo.shares_outstanding_float}get shares_outstanding_total(){return this._syminfo.shares_outstanding_total}get target_price_average(){return this._syminfo.target_price_average}get target_price_date(){return this._syminfo.target_price_date}get target_price_estimates(){return this._syminfo.pricescale}get target_price_high(){return this._syminfo.target_price_high}get target_price_low(){return this._syminfo.target_price_low}get target_price_median(){return this._syminfo.target_price_median}get ticker(){return this._syminfo.ticker||""}get tickerid(){return this._syminfo.tickerid||""}get timezone(){return this._syminfo.timezone||"UTC+8"}get type(){return this._syminfo.type||"forex"}get volumetype(){return this._syminfo.volumetype||"n/a"}}class Km{constructor(e){C(this,"_variables");this._variables=e}get future_amount(){}get future_ex_date(){}get future_pay_date(){}}class Jm{constructor(e){C(this,"_variables");this._variables=e}get future_eps(){}get future_period_end_time(){}get future_revenue(){}get future_time(){}}class _p{constructor(e){C(this,"_cacheData");C(this,"_barIndex");C(this,"_isRealTimeBar");C(this,"_barstate");C(this,"_priceVariables");C(this,"_lastBarIndex");C(this,"_currentBarTime");C(this,"_lastBarTime");C(this,"_period");C(this,"_offsetTime");C(this,"_timeframe");C(this,"_ta");C(this,"_polyline");C(this,"_label");C(this,"_line");C(this,"_linefill");C(this,"_box");C(this,"_table");C(this,"_strategy");C(this,"_session");C(this,"syminfo");C(this,"chart");C(this,"earnings");C(this,"dividends");C(this,"_timeTradingday");C(this,"_mintick");C(this,"_cacheSpace");C(this,"_precision");C(this,"_nextBarTime");C(this,"_isRepeated");C(this,"_preCacheData");C(this,"__requestName","");C(this,"__isFirstRun",!1);C(this,"_maxBarsBack",0);C(this,"_maxBarsBackOfKey");C(this,"__isReqRepeated");C(this,"_newCacheData",{});this._cacheData={varData:{},varipData:{}},this._preCacheData={varData:{},varipData:{}},this._barIndex=0,this._lastBarIndex=0,this._currentBarTime=0,this._lastBarTime=0,this._offsetTime=0,this._period="",this._isRealTimeBar=!1,this._barstate=new $m,this._timeframe=new Ym,this._priceVariables={close:0,open:0,low:0,high:0,volume:0},this._ta=new Hm(e),this._polyline=new Sr(this,N0.POLYLINE),this._label=new Sr(this,N0.LABEL),this._line=new Sr(this,N0.LINE),this._linefill=new Sr(this,N0.LINEFILL),this._box=new Sr(this,N0.BOX),this._table=new Sr(this,N0.TABLE),this._strategy=new jm(this),this._session=new Um(this),this.syminfo=new Vm,this.chart=new Gm,this.earnings=new Jm(this),this.dividends=new Km(this),this._cacheSpace=Object.create(null),this._maxBarsBackOfKey=Object.create(null)}getVarCacheData(){return{cacheData:this._cacheData,preCacheData:this._preCacheData,cacheSpace:this._cacheSpace,taCacheData:this._ta._varTaCacheData,polylineCacheData:this._polyline._cacheData,labelCacheData:this._label._cacheData,lineCacheData:this._line._cacheData,linefillCacheData:this._linefill._cacheData,boxCacheData:this._box._cacheData,tableCacheData:this._table._cacheData,barstateCacheData:this.barstate._barstateCacheData}}setVarCacheData(e){if(!e)return;const{cacheData:t,preCacheData:r,cacheSpace:M,taCacheData:n,polylineCacheData:b,labelCacheData:z,lineCacheData:i,linefillCacheData:c,boxCacheData:O,tableCacheData:s,barstateCacheData:u}=e;this._cacheData=t,this._preCacheData=r,this._cacheSpace=M,this._ta._varTaCacheData=n,this._polyline._cacheData=b,this._label._cacheData=z,this._line._cacheData=i,this._linefill._cacheData=c,this._box._cacheData=O,this._table._cacheData=s,this.barstate._barstateCacheData=u}get table(){return this._table}get box(){return this._box}get linefill(){return this._linefill}get line(){return this._line}get polyline(){return this._polyline}get label(){return this._label}get ta(){return this._ta}get strategy(){return this._strategy}get session(){return this._session}get na(){}get last_bar_index(){return this._lastBarIndex}get bar_index(){return this._barIndex}get barstate(){return this._barstate}get close(){return this._priceVariables.close}get low(){return this._priceVariables.low}get open(){return this._priceVariables.open}get high(){return this._priceVariables.high}get volume(){return this._priceVariables.volume}get ohlc4(){const{close:e,open:t,high:r,low:M}=this._priceVariables;return(e+t+r+M)/4}get hl2(){const{high:e,low:t}=this._priceVariables;return(e+t)/2}get hlc3(){const{close:e,high:t,low:r}=this._priceVariables;return(e+t+r)/3}get hlcc4(){const{close:e,high:t,low:r}=this._priceVariables;return(e*2+t+r)/4}get hour(){return O1(this._currentBarTime).hour()}get minute(){return O1(this._currentBarTime).minute()}get second(){return O1(this._currentBarTime).second()}get month(){return O1(this._currentBarTime).month()+1}get year(){return O1(this._currentBarTime).year()}get dayofweek(){return O1(this.time_tradingday).weekday()}get dayofmonth(){return O1(this.time_tradingday).date()}get weekofyear(){return O1(this._currentBarTime).week()}get last_bar_time(){return this._lastBarTime}get time(){return this._currentBarTime}get time_close(){const[e,t]=ht(this._period);return O1(this._currentBarTime).add(e,t).valueOf()}get timenow(){return Date.now()}get time_tradingday(){return this._timeTradingday||this._getTimeTradingday(this._currentBarTime,this._period)}get timeframe(){return this._timeframe}get mintick(){return this._mintick}get __period(){return this._period}get precision(){return this._precision}get nextBarTime(){return this._nextBarTime}set max_bars_back(e){this._maxBarsBack=e}updateMaxLength(e){const{max_lines_count:t,max_labels_count:r,max_boxes_count:M,max_polylines_count:n}=e;M&&this._box.setMaxLen(M),r&&this._label.setMaxLen(r),t&&this._line.setMaxLen(t),n&&this._polyline.setMaxLen(n)}getTimeTradingday(e,t){const[r,M]=ht(t),n=O1(e);return["M","w","y","d"].includes(M)?n.valueOf():(n.subtract(this._offsetTime,"h"),n.startOf("d").add(this._offsetTime,"h").valueOf())}_getTimeTradingday(e,t){const[r,M]=ht(t),n=O1(e).utc(!0);return["M","w","y","d"].includes(M)?n.valueOf():n.startOf("d").valueOf()}updateOptions(e){var c;const{interval:t="1D",offsetTime:r=5,mintick:M,chart:n,syminfo:b}=e,z=((c=M.toString().split(".")[1])==null?void 0:c.length)||5;this._precision=z;const i=Q4(t);this._period=i,this._mintick=M,this._offsetTime=r,this._timeframe.update(i),this.chart.updateOptions(n),this.syminfo.update(b),this._barstate.isFirstRun=this.__isFirstRun}updateData(e,t){const{barIndex:r,c:M,o:n,h:b,l:z,volume:i,time:c,lastBarIndex:O,lastBarTime:s,isrealtime:u,time_tradingday:l,nextBarTime:q}=e;if(this._priceVariables={close:rn(M,this._precision),open:rn(n,this._precision),high:rn(b,this._precision),low:rn(z,this._precision),volume:Number(i)},this._isRealTimeBar=u,this._newCacheData={},r>this._barIndex){const{varData:A,varipData:h}=this._cacheData;this._preCacheData={varData:{},varipData:{}},u?(this._preCacheData.varData=b2.cloneDeep(A),this._preCacheData.varipData=b2.cloneDeep(h)):this._preCacheData={varData:{...A},varipData:{...h}}}this._isRepeated=t,this._timeTradingday=l,this._currentBarTime=c*1e3,this._lastBarIndex=O,this._barIndex=r,this._lastBarTime=s*1e3,this._nextBarTime=q*1e3,this._barstate.update(r,O,u,!0),this.ta.update({...this._priceVariables,hlc3:this.hlc3,barIndex:r})}getCacheData(e,t,r){let M=this._cacheData[e],n=1;if(M?(M.barIndex<this._barIndex&&(n=0),M=M.data):M=this.setCacheData(e,r),t===0)return r;const b=this._cacheSpace[e]||0;return t=Math.floor(t),b<t&&(this._cacheSpace[e]=t),M[M.length-n-t]}setCacheData(e,t){let r=this._cacheData[e]||{barIndex:-1,data:[]};if(r.barIndex>this._barIndex)return r.data;t=this._cacheCopy(t),r.barIndex===this._barIndex?r.data[r.data.length-1]=t:r.data.push(t);const M=this._cacheSpace[e]||0,n=ui.includes(e)?500:50;return M&&r.data.length>(this._maxBarsBackOfKey[e]||this._maxBarsBack||M+n)&&r.data.shift(),r.barIndex=this._barIndex,this._cacheData[e]=r,r.data}__setBarsBackOfKey(e,t){this._maxBarsBackOfKey[e]=t}__getBarsBackOfKey(e){return this._maxBarsBackOfKey[e]}getTypeInstance(e,t,r){return new Oi(e,t,r)}verifyVarAndVarip(e,t,r){const M=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`,n=this._isRepeated||this.__isReqRepeated?this._preCacheData:this._cacheData;if(r==="var"&&n.varData.hasOwnProperty(M))return this._upadteChartDraws(n.varData,M),!0;const b=this.__isReqRepeated?this._preCacheData.varipData:this._cacheData.varipData;return r==="varip"&&b.hasOwnProperty(M)?(this._upadteChartDraws(b,M),!0):!1}getVarValue(e,t,r){const M=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`;(this._isRepeated||this.__isReqRepeated)&&(this._cacheData.varData[M]=this._preCacheData.varData[M],this.__isReqRepeated&&(this._cacheData.varipData[M]=this._preCacheData.varipData[M]));const n=this._cacheData;if(r==="var"){const b=n.varData[M];return this._isRealTimeBar?this._newCacheData.hasOwnProperty(M)?this._newCacheData[M]:this._cacheCopy(b):b}return this._cacheData.varipData[M]}setVarValue(e,t,r,M){var z;const n=`${e}_${t.replace(/\$[\d]+_\$/g,"")}`;let b;switch(typeof r=="object"&&((z=r==null?void 0:r.varipKeys)!=null&&z.length)&&M!=="varip"&&(M="var",b=r.varipKeys),M){case"var":if(this._isRealTimeBar){if(b&&b.length)for(const i of b)this._cacheData.varData[n][i]=r[i];this._newCacheData[n]=r}else this._chartDrawsHandle(r,this._cacheData.varData[n]),this._cacheData.varData[n]=r;break;case"varip":this._chartDrawsHandle(r,this._cacheData.varipData[n]),this._cacheData.varipData[n]=r;break}return r}_upadteChartDraws(e,t){const r=e[t],M=this._isRealTimeBar?r==null?void 0:r.preId:r==null?void 0:r.id;if(!M)return;let n;switch(r==null?void 0:r.type){case N0.BOX:n=this._setChartDraw(M,this._box);break;case N0.LINE:n=this._setChartDraw(M,this._line);break;case N0.POLYLINE:n=this._setChartDraw(M,this._polyline);break;case N0.LABEL:n=this._setChartDraw(M,this._label);break;case N0.LINEFILL:n=this._setChartDraw(M,this._linefill);break;case N0.TABLE:n=this._setChartDraw(M,this._table);break}n&&(e[t]=n)}_cacheCopy(e){return typeof e!="object"||!e||e.isDraw?e:b2.cloneDeep(e)}_updateId(e){const{bar_index:t,_isRealTimeBar:r}=this,M=e.id;if(!e._suffix)e._suffix=`_${t}`,e.id=`${e.id}${e._suffix}`;else{const n=e.id.split("_");n.pop(),e.id=`${n.join("_")}_${t}`}return e.line1&&nt.__updateFillKeys(e.line1,M,e.id),e.line2&&nt.__updateFillKeys(e.line2,M,e.id),r||(e.preId=e.id),e.id}_setChartDraw(e,t){const r=t.getInstance(e);let M=t.get(e);if(!M||!r)return;const n=this._updateId(r)||e;return n===e&&!this._isRealTimeBar||(M=JSON.parse(JSON.stringify(M)),this._isRealTimeBar||(r.data=M),t.deleteHandle(e,!1),t.set(n,M,r)),r}_chartDrawsHandle(e,t){if(typeof e!="object")return;const r=t==null?void 0:t.id;let M=e==null?void 0:e.id;M&&e.data&&(e.data.isVar=!0),r!==M&&r&&t.data&&(t.data.isVar=!1)}add(e,t){return Array.isArray(e)&&Array.isArray(t)?b2.uniq([...e,...t]):typeof e=="number"||typeof t=="number"?Number(e)+Number(t):(e||"")+(t||"")}sub(e,t){return Array.isArray(e)&&Array.isArray(t)?e.filter(r=>!t.includes(r)):Number(e)-Number(t)}div(e,t){if(t)return e/t}notEqual(e,t,r,M){return e===void 0&&typeof t=="number"||t===void 0&&typeof e=="number"||e===void 0&&t===void 0?!1:!this.equal(e,t,r,M)}equal(e,t,r,M){if(typeof e=="number"&&typeof t=="number"&&isNaN(e)&&isNaN(t))return!0;if(e!==void 0&&t!==void 0)return e==t;if(e===void 0&&typeof t=="number"||t===void 0&&typeof e=="number")return!1;if(!(r.endsWith(N0.BOOL)&&e===void 0))return(r.endsWith(N0.FLOAT)||r.endsWith(N0.INT)||M.endsWith(N0.FLOAT)||M.endsWith(N0.INT))&&e===void 0&&t===void 0?!1:r.endsWith(N0.STRING)&&e===""&&t===void 0||M.endsWith(N0.STRING)&&t===""&&e===void 0?!0:r.endsWith(N0.NA)&&M.endsWith(N0.NA)?!1:e==t}compareDataHandle(e){if(typeof e!="number"||!e)return e;const t=String(e);if(!t.includes(".")&&!/[eE]/.test(t))return e;const[r,M]=e.toFixed(11).split(".");return+`${r}.${M.slice(0,10)}`}}class Sr{constructor(e,t,r=50){C(this,"_all");C(this,"_allInstance");C(this,"_pseudoArrayAll");C(this,"_maxLength");C(this,"_deleteIds");C(this,"_variables");C(this,"_preDeleteIds");C(this,"_againAddItems");C(this,"_tmpData");C(this,"_tmpInstance");C(this,"_type");C(this,"_tmpIds",[]);this._all=new Map,this._allInstance=new Map,this._pseudoArrayAll=p1(0,void 0,t),this._maxLength=r,this._deleteIds=new Map,this._variables=e,this._preDeleteIds=new Map,this._againAddItems=[],this._tmpData=new Map,this._tmpInstance=new Map,this._type=t}get _cacheData(){return{allInstance:Array.from(this._allInstance),tmpIds:this._tmpIds,preDeleteIds:Array.from(this._preDeleteIds)}}set _cacheData(e){this._allInstance=new Map(e.allInstance),this._all=new Map(e.allInstance.map(([t,r])=>[t,r.data])),this._tmpIds=e.tmpIds,this._preDeleteIds=new Map(e.preDeleteIds)}setMaxLen(e){this._maxLength=e}get size(){return this._all.size+this._tmpData.size}get __allInstance(){return this._allInstance}get data(){const e=[],t=b2.flatMap([...this._deleteIds.values()]),r=b2.uniq([...this._tmpData.keys(),...this._all.keys()]),M=[];for(const n of r)if(!t.some(b=>b.key===n)){const b=this._tmpData.get(n)||this._all.get(n),z=b==null?void 0:b.id;b&&!M.includes(z)&&(M.push(z),e.push(b))}return this._variables._isRealTimeBar&&this._preDeleteIds.set(this._variables.last_bar_index,this._deleteIds.get(this._variables.last_bar_index)||[]),this._tmpDataHandle(),this._type===N0.LINEFILL?e:e.slice(-this._maxLength)}get all(){return this._pseudoArrayAll._value=[...this._allInstance.values(),...this._tmpInstance.values()],this._pseudoArrayAll}add(e,t,r){if(this.set(e,t,r),!this._variables._isRealTimeBar&&this._type!==N0.LINEFILL&&this._all.size>this._maxLength){const{bar_index:M}=t;for(const[n,b]of this._all){const{isVar:z,id:i,bar_index:c}=b;if(c===M)break;if(z)continue;this.deleteHandle(i);break}}}getValOfBarIndex(e){let t=[];const r=b2.uniq([...this._all.keys(),...this._tmpData.keys()]),M=b2.flatMap([...this._deleteIds.values()]);for(const n of e){const b=r.filter(z=>z.endsWith(`_${n}`));for(const z of b){if(M.some(c=>c.key===z))continue;const i=this._tmpData.get(z)||this._all.get(z);i&&t.push(i)}}return this._againAddItems.length&&(t=this._againAddItems.concat(t),this._againAddItems=[]),this._tmpDataHandle(),t.length?this._type===N0.LINEFILL?t:t.slice(-this._maxLength):void 0}getDeleteIds(e){let t=[];const{bar_index:r,_isRealTimeBar:M}=this._variables,n=[];for(const z of e){let i=[...this._deleteIds.get(z)||[]];const c=this._preDeleteIds.get(z)||[];if(z===r&&M){let O=[];for(const s of c){const u=i.findIndex(l=>l.id===s.id);if(u===-1){const l=this._all.get(s.key);l&&n.push(l)}else O.push(s),i.splice(u,1)}this._preDeleteIds.set(r,b2.uniqBy([...i,...O],"id"))}else{const O=[];for(const s of i)c.some(u=>u.id===s.id)||O.push(s);i=O,this._preDeleteIds.delete(z)}t=t.concat(i)}const b=[...this._all.values(),...this._tmpData.values()];for(const z of this._tmpIds)b.some(i=>i.id===z.id)||t.push(z);return this._againAddItems=n,b2.uniq(t.map(z=>z.id))}set(e,t,r){this._variables._isRealTimeBar?(this._tmpData.set(e,t),this._tmpInstance.set(e,r)):(this._all.set(e,t),this._allInstance.set(e,r))}get(e){const t=this._all.get(e);let r=this._tmpData.get(e);return this._variables._isRealTimeBar?(r||(r=t?{...t}:void 0,r&&this._tmpData.set(e,r)),r):(this._tmpData.clear(),this._tmpInstance.clear(),t)}getInstance(e){return this._allInstance.get(e)}deleteHandle(e,t=!0,r=!1){var M;if(this._type===N0.LINE&&t){const n=(M=this._allInstance.get(e))==null?void 0:M.fillKeys;if(n&&n.length)for(const b of n)this._variables.linefill.deleteHandle(b)}if(this._variables._isRealTimeBar){if(r){const n=this._tmpInstance.get(e);n&&(n.data=void 0)}this._tmpData.delete(e),this._tmpInstance.delete(e)}else{if(r){const n=this._allInstance.get(e);n&&(n.data=void 0)}this._all.delete(e),this._allInstance.delete(e)}}delete(e,t,r){const M=this._all.get(e);if(this._variables._isRealTimeBar||this.deleteHandle(e,!1,!0),!(this._variables.__isFirstRun&&!this._variables._isRealTimeBar)&&typeof t=="number"){const n=this._deleteIds.get(t)||[];n.push({key:e,id:(M==null?void 0:M.id)||r}),this._deleteIds.set(t,n)}}_tmpDataHandle(){var e;this._tmpIds=[];for(const[t]of this._tmpInstance){const r=(e=this._tmpData.get(t))==null?void 0:e.id;r&&this._tmpIds.push({id:r,key:t})}this._tmpData.clear(),this._tmpInstance.clear(),this._deleteIds.clear()}}/**
86
86
  * @license
87
87
  * Copyright 2019 Google LLC
88
88
  * SPDX-License-Identifier: Apache-2.0