@guihz/trading-vue-editor-tes 0.0.236 → 0.0.238

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.
@@ -59,11 +59,11 @@ ${uo}rows: ${i.rows}
59
59
  ${uo}columns: ${i.columns}
60
60
  }`}function my(i,t,e,r,n){const{rows:s,columns:a}=i,u=Math.min(s,t),c=Math.min(a,e),f=[];if(n==="auto"){n=!1;t:for(let d=0;d<u;d++)for(let h=0;h<c;h++)if(i.get(d,h)<0){n=!0;break t}}for(let d=0;d<u;d++){let h=[];for(let _=0;_<c;_++)h.push(gy(i.get(d,_),r,n));f.push(`${h.join(" ")}`)}return c!==a&&(f[f.length-1]+=` ... ${a-e} more columns`),u!==s&&f.push(`... ${s-t} more rows`),f.join(`
61
61
  ${lh}`)}function gy(i,t,e){return(i>=0&&e?` ${fh(i,t-1)}`:fh(i,t)).padEnd(t)}function fh(i,t){let e=i.toString();if(e.length<=t)return e;let r=i.toFixed(t);if(r.length>t&&(r=i.toFixed(Math.max(0,t-(r.length-t)))),r.length<=t&&!r.startsWith("0.000")&&!r.startsWith("-0.000"))return r;let n=i.toExponential(t);return n.length>t&&(n=i.toExponential(Math.max(0,t-(n.length-t)))),n.slice(0)}function vy(i,t){i.prototype.add=function(r){return typeof r=="number"?this.addS(r):this.addM(r)},i.prototype.addS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)+r);return this},i.prototype.addM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)+r.get(n,s));return this},i.add=function(r,n){return new t(r).add(n)},i.prototype.sub=function(r){return typeof r=="number"?this.subS(r):this.subM(r)},i.prototype.subS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)-r);return this},i.prototype.subM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)-r.get(n,s));return this},i.sub=function(r,n){return new t(r).sub(n)},i.prototype.subtract=i.prototype.sub,i.prototype.subtractS=i.prototype.subS,i.prototype.subtractM=i.prototype.subM,i.subtract=i.sub,i.prototype.mul=function(r){return typeof r=="number"?this.mulS(r):this.mulM(r)},i.prototype.mulS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)*r);return this},i.prototype.mulM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)*r.get(n,s));return this},i.mul=function(r,n){return new t(r).mul(n)},i.prototype.multiply=i.prototype.mul,i.prototype.multiplyS=i.prototype.mulS,i.prototype.multiplyM=i.prototype.mulM,i.multiply=i.mul,i.prototype.div=function(r){return typeof r=="number"?this.divS(r):this.divM(r)},i.prototype.divS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)/r);return this},i.prototype.divM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)/r.get(n,s));return this},i.div=function(r,n){return new t(r).div(n)},i.prototype.divide=i.prototype.div,i.prototype.divideS=i.prototype.divS,i.prototype.divideM=i.prototype.divM,i.divide=i.div,i.prototype.mod=function(r){return typeof r=="number"?this.modS(r):this.modM(r)},i.prototype.modS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)%r);return this},i.prototype.modM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)%r.get(n,s));return this},i.mod=function(r,n){return new t(r).mod(n)},i.prototype.modulus=i.prototype.mod,i.prototype.modulusS=i.prototype.modS,i.prototype.modulusM=i.prototype.modM,i.modulus=i.mod,i.prototype.and=function(r){return typeof r=="number"?this.andS(r):this.andM(r)},i.prototype.andS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)&r);return this},i.prototype.andM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)&r.get(n,s));return this},i.and=function(r,n){return new t(r).and(n)},i.prototype.or=function(r){return typeof r=="number"?this.orS(r):this.orM(r)},i.prototype.orS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)|r);return this},i.prototype.orM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)|r.get(n,s));return this},i.or=function(r,n){return new t(r).or(n)},i.prototype.xor=function(r){return typeof r=="number"?this.xorS(r):this.xorM(r)},i.prototype.xorS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)^r);return this},i.prototype.xorM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)^r.get(n,s));return this},i.xor=function(r,n){return new t(r).xor(n)},i.prototype.leftShift=function(r){return typeof r=="number"?this.leftShiftS(r):this.leftShiftM(r)},i.prototype.leftShiftS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)<<r);return this},i.prototype.leftShiftM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)<<r.get(n,s));return this},i.leftShift=function(r,n){return new t(r).leftShift(n)},i.prototype.signPropagatingRightShift=function(r){return typeof r=="number"?this.signPropagatingRightShiftS(r):this.signPropagatingRightShiftM(r)},i.prototype.signPropagatingRightShiftS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)>>r);return this},i.prototype.signPropagatingRightShiftM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)>>r.get(n,s));return this},i.signPropagatingRightShift=function(r,n){return new t(r).signPropagatingRightShift(n)},i.prototype.rightShift=function(r){return typeof r=="number"?this.rightShiftS(r):this.rightShiftM(r)},i.prototype.rightShiftS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)>>>r);return this},i.prototype.rightShiftM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,this.get(n,s)>>>r.get(n,s));return this},i.rightShift=function(r,n){return new t(r).rightShift(n)},i.prototype.zeroFillRightShift=i.prototype.rightShift,i.prototype.zeroFillRightShiftS=i.prototype.rightShiftS,i.prototype.zeroFillRightShiftM=i.prototype.rightShiftM,i.zeroFillRightShift=i.rightShift,i.prototype.not=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,~this.get(r,n));return this},i.not=function(r){return new t(r).not()},i.prototype.abs=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.abs(this.get(r,n)));return this},i.abs=function(r){return new t(r).abs()},i.prototype.acos=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.acos(this.get(r,n)));return this},i.acos=function(r){return new t(r).acos()},i.prototype.acosh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.acosh(this.get(r,n)));return this},i.acosh=function(r){return new t(r).acosh()},i.prototype.asin=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.asin(this.get(r,n)));return this},i.asin=function(r){return new t(r).asin()},i.prototype.asinh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.asinh(this.get(r,n)));return this},i.asinh=function(r){return new t(r).asinh()},i.prototype.atan=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.atan(this.get(r,n)));return this},i.atan=function(r){return new t(r).atan()},i.prototype.atanh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.atanh(this.get(r,n)));return this},i.atanh=function(r){return new t(r).atanh()},i.prototype.cbrt=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.cbrt(this.get(r,n)));return this},i.cbrt=function(r){return new t(r).cbrt()},i.prototype.ceil=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.ceil(this.get(r,n)));return this},i.ceil=function(r){return new t(r).ceil()},i.prototype.clz32=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.clz32(this.get(r,n)));return this},i.clz32=function(r){return new t(r).clz32()},i.prototype.cos=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.cos(this.get(r,n)));return this},i.cos=function(r){return new t(r).cos()},i.prototype.cosh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.cosh(this.get(r,n)));return this},i.cosh=function(r){return new t(r).cosh()},i.prototype.exp=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.exp(this.get(r,n)));return this},i.exp=function(r){return new t(r).exp()},i.prototype.expm1=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.expm1(this.get(r,n)));return this},i.expm1=function(r){return new t(r).expm1()},i.prototype.floor=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.floor(this.get(r,n)));return this},i.floor=function(r){return new t(r).floor()},i.prototype.fround=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.fround(this.get(r,n)));return this},i.fround=function(r){return new t(r).fround()},i.prototype.log=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.log(this.get(r,n)));return this},i.log=function(r){return new t(r).log()},i.prototype.log1p=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.log1p(this.get(r,n)));return this},i.log1p=function(r){return new t(r).log1p()},i.prototype.log10=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.log10(this.get(r,n)));return this},i.log10=function(r){return new t(r).log10()},i.prototype.log2=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.log2(this.get(r,n)));return this},i.log2=function(r){return new t(r).log2()},i.prototype.round=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.round(this.get(r,n)));return this},i.round=function(r){return new t(r).round()},i.prototype.sign=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.sign(this.get(r,n)));return this},i.sign=function(r){return new t(r).sign()},i.prototype.sin=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.sin(this.get(r,n)));return this},i.sin=function(r){return new t(r).sin()},i.prototype.sinh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.sinh(this.get(r,n)));return this},i.sinh=function(r){return new t(r).sinh()},i.prototype.sqrt=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.sqrt(this.get(r,n)));return this},i.sqrt=function(r){return new t(r).sqrt()},i.prototype.tan=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.tan(this.get(r,n)));return this},i.tan=function(r){return new t(r).tan()},i.prototype.tanh=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.tanh(this.get(r,n)));return this},i.tanh=function(r){return new t(r).tanh()},i.prototype.trunc=function(){for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.set(r,n,Math.trunc(this.get(r,n)));return this},i.trunc=function(r){return new t(r).trunc()},i.pow=function(r,n){return new t(r).pow(n)},i.prototype.pow=function(r){return typeof r=="number"?this.powS(r):this.powM(r)},i.prototype.powS=function(r){for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.pow(this.get(n,s),r));return this},i.prototype.powM=function(r){if(r=t.checkMatrix(r),this.rows!==r.rows||this.columns!==r.columns)throw new RangeError("Matrices dimensions must be equal");for(let n=0;n<this.rows;n++)for(let s=0;s<this.columns;s++)this.set(n,s,Math.pow(this.get(n,s),r.get(n,s)));return this}}function Tr(i,t,e){let r=e?i.rows:i.rows-1;if(t<0||t>r)throw new RangeError("Row index out of range")}function Ir(i,t,e){let r=e?i.columns:i.columns-1;if(t<0||t>r)throw new RangeError("Column index out of range")}function Fi(i,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==i.columns)throw new RangeError("vector size must be the same as the number of columns");return t}function Ni(i,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==i.rows)throw new RangeError("vector size must be the same as the number of rows");return t}function Xa(i,t){if(!fr.isAnyArray(t))throw new TypeError("row indices must be an array");for(let e=0;e<t.length;e++)if(t[e]<0||t[e]>=i.rows)throw new RangeError("row indices are out of range")}function Qa(i,t){if(!fr.isAnyArray(t))throw new TypeError("column indices must be an array");for(let e=0;e<t.length;e++)if(t[e]<0||t[e]>=i.columns)throw new RangeError("column indices are out of range")}function tu(i,t,e,r,n){if(arguments.length!==5)throw new RangeError("expected 4 arguments");if(co("startRow",t),co("endRow",e),co("startColumn",r),co("endColumn",n),t>e||r>n||t<0||t>=i.rows||e<0||e>=i.rows||r<0||r>=i.columns||n<0||n>=i.columns)throw new RangeError("Submatrix indices are out of range")}function lo(i,t=0){let e=[];for(let r=0;r<i;r++)e.push(t);return e}function co(i,t){if(typeof t!="number")throw new TypeError(`${i} must be a number`)}function Si(i){if(i.isEmpty())throw new Error("Empty matrix has no elements to index")}function yy(i){let t=lo(i.rows);for(let e=0;e<i.rows;++e)for(let r=0;r<i.columns;++r)t[e]+=i.get(e,r);return t}function wy(i){let t=lo(i.columns);for(let e=0;e<i.rows;++e)for(let r=0;r<i.columns;++r)t[r]+=i.get(e,r);return t}function Dy(i){let t=0;for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)t+=i.get(e,r);return t}function by(i){let t=lo(i.rows,1);for(let e=0;e<i.rows;++e)for(let r=0;r<i.columns;++r)t[e]*=i.get(e,r);return t}function xy(i){let t=lo(i.columns,1);for(let e=0;e<i.rows;++e)for(let r=0;r<i.columns;++r)t[r]*=i.get(e,r);return t}function Ey(i){let t=1;for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)t*=i.get(e,r);return t}function Cy(i,t,e){const r=i.rows,n=i.columns,s=[];for(let a=0;a<r;a++){let u=0,c=0,f=0;for(let d=0;d<n;d++)f=i.get(a,d)-e[a],u+=f,c+=f*f;t?s.push((c-u*u/n)/(n-1)):s.push((c-u*u/n)/n)}return s}function Ay(i,t,e){const r=i.rows,n=i.columns,s=[];for(let a=0;a<n;a++){let u=0,c=0,f=0;for(let d=0;d<r;d++)f=i.get(d,a)-e[a],u+=f,c+=f*f;t?s.push((c-u*u/r)/(r-1)):s.push((c-u*u/r)/r)}return s}function My(i,t,e){const r=i.rows,n=i.columns,s=r*n;let a=0,u=0,c=0;for(let f=0;f<r;f++)for(let d=0;d<n;d++)c=i.get(f,d)-e,a+=c,u+=c*c;return t?(u-a*a/s)/(s-1):(u-a*a/s)/s}function Fy(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)-t[e])}function Ny(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)-t[r])}function Sy(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)-t)}function Oy(i){const t=[];for(let e=0;e<i.rows;e++){let r=0;for(let n=0;n<i.columns;n++)r+=Math.pow(i.get(e,n),2)/(i.columns-1);t.push(Math.sqrt(r))}return t}function By(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)/t[e])}function Ty(i){const t=[];for(let e=0;e<i.columns;e++){let r=0;for(let n=0;n<i.rows;n++)r+=Math.pow(i.get(n,e),2)/(i.rows-1);t.push(Math.sqrt(r))}return t}function Iy(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)/t[r])}function $y(i){const t=i.size-1;let e=0;for(let r=0;r<i.columns;r++)for(let n=0;n<i.rows;n++)e+=Math.pow(i.get(n,r),2)/t;return Math.sqrt(e)}function Ly(i,t){for(let e=0;e<i.rows;e++)for(let r=0;r<i.columns;r++)i.set(e,r,i.get(e,r)/t)}class $t{static from1DArray(t,e,r){if(t*e!==r.length)throw new RangeError("data length does not match given dimensions");let s=new dt(t,e);for(let a=0;a<t;a++)for(let u=0;u<e;u++)s.set(a,u,r[a*e+u]);return s}static rowVector(t){let e=new dt(1,t.length);for(let r=0;r<t.length;r++)e.set(0,r,t[r]);return e}static columnVector(t){let e=new dt(t.length,1);for(let r=0;r<t.length;r++)e.set(r,0,t[r]);return e}static zeros(t,e){return new dt(t,e)}static ones(t,e){return new dt(t,e).fill(1)}static rand(t,e,r={}){if(typeof r!="object")throw new TypeError("options must be an object");const{random:n=Math.random}=r;let s=new dt(t,e);for(let a=0;a<t;a++)for(let u=0;u<e;u++)s.set(a,u,n());return s}static randInt(t,e,r={}){if(typeof r!="object")throw new TypeError("options must be an object");const{min:n=0,max:s=1e3,random:a=Math.random}=r;if(!Number.isInteger(n))throw new TypeError("min must be an integer");if(!Number.isInteger(s))throw new TypeError("max must be an integer");if(n>=s)throw new RangeError("min must be smaller than max");let u=s-n,c=new dt(t,e);for(let f=0;f<t;f++)for(let d=0;d<e;d++){let h=n+Math.round(a()*u);c.set(f,d,h)}return c}static eye(t,e,r){e===void 0&&(e=t),r===void 0&&(r=1);let n=Math.min(t,e),s=this.zeros(t,e);for(let a=0;a<n;a++)s.set(a,a,r);return s}static diag(t,e,r){let n=t.length;e===void 0&&(e=n),r===void 0&&(r=e);let s=Math.min(n,e,r),a=this.zeros(e,r);for(let u=0;u<s;u++)a.set(u,u,t[u]);return a}static min(t,e){t=this.checkMatrix(t),e=this.checkMatrix(e);let r=t.rows,n=t.columns,s=new dt(r,n);for(let a=0;a<r;a++)for(let u=0;u<n;u++)s.set(a,u,Math.min(t.get(a,u),e.get(a,u)));return s}static max(t,e){t=this.checkMatrix(t),e=this.checkMatrix(e);let r=t.rows,n=t.columns,s=new this(r,n);for(let a=0;a<r;a++)for(let u=0;u<n;u++)s.set(a,u,Math.max(t.get(a,u),e.get(a,u)));return s}static checkMatrix(t){return $t.isMatrix(t)?t:new dt(t)}static isMatrix(t){return t!=null&&t.klass==="Matrix"}get size(){return this.rows*this.columns}apply(t){if(typeof t!="function")throw new TypeError("callback must be a function");for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)t.call(this,e,r);return this}to1DArray(){let t=[];for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)t.push(this.get(e,r));return t}to2DArray(){let t=[];for(let e=0;e<this.rows;e++){t.push([]);for(let r=0;r<this.columns;r++)t[e].push(this.get(e,r))}return t}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 t=0;t<this.rows;t++)for(let e=0;e<=t;e++)if(this.get(t,e)!==this.get(e,t))return!1;return!0}return!1}isDistance(){if(!this.isSymmetric())return!1;for(let t=0;t<this.rows;t++)if(this.get(t,t)!==0)return!1;return!0}isEchelonForm(){let t=0,e=0,r=-1,n=!0,s=!1;for(;t<this.rows&&n;){for(e=0,s=!1;e<this.columns&&s===!1;)this.get(t,e)===0?e++:this.get(t,e)===1&&e>r?(s=!0,r=e):(n=!1,s=!0);t++}return n}isReducedEchelonForm(){let t=0,e=0,r=-1,n=!0,s=!1;for(;t<this.rows&&n;){for(e=0,s=!1;e<this.columns&&s===!1;)this.get(t,e)===0?e++:this.get(t,e)===1&&e>r?(s=!0,r=e):(n=!1,s=!0);for(let a=e+1;a<this.rows;a++)this.get(t,a)!==0&&(n=!1);t++}return n}echelonForm(){let t=this.clone(),e=0,r=0;for(;e<t.rows&&r<t.columns;){let n=e;for(let s=e;s<t.rows;s++)t.get(s,r)>t.get(n,r)&&(n=s);if(t.get(n,r)===0)r++;else{t.swapRows(e,n);let s=t.get(e,r);for(let a=r;a<t.columns;a++)t.set(e,a,t.get(e,a)/s);for(let a=e+1;a<t.rows;a++){let u=t.get(a,r)/t.get(e,r);t.set(a,r,0);for(let c=r+1;c<t.columns;c++)t.set(a,c,t.get(a,c)-t.get(e,c)*u)}e++,r++}}return t}reducedEchelonForm(){let t=this.echelonForm(),e=t.columns,r=t.rows,n=r-1;for(;n>=0;)if(t.maxRow(n)===0)n--;else{let s=0,a=!1;for(;s<r&&a===!1;)t.get(n,s)===1?a=!0:s++;for(let u=0;u<n;u++){let c=t.get(u,s);for(let f=s;f<e;f++){let d=t.get(u,f)-c*t.get(n,f);t.set(u,f,d)}}n--}return t}set(){throw new Error("set method is unimplemented")}get(){throw new Error("get method is unimplemented")}repeat(t={}){if(typeof t!="object")throw new TypeError("options must be an object");const{rows:e=1,columns:r=1}=t;if(!Number.isInteger(e)||e<=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 n=new dt(this.rows*e,this.columns*r);for(let s=0;s<e;s++)for(let a=0;a<r;a++)n.setSubMatrix(this,this.rows*s,this.columns*a);return n}fill(t){for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,t);return this}neg(){return this.mulS(-1)}getRow(t){Tr(this,t);let e=[];for(let r=0;r<this.columns;r++)e.push(this.get(t,r));return e}getRowVector(t){return dt.rowVector(this.getRow(t))}setRow(t,e){Tr(this,t),e=Fi(this,e);for(let r=0;r<this.columns;r++)this.set(t,r,e[r]);return this}swapRows(t,e){Tr(this,t),Tr(this,e);for(let r=0;r<this.columns;r++){let n=this.get(t,r);this.set(t,r,this.get(e,r)),this.set(e,r,n)}return this}getColumn(t){Ir(this,t);let e=[];for(let r=0;r<this.rows;r++)e.push(this.get(r,t));return e}getColumnVector(t){return dt.columnVector(this.getColumn(t))}setColumn(t,e){Ir(this,t),e=Ni(this,e);for(let r=0;r<this.rows;r++)this.set(r,t,e[r]);return this}swapColumns(t,e){Ir(this,t),Ir(this,e);for(let r=0;r<this.rows;r++){let n=this.get(r,t);this.set(r,t,this.get(r,e)),this.set(r,e,n)}return this}addRowVector(t){t=Fi(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)+t[r]);return this}subRowVector(t){t=Fi(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)-t[r]);return this}mulRowVector(t){t=Fi(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)*t[r]);return this}divRowVector(t){t=Fi(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)/t[r]);return this}addColumnVector(t){t=Ni(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)+t[e]);return this}subColumnVector(t){t=Ni(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)-t[e]);return this}mulColumnVector(t){t=Ni(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)*t[e]);return this}divColumnVector(t){t=Ni(this,t);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)this.set(e,r,this.get(e,r)/t[e]);return this}mulRow(t,e){Tr(this,t);for(let r=0;r<this.columns;r++)this.set(t,r,this.get(t,r)*e);return this}mulColumn(t,e){Ir(this,t);for(let r=0;r<this.rows;r++)this.set(r,t,this.get(r,t)*e);return this}max(t){if(this.isEmpty())return NaN;switch(t){case"row":{const e=new Array(this.rows).fill(Number.NEGATIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)>e[r]&&(e[r]=this.get(r,n));return e}case"column":{const e=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)>e[n]&&(e[n]=this.get(r,n));return e}case void 0:{let e=this.get(0,0);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)>e&&(e=this.get(r,n));return e}default:throw new Error(`invalid option: ${t}`)}}maxIndex(){Si(this);let t=this.get(0,0),e=[0,0];for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)>t&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}min(t){if(this.isEmpty())return NaN;switch(t){case"row":{const e=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)<e[r]&&(e[r]=this.get(r,n));return e}case"column":{const e=new Array(this.columns).fill(Number.POSITIVE_INFINITY);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)<e[n]&&(e[n]=this.get(r,n));return e}case void 0:{let e=this.get(0,0);for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)<e&&(e=this.get(r,n));return e}default:throw new Error(`invalid option: ${t}`)}}minIndex(){Si(this);let t=this.get(0,0),e=[0,0];for(let r=0;r<this.rows;r++)for(let n=0;n<this.columns;n++)this.get(r,n)<t&&(t=this.get(r,n),e[0]=r,e[1]=n);return e}maxRow(t){if(Tr(this,t),this.isEmpty())return NaN;let e=this.get(t,0);for(let r=1;r<this.columns;r++)this.get(t,r)>e&&(e=this.get(t,r));return e}maxRowIndex(t){Tr(this,t),Si(this);let e=this.get(t,0),r=[t,0];for(let n=1;n<this.columns;n++)this.get(t,n)>e&&(e=this.get(t,n),r[1]=n);return r}minRow(t){if(Tr(this,t),this.isEmpty())return NaN;let e=this.get(t,0);for(let r=1;r<this.columns;r++)this.get(t,r)<e&&(e=this.get(t,r));return e}minRowIndex(t){Tr(this,t),Si(this);let e=this.get(t,0),r=[t,0];for(let n=1;n<this.columns;n++)this.get(t,n)<e&&(e=this.get(t,n),r[1]=n);return r}maxColumn(t){if(Ir(this,t),this.isEmpty())return NaN;let e=this.get(0,t);for(let r=1;r<this.rows;r++)this.get(r,t)>e&&(e=this.get(r,t));return e}maxColumnIndex(t){Ir(this,t),Si(this);let e=this.get(0,t),r=[0,t];for(let n=1;n<this.rows;n++)this.get(n,t)>e&&(e=this.get(n,t),r[0]=n);return r}minColumn(t){if(Ir(this,t),this.isEmpty())return NaN;let e=this.get(0,t);for(let r=1;r<this.rows;r++)this.get(r,t)<e&&(e=this.get(r,t));return e}minColumnIndex(t){Ir(this,t),Si(this);let e=this.get(0,t),r=[0,t];for(let n=1;n<this.rows;n++)this.get(n,t)<e&&(e=this.get(n,t),r[0]=n);return r}diag(){let t=Math.min(this.rows,this.columns),e=[];for(let r=0;r<t;r++)e.push(this.get(r,r));return e}norm(t="frobenius"){switch(t){case"max":return this.max();case"frobenius":return Math.sqrt(this.dot(this));default:throw new RangeError(`unknown norm type: ${t}`)}}cumulativeSum(){let t=0;for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)t+=this.get(e,r),this.set(e,r,t);return this}dot(t){$t.isMatrix(t)&&(t=t.to1DArray());let e=this.to1DArray();if(e.length!==t.length)throw new RangeError("vectors do not have the same size");let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}mmul(t){t=dt.checkMatrix(t);let e=this.rows,r=this.columns,n=t.columns,s=new dt(e,n),a=new Float64Array(r);for(let u=0;u<n;u++){for(let c=0;c<r;c++)a[c]=t.get(c,u);for(let c=0;c<e;c++){let f=0;for(let d=0;d<r;d++)f+=this.get(c,d)*a[d];s.set(c,u,f)}}return s}strassen2x2(t){t=dt.checkMatrix(t);let e=new dt(2,2);const r=this.get(0,0),n=t.get(0,0),s=this.get(0,1),a=t.get(0,1),u=this.get(1,0),c=t.get(1,0),f=this.get(1,1),d=t.get(1,1),h=(r+f)*(n+d),_=(u+f)*n,g=r*(a-d),y=f*(c-n),p=(r+s)*d,w=(u-r)*(n+a),v=(s-f)*(c+d),x=h+y-p+v,b=g+p,C=_+y,E=h-_+g+w;return e.set(0,0,x),e.set(0,1,b),e.set(1,0,C),e.set(1,1,E),e}strassen3x3(t){t=dt.checkMatrix(t);let e=new dt(3,3);const r=this.get(0,0),n=this.get(0,1),s=this.get(0,2),a=this.get(1,0),u=this.get(1,1),c=this.get(1,2),f=this.get(2,0),d=this.get(2,1),h=this.get(2,2),_=t.get(0,0),g=t.get(0,1),y=t.get(0,2),p=t.get(1,0),w=t.get(1,1),v=t.get(1,2),x=t.get(2,0),b=t.get(2,1),C=t.get(2,2),E=(r+n+s-a-u-d-h)*w,A=(r-a)*(-g+w),N=u*(-_+g+p-w-v-x+C),S=(-r+a+u)*(_-g+w),I=(a+u)*(-_+g),F=r*_,O=(-r+f+d)*(_-y+v),L=(-r+f)*(y-v),z=(f+d)*(-_+y),q=(r+n+s-u-c-f-d)*v,W=d*(-_+y+p-w-v-x+b),P=(-s+d+h)*(w+x-b),Z=(s-h)*(w-b),Y=s*x,G=(d+h)*(-x+b),X=(-s+u+c)*(v+x-C),ut=(s-c)*(v-C),_t=(u+c)*(-x+C),at=n*p,vt=c*b,wt=a*y,Ct=f*g,bt=h*C,re=F+Y+at,Bt=E+S+I+F+P+Y+G,Nt=F+O+z+q+Y+X+_t,he=A+N+S+F+Y+X+ut,se=A+S+I+F+vt,qt=Y+X+ut+_t+wt,Xt=F+O+L+W+P+Z+Y,Le=P+Z+Y+G+Ct,Dr=F+O+L+z+bt;return e.set(0,0,re),e.set(0,1,Bt),e.set(0,2,Nt),e.set(1,0,he),e.set(1,1,se),e.set(1,2,qt),e.set(2,0,Xt),e.set(2,1,Le),e.set(2,2,Dr),e}mmulStrassen(t){t=dt.checkMatrix(t);let e=this.clone(),r=e.rows,n=e.columns,s=t.rows,a=t.columns;n!==s&&console.warn(`Multiplying ${r} x ${n} and ${s} x ${a} matrix: dimensions do not match.`);function u(h,_,g){let y=h.rows,p=h.columns;if(y===_&&p===g)return h;{let w=$t.zeros(_,g);return w=w.setSubMatrix(h,0,0),w}}let c=Math.max(r,s),f=Math.max(n,a);e=u(e,c,f),t=u(t,c,f);function d(h,_,g,y){if(g<=512||y<=512)return h.mmul(_);g%2===1&&y%2===1?(h=u(h,g+1,y+1),_=u(_,g+1,y+1)):g%2===1?(h=u(h,g+1,y),_=u(_,g+1,y)):y%2===1&&(h=u(h,g,y+1),_=u(_,g,y+1));let p=parseInt(h.rows/2,10),w=parseInt(h.columns/2,10),v=h.subMatrix(0,p-1,0,w-1),x=_.subMatrix(0,p-1,0,w-1),b=h.subMatrix(0,p-1,w,h.columns-1),C=_.subMatrix(0,p-1,w,_.columns-1),E=h.subMatrix(p,h.rows-1,0,w-1),A=_.subMatrix(p,_.rows-1,0,w-1),N=h.subMatrix(p,h.rows-1,w,h.columns-1),S=_.subMatrix(p,_.rows-1,w,_.columns-1),I=d($t.add(v,N),$t.add(x,S),p,w),F=d($t.add(E,N),x,p,w),O=d(v,$t.sub(C,S),p,w),L=d(N,$t.sub(A,x),p,w),z=d($t.add(v,b),S,p,w),q=d($t.sub(E,v),$t.add(x,C),p,w),W=d($t.sub(b,N),$t.add(A,S),p,w),P=$t.add(I,L);P.sub(z),P.add(W);let Z=$t.add(O,z),Y=$t.add(F,L),G=$t.sub(I,F);G.add(O),G.add(q);let X=$t.zeros(2*P.rows,2*P.columns);return X=X.setSubMatrix(P,0,0),X=X.setSubMatrix(Z,P.rows,0),X=X.setSubMatrix(Y,0,P.columns),X=X.setSubMatrix(G,P.rows,P.columns),X.subMatrix(0,g-1,0,y-1)}return d(e,t,c,f)}scaleRows(t={}){if(typeof t!="object")throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let n=new dt(this.rows,this.columns);for(let s=0;s<this.rows;s++){const a=this.getRow(s);a.length>0&&uh(a,{min:e,max:r,output:a}),n.setRow(s,a)}return n}scaleColumns(t={}){if(typeof t!="object")throw new TypeError("options must be an object");const{min:e=0,max:r=1}=t;if(!Number.isFinite(e))throw new TypeError("min must be a number");if(!Number.isFinite(r))throw new TypeError("max must be a number");if(e>=r)throw new RangeError("min must be smaller than max");let n=new dt(this.rows,this.columns);for(let s=0;s<this.columns;s++){const a=this.getColumn(s);a.length&&uh(a,{min:e,max:r,output:a}),n.setColumn(s,a)}return n}flipRows(){const t=Math.ceil(this.columns/2);for(let e=0;e<this.rows;e++)for(let r=0;r<t;r++){let n=this.get(e,r),s=this.get(e,this.columns-1-r);this.set(e,r,s),this.set(e,this.columns-1-r,n)}return this}flipColumns(){const t=Math.ceil(this.rows/2);for(let e=0;e<this.columns;e++)for(let r=0;r<t;r++){let n=this.get(r,e),s=this.get(this.rows-1-r,e);this.set(r,e,s),this.set(this.rows-1-r,e,n)}return this}kroneckerProduct(t){t=dt.checkMatrix(t);let e=this.rows,r=this.columns,n=t.rows,s=t.columns,a=new dt(e*n,r*s);for(let u=0;u<e;u++)for(let c=0;c<r;c++)for(let f=0;f<n;f++)for(let d=0;d<s;d++)a.set(n*u+f,s*c+d,this.get(u,c)*t.get(f,d));return a}kroneckerSum(t){if(t=dt.checkMatrix(t),!this.isSquare()||!t.isSquare())throw new Error("Kronecker Sum needs two Square Matrices");let e=this.rows,r=t.rows,n=this.kroneckerProduct(dt.eye(r,r)),s=dt.eye(e,e).kroneckerProduct(t);return n.add(s)}transpose(){let t=new dt(this.columns,this.rows);for(let e=0;e<this.rows;e++)for(let r=0;r<this.columns;r++)t.set(r,e,this.get(e,r));return t}sortRows(t=hh){for(let e=0;e<this.rows;e++)this.setRow(e,this.getRow(e).sort(t));return this}sortColumns(t=hh){for(let e=0;e<this.columns;e++)this.setColumn(e,this.getColumn(e).sort(t));return this}subMatrix(t,e,r,n){tu(this,t,e,r,n);let s=new dt(e-t+1,n-r+1);for(let a=t;a<=e;a++)for(let u=r;u<=n;u++)s.set(a-t,u-r,this.get(a,u));return s}subMatrixRow(t,e,r){if(e===void 0&&(e=0),r===void 0&&(r=this.columns-1),e>r||e<0||e>=this.columns||r<0||r>=this.columns)throw new RangeError("Argument out of range");let n=new dt(t.length,r-e+1);for(let s=0;s<t.length;s++)for(let a=e;a<=r;a++){if(t[s]<0||t[s]>=this.rows)throw new RangeError(`Row index out of range: ${t[s]}`);n.set(s,a-e,this.get(t[s],a))}return n}subMatrixColumn(t,e,r){if(e===void 0&&(e=0),r===void 0&&(r=this.rows-1),e>r||e<0||e>=this.rows||r<0||r>=this.rows)throw new RangeError("Argument out of range");let n=new dt(r-e+1,t.length);for(let s=0;s<t.length;s++)for(let a=e;a<=r;a++){if(t[s]<0||t[s]>=this.columns)throw new RangeError(`Column index out of range: ${t[s]}`);n.set(a-e,s,this.get(a,t[s]))}return n}setSubMatrix(t,e,r){if(t=dt.checkMatrix(t),t.isEmpty())return this;let n=e+t.rows-1,s=r+t.columns-1;tu(this,e,n,r,s);for(let a=0;a<t.rows;a++)for(let u=0;u<t.columns;u++)this.set(e+a,r+u,t.get(a,u));return this}selection(t,e){Xa(this,t),Qa(this,e);let r=new dt(t.length,e.length);for(let n=0;n<t.length;n++){let s=t[n];for(let a=0;a<e.length;a++){let u=e[a];r.set(n,a,this.get(s,u))}}return r}trace(){let t=Math.min(this.rows,this.columns),e=0;for(let r=0;r<t;r++)e+=this.get(r,r);return e}clone(){return this.constructor.copy(this,new dt(this.rows,this.columns))}static copy(t,e){for(const[r,n,s]of t.entries())e.set(r,n,s);return e}sum(t){switch(t){case"row":return yy(this);case"column":return wy(this);case void 0:return Dy(this);default:throw new Error(`invalid option: ${t}`)}}product(t){switch(t){case"row":return by(this);case"column":return xy(this);case void 0:return Ey(this);default:throw new Error(`invalid option: ${t}`)}}mean(t){const e=this.sum(t);switch(t){case"row":{for(let r=0;r<this.rows;r++)e[r]/=this.columns;return e}case"column":{for(let r=0;r<this.columns;r++)e[r]/=this.rows;return e}case void 0:return e/this.size;default:throw new Error(`invalid option: ${t}`)}}variance(t,e={}){if(typeof t=="object"&&(e=t,t=void 0),typeof e!="object")throw new TypeError("options must be an object");const{unbiased:r=!0,mean:n=this.mean(t)}=e;if(typeof r!="boolean")throw new TypeError("unbiased must be a boolean");switch(t){case"row":{if(!fr.isAnyArray(n))throw new TypeError("mean must be an array");return Cy(this,r,n)}case"column":{if(!fr.isAnyArray(n))throw new TypeError("mean must be an array");return Ay(this,r,n)}case void 0:{if(typeof n!="number")throw new TypeError("mean must be a number");return My(this,r,n)}default:throw new Error(`invalid option: ${t}`)}}standardDeviation(t,e){typeof t=="object"&&(e=t,t=void 0);const r=this.variance(t,e);if(t===void 0)return Math.sqrt(r);for(let n=0;n<r.length;n++)r[n]=Math.sqrt(r[n]);return r}center(t,e={}){if(typeof t=="object"&&(e=t,t=void 0),typeof e!="object")throw new TypeError("options must be an object");const{center:r=this.mean(t)}=e;switch(t){case"row":{if(!fr.isAnyArray(r))throw new TypeError("center must be an array");return Fy(this,r),this}case"column":{if(!fr.isAnyArray(r))throw new TypeError("center must be an array");return Ny(this,r),this}case void 0:{if(typeof r!="number")throw new TypeError("center must be a number");return Sy(this,r),this}default:throw new Error(`invalid option: ${t}`)}}scale(t,e={}){if(typeof t=="object"&&(e=t,t=void 0),typeof e!="object")throw new TypeError("options must be an object");let r=e.scale;switch(t){case"row":{if(r===void 0)r=Oy(this);else if(!fr.isAnyArray(r))throw new TypeError("scale must be an array");return By(this,r),this}case"column":{if(r===void 0)r=Ty(this);else if(!fr.isAnyArray(r))throw new TypeError("scale must be an array");return Iy(this,r),this}case void 0:{if(r===void 0)r=$y(this);else if(typeof r!="number")throw new TypeError("scale must be a number");return Ly(this,r),this}default:throw new Error(`invalid option: ${t}`)}}toString(t){return ch(this,t)}[Symbol.iterator](){return this.entries()}*entries(){for(let t=0;t<this.rows;t++)for(let e=0;e<this.columns;e++)yield[t,e,this.get(t,e)]}*values(){for(let t=0;t<this.rows;t++)for(let e=0;e<this.columns;e++)yield this.get(t,e)}}$t.prototype.klass="Matrix",typeof Symbol<"u"&&($t.prototype[Symbol.for("nodejs.util.inspect.custom")]=py);function hh(i,t){return i-t}function Ry(i){return i.every(t=>typeof t=="number")}$t.random=$t.rand,$t.randomInt=$t.randInt,$t.diagonal=$t.diag,$t.prototype.diagonal=$t.prototype.diag,$t.identity=$t.eye,$t.prototype.negate=$t.prototype.neg,$t.prototype.tensorProduct=$t.prototype.kroneckerProduct;let dt=(Ri=class extends $t{constructor(e,r){super();Yl(this,cs);$(this,"data");if(Ri.isMatrix(e))Vl(this,cs,Hl).call(this,e.rows,e.columns),Ri.copy(e,this);else if(Number.isInteger(e)&&e>=0)Vl(this,cs,Hl).call(this,e,r);else if(fr.isAnyArray(e)){const n=e;if(e=n.length,r=e?n[0].length:0,typeof r!="number")throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let s=0;s<e;s++){if(n[s].length!==r)throw new RangeError("Inconsistent array dimensions");if(!Ry(n[s]))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(n[s]))}this.rows=e,this.columns=r}else throw new TypeError("First argument must be a positive number or an array")}set(e,r,n){return this.data[e][r]=n,this}get(e,r){return this.data[e][r]}removeRow(e){return Tr(this,e),this.data.splice(e,1),this.rows-=1,this}addRow(e,r){return r===void 0&&(r=e,e=this.rows),Tr(this,e,!0),r=Float64Array.from(Fi(this,r)),this.data.splice(e,0,r),this.rows+=1,this}removeColumn(e){Ir(this,e);for(let r=0;r<this.rows;r++){const n=new Float64Array(this.columns-1);for(let s=0;s<e;s++)n[s]=this.data[r][s];for(let s=e+1;s<this.columns;s++)n[s-1]=this.data[r][s];this.data[r]=n}return this.columns-=1,this}addColumn(e,r){typeof r>"u"&&(r=e,e=this.columns),Ir(this,e,!0),r=Ni(this,r);for(let n=0;n<this.rows;n++){const s=new Float64Array(this.columns+1);let a=0;for(;a<e;a++)s[a]=this.data[n][a];for(s[a++]=r[n];a<this.columns+1;a++)s[a]=this.data[n][a-1];this.data[n]=s}return this.columns+=1,this}},cs=new WeakSet,Hl=function(e,r){if(this.data=[],Number.isInteger(r)&&r>=0)for(let n=0;n<e;n++)this.data.push(new Float64Array(r));else throw new TypeError("nColumns must be a positive integer");this.rows=e,this.columns=r},Ri);vy($t,dt);const Oo=class Oo extends $t{constructor(e){super();Yl(this,tr,void 0);if(dt.isMatrix(e)){if(!e.isSymmetric())throw new TypeError("not symmetric data");ba(this,tr,dt.copy(e,new dt(e.rows,e.rows)))}else if(Number.isInteger(e)&&e>=0)ba(this,tr,new dt(e,e));else if(ba(this,tr,new dt(e)),!this.isSymmetric())throw new TypeError("not symmetric data")}get size(){return tn(this,tr).size}get rows(){return tn(this,tr).rows}get columns(){return tn(this,tr).columns}get diagonalSize(){return this.rows}static isSymmetricMatrix(e){return dt.isMatrix(e)&&e.klassType==="SymmetricMatrix"}static zeros(e){return new this(e)}static ones(e){return new this(e).fill(1)}clone(){const e=new Oo(this.diagonalSize);for(const[r,n,s]of this.upperRightEntries())e.set(r,n,s);return e}toMatrix(){return new dt(this)}get(e,r){return tn(this,tr).get(e,r)}set(e,r,n){return tn(this,tr).set(e,r,n),tn(this,tr).set(r,e,n),this}removeCross(e){return tn(this,tr).removeRow(e),tn(this,tr).removeColumn(e),this}addCross(e,r){r===void 0&&(r=e,e=this.diagonalSize);const n=r.slice();return n.splice(e,1),tn(this,tr).addRow(e,n),tn(this,tr).addColumn(e,r),this}applyMask(e){if(e.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const r=[];for(const[n,s]of e.entries())s||r.push(n);r.reverse();for(const n of r)this.removeCross(n);return this}toCompact(){const{diagonalSize:e}=this,r=new Array(e*(e+1)/2);for(let n=0,s=0,a=0;a<r.length;a++)r[a]=this.get(s,n),++n>=e&&(n=++s);return r}static fromCompact(e){const r=e.length,n=(Math.sqrt(8*r+1)-1)/2;if(!Number.isInteger(n))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(e)}`);const s=new Oo(n);for(let a=0,u=0,c=0;c<r;c++)s.set(a,u,e[c]),++a>=n&&(a=++u);return s}*upperRightEntries(){for(let e=0,r=0;e<this.diagonalSize;void 0){const n=this.get(e,r);yield[e,r,n],++r>=this.diagonalSize&&(r=++e)}}*upperRightValues(){for(let e=0,r=0;e<this.diagonalSize;void 0)yield this.get(e,r),++r>=this.diagonalSize&&(r=++e)}};tr=new WeakMap;let ri=Oo;ri.prototype.klassType="SymmetricMatrix";class fo extends ri{static isDistanceMatrix(t){return ri.isSymmetricMatrix(t)&&t.klassSubType==="DistanceMatrix"}constructor(t){if(super(t),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(t,e,r){return t===e&&(r=0),super.set(t,e,r)}addCross(t,e){return e===void 0&&(e=t,t=this.diagonalSize),e=e.slice(),e[t]=0,super.addCross(t,e)}toSymmetricMatrix(){return new ri(this)}clone(){const t=new fo(this.diagonalSize);for(const[e,r,n]of this.upperRightEntries())e!==r&&t.set(e,r,n);return t}toCompact(){const{diagonalSize:t}=this,e=(t-1)*t/2,r=new Array(e);for(let n=1,s=0,a=0;a<r.length;a++)r[a]=this.get(s,n),++n>=t&&(n=++s+1);return r}static fromCompact(t){const e=t.length,r=(Math.sqrt(8*e+1)+1)/2;if(!Number.isInteger(r))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(t)}`);const n=new this(r);for(let s=1,a=0,u=0;u<e;u++)n.set(s,a,t[u]),++s>=r&&(s=++a+1);return n}}fo.prototype.klassSubType="DistanceMatrix";class _n extends $t{constructor(t,e,r){super(),this.matrix=t,this.rows=e,this.columns=r}}class Py extends _n{constructor(t,e){Ir(t,e),super(t,t.rows,1),this.column=e}set(t,e,r){return this.matrix.set(t,this.column,r),this}get(t){return this.matrix.get(t,this.column)}}class ky extends _n{constructor(t,e){Qa(t,e),super(t,t.rows,e.length),this.columnIndices=e}set(t,e,r){return this.matrix.set(t,this.columnIndices[e],r),this}get(t,e){return this.matrix.get(t,this.columnIndices[e])}}class zy extends _n{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(t,this.columns-e-1,r),this}get(t,e){return this.matrix.get(t,this.columns-e-1)}}class qy extends _n{constructor(t){super(t,t.rows,t.columns)}set(t,e,r){return this.matrix.set(this.rows-t-1,e,r),this}get(t,e){return this.matrix.get(this.rows-t-1,e)}}class Uy extends _n{constructor(t,e){Tr(t,e),super(t,1,t.columns),this.row=e}set(t,e,r){return this.matrix.set(this.row,e,r),this}get(t,e){return this.matrix.get(this.row,e)}}class Wy extends _n{constructor(t,e){Xa(t,e),super(t,e.length,t.columns),this.rowIndices=e}set(t,e,r){return this.matrix.set(this.rowIndices[t],e,r),this}get(t,e){return this.matrix.get(this.rowIndices[t],e)}}class ho extends _n{constructor(t,e,r){Xa(t,e),Qa(t,r),super(t,e.length,r.length),this.rowIndices=e,this.columnIndices=r}set(t,e,r){return this.matrix.set(this.rowIndices[t],this.columnIndices[e],r),this}get(t,e){return this.matrix.get(this.rowIndices[t],this.columnIndices[e])}}class jy extends _n{constructor(t,e,r,n,s){tu(t,e,r,n,s),super(t,r-e+1,s-n+1),this.startRow=e,this.startColumn=n}set(t,e,r){return this.matrix.set(this.startRow+t,this.startColumn+e,r),this}get(t,e){return this.matrix.get(this.startRow+t,this.startColumn+e)}}class Yy extends _n{constructor(t){super(t,t.columns,t.rows)}set(t,e,r){return this.matrix.set(e,t,r),this}get(t,e){return this.matrix.get(e,t)}}class dh extends $t{constructor(t,e={}){const{rows:r=1}=e;if(t.length%r!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=r,this.columns=t.length/r,this.data=t}set(t,e,r){let n=this._calculateIndex(t,e);return this.data[n]=r,this}get(t,e){let r=this._calculateIndex(t,e);return this.data[r]}_calculateIndex(t,e){return t*this.columns+e}}class wr extends $t{constructor(t){super(),this.data=t,this.rows=t.length,this.columns=t[0].length}set(t,e,r){return this.data[t][e]=r,this}get(t,e){return this.data[t][e]}}function Vy(i,t){if(fr.isAnyArray(i))return i[0]&&fr.isAnyArray(i[0])?new wr(i):new dh(i,t);throw new Error("the argument is not an array")}class _o{constructor(t){t=wr.checkMatrix(t);let e=t.clone(),r=e.rows,n=e.columns,s=new Float64Array(r),a=1,u,c,f,d,h,_,g,y,p;for(u=0;u<r;u++)s[u]=u;for(y=new Float64Array(r),c=0;c<n;c++){for(u=0;u<r;u++)y[u]=e.get(u,c);for(u=0;u<r;u++){for(p=Math.min(u,c),h=0,f=0;f<p;f++)h+=e.get(u,f)*y[f];y[u]-=h,e.set(u,c,y[u])}for(d=c,u=c+1;u<r;u++)Math.abs(y[u])>Math.abs(y[d])&&(d=u);if(d!==c){for(f=0;f<n;f++)_=e.get(d,f),e.set(d,f,e.get(c,f)),e.set(c,f,_);g=s[d],s[d]=s[c],s[c]=g,a=-a}if(c<r&&e.get(c,c)!==0)for(u=c+1;u<r;u++)e.set(u,c,e.get(u,c)/e.get(c,c))}this.LU=e,this.pivotVector=s,this.pivotSign=a}isSingular(){let t=this.LU,e=t.columns;for(let r=0;r<e;r++)if(t.get(r,r)===0)return!0;return!1}solve(t){t=dt.checkMatrix(t);let e=this.LU;if(e.rows!==t.rows)throw new Error("Invalid matrix dimensions");if(this.isSingular())throw new Error("LU matrix is singular");let n=t.columns,s=t.subMatrixRow(this.pivotVector,0,n-1),a=e.columns,u,c,f;for(f=0;f<a;f++)for(u=f+1;u<a;u++)for(c=0;c<n;c++)s.set(u,c,s.get(u,c)-s.get(f,c)*e.get(u,f));for(f=a-1;f>=0;f--){for(c=0;c<n;c++)s.set(f,c,s.get(f,c)/e.get(f,f));for(u=0;u<f;u++)for(c=0;c<n;c++)s.set(u,c,s.get(u,c)-s.get(f,c)*e.get(u,f))}return s}get determinant(){let t=this.LU;if(!t.isSquare())throw new Error("Matrix must be square");let e=this.pivotSign,r=t.columns;for(let n=0;n<r;n++)e*=t.get(n,n);return e}get lowerTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,n=new dt(e,r);for(let s=0;s<e;s++)for(let a=0;a<r;a++)s>a?n.set(s,a,t.get(s,a)):s===a?n.set(s,a,1):n.set(s,a,0);return n}get upperTriangularMatrix(){let t=this.LU,e=t.rows,r=t.columns,n=new dt(e,r);for(let s=0;s<e;s++)for(let a=0;a<r;a++)s<=a?n.set(s,a,t.get(s,a)):n.set(s,a,0);return n}get pivotPermutationVector(){return Array.from(this.pivotVector)}}function pn(i,t){let e=0;return Math.abs(i)>Math.abs(t)?(e=t/i,Math.abs(i)*Math.sqrt(1+e*e)):t!==0?(e=i/t,Math.abs(t)*Math.sqrt(1+e*e)):0}class eu{constructor(t){t=wr.checkMatrix(t);let e=t.clone(),r=t.rows,n=t.columns,s=new Float64Array(n),a,u,c,f;for(c=0;c<n;c++){let d=0;for(a=c;a<r;a++)d=pn(d,e.get(a,c));if(d!==0){for(e.get(c,c)<0&&(d=-d),a=c;a<r;a++)e.set(a,c,e.get(a,c)/d);for(e.set(c,c,e.get(c,c)+1),u=c+1;u<n;u++){for(f=0,a=c;a<r;a++)f+=e.get(a,c)*e.get(a,u);for(f=-f/e.get(c,c),a=c;a<r;a++)e.set(a,u,e.get(a,u)+f*e.get(a,c))}}s[c]=-d}this.QR=e,this.Rdiag=s}solve(t){t=dt.checkMatrix(t);let e=this.QR,r=e.rows;if(t.rows!==r)throw new Error("Matrix row dimensions must agree");if(!this.isFullRank())throw new Error("Matrix is rank deficient");let n=t.columns,s=t.clone(),a=e.columns,u,c,f,d;for(f=0;f<a;f++)for(c=0;c<n;c++){for(d=0,u=f;u<r;u++)d+=e.get(u,f)*s.get(u,c);for(d=-d/e.get(f,f),u=f;u<r;u++)s.set(u,c,s.get(u,c)+d*e.get(u,f))}for(f=a-1;f>=0;f--){for(c=0;c<n;c++)s.set(f,c,s.get(f,c)/this.Rdiag[f]);for(u=0;u<f;u++)for(c=0;c<n;c++)s.set(u,c,s.get(u,c)-s.get(f,c)*e.get(u,f))}return s.subMatrix(0,a-1,0,n-1)}isFullRank(){let t=this.QR.columns;for(let e=0;e<t;e++)if(this.Rdiag[e]===0)return!1;return!0}get upperTriangularMatrix(){let t=this.QR,e=t.columns,r=new dt(e,e),n,s;for(n=0;n<e;n++)for(s=0;s<e;s++)n<s?r.set(n,s,t.get(n,s)):n===s?r.set(n,s,this.Rdiag[n]):r.set(n,s,0);return r}get orthogonalMatrix(){let t=this.QR,e=t.rows,r=t.columns,n=new dt(e,r),s,a,u,c;for(u=r-1;u>=0;u--){for(s=0;s<e;s++)n.set(s,u,0);for(n.set(u,u,1),a=u;a<r;a++)if(t.get(u,u)!==0){for(c=0,s=u;s<e;s++)c+=t.get(s,u)*n.get(s,a);for(c=-c/t.get(u,u),s=u;s<e;s++)n.set(s,a,n.get(s,a)+c*t.get(s,u))}}return n}}class Oi{constructor(t,e={}){if(t=wr.checkMatrix(t),t.isEmpty())throw new Error("Matrix must be non-empty");let r=t.rows,n=t.columns;const{computeLeftSingularVectors:s=!0,computeRightSingularVectors:a=!0,autoTranspose:u=!1}=e;let c=!!s,f=!!a,d=!1,h;if(r<n)if(!u)h=t.clone(),console.warn("Computing SVD on a matrix with more columns than rows. Consider enabling autoTranspose");else{h=t.transpose(),r=h.rows,n=h.columns,d=!0;let F=c;c=f,f=F}else h=t.clone();let _=Math.min(r,n),g=Math.min(r+1,n),y=new Float64Array(g),p=new dt(r,_),w=new dt(n,n),v=new Float64Array(n),x=new Float64Array(r),b=new Float64Array(g);for(let F=0;F<g;F++)b[F]=F;let C=Math.min(r-1,n),E=Math.max(0,Math.min(n-2,r)),A=Math.max(C,E);for(let F=0;F<A;F++){if(F<C){y[F]=0;for(let O=F;O<r;O++)y[F]=pn(y[F],h.get(O,F));if(y[F]!==0){h.get(F,F)<0&&(y[F]=-y[F]);for(let O=F;O<r;O++)h.set(O,F,h.get(O,F)/y[F]);h.set(F,F,h.get(F,F)+1)}y[F]=-y[F]}for(let O=F+1;O<n;O++){if(F<C&&y[F]!==0){let L=0;for(let z=F;z<r;z++)L+=h.get(z,F)*h.get(z,O);L=-L/h.get(F,F);for(let z=F;z<r;z++)h.set(z,O,h.get(z,O)+L*h.get(z,F))}v[O]=h.get(F,O)}if(c&&F<C)for(let O=F;O<r;O++)p.set(O,F,h.get(O,F));if(F<E){v[F]=0;for(let O=F+1;O<n;O++)v[F]=pn(v[F],v[O]);if(v[F]!==0){v[F+1]<0&&(v[F]=0-v[F]);for(let O=F+1;O<n;O++)v[O]/=v[F];v[F+1]+=1}if(v[F]=-v[F],F+1<r&&v[F]!==0){for(let O=F+1;O<r;O++)x[O]=0;for(let O=F+1;O<r;O++)for(let L=F+1;L<n;L++)x[O]+=v[L]*h.get(O,L);for(let O=F+1;O<n;O++){let L=-v[O]/v[F+1];for(let z=F+1;z<r;z++)h.set(z,O,h.get(z,O)+L*x[z])}}if(f)for(let O=F+1;O<n;O++)w.set(O,F,v[O])}}let N=Math.min(n,r+1);if(C<n&&(y[C]=h.get(C,C)),r<N&&(y[N-1]=0),E+1<N&&(v[E]=h.get(E,N-1)),v[N-1]=0,c){for(let F=C;F<_;F++){for(let O=0;O<r;O++)p.set(O,F,0);p.set(F,F,1)}for(let F=C-1;F>=0;F--)if(y[F]!==0){for(let O=F+1;O<_;O++){let L=0;for(let z=F;z<r;z++)L+=p.get(z,F)*p.get(z,O);L=-L/p.get(F,F);for(let z=F;z<r;z++)p.set(z,O,p.get(z,O)+L*p.get(z,F))}for(let O=F;O<r;O++)p.set(O,F,-p.get(O,F));p.set(F,F,1+p.get(F,F));for(let O=0;O<F-1;O++)p.set(O,F,0)}else{for(let O=0;O<r;O++)p.set(O,F,0);p.set(F,F,1)}}if(f)for(let F=n-1;F>=0;F--){if(F<E&&v[F]!==0)for(let O=F+1;O<n;O++){let L=0;for(let z=F+1;z<n;z++)L+=w.get(z,F)*w.get(z,O);L=-L/w.get(F+1,F);for(let z=F+1;z<n;z++)w.set(z,O,w.get(z,O)+L*w.get(z,F))}for(let O=0;O<n;O++)w.set(O,F,0);w.set(F,F,1)}let S=N-1,I=Number.EPSILON;for(;N>0;){let F,O;for(F=N-2;F>=-1&&F!==-1;F--){const L=Number.MIN_VALUE+I*Math.abs(y[F]+Math.abs(y[F+1]));if(Math.abs(v[F])<=L||Number.isNaN(v[F])){v[F]=0;break}}if(F===N-2)O=4;else{let L;for(L=N-1;L>=F&&L!==F;L--){let z=(L!==N?Math.abs(v[L]):0)+(L!==F+1?Math.abs(v[L-1]):0);if(Math.abs(y[L])<=I*z){y[L]=0;break}}L===F?O=3:L===N-1?O=1:(O=2,F=L)}switch(F++,O){case 1:{let L=v[N-2];v[N-2]=0;for(let z=N-2;z>=F;z--){let q=pn(y[z],L),W=y[z]/q,P=L/q;if(y[z]=q,z!==F&&(L=-P*v[z-1],v[z-1]=W*v[z-1]),f)for(let Z=0;Z<n;Z++)q=W*w.get(Z,z)+P*w.get(Z,N-1),w.set(Z,N-1,-P*w.get(Z,z)+W*w.get(Z,N-1)),w.set(Z,z,q)}break}case 2:{let L=v[F-1];v[F-1]=0;for(let z=F;z<N;z++){let q=pn(y[z],L),W=y[z]/q,P=L/q;if(y[z]=q,L=-P*v[z],v[z]=W*v[z],c)for(let Z=0;Z<r;Z++)q=W*p.get(Z,z)+P*p.get(Z,F-1),p.set(Z,F-1,-P*p.get(Z,z)+W*p.get(Z,F-1)),p.set(Z,z,q)}break}case 3:{const L=Math.max(Math.abs(y[N-1]),Math.abs(y[N-2]),Math.abs(v[N-2]),Math.abs(y[F]),Math.abs(v[F])),z=y[N-1]/L,q=y[N-2]/L,W=v[N-2]/L,P=y[F]/L,Z=v[F]/L,Y=((q+z)*(q-z)+W*W)/2,G=z*W*(z*W);let X=0;(Y!==0||G!==0)&&(Y<0?X=0-Math.sqrt(Y*Y+G):X=Math.sqrt(Y*Y+G),X=G/(Y+X));let ut=(P+z)*(P-z)+X,_t=P*Z;for(let at=F;at<N-1;at++){let vt=pn(ut,_t);vt===0&&(vt=Number.MIN_VALUE);let wt=ut/vt,Ct=_t/vt;if(at!==F&&(v[at-1]=vt),ut=wt*y[at]+Ct*v[at],v[at]=wt*v[at]-Ct*y[at],_t=Ct*y[at+1],y[at+1]=wt*y[at+1],f)for(let bt=0;bt<n;bt++)vt=wt*w.get(bt,at)+Ct*w.get(bt,at+1),w.set(bt,at+1,-Ct*w.get(bt,at)+wt*w.get(bt,at+1)),w.set(bt,at,vt);if(vt=pn(ut,_t),vt===0&&(vt=Number.MIN_VALUE),wt=ut/vt,Ct=_t/vt,y[at]=vt,ut=wt*v[at]+Ct*y[at+1],y[at+1]=-Ct*v[at]+wt*y[at+1],_t=Ct*v[at+1],v[at+1]=wt*v[at+1],c&&at<r-1)for(let bt=0;bt<r;bt++)vt=wt*p.get(bt,at)+Ct*p.get(bt,at+1),p.set(bt,at+1,-Ct*p.get(bt,at)+wt*p.get(bt,at+1)),p.set(bt,at,vt)}v[N-2]=ut;break}case 4:{if(y[F]<=0&&(y[F]=y[F]<0?-y[F]:0,f))for(let L=0;L<=S;L++)w.set(L,F,-w.get(L,F));for(;F<S&&!(y[F]>=y[F+1]);){let L=y[F];if(y[F]=y[F+1],y[F+1]=L,f&&F<n-1)for(let z=0;z<n;z++)L=w.get(z,F+1),w.set(z,F+1,w.get(z,F)),w.set(z,F,L);if(c&&F<r-1)for(let z=0;z<r;z++)L=p.get(z,F+1),p.set(z,F+1,p.get(z,F)),p.set(z,F,L);F++}N--;break}}}if(d){let F=w;w=p,p=F}this.m=r,this.n=n,this.s=y,this.U=p,this.V=w}solve(t){let e=t,r=this.threshold,n=this.s.length,s=dt.zeros(n,n);for(let _=0;_<n;_++)Math.abs(this.s[_])<=r?s.set(_,_,0):s.set(_,_,1/this.s[_]);let a=this.U,u=this.rightSingularVectors,c=u.mmul(s),f=u.rows,d=a.rows,h=dt.zeros(f,d);for(let _=0;_<f;_++)for(let g=0;g<d;g++){let y=0;for(let p=0;p<n;p++)y+=c.get(_,p)*a.get(g,p);h.set(_,g,y)}return h.mmul(e)}solveForDiagonal(t){return this.solve(dt.diag(t))}inverse(){let t=this.V,e=this.threshold,r=t.rows,n=t.columns,s=new dt(r,this.s.length);for(let d=0;d<r;d++)for(let h=0;h<n;h++)Math.abs(this.s[h])>e&&s.set(d,h,t.get(d,h)/this.s[h]);let a=this.U,u=a.rows,c=a.columns,f=new dt(r,u);for(let d=0;d<r;d++)for(let h=0;h<u;h++){let _=0;for(let g=0;g<c;g++)_+=s.get(d,g)*a.get(h,g);f.set(d,h,_)}return f}get condition(){return this.s[0]/this.s[Math.min(this.m,this.n)-1]}get norm2(){return this.s[0]}get rank(){let t=Math.max(this.m,this.n)*this.s[0]*Number.EPSILON,e=0,r=this.s;for(let n=0,s=r.length;n<s;n++)r[n]>t&&e++;return e}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 dt.diag(this.s)}}function Hy(i,t=!1){return i=wr.checkMatrix(i),t?new Oi(i).inverse():_h(i,dt.eye(i.rows))}function _h(i,t,e=!1){return i=wr.checkMatrix(i),t=wr.checkMatrix(t),e?new Oi(i).solve(t):i.isSquare()?new _o(i).solve(t):new eu(i).solve(t)}function po(i){if(i=dt.checkMatrix(i),i.isSquare()){if(i.columns===0)return 1;let t,e,r,n;if(i.columns===2)return t=i.get(0,0),e=i.get(0,1),r=i.get(1,0),n=i.get(1,1),t*n-e*r;if(i.columns===3){let s,a,u;return s=new ho(i,[1,2],[1,2]),a=new ho(i,[1,2],[0,2]),u=new ho(i,[1,2],[0,1]),t=i.get(0,0),e=i.get(0,1),r=i.get(0,2),t*po(s)-e*po(a)+r*po(u)}else return new _o(i).determinant}else throw Error("determinant can only be calculated for a square matrix")}function Zy(i,t){let e=[];for(let r=0;r<i;r++)r!==t&&e.push(r);return e}function Ky(i,t,e,r=1e-9,n=1e-9){if(i>n)return new Array(t.rows+1).fill(0);{let s=t.addRow(e,[0]);for(let a=0;a<s.rows;a++)Math.abs(s.get(a,0))<r&&s.set(a,0,0);return s.to1DArray()}}function Gy(i,t={}){const{thresholdValue:e=1e-9,thresholdError:r=1e-9}=t;i=dt.checkMatrix(i);let n=i.rows,s=new dt(n,n);for(let a=0;a<n;a++){let u=dt.columnVector(i.getRow(a)),c=i.subMatrixRow(Zy(n,a)).transpose(),d=new Oi(c).solve(u),h=dt.sub(u,c.mmul(d)).abs().max();s.setRow(a,Ky(h,d,a,e,r))}return s}function Jy(i,t=Number.EPSILON){if(i=dt.checkMatrix(i),i.isEmpty())return i.transpose();let e=new Oi(i,{autoTranspose:!0}),r=e.leftSingularVectors,n=e.rightSingularVectors,s=e.diagonal;for(let a=0;a<s.length;a++)Math.abs(s[a])>t?s[a]=1/s[a]:s[a]=0;return n.mmul(dt.diag(s).mmul(r.transpose()))}function Xy(i,t=i,e={}){i=new dt(i);let r=!1;if(typeof t=="object"&&!dt.isMatrix(t)&&!fr.isAnyArray(t)?(e=t,t=i,r=!0):t=new dt(t),i.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:n=!0}=e;n&&(i=i.center("column"),r||(t=t.center("column")));const s=i.transpose().mmul(t);for(let a=0;a<s.rows;a++)for(let u=0;u<s.columns;u++)s.set(a,u,s.get(a,u)*(1/(i.rows-1)));return s}function Qy(i,t=i,e={}){i=new dt(i);let r=!1;if(typeof t=="object"&&!dt.isMatrix(t)&&!fr.isAnyArray(t)?(e=t,t=i,r=!0):t=new dt(t),i.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:n=!0,scale:s=!0}=e;n&&(i.center("column"),r||t.center("column")),s&&(i.scale("column"),r||t.scale("column"));const a=i.standardDeviation("column",{unbiased:!0}),u=r?a:t.standardDeviation("column",{unbiased:!0}),c=i.transpose().mmul(t);for(let f=0;f<c.rows;f++)for(let d=0;d<c.columns;d++)c.set(f,d,c.get(f,d)*(1/(a[f]*u[d]))*(1/(i.rows-1)));return c}let ph=class{constructor(t,e={}){const{assumeSymmetric:r=!1}=e;if(t=wr.checkMatrix(t),!t.isSquare())throw new Error("Matrix is not a square matrix");if(t.isEmpty())throw new Error("Matrix must be non-empty");let n=t.columns,s=new dt(n,n),a=new Float64Array(n),u=new Float64Array(n),c=t,f,d,h=!1;if(r?h=!0:h=t.isSymmetric(),h){for(f=0;f<n;f++)for(d=0;d<n;d++)s.set(f,d,c.get(f,d));tw(n,u,a,s),ew(n,u,a,s)}else{let _=new dt(n,n),g=new Float64Array(n);for(d=0;d<n;d++)for(f=0;f<n;f++)_.set(f,d,c.get(f,d));rw(n,_,g,s),nw(n,u,a,s,_)}this.n=n,this.e=u,this.d=a,this.V=s}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let t=this.n,e=this.e,r=this.d,n=new dt(t,t),s,a;for(s=0;s<t;s++){for(a=0;a<t;a++)n.set(s,a,0);n.set(s,s,r[s]),e[s]>0?n.set(s,s+1,e[s]):e[s]<0&&n.set(s,s-1,e[s])}return n}};function tw(i,t,e,r){let n,s,a,u,c,f,d,h;for(c=0;c<i;c++)e[c]=r.get(i-1,c);for(u=i-1;u>0;u--){for(h=0,a=0,f=0;f<u;f++)h=h+Math.abs(e[f]);if(h===0)for(t[u]=e[u-1],c=0;c<u;c++)e[c]=r.get(u-1,c),r.set(u,c,0),r.set(c,u,0);else{for(f=0;f<u;f++)e[f]/=h,a+=e[f]*e[f];for(n=e[u-1],s=Math.sqrt(a),n>0&&(s=-s),t[u]=h*s,a=a-n*s,e[u-1]=n-s,c=0;c<u;c++)t[c]=0;for(c=0;c<u;c++){for(n=e[c],r.set(c,u,n),s=t[c]+r.get(c,c)*n,f=c+1;f<=u-1;f++)s+=r.get(f,c)*e[f],t[f]+=r.get(f,c)*n;t[c]=s}for(n=0,c=0;c<u;c++)t[c]/=a,n+=t[c]*e[c];for(d=n/(a+a),c=0;c<u;c++)t[c]-=d*e[c];for(c=0;c<u;c++){for(n=e[c],s=t[c],f=c;f<=u-1;f++)r.set(f,c,r.get(f,c)-(n*t[f]+s*e[f]));e[c]=r.get(u-1,c),r.set(u,c,0)}}e[u]=a}for(u=0;u<i-1;u++){if(r.set(i-1,u,r.get(u,u)),r.set(u,u,1),a=e[u+1],a!==0){for(f=0;f<=u;f++)e[f]=r.get(f,u+1)/a;for(c=0;c<=u;c++){for(s=0,f=0;f<=u;f++)s+=r.get(f,u+1)*r.get(f,c);for(f=0;f<=u;f++)r.set(f,c,r.get(f,c)-s*e[f])}}for(f=0;f<=u;f++)r.set(f,u+1,0)}for(c=0;c<i;c++)e[c]=r.get(i-1,c),r.set(i-1,c,0);r.set(i-1,i-1,1),t[0]=0}function ew(i,t,e,r){let n,s,a,u,c,f,d,h,_,g,y,p,w,v,x,b;for(a=1;a<i;a++)t[a-1]=t[a];t[i-1]=0;let C=0,E=0,A=Number.EPSILON;for(f=0;f<i;f++){for(E=Math.max(E,Math.abs(e[f])+Math.abs(t[f])),d=f;d<i&&!(Math.abs(t[d])<=A*E);)d++;if(d>f)do{for(n=e[f],h=(e[f+1]-n)/(2*t[f]),_=pn(h,1),h<0&&(_=-_),e[f]=t[f]/(h+_),e[f+1]=t[f]*(h+_),g=e[f+1],s=n-e[f],a=f+2;a<i;a++)e[a]-=s;for(C=C+s,h=e[d],y=1,p=y,w=y,v=t[f+1],x=0,b=0,a=d-1;a>=f;a--)for(w=p,p=y,b=x,n=y*t[a],s=y*h,_=pn(h,t[a]),t[a+1]=x*_,x=t[a]/_,y=h/_,h=y*e[a]-x*n,e[a+1]=s+x*(y*n+x*e[a]),c=0;c<i;c++)s=r.get(c,a+1),r.set(c,a+1,x*r.get(c,a)+y*s),r.set(c,a,y*r.get(c,a)-x*s);h=-x*b*w*v*t[f]/g,t[f]=x*h,e[f]=y*h}while(Math.abs(t[f])>A*E);e[f]=e[f]+C,t[f]=0}for(a=0;a<i-1;a++){for(c=a,h=e[a],u=a+1;u<i;u++)e[u]<h&&(c=u,h=e[u]);if(c!==a)for(e[c]=e[a],e[a]=h,u=0;u<i;u++)h=r.get(u,a),r.set(u,a,r.get(u,c)),r.set(u,c,h)}}function rw(i,t,e,r){let n=0,s=i-1,a,u,c,f,d,h,_;for(h=n+1;h<=s-1;h++){for(_=0,f=h;f<=s;f++)_=_+Math.abs(t.get(f,h-1));if(_!==0){for(c=0,f=s;f>=h;f--)e[f]=t.get(f,h-1)/_,c+=e[f]*e[f];for(u=Math.sqrt(c),e[h]>0&&(u=-u),c=c-e[h]*u,e[h]=e[h]-u,d=h;d<i;d++){for(a=0,f=s;f>=h;f--)a+=e[f]*t.get(f,d);for(a=a/c,f=h;f<=s;f++)t.set(f,d,t.get(f,d)-a*e[f])}for(f=0;f<=s;f++){for(a=0,d=s;d>=h;d--)a+=e[d]*t.get(f,d);for(a=a/c,d=h;d<=s;d++)t.set(f,d,t.get(f,d)-a*e[d])}e[h]=_*e[h],t.set(h,h-1,_*u)}}for(f=0;f<i;f++)for(d=0;d<i;d++)r.set(f,d,f===d?1:0);for(h=s-1;h>=n+1;h--)if(t.get(h,h-1)!==0){for(f=h+1;f<=s;f++)e[f]=t.get(f,h-1);for(d=h;d<=s;d++){for(u=0,f=h;f<=s;f++)u+=e[f]*r.get(f,d);for(u=u/e[h]/t.get(h,h-1),f=h;f<=s;f++)r.set(f,d,r.get(f,d)+u*e[f])}}}function nw(i,t,e,r,n){let s=i-1,a=0,u=i-1,c=Number.EPSILON,f=0,d=0,h=0,_=0,g=0,y=0,p=0,w=0,v,x,b,C,E,A,N,S,I,F,O,L,z,q,W;for(v=0;v<i;v++)for((v<a||v>u)&&(e[v]=n.get(v,v),t[v]=0),x=Math.max(v-1,0);x<i;x++)d=d+Math.abs(n.get(v,x));for(;s>=a;){for(C=s;C>a&&(y=Math.abs(n.get(C-1,C-1))+Math.abs(n.get(C,C)),y===0&&(y=d),!(Math.abs(n.get(C,C-1))<c*y));)C--;if(C===s)n.set(s,s,n.get(s,s)+f),e[s]=n.get(s,s),t[s]=0,s--,w=0;else if(C===s-1){if(N=n.get(s,s-1)*n.get(s-1,s),h=(n.get(s-1,s-1)-n.get(s,s))/2,_=h*h+N,p=Math.sqrt(Math.abs(_)),n.set(s,s,n.get(s,s)+f),n.set(s-1,s-1,n.get(s-1,s-1)+f),S=n.get(s,s),_>=0){for(p=h>=0?h+p:h-p,e[s-1]=S+p,e[s]=e[s-1],p!==0&&(e[s]=S-N/p),t[s-1]=0,t[s]=0,S=n.get(s,s-1),y=Math.abs(S)+Math.abs(p),h=S/y,_=p/y,g=Math.sqrt(h*h+_*_),h=h/g,_=_/g,x=s-1;x<i;x++)p=n.get(s-1,x),n.set(s-1,x,_*p+h*n.get(s,x)),n.set(s,x,_*n.get(s,x)-h*p);for(v=0;v<=s;v++)p=n.get(v,s-1),n.set(v,s-1,_*p+h*n.get(v,s)),n.set(v,s,_*n.get(v,s)-h*p);for(v=a;v<=u;v++)p=r.get(v,s-1),r.set(v,s-1,_*p+h*r.get(v,s)),r.set(v,s,_*r.get(v,s)-h*p)}else e[s-1]=S+h,e[s]=S+h,t[s-1]=p,t[s]=-p;s=s-2,w=0}else{if(S=n.get(s,s),I=0,N=0,C<s&&(I=n.get(s-1,s-1),N=n.get(s,s-1)*n.get(s-1,s)),w===10){for(f+=S,v=a;v<=s;v++)n.set(v,v,n.get(v,v)-S);y=Math.abs(n.get(s,s-1))+Math.abs(n.get(s-1,s-2)),S=I=.75*y,N=-.4375*y*y}if(w===30&&(y=(I-S)/2,y=y*y+N,y>0)){for(y=Math.sqrt(y),I<S&&(y=-y),y=S-N/((I-S)/2+y),v=a;v<=s;v++)n.set(v,v,n.get(v,v)-y);f+=y,S=I=N=.964}for(w=w+1,E=s-2;E>=C&&(p=n.get(E,E),g=S-p,y=I-p,h=(g*y-N)/n.get(E+1,E)+n.get(E,E+1),_=n.get(E+1,E+1)-p-g-y,g=n.get(E+2,E+1),y=Math.abs(h)+Math.abs(_)+Math.abs(g),h=h/y,_=_/y,g=g/y,!(E===C||Math.abs(n.get(E,E-1))*(Math.abs(_)+Math.abs(g))<c*(Math.abs(h)*(Math.abs(n.get(E-1,E-1))+Math.abs(p)+Math.abs(n.get(E+1,E+1))))));)E--;for(v=E+2;v<=s;v++)n.set(v,v-2,0),v>E+2&&n.set(v,v-3,0);for(b=E;b<=s-1&&(q=b!==s-1,b!==E&&(h=n.get(b,b-1),_=n.get(b+1,b-1),g=q?n.get(b+2,b-1):0,S=Math.abs(h)+Math.abs(_)+Math.abs(g),S!==0&&(h=h/S,_=_/S,g=g/S)),S!==0);b++)if(y=Math.sqrt(h*h+_*_+g*g),h<0&&(y=-y),y!==0){for(b!==E?n.set(b,b-1,-y*S):C!==E&&n.set(b,b-1,-n.get(b,b-1)),h=h+y,S=h/y,I=_/y,p=g/y,_=_/h,g=g/h,x=b;x<i;x++)h=n.get(b,x)+_*n.get(b+1,x),q&&(h=h+g*n.get(b+2,x),n.set(b+2,x,n.get(b+2,x)-h*p)),n.set(b,x,n.get(b,x)-h*S),n.set(b+1,x,n.get(b+1,x)-h*I);for(v=0;v<=Math.min(s,b+3);v++)h=S*n.get(v,b)+I*n.get(v,b+1),q&&(h=h+p*n.get(v,b+2),n.set(v,b+2,n.get(v,b+2)-h*g)),n.set(v,b,n.get(v,b)-h),n.set(v,b+1,n.get(v,b+1)-h*_);for(v=a;v<=u;v++)h=S*r.get(v,b)+I*r.get(v,b+1),q&&(h=h+p*r.get(v,b+2),r.set(v,b+2,r.get(v,b+2)-h*g)),r.set(v,b,r.get(v,b)-h),r.set(v,b+1,r.get(v,b+1)-h*_)}}}if(d!==0){for(s=i-1;s>=0;s--)if(h=e[s],_=t[s],_===0)for(C=s,n.set(s,s,1),v=s-1;v>=0;v--){for(N=n.get(v,v)-h,g=0,x=C;x<=s;x++)g=g+n.get(v,x)*n.get(x,s);if(t[v]<0)p=N,y=g;else if(C=v,t[v]===0?n.set(v,s,N!==0?-g/N:-g/(c*d)):(S=n.get(v,v+1),I=n.get(v+1,v),_=(e[v]-h)*(e[v]-h)+t[v]*t[v],A=(S*y-p*g)/_,n.set(v,s,A),n.set(v+1,s,Math.abs(S)>Math.abs(p)?(-g-N*A)/S:(-y-I*A)/p)),A=Math.abs(n.get(v,s)),c*A*A>1)for(x=v;x<=s;x++)n.set(x,s,n.get(x,s)/A)}else if(_<0)for(C=s-1,Math.abs(n.get(s,s-1))>Math.abs(n.get(s-1,s))?(n.set(s-1,s-1,_/n.get(s,s-1)),n.set(s-1,s,-(n.get(s,s)-h)/n.get(s,s-1))):(W=mo(0,-n.get(s-1,s),n.get(s-1,s-1)-h,_),n.set(s-1,s-1,W[0]),n.set(s-1,s,W[1])),n.set(s,s-1,0),n.set(s,s,1),v=s-2;v>=0;v--){for(F=0,O=0,x=C;x<=s;x++)F=F+n.get(v,x)*n.get(x,s-1),O=O+n.get(v,x)*n.get(x,s);if(N=n.get(v,v)-h,t[v]<0)p=N,g=F,y=O;else if(C=v,t[v]===0?(W=mo(-F,-O,N,_),n.set(v,s-1,W[0]),n.set(v,s,W[1])):(S=n.get(v,v+1),I=n.get(v+1,v),L=(e[v]-h)*(e[v]-h)+t[v]*t[v]-_*_,z=(e[v]-h)*2*_,L===0&&z===0&&(L=c*d*(Math.abs(N)+Math.abs(_)+Math.abs(S)+Math.abs(I)+Math.abs(p))),W=mo(S*g-p*F+_*O,S*y-p*O-_*F,L,z),n.set(v,s-1,W[0]),n.set(v,s,W[1]),Math.abs(S)>Math.abs(p)+Math.abs(_)?(n.set(v+1,s-1,(-F-N*n.get(v,s-1)+_*n.get(v,s))/S),n.set(v+1,s,(-O-N*n.get(v,s)-_*n.get(v,s-1))/S)):(W=mo(-g-I*n.get(v,s-1),-y-I*n.get(v,s),p,_),n.set(v+1,s-1,W[0]),n.set(v+1,s,W[1]))),A=Math.max(Math.abs(n.get(v,s-1)),Math.abs(n.get(v,s))),c*A*A>1)for(x=v;x<=s;x++)n.set(x,s-1,n.get(x,s-1)/A),n.set(x,s,n.get(x,s)/A)}for(v=0;v<i;v++)if(v<a||v>u)for(x=v;x<i;x++)r.set(v,x,n.get(v,x));for(x=i-1;x>=a;x--)for(v=a;v<=u;v++){for(p=0,b=a;b<=Math.min(x,u);b++)p=p+r.get(v,b)*n.get(b,x);r.set(v,x,p)}}}function mo(i,t,e,r){let n,s;return Math.abs(e)>Math.abs(r)?(n=r/e,s=e+n*r,[(i+n*t)/s,(t-n*i)/s]):(n=e/r,s=r+n*e,[(n*i+t)/s,(n*t-i)/s])}class mh{constructor(t){if(t=wr.checkMatrix(t),!t.isSymmetric())throw new Error("Matrix is not symmetric");let e=t,r=e.rows,n=new dt(r,r),s=!0,a,u,c;for(u=0;u<r;u++){let f=0;for(c=0;c<u;c++){let d=0;for(a=0;a<c;a++)d+=n.get(c,a)*n.get(u,a);d=(e.get(u,c)-d)/n.get(c,c),n.set(u,c,d),f=f+d*d}for(f=e.get(u,u)-f,s&=f>0,n.set(u,u,Math.sqrt(Math.max(f,0))),c=u+1;c<r;c++)n.set(u,c,0)}this.L=n,this.positiveDefinite=!!s}isPositiveDefinite(){return this.positiveDefinite}solve(t){t=wr.checkMatrix(t);let e=this.L,r=e.rows;if(t.rows!==r)throw new Error("Matrix dimensions do not match");if(this.isPositiveDefinite()===!1)throw new Error("Matrix is not positive definite");let n=t.columns,s=t.clone(),a,u,c;for(c=0;c<r;c++)for(u=0;u<n;u++){for(a=0;a<c;a++)s.set(c,u,s.get(c,u)-s.get(a,u)*e.get(c,a));s.set(c,u,s.get(c,u)/e.get(c,c))}for(c=r-1;c>=0;c--)for(u=0;u<n;u++){for(a=c+1;a<r;a++)s.set(c,u,s.get(c,u)-s.get(a,u)*e.get(a,c));s.set(c,u,s.get(c,u)/e.get(c,c))}return s}get lowerTriangularMatrix(){return this.L}}class gh{constructor(t,e={}){t=wr.checkMatrix(t);let{Y:r}=e;const{scaleScores:n=!1,maxIterations:s=1e3,terminationCriteria:a=1e-10}=e;let u;if(r){if(fr.isAnyArray(r)&&typeof r[0]=="number"?r=dt.columnVector(r):r=wr.checkMatrix(r),r.rows!==t.rows)throw new Error("Y should have the same number of rows as X");u=r.getColumnVector(0)}else u=t.getColumnVector(0);let c=1,f,d,h,_;for(let g=0;g<s&&c>a;g++)h=t.transpose().mmul(u).div(u.transpose().mmul(u).get(0,0)),h=h.div(h.norm()),f=t.mmul(h).div(h.transpose().mmul(h).get(0,0)),g>0&&(c=f.clone().sub(_).pow(2).sum()),_=f.clone(),r?(d=r.transpose().mmul(f).div(f.transpose().mmul(f).get(0,0)),d=d.div(d.norm()),u=r.mmul(d).div(d.transpose().mmul(d).get(0,0))):u=f;if(r){let g=t.transpose().mmul(f).div(f.transpose().mmul(f).get(0,0));g=g.div(g.norm());let y=t.clone().sub(f.clone().mmul(g.transpose())),p=u.transpose().mmul(f).div(f.transpose().mmul(f).get(0,0)),w=r.clone().sub(f.clone().mulS(p.get(0,0)).mmul(d.transpose()));this.t=f,this.p=g.transpose(),this.w=h.transpose(),this.q=d,this.u=u,this.s=f.transpose().mmul(f),this.xResidual=y,this.yResidual=w,this.betas=p}else this.w=h.transpose(),this.s=f.transpose().mmul(f).sqrt(),n?this.t=f.clone().div(this.s.get(0,0)):this.t=f,this.xResidual=t.sub(f.mmul(h.transpose()))}}zt.AbstractMatrix=$t,zt.CHO=mh,zt.CholeskyDecomposition=mh,zt.DistanceMatrix=fo,zt.EVD=ph;var iw=zt.EigenvalueDecomposition=ph;zt.LU=_o,zt.LuDecomposition=_o;var vh=zt.Matrix=dt;zt.MatrixColumnSelectionView=ky,zt.MatrixColumnView=Py,zt.MatrixFlipColumnView=zy,zt.MatrixFlipRowView=qy,zt.MatrixRowSelectionView=Wy,zt.MatrixRowView=Uy,zt.MatrixSelectionView=ho,zt.MatrixSubView=jy,zt.MatrixTransposeView=Yy,zt.NIPALS=gh,zt.Nipals=gh,zt.QR=eu,zt.QrDecomposition=eu,zt.SVD=Oi,zt.SingularValueDecomposition=Oi,zt.SymmetricMatrix=ri,zt.WrapperMatrix1D=dh,zt.WrapperMatrix2D=wr,zt.correlation=Qy,zt.covariance=Xy;var yh=zt.default=dt;zt.determinant=po,zt.inverse=Hy,zt.linearDependencies=Gy,zt.pseudoInverse=Jy,zt.solve=_h,zt.wrap=Vy;const wh=iw,Dh=vh;yh.Matrix&&yh.Matrix;class sw{constructor(t){$(this,"_errorListener");this._errorListener=t}new({rows:t,columns:e,initial_value:r}={}){return new ru(t,e,r,this._errorListener)}avg({id:t}){return t==null?void 0:t.avg()}col({id:t,column:e}){return t==null?void 0:t.col({column:e})}det({id:t}){return t==null?void 0:t.det()}get({id:t,row:e,column:r}){return t==null?void 0:t.get({row:e,column:r})}inv({id:t}){return t==null?void 0:t.inv()}max({id:t}){return t==null?void 0:t.max()}min({id:t}){return t==null?void 0:t.min()}pow({id:t,power:e}){return t==null?void 0:t.pow({power:e})}row({id:t,row:e}){return t==null?void 0:t.row({row:e})}set({id:t,row:e,column:r,value:n}){t==null||t.set({row:e,column:r,value:n})}sum({id1:t,id2:e}){return t==null?void 0:t.sum({id2:e})}copy({id:t}){return t==null?void 0:t.copy()}diff({id1:t,id2:e}){return t==null?void 0:t.diff({id2:e})}rows({id:t}){return t==null?void 0:t.rows()}columns({id:t}){return t==null?void 0:t.columns()}fill({id:t,value:e,from_row:r,to_row:n,from_column:s,to_column:a}){t==null||t.fill({value:e,from_row:r,to_row:n,from_column:s,to_column:a})}kron({id1:t,id2:e}){return t==null?void 0:t.kron({id2:e})}mode({id:t}){return t==null?void 0:t.mode()}mult({id1:t,id2:e}){return t==null?void 0:t.mult({id2:e})}pinv({id:t}){return t==null?void 0:t.pinv()}rank({id:t}){return t==null?void 0:t.rank()}sort({id:t,column:e,order:r}){t==null||t.sort({column:e,order:r})}trace({id:t}){return t==null?void 0:t.trace()}concat({id1:t,id2:e}){return t==null?void 0:t.concat({id2:e})}median({id:t}){return t==null?void 0:t.median()}add_col({id:t,column:e,array_id:r}){t==null||t.add_col({column:e,array_id:r})}add_row({id:t,row:e,array_id:r}){t==null||t.add_row({row:e,array_id:r})}is_zero({id:t}){return t==null?void 0:t.is_zero()}reshape({id:t,rows:e,columns:r},n){return t==null?void 0:t.reshape({rows:e,columns:r},n)}reverse({id:t}){t==null||t.reverse()}is_binary({id:t}){return t==null?void 0:t.is_binary()}is_square({id:t}){return t==null?void 0:t.is_square()}submatrix({id:t,from_row:e,to_row:r,from_column:n,to_column:s}){return t==null?void 0:t.submatrix({from_row:e,to_row:r,from_column:n,to_column:s})}swap_rows({id:t,row1:e,row2:r}){t==null||t.swap_rows({row1:e,row2:r})}transpose({id:t}){return t==null?void 0:t.transpose()}remove_col({id:t,column:e}){return t==null?void 0:t.remove_col({column:e})}remove_row({id:t,row:e}){return t==null?void 0:t.remove_row({row:e})}eigenvalues({id:t}){return t==null?void 0:t.eigenvalues()}is_diagonal({id:t}){return t==null?void 0:t.is_diagonal()}is_identity({id:t}){return t==null?void 0:t.is_identity()}eigenvectors({id:t}){return t==null?void 0:t.eigenvectors()}is_symmetric({id:t}){return t==null?void 0:t.is_symmetric()}swap_columns({id:t,column1:e,column2:r}){t==null||t.swap_columns({column1:e,column2:r})}is_stochastic({id:t}){return t==null?void 0:t.is_stochastic()}is_triangular({id:t}){return t==null?void 0:t.is_triangular()}elements_count({id:t}){return t==null?void 0:t.elements_count()}is_antidiagonal({id:t}){return t==null?void 0:t.is_antidiagonal()}is_antisymmetric({id:t}){return t==null?void 0:t.is_antisymmetric()}}class ru{constructor(t=0,e=0,r=void 0,n){$(this,"_matrixInstance");$(this,"_errorListener");this._matrixInstance=this._createMatrix(t,e,r),this._errorListener=n}get _matrixArray(){return this._matrixInstance.map(t=>[...t._value])}get _value(){return this._matrixInstance}set _value(t){this._matrixInstance=t}get isMatrix(){return!0}_createMatrix(t,e,r){return Array.from(new Array(t),()=>new ee(e,r,this._errorListener))}avg(){let t=0,e=0;for(const n of this._matrixInstance)for(const s of n._value)t+=mt(s)?0:s,e+=1;return t/e}col({column:t}){const e=[],r=new ee(0,void 0,this._errorListener);if(mt(t))return r;for(const n of this._matrixInstance)e.push(n._value[t]);return r._value=e,r}det(){return oh(this._matrixArray)}get({row:t,column:e}){var r,n;if(!(mt(t)||mt(e)))return(n=(r=this._matrixInstance[t])==null?void 0:r._value)==null?void 0:n[e]}inv(){const t=ao(this._matrixArray);return this._newMatrix(t)}max(){return ty(this._matrixArray)}min(){return Ja(this._matrixArray)}pow({power:t}){const e=mt(t)?this._matrixArray:ry(this._matrixArray,t);return this._newMatrix(e)}row({row:t}){return mt(t)?new ee(0,void 0,this._errorListener):this._matrixInstance[t]}set({row:t,column:e,value:r}){mt(t)||mt(e)||this._matrixInstance[t].set({index:e,value:r})}sum({id2:t}){const e=os(this._matrixArray,typeof t=="number"?t:t._matrixArray);return this._newMatrix(e)}copy(){return this._newMatrix(this._matrixArray)}diff({id2:t}){const e=Z1(this._matrixArray,typeof t=="number"?t:t._matrixArray);return this._newMatrix(e)}rows(){return this._matrixInstance.length}columns(){return this._matrixArray.length&&this._matrixArray[0].length}fill({value:t,from_row:e,to_row:r,from_column:n,to_column:s}={}){mt(e)&&(e=0),mt(r)&&(r=this.rows()),mt(n)&&(n=0),mt(s)&&(s=this.columns());for(const[a,u]of this._matrixInstance.entries())for(const[c]of u._value.entries())a<r&&a>=e&&c>=n&&c<s&&u.set({index:c,value:t})}kron({id2:t}){const e=V1(this._matrixArray,t._matrixArray);return this._newMatrix(e)}mode(){return Ja(Qf(this._matrixArray))}mult({id2:t}){const e=typeof t=="number"?t:t._matrixArray?t._matrixArray:t._value,r=Mi(this._matrixArray,e);return this._newMatrix(r)}pinv(){const t=ey(this._matrixArray);return this._newMatrix(t)}rank(){return this._matrixRank(this._matrixArray)}sort({column:t,order:e=Gn.ascending}={}){mt(t)&&(t=0),this._matrixInstance.sort((r,n)=>{const s=r._value[t],a=n._value[t];return e!==Gn.descending?s-a:a-s})}trace(){return Q1(this._matrixArray)}concat({id2:t}){for(const e of t._value)this._matrixInstance.push(e);return this}median(){return ah(this._matrixArray)}add_col({column:t,array_id:e}={}){mt(t)&&(t=this.columns());for(const[r,n]of this._matrixInstance.entries())n.insert({index:t,value:e?e._value[r]:void 0})}add_row({row:t,array_id:e}){mt(t)&&(t=this.rows()),this._matrixInstance.splice(t,0,e||new ee(this.columns(),void 0,this._errorListener))}is_zero(){return this._matrixArray.every(t=>t.every(e=>e===0))}reshape({rows:t=0,columns:e=0},r){if(t*e!==this.columns()*this.rows()){this._errorListener.addError(ie.matrixRehapeErr,r,Rt.Error);return}const n=U1(this._matrixArray,[t,e]);this._matrixInstance=n.map(s=>{const a=new ee(0,void 0,this._errorListener);return a._value=[...s],a})}reverse(){this._matrixInstance.reverse();for(const t of this._matrixInstance)t.reverse()}is_binary(){return this._matrixArray.every(t=>t.every(e=>e===0||e===1))}is_square(){return this.rows()===this.columns()}submatrix({from_row:t,to_row:e,from_column:r,to_column:n}={}){mt(t)&&(t=0),mt(e)&&(e=this.rows()),mt(r)&&(r=0),mt(n)&&(n=this.columns());const s=this._matrixArray.splice(t,e),a=[];for(const u of s)a.push(u.splice(r,n));return this._newMatrix(a)}swap_rows({row1:t,row2:e}){if(mt(t)||mt(e))return;const r=this._matrixInstance[t],n=this._matrixInstance[e];this._matrixInstance[t]=n,this._matrixInstance[e]=r}transpose(){const t=eh(this._matrixArray);return this._newMatrix(t)}remove_col({column:t}={}){mt(t)&&(t=this.columns());const e=[];for(const n of this._matrixInstance){const s=n._value.splice(t,1);e.push(s[0])}const r=new ee(0,void 0,this._errorListener);return r._value=e,r}remove_row({row:t}={}){return mt(t)&&(t=this.rows()),this._matrixInstance.splice(t,1)[0]}eigenvalues(){const t=new wh(new Dh(this._matrixArray)),e=new ee(0,void 0,this._errorListener);return e._value=t.realEigenvalues,e}is_diagonal(){const t=this.rows(),e=this.columns();if(t!==e)return!1;const r=this._matrixArray;for(let n=0;n<t;n++)for(let s=0;s<e;s++)if(n!==s&&r[n][s]!==0)return!1;return!0}is_identity(){const t=this.rows(),e=this.columns();if(t!==e)return!1;const r=this._matrixArray;for(let n=0;n<t;n++)for(let s=0;s<e;s++)if(n!==s&&r[n][s]!==0||n===s&&r[n][s]!==1)return!1;return!0}eigenvectors(){const t=new wh(new Dh(this._matrixArray));return this._newMatrix(t.eigenvectorMatrix.to2DArray())}is_symmetric(){const t=this.rows(),e=this.columns();if(t!==e)return!1;const r=this._matrixArray;for(let n=0;n<t;n++)for(let s=n+1;s<e;s++)if(r[n][s]!==r[s][n])return!1;return!0}swap_columns({column1:t,column2:e}){if(!(mt(t)||mt(e)))for(const r of this._matrixInstance){const n=r._value[t],s=r._value[e];r.set({index:t,value:s}),r.set({index:e,value:n})}}is_stochastic(){const t=this._matrixArray;for(let e=0;e<t.length;e++){let r=0;for(let n=0;n<t[e].length;n++){if(t[e][n]<0)return!1;r+=t[e][n]}if(Math.abs(r-1)>Number.EPSILON)return!1}return!0}is_triangular(){const t=this.rows(),e=this.columns();return t!==e?!1:this._isUpperTriangular(t)||this._isLowerTriangular(t)}elements_count(){return W1(this._matrixArray)}is_antidiagonal(){const t=this.rows(),e=this.columns();if(t!==e)return!1;const r=this._matrixArray;for(let n=0;n<t;n++)for(let s=0;s<t;s++)if(n+s!==t-1&&r[n][s]!==0)return!1;return!0}is_antisymmetric(){const t=this.rows(),e=this.columns();if(t!==e)return!1;const r=this._matrixArray;for(let n=0;n<t;n++)for(let s=0;s<t;s++)if(n!==s&&r[n][s]!==-r[s][n])return!1;return!0}_isUpperTriangular(t){const e=this._matrixArray;for(let r=1;r<t;r++)for(let n=0;n<r;n++)if(e[r][n]!==0)return!1;return!0}_isLowerTriangular(t){const e=this._matrixArray;for(let r=0;r<t-1;r++)for(let n=r+1;n<t;n++)if(e[r][n]!==0)return!1;return!0}_newMatrix(t){const e=new ru(0,0,void 0,this._errorListener);return e._value=t.map(r=>{const n=new ee(0,void 0,this._errorListener);return n._value=[...r],n}),e}_matrixRank(t){let e=0;const r=t.length,n=t[0].length,s=[...t].map(a=>[...a]);for(let a=0;a<r&&!(a>=n);a++){let u=a;for(;u<r&&s[u][a]===0;)u++;if(u===r)continue;if(u!==a){const f=s[u];s[u]=s[a],s[a]=f}const c=s[a][a];for(let f=0;f<n;f++)s[a][f]/=c;for(let f=a+1;f<r;f++){const d=s[f][a];s[f]=s[f].map((h,_)=>h-d*s[a][_]),s[f][a]=0}}for(let a=0;a<r;a++)s[a].some(u=>Number(u.toFixed(8))!==0)&&e++;return e}}class ow{constructor(t){$(this,"_variables");$(this,"_cacheData");this._variables=t,this._cacheData={}}change({timeframe:t},e){if(!t)return!0;const{time:r,__period:n}=this._variables,s=gr(t,r),a=gr(n,r);if(s<a)return!0;const u=`change_${e}`,c=this._cacheData[u],f=this._variables.time;if(c){if(c.offset){if(c.currentTime+c.offset<=f)return this._cacheData[u]={currentTime:f,offset:0},!0}else if(c.currentTime+s*1e3<=f)return this._cacheData[u]={currentTime:f,offset:0},!0}else{const d=this._calcTimeOffset(f,t);return this._cacheData[u]={currentTime:f,offset:d},!1}return!1}in_seconds({timeframe:t}={}){const{time:e,__period:r}=this._variables;return gr(t||r,e)}from_seconds({seconds:t=0}){const e=t*1e3,r=Wt.duration(e);if(r.years())return"12M";const s=r.asMonths();if(so(s))return`${s}M`;const a=r.asWeeks();if(so(a))return`${a}M`;const u=r.asDays();if(u>=1)return`${Math.ceil(u)}D`;const c=r.asMinutes();if(c>=1)return`${Math.ceil(c)}`;const f=r.asSeconds();return f<=1?"1S":f<=5?"5S":f<=10?"10S":f<=15?"15S":f<=30?"30S":"1"}_calcTimeOffset(t,e){let r=0;if(e.includes("W")){const u=Wt(t).day();e="1D",u!==1&&(r=(8-u)*60*60*24*1e3)}else if(e.includes("M")){const u=Wt(t).date();e="1D";const c=Wt(t).daysInMonth();u!==1&&(r=(c-u+1)*60*60*24*1e3)}const n=this._variables.getTimeTradingday(t,e),s=gr(e,t)*1e3,a=t-n-Math.floor((t-n)/s)*s;return r?r-a:a}}var bh={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){var e={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};return function(r,n,s){var a=n.prototype,u=a.format;s.en.formats=e,a.format=function(c){c===void 0&&(c="YYYY-MM-DDTHH:mm:ssZ");var f=this.$locale().formats,d=function(h,_){return h.replace(/(\[[^\]]+])|(LTS?|l{1,4}|L{1,4})/g,function(g,y,p){var w=p&&p.toUpperCase();return y||_[p]||e[p]||_[w].replace(/(\[[^\]]+])|(MMMM|MM|DD|dddd)/g,function(v,x,b){return x||b.slice(1)})})}(c,f===void 0?{}:f);return u.call(this,d)}}})})(bh);var aw=bh.exports,uw=Kt(aw);Wt.extend(uw);class lw{constructor(t,e){$(this,"_errorListener");$(this,"_intlNumberFormatter");$(this,"_precision");$(this,"_intlFormat");this._errorListener=t,this._precision=e,this._intlNumberFormatter=new Intl.NumberFormat("en",{notation:"compact"}),this._intlFormat=new Intl.NumberFormat("en-US")}pos({source:t="",str:e=""}){return t==null?void 0:t.indexOf(e)}trim({source:t=""}){return t==null?void 0:t.trim()}lower({source:t=""}){return t==null?void 0:t.toLocaleLowerCase()}match({source:t="",regex:e=""}){const r=t==null?void 0:t.match(new RegExp(e));return r?r[0]:""}split({string:t="",separator:e=""}){const r=t==null?void 0:t.split(e),n=new ee;return n._value=r||[],n}upper({source:t=""}){return t==null?void 0:t.toLocaleUpperCase()}format({formatString:t=""},e){return this._strFormat(t,e)}length({string:t=""}){return t==null?void 0:t.length}repeat({source:t="",repeat:e,separator:r=""},n){if(mt(e)){this._errorListener.addError(ie.arrLenErr,n,Rt.Error);return}return Array.from(new Array(e),()=>t).join(r)}replace({source:t="",target:e="",replacement:r="",occurrence:n}){mt(n)&&(n=0);let s=-1;for(let a=0;a<n+1&&(s=t.indexOf(e,s+1),s!==-1);a++);return s!==-1?t.substring(0,s)+r+t.substring(s+e.length):t}contains({source:t="",str:e=""}){return t==null?void 0:t.includes(e)}endswith({source:t="",str:e=""}){return t==null?void 0:t.endsWith(e)}tonumber({string:t=""}){if(/[^\d.]/.test(t))return;const e=parseFloat(t);return isNaN(e)?void 0:e}tostring({value:t,format:e}){if(t===void 0)return"NaN";if(typeof t=="object"){if(t.isArray)return this._arrToStr(t._value,e);if(t.isMatrix){const r=[];for(const n of t._matrixArray)r.push(this._arrToStr(n,e));return r.join(`
62
- `)}}if(typeof t=="string")return t;if(typeof t=="boolean")return String(t);if(typeof t=="number")return String(this._toStringFormat(t,e==null?void 0:e.replace(/0/g,"#")))}_arrToStr(t,e){return`[${t.map(n=>typeof n=="number"?this._toStringFormat(n,e):n).toString()}]`}substring({source:t="",begin_pos:e=0,end_pos:r}){return mt(e)&&(e=0),mt(r)&&(r=void 0),t==null?void 0:t.substring(e,r)}startswith({source:t="",str:e=""}){return t==null?void 0:t.startsWith(e)}format_time({time:t,format:e="yyyy-MM-dd'T'HH:mm:ssZ",timezone:r}){return mt(t)&&(t=0),mr(t,r).format(e)}replace_all({source:t="",target:e="",replacement:r=""}){return t==null?void 0:t.replace(new RegExp(e,"g"),r)}_toStringFormat(t,e){if(!e)return Number(t.toFixed(this._precision));switch(e){case Gt.mintick:return t.toFixed(this._precision);case Gt.percent:return`${t}%`;case Gt.volume:return this._intlNumberFormatter.format(Math.round(t));default:return this._formatOthers(t,e)}}_formatOthers(t,e){var u;let[r,n]=e.split(".");e.split("%").length===2&&(t=t*100);let[s,a=""]=String(t).split(".");if(r.includes("#")){if(r.includes(",")){const c=r.split(","),f=((u=c[c.length-1])==null?void 0:u.replace(/[^#]/g,"").length)||0;f&&(s=s.replace(new RegExp(`\\B(?=(\\d{${f}})+(?!\\d))`,"g"),",")),r=c.join("")}s=r.replace(/#/,s).replace(/#/g,"")}else s=`${r}${s}`;if(n&&n.includes("#")){const c=n.split("#").length-1,f=+`${s}.${a}`;if(!isNaN(f))return`${f.toFixed(c)}${n.replace(/#/g,"")}`;a=`${a.substring(0,c)}${n.replace(/#/g,"")}`}else a=n||"";return a?`${s}.${a}`:s}_formatNumber(t,e){if(!e)return Number(t.toFixed(this._precision));switch(e){case"integer":return String(Math.round(t));case"currency":return`$${t}`;case"percent":return`${t*100}%`;default:return this._formatOthers(t,e)}}strformat({formatString:t=""},e,r){return this._strFormat(t,e,r)}_strFormat(t,e,r){return t.replace(/{[^{}]+}/g,n=>{if(!n)return n;const s=n.replace(/[{}]/g,"").split(","),a=Number(s[0]);if(isNaN(a)||e.length<=a)return n;const u=e[a];if(s.length===1)return typeof u=="number"&&r?this._intlFormat.format(u):u;if(s.length===2){const c=s[1].trim();return c==="number"?r?this._intlFormat.format(u):u:c==="date"?Wt(u).format("LL"):n}else{const c=s[1].trim(),f=s[2].trim();if(c==="number")return this._formatNumber(u,f);if(c==="date"){let d="YYYY-MM-DD";switch(f){case"long":d="LL";break;case"short":d="L";break;default:f&&(d=f)}return Wt(u).format(d)}return n}})}}class cw{constructor(t){$(this,"_errorListener");this._errorListener=t}new(){return new nu(this._errorListener)}copy({id:t}){return t==null?void 0:t.copy()}get({id:t,key:e}){return t==null?void 0:t.get({key:e})}put({id:t,key:e,value:r}){return t==null?void 0:t.put({key:e,value:r})}keys({id:t}){return t==null?void 0:t.keys()}size({id:t}){return t==null?void 0:t.size()}clear({id:t}){t==null||t.clear()}remove({id:t,key:e}){return t==null?void 0:t.remove({key:e})}values({id:t}){return t==null?void 0:t.values()}put_all({id:t,id2:e}){t==null||t.put_all({id2:e})}contains({id:t,key:e}){return t==null?void 0:t.contains({key:e})}}class nu{constructor(t){$(this,"_errorListener");$(this,"_mapInstance");this._errorListener=t,this._mapInstance=new Map}get isMap(){return!0}_copyMap(t){const e=new nu(this._errorListener);return e._mapInstance=new Map(t.entries()),e}copy(){return this._copyMap(this._mapInstance)}get({key:t}){return this._mapInstance.get(t)}put({key:t,value:e}){return this._mapInstance.set(t,e)}keys(){const t=new ee(0,void 0,this._errorListener);return t._value=[...this._mapInstance.keys()],t}size(){return this._mapInstance.size}clear(){this._mapInstance.clear()}remove({key:t}){const e=this._mapInstance.get(t);return this._mapInstance.delete(t),e||void 0}values(){const t=new ee(0,void 0,this._errorListener);return t._value=[...this._mapInstance.values()],t}put_all({id2:t}){this._mapInstance=new Map([...this._mapInstance,...t._mapInstance])}contains({key:t}){return this._mapInstance.has(t)}}class fw{constructor(t){$(this,"_variables");this._variables=t}new({price:t,time:e,index:r}){return new Bi(t,r,e)}now({price:t}){const{time:e,bar_index:r}=this._variables;return new Bi(t,r,e)}copy({id:t}){return t==null?void 0:t.copy()}from_index({price:t,index:e}){return new Bi(t,e)}from_time({price:t,time:e}){return new Bi(t,void 0,e)}}class Bi{constructor(t,e,r){$(this,"_index");$(this,"_price");$(this,"_time");this._index=e,this._price=t,this._time=r}get index(){return this._index}set index(t){this._index=t}get price(){return this._price}set price(t){this._price=t}get time(){return this._time}set time(t){this._time=t}copy(){return new Bi(this._price,this._index,this._time)}}class hw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultLabel",{text:"",xloc:be.bar_index,yloc:Vr.price,size:ir.normal,style:ye.styleLabelDown,textalign:jt.alignCenter});this._variables=t,this._errorListener=e}new(t,e){const{time:r,high:n,low:s,bar_index:a}=this._variables,u=`label_${e}_${a}`;ve(t,["color","textcolor"]);const c={...this._defaultLabel,...t,id:u,time:r,high:n,low:s,bar_index:a};t.point&&(c.x=c.xloc===be.bar_index?t.point.index:t.point.time,c.y=t.point.price),c.yloc===Vr.abovebar?c.y=n:c.yloc===Vr.belowbar&&(c.y=s),this._verfiyArgs(t,e);const f=new go(u,this._variables,this._errorListener);return e.startsWith("export")||this._variables.label.add(u,c,f),f}_verfiyArgs(t,e){const{xloc:r,yloc:n,style:s,size:a,textalign:u,text_font_family:c}=t,f="label.new";this._paramVerfiy(s,e,f,Object.values(ye),"style"),this._paramVerfiy(r,e,f,Object.values(be),"xloc"),this._paramVerfiy(n,e,f,Object.values(Vr),"yloc"),this._paramVerfiy(a,e,f,Object.values(ir),"size"),this._paramVerfiy(u,e,f,[jt.alignLeft,jt.alignCenter,jt.alignRight],"textalign"),this._paramVerfiy(c,e,f,Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}label(t){return t.x}copy({id:t},e){return t==null?void 0:t.copy(e)}get_x({id:t},e){return t==null?void 0:t.get_x(e)}get_y({id:t},e){return t==null?void 0:t.get_y(e)}set_x({id:t,...e},r){t==null||t.set_x(e,r)}set_y({id:t,...e},r){t==null||t.set_y(e,r)}delete({id:t}){t==null||t.delete()}get_text({id:t},e){return t==null?void 0:t.get_text(e)}set_xy({id:t,...e},r){t==null||t.set_xy(e,r)}set_size({id:t,...e},r){t==null||t.set_size(e,r)}set_xloc({id:t,...e},r){t==null||t.set_xloc(e,r)}set_yloc({id:t,...e},r){t==null||t.set_yloc(e,r)}set_style({id:t,...e},r){t==null||t.set_style(e,r)}set_color({id:t,...e},r){t==null||t.set_color(e,r)}set_tooltip({id:t,...e},r){t==null||t.set_tooltip(e,r)}set_point({id:t,...e},r){t==null||t.set_point(e,r)}set_text({id:t,...e},r){t==null||t.set_text(e,r)}set_textcolor({id:t,...e},r){t==null||t.set_textcolor(e,r)}set_textalign({id:t,...e},r){t==null||t.set_textalign(e,r)}set_text_font_family({id:t,...e},r){t==null||t.set_text_font_family(e,r)}}class go{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");this._id=t,this._variables=e,this._errorListener=r}get type(){return te.LABEL}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.label.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`label_${t}_${e}`,n=this._getLabel(t),s=new go(r,this._variables,this._errorListener);if(n){const a={...n,id:r,bar_index:e};this._variables.label.add(r,a,s)}return s}get_x(t){var e;return(e=this._getLabel(t))==null?void 0:e.x}get_y(t){var e;return(e=this._getLabel(t))==null?void 0:e.y}set_x({x:t},e){const r=this._getLabel(e);r&&(r.x=t)}set_y({y:t},e){const r=this._getLabel(e);r&&(r.y=t)}delete(){this._variables.label.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}set_xy({x:t,y:e},r){const n=this._getLabel(r);n&&(n.x=t,n.y=e)}get_text(t){var e;return(e=this._getLabel(t))==null?void 0:e.text}set_size({size:t},e){const r=this._getLabel(e);r&&(r.size=t),this._paramVerfiy(t,e,"label.set_size",Object.values(ir),"size")}set_text({text:t},e){const r=this._getLabel(e);r&&(r.text=t)}set_xloc({x:t,xloc:e},r){const n=this._getLabel(r);n&&(n.x=t,n.xloc=e,this._paramVerfiy(e,r,"label.set_xloc",Object.values(be),"xloc"))}set_yloc({yloc:t},e){const r=this._getLabel(e),{high:n,low:s}=this._variables;r&&(r.yloc=t,t===Vr.abovebar?r.y=n:t===Vr.belowbar&&(r.y=s),this._paramVerfiy(t,e,"label.set_yloc",Object.values(Vr),"yloc"))}set_color(t,e){const r=this._getLabel(e);ve(t,["color"]),r&&(r.color=t.color)}set_point({point:t},e){const r=this._getLabel(e);r&&(r.x=r.xloc===be.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,r.y=t==null?void 0:t.price)}set_style({style:t},e){const r=this._getLabel(e);r&&(r.style=t),this._paramVerfiy(t,e,"label.set_style",Object.values(ye),"style")}set_tooltip({tooltip:t},e){const r=this._getLabel(e);r&&(r.tooltip=t)}set_textalign({textalign:t},e){const r=this._getLabel(e);r&&(r.textalign=t),this._paramVerfiy(t,e,"label.set_textalign",[jt.alignLeft,jt.alignCenter,jt.alignRight],"textalign")}set_textcolor(t,e){const r=this._getLabel(e);ve(t,["textcolor"]),r&&(r.textcolor=t.textcolor)}set_text_font_family({text_font_family:t},e){const r=this._getLabel(e);r&&(r.text_font_family=t),this._paramVerfiy(t,e,"label.set_text_font_family",Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getLabel(t){const e=this._variables.label.get(this._id);return e||console.log(`错误${t}: label 不存在`),e}}const dw={freq_all:jr.freqAll,freq_once_per_bar:jr.freqOncePerBar,freq_once_per_bar_close:jr.freqOncePerBarClose},_w={gaps_off:ln.gapsOff,gaps_on:ln.gapsOn,lookahead_off:ln.lookaheadOff,lookahead_on:ln.lookaheadOn},Ti={aqua:"#00BCD4",black:"#363A45",blue:"#2196F3",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"},xh={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"},pw={friday:6,monday:2,saturday:7,sunday:1,thursday:5,tuesday:3,wednesday:4},Eh={all:[Ze.dataWindow,Ze.pane,Ze.priceScale,Ze.statusLine],data_window:[Ze.dataWindow],none:[],pane:[Ze.pane],price_scale:[Ze.priceScale],status_line:[Ze.statusLine]},mw={both:Yr.both,left:Yr.left,none:Yr.none,right:Yr.right},gw={inherit:Gt.inherit,mintick:Gt.mintick,percent:Gt.percent,price:Gt.price,volume:Gt.volume},vw={style_solid:Ss.styleSolid,style_dashed:Ss.styleDashed,style_dotted:Ss.styleDotted},yw={style_arrowdown:ye.styleArrowdown,style_arrowup:ye.styleArrowup,style_circle:ye.styleCircle,style_cross:ye.styleCross,style_diamond:ye.styleDiamond,style_flag:ye.styleFlag,style_label_center:ye.styleLabelCenter,style_label_down:ye.styleLabelDown,style_label_left:ye.styleLabelLeft,style_label_lower_left:ye.styleLabelLowerLeft,style_label_lower_right:ye.styleLabelLowerRight,style_label_right:ye.styleLabelRight,style_label_up:ye.styleLabelUp,style_label_upper_left:ye.styleLabelUpperLeft,style_label_upper_right:ye.styleLabelUpperRight,style_none:ye.styleNone,style_square:ye.styleSquare,style_text_outline:ye.styleTextOutline,style_triangledown:ye.styleTriangledown,style_triangleup:ye.styleTriangleup,style_xcross:ye.styleXcross},ww={style_arrow_both:Re.styleArrowBoth,style_arrow_left:Re.styleArrowLeft,style_arrow_right:Re.styleArrowRight,style_dashed:Re.styleDashed,style_dotted:Re.styleDotted,style_solid:Re.styleSolid},Dw={abovebar:cn.abovebar,absolute:cn.absolute,belowbar:cn.belowbar,bottom:cn.bottom,top:cn.top},bw={e:2.718281828459045,phi:1.618033988749895,pi:3.141592653589793,rphi:.6180339887498948},xw={style_area:Or.styleArea,style_areabr:Or.styleAreabr,style_circles:Or.styleCircles,style_columns:Or.styleColumns,style_cross:Or.styleCross,style_histogram:Or.styleHistogram,style_line:Or.styleLine,style_linebr:Or.styleLinebr,style_stepline:Or.styleStepline,style_stepline_diamond:Or.styleSteplineDiamond,style_steplinebr:Or.styleSteplinebr},Ew={bottom_center:vr.bottomCenter,bottom_left:vr.bottomLeft,bottom_right:vr.bottomRight,middle_center:vr.middleCenter,middle_left:vr.middleLeft,middle_right:vr.middleRight,top_center:vr.topCenter,top_left:vr.topLeft,top_right:vr.topRight},Cw={left:Os.left,none:Os.none,right:Os.right},Aw={arrowdown:lr.arrowdown,arrowup:lr.arrowup,circle:lr.circle,cross:lr.cross,diamond:lr.diamond,flag:lr.flag,labeldown:lr.labeldown,labelup:lr.labelup,square:lr.square,triangledown:lr.triangledown,triangleup:lr.triangleup,xcross:lr.xcross},Mw={auto:ir.auto,huge:ir.huge,large:ir.large,normal:ir.normal,small:ir.small,tiny:ir.tiny},Fw={cash:Pe.cash,fixed:Pe.fixed,percent_of_equity:Pe.percentOfEquity,commission:{cash_per_contract:je.cashPerContract,cash_per_order:je.cashPerOrder,percent:je.percent},direction:{all:fe.all,long:fe.long,short:fe.short},oca:{cancel:fn.cancel,none:fn.none,reduce:fn.reduce}},Nw={align_bottom:jt.alignBottom,align_center:jt.alignCenter,align_left:jt.alignLeft,align_right:jt.alignRight,align_top:jt.alignTop,wrap_auto:jt.wrapAuto,wrap_none:jt.wrapNone},Sw={bar_index:be.bar_index,bar_time:be.bar_time},Ow={abovebar:Vr.abovebar,belowbar:Vr.belowbar,price:Vr.price},Bw={actual:Bs.actual,estimate:Bs.estimate,standardized:Bs.standardized};class Ch{constructor(){$(this,"adjustment",{dividends:Ns.dividends,none:Ns.none,splits:Ns.splits});$(this,"alert",dw);$(this,"barmerge",_w);$(this,"color",Ti);$(this,"currency",xh);$(this,"dayofweek",pw);$(this,"earnings",Bw);$(this,"display",Eh);$(this,"extend",mw);$(this,"font",{family_default:Jn.familyDefault,family_monospace:Jn.familyMonospace});$(this,"format",gw);$(this,"hline",vw);$(this,"label",yw);$(this,"line",ww);$(this,"location",Dw);$(this,"math",bw);$(this,"order",{ascending:Gn.ascending,descending:Gn.descending});$(this,"plot",xw);$(this,"position",Ew);$(this,"scale",Cw);$(this,"session",{extended:Mn.extended,regular:Mn.regular});$(this,"shape",Aw);$(this,"size",Mw);$(this,"splits",{denominator:"denominator",numerator:"numerator"});$(this,"strategy",Fw);$(this,"text",Nw);$(this,"xloc",Sw);$(this,"yloc",Ow)}updateData(){}}class Tw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultPolyline",{curved:!1,closed:!1,xloc:be.bar_index,line_color:Ti.blue,line_style:Re.styleSolid,line_width:1});this._variables=t,this._errorListener=e}new(t,e){var u;const{bar_index:r}=this._variables,n=`polyline_${e}_${r}`,s=Object.assign({},this._defaultPolyline,t,{id:n,bar_index:r,points:(u=t.points)==null?void 0:u._value.map(c=>({time:c.time,index:c.index,price:c.price}))});ve(s,["line_color","fill_color"]);const a=new Ah(n,this._variables);return this._verfiyArgs(t,e),e.startsWith("export")||this._variables.polyline.add(n,s,a),a}_verfiyArgs(t,e){const{line_style:r,xloc:n}=t,s="polyline.new";this._paramVerfiy(r,e,s,Object.values(Re),"line_style"),this._paramVerfiy(n,e,s,Object.values(be),"xloc")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}delete({id:t}){t&&t.delete()}}class Ah{constructor(t,e){$(this,"_id");$(this,"_variables");$(this,"_suffix");this._variables=e,this._id=t}get type(){return te.POLYLINE}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.polyline.get(this._id)}delete(){this._variables.polyline.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}}class Iw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultLine",{xloc:be.bar_index,extend:Yr.none,style:Re.styleSolid});this._variables=t,this._errorListener=e}new({first_point:t,second_point:e,...r},n){const{bar_index:s}=this._variables,a=`line_${n}_${s}`;ve(r,["color"]);const u={...this._defaultLine,...r,id:a,bar_index:s};if(t&&e){const f=u.xloc===be.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,d=u.xloc===be.bar_index?e==null?void 0:e.index:e==null?void 0:e.time;Object.assign(u,{x1:f,y1:t==null?void 0:t.price,x2:d,y2:e==null?void 0:e.price})}this._verfiyArgs(r,n);const c=new vo(a,this._variables,this._errorListener);return n.startsWith("export")||this._variables.line.add(a,u,c),c}_verfiyArgs(t,e){const{extend:r,xloc:n,style:s}=t,a="line.new";this._paramVerfiy(s,e,a,Object.values(Re),"style"),this._paramVerfiy(r,e,a,Object.values(Yr),"extend"),this._paramVerfiy(n,e,a,Object.values(be),"xloc")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}line(t){return t.x}copy({id:t},e){return t==null?void 0:t.copy(e)}delete({id:t}){t==null||t.delete()}get_x1({id:t},e){return t==null?void 0:t.get_x1(e)}get_x2({id:t},e){return t==null?void 0:t.get_x2(e)}get_y1({id:t},e){return t==null?void 0:t.get_y1(e)}get_y2({id:t},e){return t==null?void 0:t.get_y2(e)}set_x1({id:t,...e},r){t==null||t.set_x1(e,r)}set_x2({id:t,...e},r){t==null||t.set_x2(e,r)}set_y1({id:t,...e},r){t==null||t.set_y1(e,r)}set_y2({id:t,...e},r){t==null||t.set_y2(e,r)}set_xy1({id:t,...e},r){t==null||t.set_xy1(e,r)}set_xy2({id:t,...e},r){t==null||t.set_xy2(e,r)}set_xloc({id:t,...e},r){t==null||t.set_xloc(e,r)}get_price({id:t,...e},r){return t==null?void 0:t.get_price(e,r)}set_color({id:t,...e},r){t==null||t.set_color(e,r)}set_style({id:t,...e},r){t==null||t.set_style(e,r)}set_width({id:t,...e},r){t==null||t.set_width(e,r)}set_extend({id:t,...e},r){t==null||t.set_extend(e,r)}set_first_point({id:t,...e},r){t==null||t.set_first_point(e,r)}set_second_point({id:t,...e},r){t==null||t.set_second_point(e,r)}}class vo{constructor(t,e,r){$(this,"_variables");$(this,"_id");$(this,"_suffix","");$(this,"_errorListener");this._id=t,this._variables=e,this._errorListener=r}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get type(){return te.LINE}get data(){return this._variables.line.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`line_${t}_${e}`,n=this._getLine(t),s=new vo(r,this._variables,this._errorListener);return n&&this._variables.line.add(r,{...n,id:r,bar_index:e,isVar:void 0},s),s}delete(){this._variables.line.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_price({x:t},e){const r=this._getLine(e);if(t===void 0)return t;if(r&&r.xloc===be.bar_index){const{x1:n,y1:s,x2:a,y2:u}=r;return n===void 0||a===void 0||s===void 0||u===void 0?void 0:(u-s)/(a-n)*(t-n)+s}}get_x1(t){var e;return(e=this._getLine(t))==null?void 0:e.x1}get_x2(t){var e;return(e=this._getLine(t))==null?void 0:e.x2}get_y1(t){var e;return(e=this._getLine(t))==null?void 0:e.y1}get_y2(t){var e;return(e=this._getLine(t))==null?void 0:e.y2}set_x1({x:t},e){const r=this._getLine(e);r&&(r.x1=t)}set_x2({x:t},e){const r=this._getLine(e);r&&(r.x2=t)}set_y1({y:t},e){const r=this._getLine(e);r&&(r.y1=t)}set_y2({y:t},e){const r=this._getLine(e);r&&(r.y2=t)}set_xy1({x:t,y:e},r){const n=this._getLine(r);n&&(n.x1=t,n.y1=e)}set_xy2({x:t,y:e},r){const n=this._getLine(r);n&&(n.x2=t,n.y2=e)}set_xloc({xloc:t,x1:e,x2:r},n){const s=this._getLine(n);s&&(s.xloc=t,s.x1=e,s.x2=r,this._paramVerfiy(t,n,"line.set_xloc",Object.values(be),"xloc"))}set_color(t,e){const r=this._getLine(e);r&&(ve(t,["color"]),r.color=t.color)}set_style({style:t},e){const r=this._getLine(e);r&&(r.style=t,this._paramVerfiy(t,e,"line.set_style",Object.values(Re),"style"))}set_width({width:t},e){const r=this._getLine(e);r&&(r.width=t)}set_extend({extend:t},e){const r=this._getLine(e);r&&(r.extend=t,this._paramVerfiy(t,e,"line.set_extend",Object.values(Yr),"extend"))}set_first_point({point:t},e){const r=this._getLine(e);if(r){const{index:n,time:s,price:a}=t||{},u=r.xloc===be.bar_index?n:s,c=a;u&&(r.x1=u),c&&(r.y1=c)}}set_second_point({point:t},e){const r=this._getLine(e);if(r){const{index:n,time:s,price:a}=t||{},u=r.xloc===be.bar_index?n:s,c=a;u&&(r.x2=u),c&&(r.y2=c)}}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getLine(t){const e=this._variables.line.get(this._id);return e||console.log(`${t}: line 不存在`),e}}class $w{constructor(t){$(this,"_variables");this._variables=t}new(t,e){const{line1:r,line2:n}=t,{bar_index:s}=this._variables,a=`linefill_${e}_${s}`,u=r==null?void 0:r.data,c=n==null?void 0:n.data;u&&(u.linefills=u.linefills||[],u.linefills.push(a)),c&&(c.linefills=c.linefills||[],c.linefills.push(a)),ve(t,["color"]);const f=new yo(this._variables,a,r,n);return e.startsWith("export")||(u||c)&&this._variables.linefill.add(a,{line1:u,line2:c,color:t.color,id:a,bar_index:s},f),f}delete({id:t}){t==null||t.delete()}get_line1({id:t}){return t==null?void 0:t.get_line1()}get_line2({id:t}){return t==null?void 0:t.get_line2()}set_color({id:t,...e}){t==null||t.set_color(e)}}class yo{constructor(t,e,r,n){$(this,"_id");$(this,"_line1");$(this,"_line2");$(this,"_variables");$(this,"_suffix");this._variables=t,this._id=e,this._line1=r,this._line2=n}get type(){return te.LINEFILL}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.linefill.get(this._id)}linefill(t,e){return t.x?t.x:new yo(this._variables,e)}delete(){var e,r;const t=this._variables.linefill.get(this._id);if(t){const{line1:n,line2:s}=t;n&&(n.linefills=(e=n.linefills)==null?void 0:e.filter(a=>a!==this._id)),s&&(s.linefills=(r=s.linefills)==null?void 0:r.filter(a=>a!==this._id))}this._line1=void 0,this._line2=void 0,this._variables.linefill.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_line1(){return this._line1}get_line2(){return this._line2}set_color(t){const e=this._variables.linefill.get(this._id);e&&(ve(t,["color"]),e.color=t.color)}}class Lw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultBox",{border_color:Ti.blue,border_width:1,bgcolor:Ti.blue,xloc:be.bar_index,extend:Yr.none,style:Re.styleSolid,text:"",text_size:ir.auto,text_color:Ti.black,text_halign:jt.alignCenter,text_valign:jt.alignCenter,text_wrap:jt.wrapNone});this._variables=t,this._errorListener=e}box({x:t}){return t}new({top_left:t,bottom_right:e,...r},n){const{bar_index:s}=this._variables,a=`box_${n}_${s}`,u={...this._defaultBox,...r,id:a,bar_index:s};if(ve(u,["border_color","bgcolor","text_color"]),t){const{price:f,time:d,index:h}=t;u.top=f,u.left=u.xloc===be.bar_index?h:d}if(e){const{price:f,time:d,index:h}=e;u.bottom=f,u.right=u.xloc===be.bar_index?h:d}this._verfiyArgs(r,n);const c=new wo(this._variables,a,this._errorListener);return n.startsWith("export")||this._variables.box.add(a,u,c),c}_verfiyArgs(t,e){const{border_style:r,extend:n,xloc:s,text_size:a,text_halign:u,text_valign:c,text_wrap:f,text_font_family:d}=t,h="box.new";this._paramVerfiy(r,e,h,[Re.styleDashed,Re.styleDotted,Re.styleSolid],"border_style"),this._paramVerfiy(n,e,h,Object.values(Yr),"extend"),this._paramVerfiy(s,e,h,Object.values(be),"xloc"),this._paramVerfiy(a,e,h,Object.values(ir),"text_size"),this._paramVerfiy(u,e,h,[jt.alignLeft,jt.alignCenter,jt.alignRight],"text_halign"),this._paramVerfiy(c,e,h,[jt.alignBottom,jt.alignCenter,jt.alignTop],"text_valign"),this._paramVerfiy(f,e,h,[jt.wrapAuto,jt.wrapNone],"text_wrap"),this._paramVerfiy(d,e,h,Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}copy({id:t},e){return t==null?void 0:t.copy(e)}delete({id:t}){t==null||t.delete()}get_top({id:t}){return t==null?void 0:t.get_top()}get_bottom({id:t}){return t==null?void 0:t.get_bottom()}get_left({id:t}){return t==null?void 0:t.get_left()}get_right({id:t}){return t==null?void 0:t.get_right()}set_top({id:t,...e}){t==null||t.set_top(e)}set_bottom({id:t,...e}){t==null||t.set_bottom(e)}set_text({id:t,...e}){t==null||t.set_text(e)}set_left({id:t,...e}){t==null||t.set_left(e)}set_right({id:t,...e}){t==null||t.set_right(e)}set_extend({id:t,...e},r){t==null||t.set_extend(e,r)}set_bgcolor({id:t,...e}){t==null||t.set_bgcolor(e)}set_border_color({id:t,...e}){t==null||t.set_border_color(e)}set_border_width({id:t,...e}){t==null||t.set_border_width(e)}set_border_style({id:t,...e},r){t==null||t.set_border_style(e,r)}set_lefttop({id:t,...e}){t==null||t.set_lefttop(e)}set_rightbottom({id:t,...e}){t==null||t.set_rightbottom(e)}set_text_size({id:t,...e},r){t==null||t.set_text_size(e,r)}set_text_wrap({id:t,...e},r){t==null||t.set_text_wrap(e,r)}set_text_color({id:t,...e}){t==null||t.set_text_color(e)}set_text_halign({id:t,...e},r){t==null||t.set_text_halign(e,r)}set_text_valign({id:t,...e},r){t==null||t.set_text_valign(e,r)}set_top_left_point({id:t,...e}){t==null||t.set_top_left_point(e)}set_bottom_right_point({id:t,...e}){t==null||t.set_bottom_right_point(e)}set_text_font_family({id:t,...e},r){t==null||t.set_text_font_family(e,r)}}class wo{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");this._variables=t,this._id=e,this._errorListener=r}get type(){return te.BOX}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.box.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`box_${t}_${e}`,n=this._getBox(),s=new wo(this._variables,r,this._errorListener);return n&&this._variables.box.add(r,{...n,id:r,bar_index:e},s),s}delete(){this._variables.box.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_top(){const t=this._getBox();return t&&t.top}set_top({top:t}){const e=this._getBox();e&&(e.top=t)}get_left(){const t=this._getBox();return t&&t.left}set_left({left:t}){const e=this._getBox();e&&(e.left=t)}set_text({text:t}){const e=this._getBox();e&&(e.text=t)}get_right(){const t=this._getBox();return t&&t.right}set_right({right:t}){const e=this._getBox();e&&(e.right=t)}get_bottom(){const t=this._getBox();return t&&t.bottom}set_bottom({bottom:t}){const e=this._getBox();e&&(e.bottom=t)}set_extend({extend:t},e){const r=this._getBox();r&&(r.extend=t,this._paramVerfiy(t,e,"box.set_extend",Object.values(Yr),"extend"))}set_bgcolor({color:t}){const e=this._getBox();e&&(e.bgcolor=t,ve(e,["bgcolor"]))}set_lefttop({left:t,top:e}){const r=this._getBox();r&&(r.left=t,r.top=e)}set_text_size({text_size:t},e){const r=this._getBox();r&&(r.text_size=t,this._paramVerfiy(t,e,"box.set_text_size",Object.values(ir),"text_size"))}set_text_wrap({text_wrap:t},e){const r=this._getBox();r&&(r.text_wrap=t,this._paramVerfiy(t,e,"box.set_text_wrap",[jt.wrapAuto,jt.wrapNone],"text_wrap"))}set_text_color({text_color:t}){const e=this._getBox();e&&(e.text_color=t,ve(e,["text_color"]))}set_rightbottom({right:t,bottom:e}){const r=this._getBox();r&&(r.right=t,r.bottom=e)}set_text_halign({text_halign:t},e){const r=this._getBox();r&&(r.text_halign=t,this._paramVerfiy(t,e,"box.set_text_halign",[jt.alignLeft,jt.alignCenter,jt.alignRight],"text_halign"))}set_text_valign({text_valign:t},e){const r=this._getBox();r&&(r.text_valign=t,this._paramVerfiy(t,e,"box.set_text_valign",[jt.alignBottom,jt.alignCenter,jt.alignTop],"text_valign"))}set_top_left_point({point:t}){const e=this._getBox();if(e){const{index:r,price:n,time:s}=t||{};e.top=n,e.left=e.xloc===be.bar_index?r:s}}set_border_color({color:t}){const e=this._getBox();e&&(e.border_color=t,ve(e,["border_color"]))}set_border_style({style:t},e){const r=this._getBox();r&&(r.border_style=t,this._paramVerfiy(t,e,"box.set_border_style",[Re.styleDashed,Re.styleDotted,Re.styleSolid],"style"))}set_border_width({width:t}){const e=this._getBox();e&&(e.border_width=t)}set_bottom_right_point({point:t}){const e=this._getBox();if(e){const{index:r,price:n,time:s}=t||{};e.bottom=n,e.right=e.xloc===be.bar_index?r:s}}set_text_font_family({text_font_family:t},e){const r=this._getBox();r&&(r.text_font_family=t,this._paramVerfiy(t,e,"box.set_text_font_family",Object.values(Jn),"text_font_family"))}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getBox(){return this._variables.box.get(this._id)}}class Rw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultTable",{position:vr.topLeft,columns:0,rows:0,frame_width:0,border_width:0});this._variables=t,this._errorListener=e}table({x:t}){return t}new(t,e){const{bar_index:r}=this._variables,n=`table_${e}_${r}`,{rows:s}=t;ve(t,["text_color","bgcolor","border_color"]);const a=Array.from(Array(s),()=>[]),u=e.split("_"),c=u.pop(),f=u.pop(),d={...this._defaultTable,...t,cell:a,id:n,bar_index:r,line:f,col:c},h=new Mh(this._variables,n,this._errorListener);return this._paramVerfiy(t.position,e,"table.new",Object.values(vr),"position"),e.startsWith("export")||this._variables.table.add(n,d,h),h}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}cell({table_id:t,...e}){t==null||t.cell(e)}cell_set_bgcolor({table_id:t,...e}){t==null||t.cell_set_bgcolor(e)}cell_set_height({table_id:t,...e}){t==null||t.cell_set_height(e)}cell_set_text({table_id:t,...e}){t==null||t.cell_set_text(e)}cell_set_text_color({table_id:t,...e}){t==null||t.cell_set_text_color(e)}cell_set_text_font_family({table_id:t,...e}){t==null||t.cell_set_text_font_family(e)}cell_set_text_halign({table_id:t,...e}){t==null||t.cell_set_text_halign(e)}cell_set_text_valign({table_id:t,...e}){t==null||t.cell_set_text_valign(e)}cell_set_text_size({table_id:t,...e}){t==null||t.cell_set_text_size(e)}cell_set_tooltip({table_id:t,...e}){t==null||t.cell_set_tooltip(e)}cell_set_width({table_id:t,...e}){t==null||t.cell_set_width(e)}clear({table_id:t,...e}){t==null||t.clear(e)}delete({table_id:t}){t==null||t.delete()}merge_cells({table_id:t,...e},r){t==null||t.merge_cells(e,r)}set_bgcolor({table_id:t,...e}){t==null||t.set_bgcolor(e)}set_border_color({table_id:t,...e}){t==null||t.set_border_color(e)}set_border_width({table_id:t,...e}){t==null||t.set_border_width(e)}set_frame_color({table_id:t,...e}){t==null||t.set_frame_color(e)}set_frame_width({table_id:t,...e}){t==null||t.set_frame_width(e)}set_position({table_id:t,...e},r){t==null||t.set_position(e,r)}}class Mh{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");$(this,"_defaultCell",{column:0,row:0,text:"",text_color:Ti.black,text_halign:jt.alignCenter,text_valign:jt.alignCenter,text_size:ir.normal});this._variables=t,this._id=e,this._errorListener=r}get type(){return te.TABLE}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.table.get(this._id)}cell(t){const e={...this._defaultCell,...t},{column:r=0,row:n=0}=e,s=this._variables.table.get(this._id);if(s){const a=s.cell||[],u=a[n]||[];u[r]=e,a[n]=u,s.cell=a}}cell_set_bgcolor({column:t=0,row:e=0,bgcolor:r}){const n=this._getTableItem(t,e);n&&(n.bgcolor=r)}cell_set_height({column:t=0,row:e=0,height:r}){const n=this._getTableItem(t,e);n&&(n.height=r)}cell_set_text({column:t=0,row:e=0,text:r}){const n=this._getTableItem(t,e);n&&(n.text=r)}cell_set_text_color({column:t=0,row:e=0,text_color:r}){const n=this._getTableItem(t,e);n&&(n.text_color=r,ve(n,["text_color"]))}cell_set_text_font_family({column:t=0,row:e=0,text_font_family:r}){const n=this._getTableItem(t,e);n&&(n.text_font_family=r)}cell_set_text_halign({column:t=0,row:e=0,text_halign:r}){const n=this._getTableItem(t,e);n&&(n.text_halign=r)}cell_set_text_valign({column:t=0,row:e=0,text_valign:r}){const n=this._getTableItem(t,e);n&&(n.text_valign=r)}cell_set_text_size({column:t=0,row:e=0,text_size:r}){const n=this._getTableItem(t,e);n&&(n.text_size=r)}cell_set_tooltip({column:t=0,row:e=0,tooltip:r}){const n=this._getTableItem(t,e);n&&(n.tooltip=r)}cell_set_width({column:t=0,row:e=0,width:r}){const n=this._getTableItem(t,e);n&&(n.width=r)}clear({start_column:t=0,start_row:e=0,end_column:r=0,end_row:n=0}){const s=this._variables.table.get(this._id);if(s){const a=s.cell;if(a)for(let u=e;u<=n;u++)for(let c=t;c<=r;c++){const f=a[u];f&&(f[c]=void 0)}}}delete(){this._variables.table.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}merge_cells({start_column:t=0,start_row:e=0,end_column:r=0,end_row:n=0},s){if(t>r||e>n){this._errorListener.addError(ie.mergeCellErr,s,Rt.Error);return}const a=this._variables.table.get(this._id);if(!a)return;const u=a.merge_cells||[];u.push({start_column:t,start_row:e,end_column:r,end_row:n}),a.merge_cells=u}set_bgcolor({bgcolor:t}){const e=this._variables.table.get(this._id);e&&(e.bgcolor=t,ve(e,["bgcolor"]))}set_border_color({border_color:t}){const e=this._variables.table.get(this._id);e&&(e.border_color=t,ve(e,["border_color"]))}set_border_width({border_width:t}){const e=this._variables.table.get(this._id);e&&(e.border_width=t)}set_frame_color({frame_color:t}){const e=this._variables.table.get(this._id);e&&(e.frame_color=t)}set_frame_width({frame_width:t}){const e=this._variables.table.get(this._id);e&&(e.frame_width=t)}set_position({position:t},e){const r=this._variables.table.get(this._id);r&&(r.position=t,this._paramVerfiy(t,e,"table.set_position",Object.values(vr),"position"))}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getTableItem(t,e){const r=this._variables.table.get(this._id);if(r){const n=r.cell;return n?n[e][t]:void 0}}}class Pw{constructor(t){$(this,"_strategy");this._strategy=t}commission({trade_num:t}){return this._verifyTradeNum(t)&&this._strategy.historyOrders[t].commission||0}entry_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].in_index}entry_comment({trade_num:t}){if(!this._verifyTradeNum(t))return"";const{comment:e,id:r}=this._strategy.historyOrders[t];return e||r}entry_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].id:""}entry_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].in_price}entry_time({trade_num:t}){if(!this._verifyTradeNum(t))return;const{in_time:e,entry_time:r}=this._strategy.historyOrders[t];return r||e}exit_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_index}exit_comment({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].out_comment:""}exit_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].out_id:""}exit_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_price}exit_time({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_time}max_drawdown({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].trading_loss:0}max_drawdown_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].trading_loss_percent:0}max_runup({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].max_profit:0}max_runup_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].max_profit_percent:0}profit({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].profit:0}profit_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].profit_percent:0}size({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{out_qty:e=0,direction:r}=this._strategy.historyOrders[t];return r===fe.long?e:-e}_verifyTradeNum(t){if(typeof t!="number"||t<0)return!1;const e=this._strategy.historyOrders.length;return!(t>=e)}}class kw{constructor(t){$(this,"_strategy");this._strategy=t}commission({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{qty:e=0,original_qty:r=0,commission:n=0}=this._strategy.orders[t];return n*e/r}entry_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.orders[t].in_index}entry_comment({trade_num:t}){if(!this._verifyTradeNum(t))return"";const{comment:e,id:r}=this._strategy.orders[t];return e||r}entry_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].id:""}entry_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.orders[t].in_price}entry_time({trade_num:t}){if(!this._verifyTradeNum(t))return;const{in_time:e,entry_time:r}=this._strategy.orders[t];return r||e}max_drawdown({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].trading_loss:0}max_drawdown_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].trading_loss_percent:0}max_runup({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].max_profit:0}max_runup_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].max_profit_percent:0}profit({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].profit:0}profit_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].profit_percent:0}size({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{qty:e=0,direction:r}=this._strategy.orders[t];return r===fe.long?e:-e}_verifyTradeNum(t){if(typeof t!="number"||t<0)return!1;const e=this._strategy.orders.length;return!(t>=e)}}class zw{constructor(t,e){$(this,"_strategy");$(this,"_errorListener");this._strategy=t,this._errorListener=e}allow_entry_in({value:t},e){this._paramVerfiy(t,e,"strategy.risk.allow_entry_in",Object.values(fe),"value"),this._strategy.updateRisk({allow_entry_in:t})}max_cons_loss_days({count:t}){this._strategy.updateRisk({max_cons_loss_days:t})}max_drawdown({value:t,type:e},r){this._paramVerfiy(e,r,"strategy.risk.max_drawdown",[Pe.percentOfEquity,Pe.cash],"type"),e===Pe.percentOfEquity&&(t=t>100?100:t),this._strategy.updateRisk({max_drawdown:t,max_drawdown_type:e})}max_intraday_filled_orders({count:t}){this._strategy.updateRisk({max_intraday_filled_orders:t})}max_intraday_loss({value:t,type:e},r){this._paramVerfiy(e,r,"strategy.risk.max_intraday_loss",[Pe.percentOfEquity,Pe.cash],"type"),e===Pe.percentOfEquity&&(t=t>100?100:t),this._strategy.updateRisk({max_intraday_loss:t,max_intraday_loss_type:e})}max_position_size({contracts:t}){this._strategy.updateRisk({max_position_size:t})}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}}var qw=20,Uw=1,ni=1e6,Fh=1e6,Ww=-7,jw=21,Yw=!1,us="[big.js] ",ii=us+"Invalid ",Do=ii+"decimal places",Vw=ii+"rounding mode",Nh=us+"Division by zero",le={},sn=void 0,Hw=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Sh(){function i(t){var e=this;if(!(e instanceof i))return t===sn?Sh():new i(t);if(t instanceof i)e.s=t.s,e.e=t.e,e.c=t.c.slice();else{if(typeof t!="string"){if(i.strict===!0&&typeof t!="bigint")throw TypeError(ii+"value");t=t===0&&1/t<0?"-0":String(t)}Zw(e,t)}e.constructor=i}return i.prototype=le,i.DP=qw,i.RM=Uw,i.NE=Ww,i.PE=jw,i.strict=Yw,i.roundDown=0,i.roundHalfUp=1,i.roundHalfEven=2,i.roundUp=3,i}function Zw(i,t){var e,r,n;if(!Hw.test(t))throw Error(ii+"number");for(i.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(e=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(e<0&&(e=r),e+=+t.slice(r+1),t=t.substring(0,r)):e<0&&(e=t.length),n=t.length,r=0;r<n&&t.charAt(r)=="0";)++r;if(r==n)i.c=[i.e=0];else{for(;n>0&&t.charAt(--n)=="0";);for(i.e=e-r-1,i.c=[],e=0;r<=n;)i.c[e++]=+t.charAt(r++)}return i}function si(i,t,e,r){var n=i.c;if(e===sn&&(e=i.constructor.RM),e!==0&&e!==1&&e!==2&&e!==3)throw Error(Vw);if(t<1)r=e===3&&(r||!!n[0])||t===0&&(e===1&&n[0]>=5||e===2&&(n[0]>5||n[0]===5&&(r||n[1]!==sn))),n.length=1,r?(i.e=i.e-t+1,n[0]=1):n[0]=i.e=0;else if(t<n.length){if(r=e===1&&n[t]>=5||e===2&&(n[t]>5||n[t]===5&&(r||n[t+1]!==sn||n[t-1]&1))||e===3&&(r||!!n[0]),n.length=t,r){for(;++n[--t]>9;)if(n[t]=0,t===0){++i.e,n.unshift(1);break}}for(t=n.length;!n[--t];)n.pop()}return i}function oi(i,t,e){var r=i.e,n=i.c.join(""),s=n.length;if(t)n=n.charAt(0)+(s>1?"."+n.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)n="0"+n;n="0."+n}else if(r>0)if(++r>s)for(r-=s;r--;)n+="0";else r<s&&(n=n.slice(0,r)+"."+n.slice(r));else s>1&&(n=n.charAt(0)+"."+n.slice(1));return i.s<0&&e?"-"+n:n}le.abs=function(){var i=new this.constructor(this);return i.s=1,i},le.cmp=function(i){var t,e=this,r=e.c,n=(i=new e.constructor(i)).c,s=e.s,a=i.s,u=e.e,c=i.e;if(!r[0]||!n[0])return r[0]?s:n[0]?-a:0;if(s!=a)return s;if(t=s<0,u!=c)return u>c^t?1:-1;for(a=(u=r.length)<(c=n.length)?u:c,s=-1;++s<a;)if(r[s]!=n[s])return r[s]>n[s]^t?1:-1;return u==c?0:u>c^t?1:-1},le.div=function(i){var t=this,e=t.constructor,r=t.c,n=(i=new e(i)).c,s=t.s==i.s?1:-1,a=e.DP;if(a!==~~a||a<0||a>ni)throw Error(Do);if(!n[0])throw Error(Nh);if(!r[0])return i.s=s,i.c=[i.e=0],i;var u,c,f,d,h,_=n.slice(),g=u=n.length,y=r.length,p=r.slice(0,u),w=p.length,v=i,x=v.c=[],b=0,C=a+(v.e=t.e-i.e)+1;for(v.s=s,s=C<0?0:C,_.unshift(0);w++<u;)p.push(0);do{for(f=0;f<10;f++){if(u!=(w=p.length))d=u>w?1:-1;else for(h=-1,d=0;++h<u;)if(n[h]!=p[h]){d=n[h]>p[h]?1:-1;break}if(d<0){for(c=w==u?n:_;w;){if(p[--w]<c[w]){for(h=w;h&&!p[--h];)p[h]=9;--p[h],p[w]+=10}p[w]-=c[w]}for(;!p[0];)p.shift()}else break}x[b++]=d?f:++f,p[0]&&d?p[w]=r[g]||0:p=[r[g]]}while((g++<y||p[0]!==sn)&&s--);return!x[0]&&b!=1&&(x.shift(),v.e--,C--),b>C&&si(v,C,e.RM,p[0]!==sn),v},le.eq=function(i){return this.cmp(i)===0},le.gt=function(i){return this.cmp(i)>0},le.gte=function(i){return this.cmp(i)>-1},le.lt=function(i){return this.cmp(i)<0},le.lte=function(i){return this.cmp(i)<1},le.minus=le.sub=function(i){var t,e,r,n,s=this,a=s.constructor,u=s.s,c=(i=new a(i)).s;if(u!=c)return i.s=-c,s.plus(i);var f=s.c.slice(),d=s.e,h=i.c,_=i.e;if(!f[0]||!h[0])return h[0]?i.s=-c:f[0]?i=new a(s):i.s=1,i;if(u=d-_){for((n=u<0)?(u=-u,r=f):(_=d,r=h),r.reverse(),c=u;c--;)r.push(0);r.reverse()}else for(e=((n=f.length<h.length)?f:h).length,u=c=0;c<e;c++)if(f[c]!=h[c]){n=f[c]<h[c];break}if(n&&(r=f,f=h,h=r,i.s=-i.s),(c=(e=h.length)-(t=f.length))>0)for(;c--;)f[t++]=0;for(c=t;e>u;){if(f[--e]<h[e]){for(t=e;t&&!f[--t];)f[t]=9;--f[t],f[e]+=10}f[e]-=h[e]}for(;f[--c]===0;)f.pop();for(;f[0]===0;)f.shift(),--_;return f[0]||(i.s=1,f=[_=0]),i.c=f,i.e=_,i},le.mod=function(i){var t,e=this,r=e.constructor,n=e.s,s=(i=new r(i)).s;if(!i.c[0])throw Error(Nh);return e.s=i.s=1,t=i.cmp(e)==1,e.s=n,i.s=s,t?new r(e):(n=r.DP,s=r.RM,r.DP=r.RM=0,e=e.div(i),r.DP=n,r.RM=s,this.minus(e.times(i)))},le.neg=function(){var i=new this.constructor(this);return i.s=-i.s,i},le.plus=le.add=function(i){var t,e,r,n=this,s=n.constructor;if(i=new s(i),n.s!=i.s)return i.s=-i.s,n.minus(i);var a=n.e,u=n.c,c=i.e,f=i.c;if(!u[0]||!f[0])return f[0]||(u[0]?i=new s(n):i.s=n.s),i;if(u=u.slice(),t=a-c){for(t>0?(c=a,r=f):(t=-t,r=u),r.reverse();t--;)r.push(0);r.reverse()}for(u.length-f.length<0&&(r=f,f=u,u=r),t=f.length,e=0;t;u[t]%=10)e=(u[--t]=u[t]+f[t]+e)/10|0;for(e&&(u.unshift(e),++c),t=u.length;u[--t]===0;)u.pop();return i.c=u,i.e=c,i},le.pow=function(i){var t=this,e=new t.constructor("1"),r=e,n=i<0;if(i!==~~i||i<-Fh||i>Fh)throw Error(ii+"exponent");for(n&&(i=-i);i&1&&(r=r.times(t)),i>>=1,!!i;)t=t.times(t);return n?e.div(r):r},le.prec=function(i,t){if(i!==~~i||i<1||i>ni)throw Error(ii+"precision");return si(new this.constructor(this),i,t)},le.round=function(i,t){if(i===sn)i=0;else if(i!==~~i||i<-ni||i>ni)throw Error(Do);return si(new this.constructor(this),i+this.e+1,t)},le.sqrt=function(){var i,t,e,r=this,n=r.constructor,s=r.s,a=r.e,u=new n("0.5");if(!r.c[0])return new n(r);if(s<0)throw Error(us+"No square root");s=Math.sqrt(+oi(r,!0,!0)),s===0||s===1/0?(t=r.c.join(""),t.length+a&1||(t+="0"),s=Math.sqrt(t),a=((a+1)/2|0)-(a<0||a&1),i=new n((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+a)):i=new n(s+""),a=i.e+(n.DP+=4);do e=i,i=u.times(e.plus(r.div(e)));while(e.c.slice(0,a).join("")!==i.c.slice(0,a).join(""));return si(i,(n.DP-=4)+i.e+1,n.RM)},le.times=le.mul=function(i){var t,e=this,r=e.constructor,n=e.c,s=(i=new r(i)).c,a=n.length,u=s.length,c=e.e,f=i.e;if(i.s=e.s==i.s?1:-1,!n[0]||!s[0])return i.c=[i.e=0],i;for(i.e=c+f,a<u&&(t=n,n=s,s=t,f=a,a=u,u=f),t=new Array(f=a+u);f--;)t[f]=0;for(c=u;c--;){for(u=0,f=a+c;f>c;)u=t[f]+s[c]*n[f-c-1]+u,t[f--]=u%10,u=u/10|0;t[f]=u}for(u?++i.e:t.shift(),c=t.length;!t[--c];)t.pop();return i.c=t,i},le.toExponential=function(i,t){var e=this,r=e.c[0];if(i!==sn){if(i!==~~i||i<0||i>ni)throw Error(Do);for(e=si(new e.constructor(e),++i,t);e.c.length<i;)e.c.push(0)}return oi(e,!0,!!r)},le.toFixed=function(i,t){var e=this,r=e.c[0];if(i!==sn){if(i!==~~i||i<0||i>ni)throw Error(Do);for(e=si(new e.constructor(e),i+e.e+1,t),i=i+e.e+1;e.c.length<i;)e.c.push(0)}return oi(e,!1,!!r)},le[Symbol.for("nodejs.util.inspect.custom")]=le.toJSON=le.toString=function(){var i=this,t=i.constructor;return oi(i,i.e<=t.NE||i.e>=t.PE,!!i.c[0])},le.toNumber=function(){var i=+oi(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(i.toString()))throw Error(us+"Imprecise conversion");return i},le.toPrecision=function(i,t){var e=this,r=e.constructor,n=e.c[0];if(i!==sn){if(i!==~~i||i<1||i>ni)throw Error(ii+"precision");for(e=si(new r(e),i,t);e.c.length<i;)e.c.push(0)}return oi(e,i<=e.e||e.e<=r.NE||e.e>=r.PE,!!n)},le.valueOf=function(){var i=this,t=i.constructor;if(t.strict===!0)throw Error(us+"valueOf disallowed");return oi(i,i.e<=t.NE||i.e>=t.PE,!0)};var iu=Sh();function Oh(i,t){return iu(i).plus(t).toNumber()}function bo(i,t){return iu(i).minus(t).toNumber()}function Ii(i,t){return iu(i).mul(t).toNumber()}let Kw=class{constructor(t,e,r,n,s){$(this,"_variables");$(this,"_options");$(this,"_totalChangeCapital");$(this,"_historyOrder");$(this,"_orders");$(this,"_exitOrders");$(this,"_pendingOrders");$(this,"_mintick");$(this,"_funcOptions");$(this,"_pendingCloseOrders");$(this,"_errorListener");$(this,"_risk");$(this,"_opentrades");$(this,"_closedtrades");$(this,"_riskNamespace");$(this,"_updateOptions",{});$(this,"_id");$(this,"_maxDrawdownVerifyIndex",0);$(this,"calcOnOrderFillsData",{index:-1});this._variables=t,this._errorListener=n,this._options={overlay:!1,format:Gt.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:Pe.fixed,default_qty_value:1,initial_capital:1e6,currency:xh.NONE,slippage:0,commission_type:je.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=e,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 kw(this),this._closedtrades=new Pw(this),this._riskNamespace=new zw(this,n),this._id=`strategy_${s}`}get orders(){return[...this._orders]}get historyOrders(){return[...this._historyOrder]}get _freezeCapital(){const{close:t}=this.calcOnOrderFillsData.data||this._variables;return this._orders.reduce((e,r)=>e+t*(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(t){this._updateOptions=t||{},Object.assign(this._options,this._updateOptions)}update(){this._maxConsLossDaysVerify(),this._ordersHandle(),this._pendingOrderHandle(),this._exitOrdersHandle(),this._maxIntradayFilledOrdersVerify(),this._maxDrawdownVerify();const{open:t,high:e,low:r}=this.calcOnOrderFillsData.data||this._variables;let n=this._variables.close;this.calcOnOrderFillsData.tradeData&&(n=this.calcOnOrderFillsData.tradeData.open),this._variables.strategy.update({open:t,close:n,high:e,low:r}),!this._options.process_orders_on_close&&this._calcLiquidate(),this._calcProfitAndLoss()}calcCurrentOrder(){this._ordersHandle(),this._pendingOrderHandle(),this._calcProfitAndLoss()}updateRisk(t){Object.assign(this._risk,t)}endExecution(){this._maxIntradayLoss(),this._pendingCloseOrderHandle(),this._options.process_orders_on_close&&this._calcLiquidate()}_maxIntradayLoss(){var g;const{max_intraday_loss:t,max_intraday_loss_type:e,isDisabledOpen:r}=this._risk;if(t===void 0||!e||r)return;const{time_tradingday:n,time:s,strategy:{netprofit:a,initial_capital:u}}=this._variables,{high:c,low:f}=this.calcOnOrderFillsData.data||this._variables;let{preNetprofit:d=0}=this._risk;s===n&&(d=a,this._risk.preNetprofit=a,this._risk.isTemporaryBan=!1);let h=d-a;h+=this._orders.reduce((y,p)=>{const{in_price:w,direction:v,qty:x=0,commission:b=0,original_qty:C=0}=p,E=v===fe.long?1:-1,A=(c-w)*x,N=(f-w)*x,S=E===1?N:-A;return y+S+x/C*b},0);let _=!1;switch(e){case Pe.cash:_=t<h;break;case Pe.percentOfEquity:const y=h/(u+a)*100;_=t<y;break}if(_){this._risk.isTemporaryBan=!0;const y=(g=this._orders[0])==null?void 0:g.direction;this._closeOrders(this._orders,y===fe.long?f:c,"Close Position (Max intraday Loss)",void 0,"close"),this._pendingOrders=[]}}_maxIntradayFilledOrdersVerify(){const{max_intraday_filled_orders:t,intradayOrders:e=0,isDisabledOpen:r}=this._risk;if(t===void 0||r)return;const{time:n,time_tradingday:s}=this._variables,{open:a}=this.calcOnOrderFillsData.data||this._variables;n===s&&(this._risk.intradayOrders=0,this._risk.isTemporaryBan=!1),t<=e&&(this._risk.isTemporaryBan=!0,this._closeOrders(this._orders,a,"Close Position (Max number of filled orders in one day)",void 0,"close"),this._pendingOrders=[])}_maxConsLossDaysVerify(){const{max_cons_loss_days:t,lossDays:e=0,isDisabledOpen:r,totalProfit:n=0}=this._risk;if(t===void 0||r)return;const{time:s,time_tradingday:a,strategy:u}=this._variables,{open:c}=this.calcOnOrderFillsData.data||this._variables;let f=e;if(s===a){const d=u.netprofit+u.openprofit;d<n?f=0:f++,Object.assign(this._risk,{lossDays:f,totalProfit:d})}t<=f&&this._riskTouchOff(c,"Close Position (Max consecutive loss days)")}_maxDrawdownVerify(){const{max_drawdown:t,max_drawdown_type:e,isDisabledOpen:r}=this._risk;if(r)return;const{bar_index:n}=this._variables,{open:s}=this.calcOnOrderFillsData.data||this._variables;if(t!==void 0&&e&&this._maxDrawdownVerifyIndex===n){const{initial_capital:a}=this._options,c=this._orders.reduce((d,h)=>{const{in_price:_,commission:g=0,qty:y=0,original_qty:p=0,direction:w}=h,v=w===fe.long?1:-1,x=(s-_)*v*y;return d+x+g*y/p},0)+this._totalChangeCapital;let f=!1;switch(e){case Pe.percentOfEquity:f=c/a*100<=-t;break;case Pe.cash:f=c<=-t;break}f&&this._riskTouchOff(s,"Close Position (Max Drawdown)")}}_riskTouchOff(t,e){this._risk.isDisabledOpen=!0,this._orders.length&&this._closeOrders(this._orders,t,e,"close"),this._pendingOrders=[]}strategy(t,e){if(!this._variables.bar_index){this._paramVerfiy(t.format,e,"strategy",[Gt.inherit,Gt.price,Gt.percent,Gt.volume],"format"),this._paramVerfiy(t.default_qty_type,e,"strategy",Object.values(Pe),"default_qty_type"),this._paramVerfiy(t.commission_type,e,"strategy",Object.values(je),"commission_type");const r=self==null?void 0:self.workerStorage.get(this._id),n={...this._updateOptions};if(r)for(const s of Object.keys({...r,...t}))t[s]!==r[s]&&delete n[s];self==null||self.workerStorage.set(this._id,t),Object.assign(this._options,t,n),this._variables.updateMaxLength(t),Object.assign(this._funcOptions,{strategy:this._options,userSetStrategyConfig:n,scriptType:"strategy"})}}order(t,e){this._risk.isDisabledOpen||(this._paramVerfiy(t.oca_type,e,"strategy.order",Object.values(fn),"oca_type"),this._orderHandle(t))}entry(t,e){this._risk.isDisabledOpen||(this._paramVerfiy(t.oca_type,e,"strategy.entry",Object.values(fn),"oca_type"),this._entryHandle(t))}close(t){if(!this._orders.filter(r=>!this._options.process_orders_on_close||r.in_index!==this._variables.bar_index).length)return;const{immediately:e}=t;if(e||this._options.process_orders_on_close){const r=this._pendingCloseOrders.find(n=>n.id===t.id&&n.place_order_type==="close");if(r){Object.assign(r,t);return}this._pendingCloseOrders.push({...t,place_order_type:"close"})}else{const r=this._pendingOrders.find(n=>n.id===t.id&&n.place_order_type==="close");if(r){Object.assign(r,t);return}this._pendingOrders.push({...t,place_order_type:"close"})}}close_all(t){if(typeof t=="string"&&(t={}),!this._orders.length)return;const{immediately:e}=t;e||this._options.process_orders_on_close?this._pendingCloseOrders.push({...t,place_order_type:"close_all"}):this._pendingOrders.push({...t,place_order_type:"close_all"})}cancel({id:t}){this._pendingOrders=this._pendingOrders.filter(e=>!(e.id===t&&e.place_order_type!=="close"))}cancel_all(){this._pendingOrders=this._pendingOrders.filter(t=>t.place_order_type==="close_all")}exit(t,e){this._exit(t,e)}convert_to_account({value:t}){return t}convert_to_symbol({value:t}){return t}default_entry_qty({fill_price:t}){return t?this._calcDefaultQty(t):0}_calcDefaultQty(t){const{default_qty_type:e=Pe.fixed,default_qty_value:r=1,initial_capital:n,commission_value:s}=this._options;let a=r;switch(e){case Pe.cash:a=r/t;break;case Pe.percentOfEquity:const u=this._getOrderProfit(t),c=n+u+this._totalChangeCapital;s?a=this._getCommQty(c,t):a=c*r/100/t;break}return Ql(a,this._getLen(t))}_getCommQty(t,e){const{commission_type:r,commission_value:n=0,default_qty_value:s=0}=this._options;let a=0;switch(r){case je.percent:a=t*s/(100*e+n*e);break;case je.cashPerContract:a=t*s/(100*e+n);break;case je.cashPerOrder:a=(t-n)*s/100/e}return a}_getLen(t){const e=String(Math.floor(t)).length-3;return e<0?0:e}_getCapital(t,e){const{margin_long:r=0,margin_short:n=0}=this._options;return r<100&&r>0&&t===1?e=e*100/r:n<=100&&n>0&&t===-1&&(e=e*100/n),e}_calcProfitAndLoss(){const{close:t}=this.calcOnOrderFillsData.data||this._variables;for(const e of this._orders){const{in_price:r,qty:n=0,direction:s}=e,a=s===fe.long?1:-1,u=(t-r)*a*n,[c,f]=this._calcProfitAndLossHandle(r,n,a);this._calcOrderPercent(e,u,c,f)}}_calcProfitAndLossHandle(t,e,r,n){const{high:s,low:a}=this.calcOnOrderFillsData.data||this._variables,u=((n||s)-t)*e,c=((n||a)-t)*e;let f=r===1?u:-c,d=r===1?c:-u;return[f,d]}_calcOrderPercent(t,e,r,n){const{commission_value:s}=this._options,{close:a}=this.calcOnOrderFillsData.data||this._variables,{original_qty:u=0,qty:c=0,in_price:f,max_profit:d=0,trading_loss:h=0}=t;let{commission:_=0}=t,g=f*c;if(s){const y=this._getCommission(a,c);_=_*c/u,r-=_,n-=_,g+=_,e=e-y-_}r=Math.max(r,d,0),n=Math.min(n,h,0),Object.assign(t,{profit:e,total_profit:this._totalChangeCapital+e,total_profit_percent:e/(this._options.initial_capital+this._totalChangeCapital)*100,max_profit:r,trading_loss:n,profit_percent:e/g*100,max_profit_percent:r/g*100,trading_loss_percent:n/g*100})}_calcLiquidate(){if(!this._orders.length)return;const{time:t}=this._variables,{high:e,low:r}=this.calcOnOrderFillsData.data||this._variables,{initial_capital:n,margin_long:s=0,margin_short:a=0}=this._options,u=this._orders[0].direction===fe.long?1:-1;let c=u===1?r:e;if(u===1&&s===100)return;const f=(u===1?s:a)/100;if(f<=0)return;let d=!1;const[h,_]=this._orders.reduce((w,v)=>{let[x,b]=w;const{in_price:C,qty:E=0,in_time:A}=v;A===t&&(d=!0);const N=C*E,S=c*E;return x+=N,b+=S,[x,b]},[0,0]);let g=0,y=0;const p=n+this._totalChangeCapital;if(d&&(g=p-h*f,g<0&&(c=this._orders[0].in_price,y=Math.abs(Math.trunc(g/f/c)*4),y=Math.max(y,1))),g>=0){const w=u*(_-h);if(g=p+w-_*f,g>=0)return;y=Math.abs(Math.trunc(g/f/c)*4)}y<=0||this._marginCallOrders(c,y,"Margin Call")}_marginCallOrders(t,e,r){const{close_entries_rule:n="FIFO"}=this._options;if(n==="FIFO"){this._processOrders(this._orders,t,e*this._orders.length,r,r,!0);return}for(const s of this.orders)s.position_close_type=s.place_order_type,s.isTiggerClose=!0,this._processOrder(s,t,e,r,r,!0);this._orders=this._orders.filter(s=>!s.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_orderHandle(t){const{process_orders_on_close:e,slippage:r=0}=this._options,{orders:n,isMarketPrice:s,quantities:a,close:u,price:c,activePrice:f,isTouch:d}=this._orderArgsParse(t),h=t.direction===fe.long?1:-1;if(a<=0)return;let _=a;if((s||d)&&e){const y=d?c:u;if(n.length){const E=this._processOrders(n,y,_,t.id,t.comment,!1,"order");if(E<=0)return;_=E}const p=y-h*r*this._mintick;if(!this._judgeCapitalEnough(_,p,h))return;this._ocaGroupVerify(_,t.oca_name,t.oca_type);const{bar_index:v,time:x}=this._variables,{high:b,low:C}=this.calcOnOrderFillsData.data||this._variables;this._calcCurrentOrder({...t,in_price:p,in_high:b,in_low:C,in_index:v,in_time:x,qty:_,place_order_type:"order"});return}this._judgeCapitalEnough(a,c,h)&&this._addPendingOrders(t,c,_,s,f)}_judgeCapitalEnough(t,e,r){let n=this._freezeCapital;if(this._orders.some(d=>(d.direction===fe.long?1:-1)!==r)&&(n=0),t<=0)return!1;const{margin_long:s=0,margin_short:a=0}=this._options;if(s===0&&r===1||a===0&&r===-1)return!0;const u=this._getOrderProfit(e),f=this._getCapital(r,this._options.initial_capital+u+this._totalChangeCapital)-n;return t*e<=f}_getOrderProfit(t){return this._orders.reduce((e,r)=>{const{in_price:n,qty:s=0,direction:a}=r,u=a===fe.long?1:-1;return e+(t-n)*s*u},0)}_ocaGroupVerify(t,e,r){if(!e||!r||r===fn.none)return!1;let n=!1;switch(r){case fn.cancel:this._pendingOrders=this._pendingOrders.filter(s=>{if(s.oca_name===e)s.isCancel=!0,n=!0;else return!0});break;case fn.reduce:this._pendingOrders=this._pendingOrders.filter(s=>{const{qty:a=0,oca_name:u}=s;if(e===u){const c=a-t;return n=!0,c<=0?(s.isCancel=!0,!1):(s.qty=c,!0)}else return!0});break}return n}_processOrders(t,e,r,n,s,a=!1,u,c){let f=r;for(const d of t)if(d.position_close_type=u||d.place_order_type,d.immediately=c,d.isTiggerClose=a||d.position_close_type==="close",f=this._processOrder(d,e,f,n,s,a),f<=0)break;return this._orders=this._orders.filter(d=>!d.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),f}_addPendingOrders(t,e,r,n,s){const a=this._pendingOrders.find(u=>u.id===t.id&&!u.isMarketPrice);if(a)Object.assign(a,{...t,in_price:e,isMarketPrice:n,qty:r,active_price:s});else{const u={...t,in_price:e,isMarketPrice:n,qty:r,active_price:s,entry_time:this._variables.time,place_order_type:"order"};this._pendingOrders.push(u)}}_orderArgsParse(t){const{direction:e,qty:r,stop:n}=t;let s=t.limit||0;const{close:a}=this.calcOnOrderFillsData.data||this._variables;let u=a,c=!1,f;const d=e===fe.long?1:-1,h=n&&(n-a)*d>=0,{backtest_fill_limits_assumption:_=0}=this._options;_>0&&s&&(s-=_*this._mintick*d);const g=s&&(s-a)*d<=0;let y=!1;h&&g?(n!==a&&(f=n),u=s):h?(u=n,y=n===a):g?(u=s,y=s===a):c=!0;const p=r!==void 0?Ql(r,this._getLen(u)):this._calcDefaultQty(u);return{orders:this._orders.filter(v=>v.direction!==e),isMarketPrice:c,activePrice:f,quantities:p,close:a,price:u,isTouch:y}}_entryHandle(t){const{process_orders_on_close:e}=this._options,{orders:r,isMarketPrice:n,quantities:s,close:a,price:u,activePrice:c,isTouch:f}=this._orderArgsParse(t);if(s<=0)return;if((n||f)&&e){this._entryOrder(r,f?u:a,s,t);return}this._judgeCapitalEnough(s,a,t.direction===fe.long?1:-1)&&this._addPendingEntry(t,u,s,n,c)}_entryOrder(t,e,r,n){const{time:s,bar_index:a}=this._variables,{high:u,low:c}=this.calcOnOrderFillsData.data||this._variables,{slippage:f=0}=this._options,{oca_name:d,oca_type:h,direction:_,comment:g,id:y}=n,p=_===fe.long?1:-1;if(r=this._getAvailablePositionSize(r,_),r<=0)return;const w=e;if(e=e+f*this._mintick*p,!this._judgeCapitalEnough(r,e,p))return;this._closeOrders(t,w,y,g,"entry",void 0,!0);const x={...n,in_price:e,qty:r,in_index:a,in_high:u,in_low:c,in_time:s,place_order_type:"entry"},{orders:b}=this._getEntryOrders(_),C=b.length;C&&C>=(this._options.pyramiding||1)||(this._ocaGroupVerify(r,d,h),this._calcCurrentOrder(x))}_getAvailablePositionSize(t,e){const{max_position_size:r,allow_entry_in:n}=this._risk;if(n&&n!==fe.all&&n!==e)return 0;if(r===void 0)return t;const s=this._orders.reduce((a,u)=>a+(u.qty||0),0);return s?s+t>r?0:t:t>r?t-r:0}_getEntryOrders(t){const e=this._pendingOrders.filter(n=>["entry","order"].includes(n.place_order_type)&&n.direction===t),r=this._orders.filter(n=>n.direction===t);return{pendingOrders:e,orders:r}}_addPendingEntry(t,e,r,n,s){if(r=this._getAvailablePositionSize(r,t.direction),r<=0)return;const{pendingOrders:a,orders:u}=this._getEntryOrders(t.direction),c=a.find(f=>f.id===t.id&&f.place_order_type==="entry");if(c)Object.assign(c,{...t,in_price:e,isMarketPrice:n,qty:r,active_price:s});else{const f={...t,in_price:e,isMarketPrice:n,qty:r,active_price:s,entry_time:this._variables.time,place_order_type:"entry"};this._pendingOrders.push(f)}}_closeAllOrders(t,e){const{comment:r,immediately:n}=t,{bar_index:s}=this._variables,a=this._orders.filter(u=>u.in_index!==s);a.length&&(this._closeOrders(a,e,"Close position order",r,"close",n),this._orders=[],this._variables.strategy.updateOrders(this._orders))}_closeOrders(t,e,r,n,s,a,u){for(const c of t)c.position_close_type=s,c.immediately=a,c.isTiggerClose=!0,this._closeOrder(c,e,r,n,u);this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_closeOrder(t,e,r,n,s){const{time:a,bar_index:u}=this._variables,{high:c,low:f}=this.calcOnOrderFillsData.data||this._variables,{slippage:d=0}=this._options,{in_price:h,qty:_=0,direction:g}=t,y=g===fe.long?1:-1;e=e-y*d*this._mintick,t.isDeal=!0;const p=(e-h)*y*_,w={...t,out_price:e,out_id:r,out_index:u,out_high:c,out_low:f,out_time:a,out_comment:n,out_qty:_,profit:p};this._calcPercent(w,s)}_exitOrdersHandle(){if(!this._exitOrders.length)return;let{open:t,low:e,high:r,close:n}=this.calcOnOrderFillsData.data||this._variables;const s=[],a=Math.abs(r-t),u=Math.abs(e-t),c=[],f=this._variables.precision;t=Number(t.toFixed(f)),e=Number(e.toFixed(f)),r=Number(r.toFixed(f)),n=Number(n.toFixed(f));for(const d of this._exitOrders){const{directionNum:h,id:_,comment:g,qty:y,comment_loss:p,comment_profit:w,comment_trailing:v,order:x}=d;if(x.isTiggerClose)continue;let b=a<u||a===u&&h===1;const C=[],[E,A]=this._getLimitPrice(d,t,e,r,b);E&&C.push({order:x,price:E,index:A,isHighFront:b,exitInfo:{id:_,comment:w||g,qty:y}});const[N,S]=this._getStopPrice(d,t,e,r,b);N&&C.push({order:x,price:N,index:S,isHighFront:b,exitInfo:{id:_,comment:p||g,qty:y}});const[I,F]=this._getTrailStopPrice(d,t,e,r,n,b);if(I&&C.push({order:x,price:I,index:F,isHighFront:b,exitInfo:{id:_,comment:v||g,qty:y}}),C.length){this._executesSort(C),s.push(C[0]);continue}c.push(d)}this._exitOrders=c,this._executesSort(s);for(const d of s){const{order:h,price:_,exitInfo:g,isHighFront:y,index:p}=d;y?(r=p===1?_:r,e=p===1?t:_):(r=p===1?t:_,e=p===1?_:e),this._variables.strategy.update({open:_,high:r,low:e,close:n}),this._processExitOnClose(h,_,g)}}_executesSort(t){return t.sort(({price:e,index:r,isHighFront:n},{price:s,index:a})=>r!==a?r-a:n?r===1?e-s:s-e:r===1?s-e:e-s),t}_getLimitPrice(t,e,r,n,s){const{limit:a,directionNum:u}=t;let c,f=1;return a&&((e-a)*u>=0?(c=e,f=1):r<=a&&n>=a&&(c=a,s&&a>e||!s&&a<e?f=1:f=2)),[c,f]}_getStopPrice(t,e,r,n,s){const{stop:a,directionNum:u}=t;let c,f=1;return a&&((e-a)*u<=0?(c=e,f=1):r<=a&&n>=a&&(c=a,s&&a>e||!s&&a<e?f=1:f=2)),[c,f]}_getTrailStopPrice(t,e,r,n,s,a){const{trail_stop_price:u,directionNum:c,active_price:f,trail_offset:d=0}=t;let h=u,_,g=1;if(h)if((h-e)*c>=0)_=e,g=1;else{const[y,p,w]=this._calcTrailStopPrice(h,n,r,s,d,c,a);_=p,g=w||1,t.trail_stop_price=y}if(f&&!_&&f<=n&&f>=r)if(d===0)_=f,a&&f>e||!a&&f<e?g=1:g=2;else{h=bo(f,Ii(d*c,this._mintick));let y=n,p=r;a?f>=e&&f<=n?(y=n,g=1):(a=!1,y=s,g=2):f<e&&f>=r?(p=r,g=1):(a=!0,p=s,g=2);const[w,v,x=1]=this._calcTrailStopPrice(h,y,p,s,d,c,a);delete t.active_price,g<x&&(g=x),t.trail_stop_price=w,_=v}return[_,g]}_ordersHandle(t){const e=this._orders.filter(a=>a.isMarketPriceLimit||a.isMarketPriceStop);if(!e.length)return;const{open:r,close:n}=this.calcOnOrderFillsData.data||this._variables,s=t?n:r;for(const a of e){const{out_comment:u,out_qty:c,out_id:f}=a;this._processExitOnClose(a,s,{id:f,comment:u,qty:c})}}_calcTrailStopPrice(t,e,r,n,s,a,u){let c=t,f;const d=bo(a===1?e:r,Ii(s*a,this._mintick));let h=1;return a===1?u?(c<d&&(c=d),c>=r&&(h=2,f=c)):c>=r?(h=1,f=c):d>c&&(c=d,d>=n&&(h=3,f=d)):u?c<=e?(h=1,f=c):d<c&&(c=d,d<=n&&(h=3,f=d)):(d<c&&(c=d),c<=e&&(h=2,f=c)),[c,f,h]}_pendingOrderHandle(){if(!this._pendingOrders.length)return;const t=[],e=this._pendingOrders.filter(r=>r.place_order_type==="exit");for(const r of this._pendingOrders){const{isCancel:n,place_order_type:s}=r;if(n)continue;let a;switch(s){case"entry":a=this._entryOrderHandle(r);break;case"order":a=this._orderOrderHandle(r);break;case"close":a=this._closeOrderHandle(r);break;case"close_all":const{open:u}=this.calcOnOrderFillsData.data||this._variables;this._closeAllOrders(r,u);break}a&&t.push(a)}for(const r of e){const n=this._exitOrderHandle(r);n&&t.push(n)}this._pendingOrders=t}_pendingCloseOrderHandle(){if(!this._pendingCloseOrders.length)return;const t=this._pendingCloseOrders.filter(r=>["close","close_all"].includes(r.place_order_type||"")),{close:e}=this.calcOnOrderFillsData.data||this._variables;this._pendingCloseOrders=[];for(const r of t)switch(r.place_order_type){case"close":const n=this._closeOrderHandle(r,!0);n&&this._pendingCloseOrders.push(n);break;case"close_all":this._closeAllOrders(r,e);break}this._ordersHandle(!0)}_entryOrderHandle(t){const{open:e,low:r,high:n}=this.calcOnOrderFillsData.data||this._variables,{isMarketPrice:s,qty:a=0,in_price:u,direction:c,active_price:f}=t;if(f&&n>=f&&r<=f)return delete t.active_price,t;let d=u;if(s&&(d=e),d<=n&&d>=r){const h=this._orders.filter(_=>_.direction!==c);this._entryOrder(h,d,a,t)}else return t}_orderOrderHandle(t){const{time:e,bar_index:r}=this._variables,{open:n,low:s,high:a}=this.calcOnOrderFillsData.data||this._variables,{slippage:u=0}=this._options,{isMarketPrice:c,qty:f=0,in_price:d,direction:h,comment:_,oca_name:g,oca_type:y,active_price:p,id:w}=t;if(p&&a>=p&&s<=p)return delete t.active_price,t;let v=d,x=f;if(c&&(v=n),v<=a&&v>=s){const b=this._orders.filter(E=>E.direction!==h);if(b.length&&(x=this._processOrders(b,v,f,w,_,!1,"order"),x<=0))return;const C=h===fe.long?1:-1;this._ocaGroupVerify(x,g,y),this._calcCurrentOrder({...t,in_price:v-C*u*this._mintick,in_index:r,in_time:e,in_high:a,in_low:s,qty:x});return}else return t}_closeOrderHandle(t,e){const{id:r,qty:n,qty_percent:s=100,comment:a,immediately:u}=t,{close_entries_rule:c="FIFO"}=this._options;let f=[];if(c==="FIFO"?f=this._orders.filter(g=>g.id===r):f=this._orders.filter(g=>g.id===r&&!g.close_qty),!f.length)return;let d=0;if(n?d=n:(d=f.reduce((g,y)=>g+(y.qty||0),d),d=s/100*d),d<=0)return;const{open:h,close:_}=this.calcOnOrderFillsData.data||this._variables;if(c==="FIFO")this._processOrders(f,e?_:h,d,`Close entry(s) order ${r}`,a,!1,"close",u);else if(this._processCloseOrders(f,e?_:h,d,`Close entry(s) order ${r}`,a,u))return t}_processCloseOrders(t,e,r,n,s,a){let u=!1;for(const c of t)c.close_qty=r,(c.qty||0)>r&&(u=!0),c.immediately=a,c.position_close_type="close",c.isTiggerClose=!0,this._processOrder(c,e,r,n,s);return this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),u}_exitOrderHandle(t){const{from_entry:e}=t,r=this._orders.filter(n=>(!e||e===n.id)&&!n.hasExit);if(!(r.length&&!this._ordersToExit(r,t,!0)))return t}_exit(t,e){if(!t.hasOwnProperty("profit")&&!t.hasOwnProperty("loss")&&!t.hasOwnProperty("stop")&&!t.hasOwnProperty("limit")&&(!t.hasOwnProperty("trail_offset")||!t.hasOwnProperty("trail_price")&&!t.hasOwnProperty("trail_points"))){this._errorListener.addError(ie.strategyExitErr,e,Rt.Error);return}const{profit:r,loss:n,stop:s,limit:a,trail_offset:u,trail_price:c,trail_points:f,from_entry:d="",id:h}=t;if(this._isNaN(r)&&this._isNaN(n)&&this._isNaN(s)&&this._isNaN(a)&&(this._isNaN(u)||this._isNaN(f)&&this._isNaN(c)))return;const _={...t,place_order_type:"exit"},g=this._orders.filter(v=>(!d||d===v.id)&&!v.hasExit),y=this._updateExitOrders(_),p=this._pendingOrders.filter(v=>(!d||d===v.id)&&["order","entry"].includes(v.place_order_type||""));if(g.length){if(!this._ordersToExit(g,_,!1))return}else if(!p.length||y)return;const w=this._pendingOrders.find(v=>v.id===h&&v.place_order_type==="exit");w?Object.assign(w,{...t}):this._pendingOrders.push(_)}_updateExitOrders(t){let e=!1;const r=this._exitOrders.filter(n=>n.id===t.id&&(n.from_entry===t.from_entry||!t.from_entry));for(const n of r){const{directionNum:s,order:a}=n;if(a.isTiggerClose){n.isClose=!0;continue}e=!0;const u={...t};if(this._stopProfit(a,s,u)){n.isClose=!0;continue}if(this._stopLoss(a,s,u)){n.isClose=!0;continue}if(this._trailStopLoss(a,s,u)){n.isClose=!0;continue}Object.assign(n,u)}return this._exitOrders=this._exitOrders.filter(n=>!n.isClose),e}_ordersToExit(t,e,r){const{qty:n,qty_percent:s=100,id:a,comment:u}=e;let c=n,f=!1;e.comment=u||a;const d=t[0],h={...e},{qty:_=0}=d,g=d.direction===fe.long?1:-1;return c=n?n>=_?_:n:s/100*_,h.qty=c,c<_&&(f=!0),this._stopProfit(d,g,h,r)||this._stopLoss(d,g,h,r)||this._trailStopLoss(d,g,h,r)||(this._exitOrders.push({...h,directionNum:g,order:d}),d.hasExit=!0),f}_addExitPendingCloseOrders(t){const e=this._pendingCloseOrders.find(r=>r.id===t.id);e?Object.assign(e,{...t}):this._pendingCloseOrders.push(t)}_stopProfit(t,e,r,n){const{limit:s,profit:a,comment_profit:u,comment:c,id:f,qty:d}=r;let h=s;const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;if(!this._isNaN(a)&&this._isNaN(s)&&(h=Oh(g,Ii(a*e,this._mintick))),r.limit=e===1?ec(h,this._variables.precision):rc(h,this._variables.precision),!n&&h!==void 0&&(h-_)*e<=0)return t.isMarketPriceLimit=!0,r.comment=u||c,Object.assign(t,{out_comment:r.comment,out_id:f,out_qty:d}),y&&this._addExitPendingCloseOrders(r),!0}_stopLoss(t,e,r,n){const{stop:s,loss:a,comment_loss:u,comment:c,id:f,qty:d}=r;let h=s;const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;if(!this._isNaN(a)&&this._isNaN(s)&&(h=bo(g,Ii(a*e,this._mintick))),r.stop=e===1?rc(h,this._variables.precision):ec(h,this._variables.precision),!n&&h!==void 0&&(h-_)*e>=0)return t.isMarketPriceStop=!0,r.comment=u||c,Object.assign(t,{out_comment:r.comment,out_id:f,out_qty:d}),y&&this._addExitPendingCloseOrders(r),!0}_trailStopLoss(t,e,r,n){const{trail_offset:s,trail_price:a,trail_points:u,comment_trailing:c,comment:f,id:d,qty:h}=r;if(!this._isNaN(s)){const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;let p;if(this._isNaN(a)?this._isNaN(u)||(p=Oh(g,Ii(u*e,this._mintick))):p=a,r.active_price=p,n)return;if(p!==void 0&&(p-_)*e<=0){const w=bo(_,Ii(s*e,this._mintick));if((w-_)*e>=0)return t.isMarketPriceStop=!0,r.comment=c||f,Object.assign(t,{out_comment:r.comment,out_id:d,out_qty:h}),y&&this._addExitPendingCloseOrders(r),!0;r.trail_stop_price=w}}}_processExitOnClose(t,e,r){const{qty:n=0,comment:s,id:a}=r,{close_entries_rule:u="FIFO"}=this._options;if(n)if(t.isTiggerClose=!0,u==="FIFO")this._processExitOrders(this._orders,e,n,a,s);else{if(t.isDeal)return;this._processOrders([t],e,n,a,s,!1,"exit")}}_processExitOrders(t,e,r,n,s){let a=r,u;for(const c of t)if(u=c,c.position_close_type="exit",a=this._processOrder(c,e,a,n,s),a<=0)break;return this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),u}_processOrder(t,e,r,n,s,a=!1){const{time:u,bar_index:c}=this._variables,{low:f,high:d}=this.calcOnOrderFillsData.data||this._variables,{slippage:h=0}=this._options,{in_price:_,qty:g=0,max_profit:y,trading_loss:p,direction:w,commission:v=0,original_qty:x=0}=t,b=w===fe.long?1:-1;if(e=e-b*h*this._mintick,r<g){const C=g-r,E=(e-_)*b*r,A=y!==void 0?y/g*r:void 0,N=p!==void 0?p/g*r:void 0,S=v*C/x;this._calcPercent({...t,out_price:e,last_commission:S,out_id:n,out_index:c,out_high:d,out_low:f,out_time:u,out_comment:s,profit:E,out_qty:r,max_profit:A,trading_loss:N});const I=(e-_)*b*C-S;Object.assign(t,{qty:C,profit:I,max_profit:y!==void 0?y-(A||0):void 0,trading_loss:p!==void 0?p-(N||0):void 0,total_profit:this._totalChangeCapital+I}),r=0}else{t.isDeal=!0;const C=(e-_)*b*g;this._calcPercent({...t,out_price:e,out_id:n,out_index:c,out_high:d,out_low:f,out_time:u,out_comment:s,out_qty:g,profit:C}),r-=g}return a&&(b===1?this._variables.strategy.marginCallLong++:this._variables.strategy.marginCallShort++),r}_calcPercent(t,e){const{commission_value:r,process_orders_on_close:n}=this._options,{in_price:s,out_qty:a=0,out_price:u=0,original_qty:c=0,direction:f,last_commission:d=0,immediately:h}=t;let{profit:_=0,max_profit:g,trading_loss:y,commission:p=0}=t,w=s*a,v=this._totalChangeCapital+this._options.initial_capital;if(this._totalChangeCapital+=_,r){const E=this._getCommission(u,a);this._totalChangeCapital-=E;let A=p*a/c;w+=A,A+=E,_=_-A,Object.assign(t,{commission:A});const N=this._orders.reduce((S,I)=>{const{qty:F=0,original_qty:O=0,commission:L=0}=I;return S+L*F/O},0);v+=N-d}const x=f===fe.long?1:-1;let[b,C]=this._calcProfitAndLossHandle(s,a,x,u);if(r){const E=p*a/c;b-=E,C-=E}g=Math.max(b,g||0),y=Math.min(C,y||0),_=parseFloat(String(_)),Object.assign(t,{max_profit:g,profit:_,trading_loss:y,total_profit:this._totalChangeCapital,total_profit_percent:_/v*100,profit_percent:_/w*100,max_profit_percent:g/w*100,trading_loss_percent:y/w*100}),this._maxDrawdownVerifyIndex=this._variables.bar_index+(n?1:0),this._risk.intradayOrders+=1,this._historyOrder.push(t),!e&&this._calcOrderFillsHandle(u,f,h)}_getCommission(t,e){const{commission_value:r=0,commission_type:n}=this._options,s=t*e;let a=0;switch(n){case je.percent:a=s*r/100;break;case je.cashPerContract:a=e*r;break;case je.cashPerOrder:a=r;break}return a}_calcCurrentOrder(t){const{commission_value:e}=this._options,{in_price:r,qty:n=0,max_profit:s=0,trading_loss:a=0,direction:u,immediately:c}=t;let{profit:f=0}=t,d=r*n;const h=this._totalChangeCapital+this._options.initial_capital;if(e){const _=this._getCommission(r,n);this._totalChangeCapital-=_,f=f-_,d+=_,Object.assign(t,{commission:_,total_profit:this._totalChangeCapital})}f=parseFloat(String(f)),Object.assign(t,{original_qty:n,profit:f,total_profit_percent:f/h*100,profit_percent:f/d*100,max_profit_percent:s/d*100,trading_loss_percent:a/d*100,stop:void 0,limit:void 0}),this._risk.intradayOrders+=1,this._orders.push(t),this._variables.strategy.updateOrders(this._orders),e&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._calcOrderFillsHandle(r,u,c)}_calcOrderFillsHandle(t,e,r=!1){const{calc_on_order_fills:n,process_orders_on_close:s,slippage:a=0}=this._options;if(n){const{open:u,high:c,low:f,close:d}=this._variables,h=e===fe.long?1:-1,_=d-h*a*this._mintick;if((r||s)&&t===_)return;const g=u-h*a*this._mintick;let y={open:u,high:c,low:f,close:d},p=this.calcOnOrderFillsData.index;const w=Math.abs(c-u)<=Math.abs(f-u);switch(p){case-1:t===g?p=0:t>g?w?(p=1,y={open:c,high:c,low:f,close:d}):(p=2,y={open:c,high:c,low:d,close:d}):w?(p=2,y={open:f,high:d,low:f,close:d}):(p=1,y={open:f,high:c,low:f,close:d});break;case 0:t===g?(p=1,w?y={open:c,high:c,low:f,close:d}:y={open:f,high:c,low:f,close:d}):t>g?w?(p=1,y={open:c,high:c,low:f,close:d}):(p=2,y={open:c,high:c,low:d,close:d}):w?(p=2,y={open:f,high:d,low:f,close:d}):(p=1,y={open:f,high:c,low:f,close:d});break;case 1:p=2,w?y={open:f,high:d,low:f,close:d}:y={open:c,high:c,low:d,close:d};break;case 2:p=-1,y=void 0;break}this.calcOnOrderFillsData={tradeData:y,index:p}}}_isNaN(t){return t===void 0||isNaN(t)}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}};var Bh={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){return function(e,r,n){r.prototype.isBetween=function(s,a,u,c){var f=n(s),d=n(a),h=(c=c||"()")[0]==="(",_=c[1]===")";return(h?this.isAfter(f,u):!this.isBefore(f,u))&&(_?this.isBefore(d,u):!this.isAfter(d,u))||(h?this.isBefore(f,u):!this.isAfter(f,u))&&(_?this.isAfter(d,u):!this.isBefore(d,u))}}})})(Bh);var Gw=Bh.exports,Jw=Kt(Gw),Th={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){return function(e,r,n){var s=r.prototype,a=function(_){var g,y=_.date,p=_.utc,w={};if(!((g=y)===null||g instanceof Date||g instanceof Array||s.$utils().u(g)||g.constructor.name!=="Object")){if(!Object.keys(y).length)return new Date;var v=p?n.utc():n();Object.keys(y).forEach(function(I){var F,O;w[F=I,O=s.$utils().p(F),O==="date"?"day":O]=y[I]});var x=w.day||(w.year||w.month>=0?1:v.date()),b=w.year||v.year(),C=w.month>=0?w.month:w.year||w.day?0:v.month(),E=w.hour||0,A=w.minute||0,N=w.second||0,S=w.millisecond||0;return p?new Date(Date.UTC(b,C,x,E,A,N,S)):new Date(b,C,x,E,A,N,S)}return y},u=s.parse;s.parse=function(_){_.date=a.bind(this)(_),u.bind(this)(_)};var c=s.set,f=s.add,d=s.subtract,h=function(_,g,y,p){p===void 0&&(p=1);var w=Object.keys(g),v=this;return w.forEach(function(x){v=_.bind(v)(g[x]*p,x)}),v};s.set=function(_,g){return g=g===void 0?_:g,_.constructor.name==="Object"?h.bind(this)(function(y,p){return c.bind(this)(p,y)},g,_):c.bind(this)(_,g)},s.add=function(_,g){return _.constructor.name==="Object"?h.bind(this)(f,_,g):f.bind(this)(_,g)},s.subtract=function(_,g){return _.constructor.name==="Object"?h.bind(this)(f,_,g,-1):d.bind(this)(_,g)}}})})(Th);var Xw=Th.exports,Qw=Kt(Xw),Ih={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){var e,r,n=1e3,s=6e4,a=36e5,u=864e5,c=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f=31536e6,d=2628e6,h=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,_={years:f,months:d,days:u,hours:a,minutes:s,seconds:n,milliseconds:1,weeks:6048e5},g=function(A){return A instanceof C},y=function(A,N,S){return new C(A,S,N.$l)},p=function(A){return r.p(A)+"s"},w=function(A){return A<0},v=function(A){return w(A)?Math.ceil(A):Math.floor(A)},x=function(A){return Math.abs(A)},b=function(A,N){return A?w(A)?{negative:!0,format:""+x(A)+N}:{negative:!1,format:""+A+N}:{negative:!1,format:""}},C=function(){function A(S,I,F){var O=this;if(this.$d={},this.$l=F,S===void 0&&(this.$ms=0,this.parseFromMilliseconds()),I)return y(S*_[p(I)],this);if(typeof S=="number")return this.$ms=S,this.parseFromMilliseconds(),this;if(typeof S=="object")return Object.keys(S).forEach(function(q){O.$d[p(q)]=S[q]}),this.calMilliseconds(),this;if(typeof S=="string"){var L=S.match(h);if(L){var z=L.slice(2).map(function(q){return q!=null?Number(q):0});return this.$d.years=z[0],this.$d.months=z[1],this.$d.weeks=z[2],this.$d.days=z[3],this.$d.hours=z[4],this.$d.minutes=z[5],this.$d.seconds=z[6],this.calMilliseconds(),this}}return this}var N=A.prototype;return N.calMilliseconds=function(){var S=this;this.$ms=Object.keys(this.$d).reduce(function(I,F){return I+(S.$d[F]||0)*_[F]},0)},N.parseFromMilliseconds=function(){var S=this.$ms;this.$d.years=v(S/f),S%=f,this.$d.months=v(S/d),S%=d,this.$d.days=v(S/u),S%=u,this.$d.hours=v(S/a),S%=a,this.$d.minutes=v(S/s),S%=s,this.$d.seconds=v(S/n),S%=n,this.$d.milliseconds=S},N.toISOString=function(){var S=b(this.$d.years,"Y"),I=b(this.$d.months,"M"),F=+this.$d.days||0;this.$d.weeks&&(F+=7*this.$d.weeks);var O=b(F,"D"),L=b(this.$d.hours,"H"),z=b(this.$d.minutes,"M"),q=this.$d.seconds||0;this.$d.milliseconds&&(q+=this.$d.milliseconds/1e3,q=Math.round(1e3*q)/1e3);var W=b(q,"S"),P=S.negative||I.negative||O.negative||L.negative||z.negative||W.negative,Z=L.format||z.format||W.format?"T":"",Y=(P?"-":"")+"P"+S.format+I.format+O.format+Z+L.format+z.format+W.format;return Y==="P"||Y==="-P"?"P0D":Y},N.toJSON=function(){return this.toISOString()},N.format=function(S){var I=S||"YYYY-MM-DDTHH:mm:ss",F={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return I.replace(c,function(O,L){return L||String(F[O])})},N.as=function(S){return this.$ms/_[p(S)]},N.get=function(S){var I=this.$ms,F=p(S);return F==="milliseconds"?I%=1e3:I=F==="weeks"?v(I/_[F]):this.$d[F],I||0},N.add=function(S,I,F){var O;return O=I?S*_[p(I)]:g(S)?S.$ms:y(S,this).$ms,y(this.$ms+O*(F?-1:1),this)},N.subtract=function(S,I){return this.add(S,I,!0)},N.locale=function(S){var I=this.clone();return I.$l=S,I},N.clone=function(){return y(this.$ms,this)},N.humanize=function(S){return e().add(this.$ms,"ms").locale(this.$l).fromNow(!S)},N.valueOf=function(){return this.asMilliseconds()},N.milliseconds=function(){return this.get("milliseconds")},N.asMilliseconds=function(){return this.as("milliseconds")},N.seconds=function(){return this.get("seconds")},N.asSeconds=function(){return this.as("seconds")},N.minutes=function(){return this.get("minutes")},N.asMinutes=function(){return this.as("minutes")},N.hours=function(){return this.get("hours")},N.asHours=function(){return this.as("hours")},N.days=function(){return this.get("days")},N.asDays=function(){return this.as("days")},N.weeks=function(){return this.get("weeks")},N.asWeeks=function(){return this.as("weeks")},N.months=function(){return this.get("months")},N.asMonths=function(){return this.as("months")},N.years=function(){return this.get("years")},N.asYears=function(){return this.as("years")},A}(),E=function(A,N,S){return A.add(N.years()*S,"y").add(N.months()*S,"M").add(N.days()*S,"d").add(N.hours()*S,"h").add(N.minutes()*S,"m").add(N.seconds()*S,"s").add(N.milliseconds()*S,"ms")};return function(A,N,S){e=S,r=S().$utils(),S.duration=function(O,L){var z=S.locale();return y(O,{$l:z},L)},S.isDuration=g;var I=N.prototype.add,F=N.prototype.subtract;N.prototype.add=function(O,L){return g(O)?E(this,O,1):I.bind(this)(O,L)},N.prototype.subtract=function(O,L){return g(O)?E(this,O,-1):F.bind(this)(O,L)}}})})(Ih);var tD=Ih.exports,eD=Kt(tD);Wt.extend(xa),Wt.extend(Ea),Wt.extend(Jw),Wt.extend(Qw),Wt.extend(eD);class $h{constructor(t,e,r){$(this,"array");$(this,"color");$(this,"math");$(this,"str");$(this,"map");$(this,"matrix");$(this,"timeframe");$(this,"ta");$(this,"input");$(this,"_variables");$(this,"_cacheData");$(this,"_options");$(this,"_errorListener");$(this,"_plots");$(this,"_plotshapes");$(this,"_plotbars");$(this,"_plotchars");$(this,"_plotarrows");$(this,"_plotcandles");$(this,"_alerts");$(this,"_bgColors");$(this,"_hlines");$(this,"_fills");$(this,"chart");$(this,"line");$(this,"label");$(this,"polyline");$(this,"box");$(this,"table");$(this,"linefill");$(this,"log");$(this,"runtime");$(this,"strategy");$(this,"request");$(this,"syminfo");$(this,"_count",0);var s;const n=((s=t.toString().split(".")[1])==null?void 0:s.length)||5;this._variables=e,this._errorListener=new aD,this.array=new I_(this._errorListener),this.math=new $_(n,this._errorListener),this.color=new oy,this.str=new lw(this._errorListener,n),this.map=new cw(this._errorListener),this.timeframe=new ow(e),this.matrix=new sw(this._errorListener),this.ta=new iy(e,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 sy(e,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 fw(e)},this.line=new Iw(e,this._errorListener),this.label=new hw(e,this._errorListener),this.polyline=new Tw(e,this._errorListener),this.box=new Lw(e,this._errorListener),this.table=new Rw(e,this._errorListener),this.linefill=new $w(e),this.log=new sD(e,this.str),this.runtime=new oD(this._errorListener),this.strategy=new Kw(this._variables,this._options,t,this._errorListener,r),this.request=new nD(this._variables,r),this.syminfo=new iD}get errors(){return this._errorListener.errors}get scriptType(){return this._options.scriptType}options(t){if(t.length)return this._getDataOfBarindex(t);const e=this.input.getInputs(),r=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const n=Object.keys(this._bgColors);let s;if(n.length){s={};for(const v of n)s[v]=[...this._bgColors[v].values()]}const a=this._hlines.size?[...this._hlines.values()]:void 0,u=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 f=this._plots.size>0?[...this._plots.values()]:void 0,d=this._plotbars.size>0?[...this._plotbars.values()]:void 0,h=this._plotshapes.size>0?[...this._plotshapes.values()]:void 0,_=this._plotarrows.size>0?[...this._plotarrows.values()]:void 0,g=this._plotcandles.size>0?[...this._plotcandles.values()]:void 0,y=this._plotchars.size>0?[...this._plotchars.values()]:void 0,p=this._getDraws(),w=this._variables.chart.isUseBgColor;return Object.assign(this._options,{inputs:e,plots:f,draws:p,alerts:r,colors:s,hlines:a,fills:u,logs:c,plotshapes:h,plotarrows:_,plotcandles:g,plotchars:y,plotbars:d,isUseBgColor:w})}_getDataOfBarindex(t){const e=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const r=Object.keys(this._bgColors);let n;if(r.length){n={};for(const v of r)n[v]=[...this._bgColors[v].values()].map(x=>{const b=[];for(const C of t){const E=x.data[C];E&&b.push(E)}return x.data=b,x})}const s=this._hlines.size?[...this._hlines.values()]:void 0,a=this._fills.size?this._getDataFromBarindex(t,[...this._fills.values()]):void 0,u=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 c=this._getDataFromBarindex(t,[...this._plots.values()]),f=this._plotbars.size>0?this._getDataFromBarindex(t,[...this._plotbars.values()]):void 0,d=this._plotarrows.size>0?this._getDataFromBarindex(t,[...this._plotarrows.values()]):void 0,h=this._plotcandles.size>0?this._getDataFromBarindex(t,[...this._plotcandles.values()]):void 0,_=this._plotchars.size>0?this._getDataFromBarindex(t,[...this._plotchars.values()]):void 0,g=this._plotshapes.size>0?this._getDataFromBarindex(t,[...this._plotshapes.values()]):void 0,y=this._getDrawsFromBarindex(t),p=this._getDrawDeletes(t),w=this._variables.chart.isUseBgColor;return Object.assign(this._options,{plots:c,plotarrows:d,plotcandles:h,plotchars:_,plotbars:f,draws:y,drawDeletes:p,alerts:e,colors:n,hlines:s,fills:a,logs:u,plotshapes:g,isUseBgColor:w})}_getDataFromBarindex(t,e){return e.map(r=>{const n=[];for(const s of t){const a=r.data[s];a&&n.push(a)}return r.data=n,{...r}})}_getDraws(){const{line:t,linefill:e,table:r,box:n,polyline:s,label:a}=this._variables,u={};return t.data.length&&(u.lines=t.data),e.data.length&&(u.linefills=e.data),r.data.length&&(u.tables=r.data),n.data.length&&(u.boxes=n.data),s.data.length&&(u.polylines=s.data),a.data.length&&(u.labels=a.data),Object.keys(u).length?u:void 0}_getDrawsFromBarindex(t){const{line:e,linefill:r,table:n,box:s,polyline:a,label:u}=this._variables,c={};return e.data.length&&(c.lines=e.getValOfBarIndex(t)),r.data.length&&(c.linefills=r.getValOfBarIndex(t)),n.data.length&&(c.tables=n.getValOfBarIndex(t)),s.data.length&&(c.boxes=s.getValOfBarIndex(t)),a.data.length&&(c.polylines=a.getValOfBarIndex(t)),u.data.length&&(c.labels=u.getValOfBarIndex(t)),Object.keys(c).length?c:void 0}_getDrawDeletes(t){const{line:e,linefill:r,table:n,box:s,polyline:a,label:u}=this._variables,c={},f=e.getDeleteIds(t),d=r.getDeleteIds(t),h=n.getDeleteIds(t),_=s.getDeleteIds(t),g=a.getDeleteIds(t),y=u.getDeleteIds(t);return f.length&&(c.lines=f),d.length&&(c.linefills=d),h.length&&(c.tables=h),_.length&&(c.boxes=_),g.length&&(c.polylines=g),y.length&&(c.labels=y),c}updateOptions(t){var n;const{inputs:e,strategy:r}=t;this.input.update(e),r&&((n=this.strategy)==null||n.updateOptions(r))}update(t){const{barIndex:e}=t;this.strategy.update(),this.math.update(e)}endExecution(){this.strategy.endExecution()}library(t,e){if(!this._variables.bar_index){const r=/^[^\W\d\s][^\W\s]*$/,{title:n}=t;r.test(n)?(T_.includes(n)||B_.includes(n))&&this._errorListener.addError(He(ie.libraryTitleIsKeywordErr,{name:n}),e,Rt.Error):this._errorListener.addError(ie.libraryTitleErr,e,Rt.Error),this._options.scriptType="library",this._options.library=t}}indicator(t,e){if(!this._variables.bar_index){const{format:r}=t;this._paramVerfiy(r,e,"indicator",[Gt.inherit,Gt.percent,Gt.price,Gt.volume]),this._variables.updateMaxLength(t),this._options.scriptType="indicator",this._options.indicator=t}}_paramVerfiy(t="",e,r,n,s="format"){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_lineWidthVerify(t,e){const{linewidth:r=1}=t;r<1&&(this._errorListener.addError(S_.lineWidthWarning,e,Rt.Warning),t.linewidth=1)}plot(t,e){const r=["color"];ve(t,r);const{series:n,color:s,...a}=t,{bar_index:u,time:c}=this._variables,f=`plot_${e}`,d=this._plots.get(f),h=(d==null?void 0:d.data)||[],_=n!==void 0&&isNaN(n)?void 0:n;if(h[u]={value:[c,_],itemStyle:{color:s}},this._seriesColorHandle(t,r,d),!d){this._count++,this._lineWidthVerify(a,e),this._paramVerfiy(t.format,e,"plot",[Gt.percent,Gt.price,Gt.volume]);const g=s?[s]:void 0;this._plots.set(f,{editable:!0,...a,colors:g,data:h,id:f,zIndex:this._count})}return{type:"plot",key:f}}plotbar(t,e){const r=["color"];ve(t,r);const{open:n,close:s,low:a,high:u,color:c,...f}=t,{bar_index:d,time:h}=this._variables,_=`plotbar_${e}`,g=this._plotbars.get(_),y=(g==null?void 0:g.data)||[],p=s!==void 0&&isNaN(s)?void 0:s,w=n!==void 0&&isNaN(n)?void 0:n,v=a!==void 0&&isNaN(a)?void 0:a,x=u!==void 0&&isNaN(u)?void 0:u,b=[h,w,p,v,x];if(y[d]={value:b,itemStyle:{color:c}},this._seriesColorHandle(t,r,g),!g){this._count++,this._paramVerfiy(t.format,e,"plotbar",[Gt.percent,Gt.price,Gt.volume]);const C=c?[c]:void 0;this._plotbars.set(_,{editable:!0,...f,colors:C,data:y,id:_,zIndex:this._count})}}_verfiyArgs(t,e,r){const{size:n,format:s,location:a,style:u}=t;this._paramVerfiy(u,r,e,Object.values(lr),"style"),this._paramVerfiy(a,r,e,Object.values(cn),"location"),this._paramVerfiy(n,r,e,Object.values(ir),"size"),this._paramVerfiy(s,r,e,[Gt.percent,Gt.price,Gt.volume],"format")}plotchar(t,e){const r=["color","textcolor"];ve(t,r);const{series:n,color:s,textcolor:a,location:u=cn.abovebar,...c}=t,{bar_index:f,time:d,high:h,low:_}=this._variables,g=`plotchar_${e}`,y=this._plotchars.get(g),p=(y==null?void 0:y.data)||[],w={value:[d,n],itemStyle:{color:s,textcolor:a},low:_,high:h};p[f]=w,this._seriesColorHandle(t,r,y),y||(this._count++,this._verfiyArgs(t,"plotchar",e),this._plotchars.set(g,{editable:!0,...c,location:u,data:p,id:g,zIndex:this._count}))}plotarrow(t,e){const r=["colorup","colordown"];ve(t,r);const{series:n,colorup:s,colordown:a,...u}=t,{bar_index:c,time:f,low:d,high:h}=this._variables,_=`plotarrow_${e}`,g=this._plotarrows.get(_),y=(g==null?void 0:g.data)||[];y[c]={value:[f,n!==void 0&&isNaN(n)?void 0:n],itemStyle:{colorup:s,colordown:a},low:d,high:h},this._seriesColorHandle(t,r,g),g||(this._count++,this._paramVerfiy(t.format,e,"plotarrow",[Gt.percent,Gt.price,Gt.volume]),this._plotarrows.set(_,{editable:!0,...u,data:y,id:_,zIndex:this._count}))}plotshape(t,e){const r=["color","textcolor"];ve(t,r);const{series:n,color:s,textcolor:a,location:u=cn.abovebar,...c}=t,{bar_index:f,time:d,low:h,high:_}=this._variables,g=`plotshape_${e}`,y=this._plotshapes.get(g),p=(y==null?void 0:y.data)||[],w={value:n,color:s,textcolor:a,time:d,low:h,high:_};if(p[f]=w,this._seriesColorHandle(t,r,y),!y){this._count++;const v=s?[s]:void 0;this._verfiyArgs(t,"plotshape",e),this._plotshapes.set(g,{editable:!0,...c,data:p,location:u,id:g,colors:v,zIndex:this._count})}}plotcandle(t,e){const r=["wickcolor","bordercolor","color"];ve(t,r);const{wickcolor:n,bordercolor:s,color:a,close:u,open:c,low:f,high:d,...h}=t,{bar_index:_,time:g}=this._variables,y=`plotcandle_${e}`,p=this._plotcandles.get(y),w=(p==null?void 0:p.data)||[],v=u!==void 0&&isNaN(u)?void 0:u,x=c!==void 0&&isNaN(c)?void 0:c,b=f!==void 0&&isNaN(f)?void 0:f,C=d!==void 0&&isNaN(d)?void 0:d,E=[g,x,v,b,C];w[_]={value:E,wickcolor:n,bordercolor:s,color:a},this._seriesColorHandle(t,r,p),p||(this._count++,this._paramVerfiy(t.format,e,"plotcandle",[Gt.percent,Gt.price,Gt.volume]),this._plotcandles.set(y,{editable:!0,...h,data:w,id:y,zIndex:this._count}))}hline(t,e){const r=`hline_${e}`;ve(t,["color"]),this._verifyDisplay(t.display,"hline",e);const s=t.display&&!t.display.length?Ze.none:Ze.all;return this._hlines.has(r)||(this._count++,this._lineWidthVerify(t,e),this._hlines.set(r,{id:r,linewidth:1,editable:!0,display:s,...t,zIndex:this._count})),{type:"hline",key:r}}fill(t,e){var S,I,F,O,L,z,q,W,P,Z;const r=["color","top_color","bottom_color"];ve(t,r);const{color:n,top_color:s,bottom_color:a,seriesColors:u,hline1:c,hline2:f,plot1:d,plot2:h,top_value:_,bottom_value:g,...y}=t,{bar_index:p,time:w}=this._variables,v=`fill_${e}`,x=this._fills.get(v),b=(x==null?void 0:x.data)||[];this._verifyDisplay(t.display,"fill",e);const C=t.display&&!t.display.length?Ze.none:Ze.all;let E,A,N="plot";if(c&&f)E=(S=this._hlines.get(c==null?void 0:c.key))==null?void 0:S.price,A=(I=this._hlines.get(f==null?void 0:f.key))==null?void 0:I.price,N="hline";else{const Y=((F=this._plots.get(d==null?void 0:d.key))==null?void 0:F.data)||[],G=((O=this._plots.get(h==null?void 0:h.key))==null?void 0:O.data)||[];E=(z=(L=Y[p])==null?void 0:L.value)==null?void 0:z[1],A=(W=(q=G[p])==null?void 0:q.value)==null?void 0:W[1]}if(b[p]={time:w,color:n,top_color:s,bottom_color:a,plot1:E,plot2:A,top_value:_,bottom_value:g},this._seriesColorHandle(t,r,x),!x){this._count++;const Y=((P=this._options.indicator)==null?void 0:P.explicit_plot_zorder)||((Z=this._options.strategy)==null?void 0:Z.explicit_plot_zorder),G=n?[n]:void 0,X=s?[s]:void 0,ut=a?[a]:void 0;this._fills.set(v,{id:v,colors:G,top_colors:X,bottom_colors:ut,display:C,data:b,type:N,editable:!0,fillgaps:!1,hline1:c,hline2:f,plot1:d,plot2:h,...y,zIndex:Y?this._count:void 0})}}alert({message:t,freq:e=jr.freqOncePerBar},r){const{bar_index:n,_isRealTimeBar:s,last_bar_index:a}=this._variables,u=`alert_${r}`,c=this._cacheData[u]||{},f=c.barIndex;if(this._paramVerfiy(e,r,"alert",[jr.freqAll,jr.freqOncePerBar,jr.freqOncePerBarClose]),e===jr.freqOncePerBar&&n===f){this._alerts.delete(u);return}this._cacheData[u]=c;const d={message:t,freq:e,id:u,type:"alert"};if(s){e!==jr.freqOncePerBarClose&&this._alerts.set(u,d),c.barIndex=n;return}if(!s&&e===jr.freqOncePerBarClose&&n===f&&a===n-1){this._alerts.set(u,d),c.barIndex=n;return}this._alerts.delete(u)}alertcondition({condition:t,message:e,title:r},n){const{_isRealTimeBar:s}=this._variables,a=`alertcondition_${n}`;s&&t?this._alerts.set(a,{message:e,title:r,id:a,type:"alertcondition"}):this._alerts.delete(a)}barcolor(t,e){this._setColors(t,"barcolor",e)}bgcolor(t,e){this._setColors(t,"bgcolor",e)}_verifyDisplay(t=Eh.all,e,r){t.length&&t.length<4&&this._errorListener.addError(He(ie.displayErr,{func:e,values:"[display.none, display.all]"}),r,Rt.Error)}_setColors(t,e,r){ve(t,["color"]);const{color:s,...a}=t;this._verifyDisplay(a.display,e,r);const u=t.display&&!t.display.length?Ze.none:Ze.all,{bar_index:c,time:f}=this._variables,d=`${e}_${r}`;this._bgColors[e]||(this._bgColors[e]=new Map);const h=this._bgColors[e].get(d),_=(h==null?void 0:h.data)||[],g=(h==null?void 0:h.setColors)||[];s&&!g.includes(s)&&g.push(s),_[c]={color:s,time:f,barIndex:c},h||this._bgColors[e].set(d,{...a,display:u,data:_,setColors:g,id:d})}max_bars_back({var:t,num:e,var_name:r}){console.log(t,e,r)}float({x:t}){return t}bool({x:t}){return t||!1}string({x:t}){return t}int({x:t}){return t&&Math.trunc(t)}na({x:t}){return!!(t===void 0||typeof t=="number"&&isNaN(t))}fixnan({source:t},e){return t===void 0||typeof t=="number"&&isNaN(t)?this._cacheData[`fixnan_${e}`]:(this._cacheData[`fixnan_${e}`]=t,t)}nz({source:t,replacement:e}){return t!==void 0&&!(typeof t=="number"&&isNaN(t))?t:e||0}time({timeframe:t="",session:e,timezone:r,bars_back:n=0},s){return this._timeHandle(this._variables.time,s,t,e,r,n)}time_close({timeframe:t="",session:e,timezone:r,bars_back:n=0},s){return this._timeHandle(this._variables.time,s,t,e,r,n,!0)}timestamp(t){const{dateString:e,timezone:r,year:n,month:s,day:a,hour:u=0,minute:c=0,second:f=0}=t;if(e)return Wt(e).utc(!/GMT|UTC/.test(e)).valueOf();let d=s-1,h=n;if(d<0){const _=Math.ceil(Math.abs(d/12));d=12*_+d,h=n-_}return mr({year:h,month:d,day:a,hour:u,minute:c,second:f},r).valueOf()}weekofyear({time:t,timezone:e}){return mr(t,e).week()}year({time:t,timezone:e}){return mr(t,e).year()}second({time:t,timezone:e}){return mr(t,e).second()}month({time:t,timezone:e}){return mr(t,e).month()+1}minute({time:t,timezone:e}){return mr(t,e).minute()}hour({time:t,timezone:e}){return mr(t,e).hour()}dayofweek({time:t,timezone:e}){return mr(t,e).day()+1}dayofmonth({time:t,timezone:e}){return mr(t,e).date()}_calcTimeOffset(t,e){const r=this._variables.getTimeTradingday(t,this._variables.timeframe.period),n=gr(e,t)*1e3;return t-r-Math.floor((t-r)/n)*n}_timeHandle(t,e,r="",n,s,a=0,u=!1){const c=r||this._variables.__period,f=gr(c,t),d=gr(this._variables.__period,t);let h;if(f<=d)h=t,u&&(h+=d*1e3);else{const _=`time_${e}`,g=this._cacheData[_];if(g)g.currentTime+f*1e3-g.offset<=t?(h=t,this._cacheData[_]={currentTime:t,offset:0}):h=g.currentTime;else{const y=this._calcTimeOffset(t,c);this._cacheData[_]={currentTime:t,offset:y},h=t}u&&(h+=f*1e3)}if(n&&n!==Mn.regular&&n!==Mn.extended){const{timePeriods:_,weeks:g}=this._parserSession(n,e),y=mr(t,s),p=y.format("YYYY-MM-DD HH:mm"),w=y.format("YYYY-MM-DD"),v=h,x=mr(h,s).format("YYYY-MM-DD HH:mm");h=void 0;for(const C of _){const[E,A]=C;let N;if(E===A&&(N=y.add(1,"day").format("YYYY-MM-DD")),Wt(p).isBetween(`${w} ${E}`,`${N||w} ${A}`,"hour","[)")){Wt(x).isBetween(`${w} ${E}`,`${N||w} ${A}`,"hour","[)")?h=v:h=mr(`${w} ${E}`,s).valueOf();break}}const b=this._variables.dayofweek;h&&!g.includes(b)&&(h=void 0)}return h&&h-a*d*1e3}_seriesColorHandle(t,e,r){var n;if(r&&e!=null&&e.length)for(const s of e){if((n=r.gradientColorKeys)!=null&&n.includes(s))continue;const a=t[s];if(!a)continue;const u=r[`${s}s`]||[];u.includes(a)||(u.push(a),r[`${s}s`]=u,u.length>5&&(r[`${s}s`]=[],r.gradientColorKeys=r.gradientColorKeys||[],r.gradientColorKeys.push(s)))}}_parserSession(t,e){const r=t.split(":"),n=r[0],a=(r[1]||"1234567").split("").map(c=>{const f=parseInt(c,10);if(f<1||f>7){this._errorListener.addError(`Invalid day of week: ${c}`,e,Rt.Error);return}return f});return{timePeriods:n.split(",").map(c=>{c===""||c===Mn.regular?c="0930-1500":c===Mn.extended&&(c="1500-1830");const f=c.split("-");return f.length!==2?[]:[this._processTime(f[0],e),this._processTime(f[1],e)]}),weeks:a}}_processTime(t,e){const r=parseInt(t.slice(0,2),10),n=parseInt(t.slice(2),10);if(!(r>=0&&r<=23)&&n>=0&&n<=59){this._errorListener.addError("Invalid time: Time must be within 00:00 to 23:59",e,Rt.Error);return}return`${r}:${n}`}}const rD={1:"1M",3:"3M",5:"5M",15:"15M",30:"30M",45:"45M",60:"1H",120:"2H",180:"3H",240:"4H",D:"1D",W:"1W",M:"1MTH","3M":"3MTH","6M":"6MTH","12M":"12MTH"};let nD=class{constructor(t,e){$(this,"_variables");$(this,"_scriptId");$(this,"_cacheData");this._variables=t,this._scriptId=e,this._cacheData=new Map}security(t,e){const r=self.workerStorage.get(`request_${this._scriptId}`),{paramsExpr:n=[]}=t,s=this._getRequestData(t,e);if(r!=null&&r.has(e)){if(!s)return;const c=r.get(e);return this._runScripts(c,e,!1,n,s)}const a=this._parseExprCode(t),u=this._runScripts(a,e,!0,n,s);return r==null||r.set(e,a),u}_parseExprCode(t){let{expression:e,paramsExpr:r=[]}=t,n=[],s=1;e=Xl(e);const a=JSON.parse(e),u=a.pop();let c=(u==null?void 0:u.memberCodes)||{},f=(u==null?void 0:u.depends)||[];if(!f.length)return`return ${u==null?void 0:u.code}`;let d=[],h=[];const _=[];if(this._getDependCodes(f,a,n,d,h,_),n.push(..._),h.length){const p=r.length;let w=[];for(let v=p-1;v>=0;v--){const x=r[v];let b=JSON.parse(Xl(x));const C=[];s!==0&&h.length&&(w.unshift("{"),s++),b=b.map(S=>{const{scope:I,code:F,varNames:O,dependSelf:L}=S;return I===2&&!C.includes(O)&&!L&&(S.code=`let ${F}`),O&&C.push(...O.split(", ")),S.memberCodes&&Object.assign(c,{...S.memberCodes}),S});const E=[],A=[];let N=h.map(S=>({...S,isArg:!1,isPreArg:!0}));h=[],this._getDependCodes(N,b,A,d,h,E),w.unshift(...A,...E),n=w.concat(n),w=[]}}for(n.push(`return ${u==null?void 0:u.code}`);s>1;)n.push("}"),s--;n=d.concat(n);let g=n.join(`
62
+ `)}}if(typeof t=="string")return t;if(typeof t=="boolean")return String(t);if(typeof t=="number")return String(this._toStringFormat(t,e==null?void 0:e.replace(/0/g,"#")))}_arrToStr(t,e){return`[${t.map(n=>typeof n=="number"?this._toStringFormat(n,e):n).toString()}]`}substring({source:t="",begin_pos:e=0,end_pos:r}){return mt(e)&&(e=0),mt(r)&&(r=void 0),t==null?void 0:t.substring(e,r)}startswith({source:t="",str:e=""}){return t==null?void 0:t.startsWith(e)}format_time({time:t,format:e="yyyy-MM-dd'T'HH:mm:ssZ",timezone:r}){return mt(t)&&(t=0),mr(t,r).format(e)}replace_all({source:t="",target:e="",replacement:r=""}){return t==null?void 0:t.replace(new RegExp(e,"g"),r)}_toStringFormat(t,e){if(!e)return Number(t.toFixed(this._precision));switch(e){case Gt.mintick:return t.toFixed(this._precision);case Gt.percent:return`${t}%`;case Gt.volume:return this._intlNumberFormatter.format(Math.round(t));default:return this._formatOthers(t,e)}}_formatOthers(t,e){var u;let[r,n]=e.split(".");e.split("%").length===2&&(t=t*100);let[s,a=""]=String(t).split(".");if(r.includes("#")){if(r.includes(",")){const c=r.split(","),f=((u=c[c.length-1])==null?void 0:u.replace(/[^#]/g,"").length)||0;f&&(s=s.replace(new RegExp(`\\B(?=(\\d{${f}})+(?!\\d))`,"g"),",")),r=c.join("")}s=r.replace(/#/,s).replace(/#/g,"")}else s=`${r}${s}`;if(n&&n.includes("#")){const c=n.split("#").length-1,f=+`${s}.${a}`;if(!isNaN(f))return`${f.toFixed(c)}${n.replace(/#/g,"")}`;a=`${a.substring(0,c)}${n.replace(/#/g,"")}`}else a=n||"";return a?`${s}.${a}`:s}_formatNumber(t,e){if(!e)return Number(t.toFixed(this._precision));switch(e){case"integer":return String(Math.round(t));case"currency":return`$${t}`;case"percent":return`${t*100}%`;default:return this._formatOthers(t,e)}}strformat({formatString:t=""},e,r){return this._strFormat(t,e,r)}_strFormat(t,e,r){return t.replace(/{[^{}]+}/g,n=>{if(!n)return n;const s=n.replace(/[{}]/g,"").split(","),a=Number(s[0]);if(isNaN(a)||e.length<=a)return n;const u=e[a];if(s.length===1)return typeof u=="number"&&r?this._intlFormat.format(u):u;if(s.length===2){const c=s[1].trim();return c==="number"?r?this._intlFormat.format(u):u:c==="date"?Wt(u).format("LL"):n}else{const c=s[1].trim(),f=s[2].trim();if(c==="number")return this._formatNumber(u,f);if(c==="date"){let d="YYYY-MM-DD";switch(f){case"long":d="LL";break;case"short":d="L";break;default:f&&(d=f)}return Wt(u).format(d)}return n}})}}class cw{constructor(t){$(this,"_errorListener");this._errorListener=t}new(){return new nu(this._errorListener)}copy({id:t}){return t==null?void 0:t.copy()}get({id:t,key:e}){return t==null?void 0:t.get({key:e})}put({id:t,key:e,value:r}){return t==null?void 0:t.put({key:e,value:r})}keys({id:t}){return t==null?void 0:t.keys()}size({id:t}){return t==null?void 0:t.size()}clear({id:t}){t==null||t.clear()}remove({id:t,key:e}){return t==null?void 0:t.remove({key:e})}values({id:t}){return t==null?void 0:t.values()}put_all({id:t,id2:e}){t==null||t.put_all({id2:e})}contains({id:t,key:e}){return t==null?void 0:t.contains({key:e})}}class nu{constructor(t){$(this,"_errorListener");$(this,"_mapInstance");this._errorListener=t,this._mapInstance=new Map}get isMap(){return!0}_copyMap(t){const e=new nu(this._errorListener);return e._mapInstance=new Map(t.entries()),e}copy(){return this._copyMap(this._mapInstance)}get({key:t}){return this._mapInstance.get(t)}put({key:t,value:e}){return this._mapInstance.set(t,e)}keys(){const t=new ee(0,void 0,this._errorListener);return t._value=[...this._mapInstance.keys()],t}size(){return this._mapInstance.size}clear(){this._mapInstance.clear()}remove({key:t}){const e=this._mapInstance.get(t);return this._mapInstance.delete(t),e||void 0}values(){const t=new ee(0,void 0,this._errorListener);return t._value=[...this._mapInstance.values()],t}put_all({id2:t}){this._mapInstance=new Map([...this._mapInstance,...t._mapInstance])}contains({key:t}){return this._mapInstance.has(t)}}class fw{constructor(t){$(this,"_variables");this._variables=t}new({price:t,time:e,index:r}){return new Bi(t,r,e)}now({price:t}){const{time:e,bar_index:r}=this._variables;return new Bi(t,r,e)}copy({id:t}){return t==null?void 0:t.copy()}from_index({price:t,index:e}){return new Bi(t,e)}from_time({price:t,time:e}){return new Bi(t,void 0,e)}}class Bi{constructor(t,e,r){$(this,"_index");$(this,"_price");$(this,"_time");this._index=e,this._price=t,this._time=r}get index(){return this._index}set index(t){this._index=t}get price(){return this._price}set price(t){this._price=t}get time(){return this._time}set time(t){this._time=t}copy(){return new Bi(this._price,this._index,this._time)}}class hw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultLabel",{text:"",xloc:be.bar_index,yloc:Vr.price,size:ir.normal,style:ye.styleLabelDown,textalign:jt.alignCenter});this._variables=t,this._errorListener=e}new(t,e){const{time:r,high:n,low:s,bar_index:a}=this._variables,u=`label_${e}_${a}`;ve(t,["color","textcolor"]);const c={...this._defaultLabel,...t,id:u,time:r,high:n,low:s,bar_index:a};t.point&&(c.x=c.xloc===be.bar_index?t.point.index:t.point.time,c.y=t.point.price),c.yloc===Vr.abovebar?c.y=n:c.yloc===Vr.belowbar&&(c.y=s),this._verfiyArgs(t,e);const f=new go(u,this._variables,this._errorListener);return e.startsWith("export")||this._variables.label.add(u,c,f),f}_verfiyArgs(t,e){const{xloc:r,yloc:n,style:s,size:a,textalign:u,text_font_family:c}=t,f="label.new";this._paramVerfiy(s,e,f,Object.values(ye),"style"),this._paramVerfiy(r,e,f,Object.values(be),"xloc"),this._paramVerfiy(n,e,f,Object.values(Vr),"yloc"),this._paramVerfiy(a,e,f,Object.values(ir),"size"),this._paramVerfiy(u,e,f,[jt.alignLeft,jt.alignCenter,jt.alignRight],"textalign"),this._paramVerfiy(c,e,f,Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}label(t){return t.x}copy({id:t},e){return t==null?void 0:t.copy(e)}get_x({id:t},e){return t==null?void 0:t.get_x(e)}get_y({id:t},e){return t==null?void 0:t.get_y(e)}set_x({id:t,...e},r){t==null||t.set_x(e,r)}set_y({id:t,...e},r){t==null||t.set_y(e,r)}delete({id:t}){t==null||t.delete()}get_text({id:t},e){return t==null?void 0:t.get_text(e)}set_xy({id:t,...e},r){t==null||t.set_xy(e,r)}set_size({id:t,...e},r){t==null||t.set_size(e,r)}set_xloc({id:t,...e},r){t==null||t.set_xloc(e,r)}set_yloc({id:t,...e},r){t==null||t.set_yloc(e,r)}set_style({id:t,...e},r){t==null||t.set_style(e,r)}set_color({id:t,...e},r){t==null||t.set_color(e,r)}set_tooltip({id:t,...e},r){t==null||t.set_tooltip(e,r)}set_point({id:t,...e},r){t==null||t.set_point(e,r)}set_text({id:t,...e},r){t==null||t.set_text(e,r)}set_textcolor({id:t,...e},r){t==null||t.set_textcolor(e,r)}set_textalign({id:t,...e},r){t==null||t.set_textalign(e,r)}set_text_font_family({id:t,...e},r){t==null||t.set_text_font_family(e,r)}}class go{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");this._id=t,this._variables=e,this._errorListener=r}get type(){return te.LABEL}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.label.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`label_${t}_${e}`,n=this._getLabel(t),s=new go(r,this._variables,this._errorListener);if(n){const a={...n,id:r,bar_index:e};this._variables.label.add(r,a,s)}return s}get_x(t){var e;return(e=this._getLabel(t))==null?void 0:e.x}get_y(t){var e;return(e=this._getLabel(t))==null?void 0:e.y}set_x({x:t},e){const r=this._getLabel(e);r&&(r.x=t)}set_y({y:t},e){const r=this._getLabel(e);r&&(r.y=t)}delete(){this._variables.label.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}set_xy({x:t,y:e},r){const n=this._getLabel(r);n&&(n.x=t,n.y=e)}get_text(t){var e;return(e=this._getLabel(t))==null?void 0:e.text}set_size({size:t},e){const r=this._getLabel(e);r&&(r.size=t),this._paramVerfiy(t,e,"label.set_size",Object.values(ir),"size")}set_text({text:t},e){const r=this._getLabel(e);r&&(r.text=t)}set_xloc({x:t,xloc:e},r){const n=this._getLabel(r);n&&(n.x=t,n.xloc=e,this._paramVerfiy(e,r,"label.set_xloc",Object.values(be),"xloc"))}set_yloc({yloc:t},e){const r=this._getLabel(e),{high:n,low:s}=this._variables;r&&(r.yloc=t,t===Vr.abovebar?r.y=n:t===Vr.belowbar&&(r.y=s),this._paramVerfiy(t,e,"label.set_yloc",Object.values(Vr),"yloc"))}set_color(t,e){const r=this._getLabel(e);ve(t,["color"]),r&&(r.color=t.color)}set_point({point:t},e){const r=this._getLabel(e);r&&(r.x=r.xloc===be.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,r.y=t==null?void 0:t.price)}set_style({style:t},e){const r=this._getLabel(e);r&&(r.style=t),this._paramVerfiy(t,e,"label.set_style",Object.values(ye),"style")}set_tooltip({tooltip:t},e){const r=this._getLabel(e);r&&(r.tooltip=t)}set_textalign({textalign:t},e){const r=this._getLabel(e);r&&(r.textalign=t),this._paramVerfiy(t,e,"label.set_textalign",[jt.alignLeft,jt.alignCenter,jt.alignRight],"textalign")}set_textcolor(t,e){const r=this._getLabel(e);ve(t,["textcolor"]),r&&(r.textcolor=t.textcolor)}set_text_font_family({text_font_family:t},e){const r=this._getLabel(e);r&&(r.text_font_family=t),this._paramVerfiy(t,e,"label.set_text_font_family",Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getLabel(t){const e=this._variables.label.get(this._id);return e||console.log(`错误${t}: label 不存在`),e}}const dw={freq_all:jr.freqAll,freq_once_per_bar:jr.freqOncePerBar,freq_once_per_bar_close:jr.freqOncePerBarClose},_w={gaps_off:ln.gapsOff,gaps_on:ln.gapsOn,lookahead_off:ln.lookaheadOff,lookahead_on:ln.lookaheadOn},Ti={aqua:"#00BCD4",black:"#363A45",blue:"#2196F3",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"},xh={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"},pw={friday:6,monday:2,saturday:7,sunday:1,thursday:5,tuesday:3,wednesday:4},Eh={all:[Ze.dataWindow,Ze.pane,Ze.priceScale,Ze.statusLine],data_window:[Ze.dataWindow],none:[],pane:[Ze.pane],price_scale:[Ze.priceScale],status_line:[Ze.statusLine]},mw={both:Yr.both,left:Yr.left,none:Yr.none,right:Yr.right},gw={inherit:Gt.inherit,mintick:Gt.mintick,percent:Gt.percent,price:Gt.price,volume:Gt.volume},vw={style_solid:Ss.styleSolid,style_dashed:Ss.styleDashed,style_dotted:Ss.styleDotted},yw={style_arrowdown:ye.styleArrowdown,style_arrowup:ye.styleArrowup,style_circle:ye.styleCircle,style_cross:ye.styleCross,style_diamond:ye.styleDiamond,style_flag:ye.styleFlag,style_label_center:ye.styleLabelCenter,style_label_down:ye.styleLabelDown,style_label_left:ye.styleLabelLeft,style_label_lower_left:ye.styleLabelLowerLeft,style_label_lower_right:ye.styleLabelLowerRight,style_label_right:ye.styleLabelRight,style_label_up:ye.styleLabelUp,style_label_upper_left:ye.styleLabelUpperLeft,style_label_upper_right:ye.styleLabelUpperRight,style_none:ye.styleNone,style_square:ye.styleSquare,style_text_outline:ye.styleTextOutline,style_triangledown:ye.styleTriangledown,style_triangleup:ye.styleTriangleup,style_xcross:ye.styleXcross},ww={style_arrow_both:Re.styleArrowBoth,style_arrow_left:Re.styleArrowLeft,style_arrow_right:Re.styleArrowRight,style_dashed:Re.styleDashed,style_dotted:Re.styleDotted,style_solid:Re.styleSolid},Dw={abovebar:cn.abovebar,absolute:cn.absolute,belowbar:cn.belowbar,bottom:cn.bottom,top:cn.top},bw={e:2.718281828459045,phi:1.618033988749895,pi:3.141592653589793,rphi:.6180339887498948},xw={style_area:Or.styleArea,style_areabr:Or.styleAreabr,style_circles:Or.styleCircles,style_columns:Or.styleColumns,style_cross:Or.styleCross,style_histogram:Or.styleHistogram,style_line:Or.styleLine,style_linebr:Or.styleLinebr,style_stepline:Or.styleStepline,style_stepline_diamond:Or.styleSteplineDiamond,style_steplinebr:Or.styleSteplinebr},Ew={bottom_center:vr.bottomCenter,bottom_left:vr.bottomLeft,bottom_right:vr.bottomRight,middle_center:vr.middleCenter,middle_left:vr.middleLeft,middle_right:vr.middleRight,top_center:vr.topCenter,top_left:vr.topLeft,top_right:vr.topRight},Cw={left:Os.left,none:Os.none,right:Os.right},Aw={arrowdown:lr.arrowdown,arrowup:lr.arrowup,circle:lr.circle,cross:lr.cross,diamond:lr.diamond,flag:lr.flag,labeldown:lr.labeldown,labelup:lr.labelup,square:lr.square,triangledown:lr.triangledown,triangleup:lr.triangleup,xcross:lr.xcross},Mw={auto:ir.auto,huge:ir.huge,large:ir.large,normal:ir.normal,small:ir.small,tiny:ir.tiny},Fw={cash:Pe.cash,fixed:Pe.fixed,percent_of_equity:Pe.percentOfEquity,commission:{cash_per_contract:je.cashPerContract,cash_per_order:je.cashPerOrder,percent:je.percent},direction:{all:fe.all,long:fe.long,short:fe.short},oca:{cancel:fn.cancel,none:fn.none,reduce:fn.reduce}},Nw={align_bottom:jt.alignBottom,align_center:jt.alignCenter,align_left:jt.alignLeft,align_right:jt.alignRight,align_top:jt.alignTop,wrap_auto:jt.wrapAuto,wrap_none:jt.wrapNone},Sw={bar_index:be.bar_index,bar_time:be.bar_time},Ow={abovebar:Vr.abovebar,belowbar:Vr.belowbar,price:Vr.price},Bw={actual:Bs.actual,estimate:Bs.estimate,standardized:Bs.standardized};class Ch{constructor(){$(this,"adjustment",{dividends:Ns.dividends,none:Ns.none,splits:Ns.splits});$(this,"alert",dw);$(this,"barmerge",_w);$(this,"color",Ti);$(this,"currency",xh);$(this,"dayofweek",pw);$(this,"earnings",Bw);$(this,"display",Eh);$(this,"extend",mw);$(this,"font",{family_default:Jn.familyDefault,family_monospace:Jn.familyMonospace});$(this,"format",gw);$(this,"hline",vw);$(this,"label",yw);$(this,"line",ww);$(this,"location",Dw);$(this,"math",bw);$(this,"order",{ascending:Gn.ascending,descending:Gn.descending});$(this,"plot",xw);$(this,"position",Ew);$(this,"scale",Cw);$(this,"session",{extended:Mn.extended,regular:Mn.regular});$(this,"shape",Aw);$(this,"size",Mw);$(this,"splits",{denominator:"denominator",numerator:"numerator"});$(this,"strategy",Fw);$(this,"text",Nw);$(this,"xloc",Sw);$(this,"yloc",Ow)}updateData(){}}class Tw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultPolyline",{curved:!1,closed:!1,xloc:be.bar_index,line_color:Ti.blue,line_style:Re.styleSolid,line_width:1});this._variables=t,this._errorListener=e}new(t,e){var u;const{bar_index:r}=this._variables,n=`polyline_${e}_${r}`,s=Object.assign({},this._defaultPolyline,t,{id:n,bar_index:r,points:(u=t.points)==null?void 0:u._value.map(c=>({time:c.time,index:c.index,price:c.price}))});ve(s,["line_color","fill_color"]);const a=new Ah(n,this._variables);return this._verfiyArgs(t,e),e.startsWith("export")||this._variables.polyline.add(n,s,a),a}_verfiyArgs(t,e){const{line_style:r,xloc:n}=t,s="polyline.new";this._paramVerfiy(r,e,s,Object.values(Re),"line_style"),this._paramVerfiy(n,e,s,Object.values(be),"xloc")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}delete({id:t}){t&&t.delete()}}class Ah{constructor(t,e){$(this,"_id");$(this,"_variables");$(this,"_suffix");this._variables=e,this._id=t}get type(){return te.POLYLINE}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.polyline.get(this._id)}delete(){this._variables.polyline.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}}class Iw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultLine",{xloc:be.bar_index,extend:Yr.none,style:Re.styleSolid});this._variables=t,this._errorListener=e}new({first_point:t,second_point:e,...r},n){const{bar_index:s}=this._variables,a=`line_${n}_${s}`;ve(r,["color"]);const u={...this._defaultLine,...r,id:a,bar_index:s};if(t&&e){const f=u.xloc===be.bar_index?t==null?void 0:t.index:t==null?void 0:t.time,d=u.xloc===be.bar_index?e==null?void 0:e.index:e==null?void 0:e.time;Object.assign(u,{x1:f,y1:t==null?void 0:t.price,x2:d,y2:e==null?void 0:e.price})}this._verfiyArgs(r,n);const c=new vo(a,this._variables,this._errorListener);return n.startsWith("export")||this._variables.line.add(a,u,c),c}_verfiyArgs(t,e){const{extend:r,xloc:n,style:s}=t,a="line.new";this._paramVerfiy(s,e,a,Object.values(Re),"style"),this._paramVerfiy(r,e,a,Object.values(Yr),"extend"),this._paramVerfiy(n,e,a,Object.values(be),"xloc")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}line(t){return t.x}copy({id:t},e){return t==null?void 0:t.copy(e)}delete({id:t}){t==null||t.delete()}get_x1({id:t},e){return t==null?void 0:t.get_x1(e)}get_x2({id:t},e){return t==null?void 0:t.get_x2(e)}get_y1({id:t},e){return t==null?void 0:t.get_y1(e)}get_y2({id:t},e){return t==null?void 0:t.get_y2(e)}set_x1({id:t,...e},r){t==null||t.set_x1(e,r)}set_x2({id:t,...e},r){t==null||t.set_x2(e,r)}set_y1({id:t,...e},r){t==null||t.set_y1(e,r)}set_y2({id:t,...e},r){t==null||t.set_y2(e,r)}set_xy1({id:t,...e},r){t==null||t.set_xy1(e,r)}set_xy2({id:t,...e},r){t==null||t.set_xy2(e,r)}set_xloc({id:t,...e},r){t==null||t.set_xloc(e,r)}get_price({id:t,...e},r){return t==null?void 0:t.get_price(e,r)}set_color({id:t,...e},r){t==null||t.set_color(e,r)}set_style({id:t,...e},r){t==null||t.set_style(e,r)}set_width({id:t,...e},r){t==null||t.set_width(e,r)}set_extend({id:t,...e},r){t==null||t.set_extend(e,r)}set_first_point({id:t,...e},r){t==null||t.set_first_point(e,r)}set_second_point({id:t,...e},r){t==null||t.set_second_point(e,r)}}class vo{constructor(t,e,r){$(this,"_variables");$(this,"_id");$(this,"_suffix","");$(this,"_errorListener");this._id=t,this._variables=e,this._errorListener=r}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get type(){return te.LINE}get data(){return this._variables.line.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`line_${t}_${e}`,n=this._getLine(t),s=new vo(r,this._variables,this._errorListener);return n&&this._variables.line.add(r,{...n,id:r,bar_index:e,isVar:void 0},s),s}delete(){this._variables.line.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_price({x:t},e){const r=this._getLine(e);if(t===void 0)return t;if(r&&r.xloc===be.bar_index){const{x1:n,y1:s,x2:a,y2:u}=r;return n===void 0||a===void 0||s===void 0||u===void 0?void 0:(u-s)/(a-n)*(t-n)+s}}get_x1(t){var e;return(e=this._getLine(t))==null?void 0:e.x1}get_x2(t){var e;return(e=this._getLine(t))==null?void 0:e.x2}get_y1(t){var e;return(e=this._getLine(t))==null?void 0:e.y1}get_y2(t){var e;return(e=this._getLine(t))==null?void 0:e.y2}set_x1({x:t},e){const r=this._getLine(e);r&&(r.x1=t)}set_x2({x:t},e){const r=this._getLine(e);r&&(r.x2=t)}set_y1({y:t},e){const r=this._getLine(e);r&&(r.y1=t)}set_y2({y:t},e){const r=this._getLine(e);r&&(r.y2=t)}set_xy1({x:t,y:e},r){const n=this._getLine(r);n&&(n.x1=t,n.y1=e)}set_xy2({x:t,y:e},r){const n=this._getLine(r);n&&(n.x2=t,n.y2=e)}set_xloc({xloc:t,x1:e,x2:r},n){const s=this._getLine(n);s&&(s.xloc=t,s.x1=e,s.x2=r,this._paramVerfiy(t,n,"line.set_xloc",Object.values(be),"xloc"))}set_color(t,e){const r=this._getLine(e);r&&(ve(t,["color"]),r.color=t.color)}set_style({style:t},e){const r=this._getLine(e);r&&(r.style=t,this._paramVerfiy(t,e,"line.set_style",Object.values(Re),"style"))}set_width({width:t},e){const r=this._getLine(e);r&&(r.width=t)}set_extend({extend:t},e){const r=this._getLine(e);r&&(r.extend=t,this._paramVerfiy(t,e,"line.set_extend",Object.values(Yr),"extend"))}set_first_point({point:t},e){const r=this._getLine(e);if(r){const{index:n,time:s,price:a}=t||{},u=r.xloc===be.bar_index?n:s,c=a;u&&(r.x1=u),c&&(r.y1=c)}}set_second_point({point:t},e){const r=this._getLine(e);if(r){const{index:n,time:s,price:a}=t||{},u=r.xloc===be.bar_index?n:s,c=a;u&&(r.x2=u),c&&(r.y2=c)}}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getLine(t){const e=this._variables.line.get(this._id);return e||console.log(`${t}: line 不存在`),e}}class $w{constructor(t){$(this,"_variables");this._variables=t}new(t,e){const{line1:r,line2:n}=t,{bar_index:s}=this._variables,a=`linefill_${e}_${s}`,u=r==null?void 0:r.data,c=n==null?void 0:n.data;u&&(u.linefills=u.linefills||[],u.linefills.push(a)),c&&(c.linefills=c.linefills||[],c.linefills.push(a)),ve(t,["color"]);const f=new yo(this._variables,a,r,n);return e.startsWith("export")||(u||c)&&this._variables.linefill.add(a,{line1:u,line2:c,color:t.color,id:a,bar_index:s},f),f}delete({id:t}){t==null||t.delete()}get_line1({id:t}){return t==null?void 0:t.get_line1()}get_line2({id:t}){return t==null?void 0:t.get_line2()}set_color({id:t,...e}){t==null||t.set_color(e)}}class yo{constructor(t,e,r,n){$(this,"_id");$(this,"_line1");$(this,"_line2");$(this,"_variables");$(this,"_suffix");this._variables=t,this._id=e,this._line1=r,this._line2=n}get type(){return te.LINEFILL}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.linefill.get(this._id)}linefill(t,e){return t.x?t.x:new yo(this._variables,e)}delete(){var e,r;const t=this._variables.linefill.get(this._id);if(t){const{line1:n,line2:s}=t;n&&(n.linefills=(e=n.linefills)==null?void 0:e.filter(a=>a!==this._id)),s&&(s.linefills=(r=s.linefills)==null?void 0:r.filter(a=>a!==this._id))}this._line1=void 0,this._line2=void 0,this._variables.linefill.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_line1(){return this._line1}get_line2(){return this._line2}set_color(t){const e=this._variables.linefill.get(this._id);e&&(ve(t,["color"]),e.color=t.color)}}class Lw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultBox",{border_color:Ti.blue,border_width:1,bgcolor:Ti.blue,xloc:be.bar_index,extend:Yr.none,style:Re.styleSolid,text:"",text_size:ir.auto,text_color:Ti.black,text_halign:jt.alignCenter,text_valign:jt.alignCenter,text_wrap:jt.wrapNone});this._variables=t,this._errorListener=e}box({x:t}){return t}new({top_left:t,bottom_right:e,...r},n){const{bar_index:s}=this._variables,a=`box_${n}_${s}`,u={...this._defaultBox,...r,id:a,bar_index:s};if(ve(u,["border_color","bgcolor","text_color"]),t){const{price:f,time:d,index:h}=t;u.top=f,u.left=u.xloc===be.bar_index?h:d}if(e){const{price:f,time:d,index:h}=e;u.bottom=f,u.right=u.xloc===be.bar_index?h:d}this._verfiyArgs(r,n);const c=new wo(this._variables,a,this._errorListener);return n.startsWith("export")||this._variables.box.add(a,u,c),c}_verfiyArgs(t,e){const{border_style:r,extend:n,xloc:s,text_size:a,text_halign:u,text_valign:c,text_wrap:f,text_font_family:d}=t,h="box.new";this._paramVerfiy(r,e,h,[Re.styleDashed,Re.styleDotted,Re.styleSolid],"border_style"),this._paramVerfiy(n,e,h,Object.values(Yr),"extend"),this._paramVerfiy(s,e,h,Object.values(be),"xloc"),this._paramVerfiy(a,e,h,Object.values(ir),"text_size"),this._paramVerfiy(u,e,h,[jt.alignLeft,jt.alignCenter,jt.alignRight],"text_halign"),this._paramVerfiy(c,e,h,[jt.alignBottom,jt.alignCenter,jt.alignTop],"text_valign"),this._paramVerfiy(f,e,h,[jt.wrapAuto,jt.wrapNone],"text_wrap"),this._paramVerfiy(d,e,h,Object.values(Jn),"text_font_family")}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}copy({id:t},e){return t==null?void 0:t.copy(e)}delete({id:t}){t==null||t.delete()}get_top({id:t}){return t==null?void 0:t.get_top()}get_bottom({id:t}){return t==null?void 0:t.get_bottom()}get_left({id:t}){return t==null?void 0:t.get_left()}get_right({id:t}){return t==null?void 0:t.get_right()}set_top({id:t,...e}){t==null||t.set_top(e)}set_bottom({id:t,...e}){t==null||t.set_bottom(e)}set_text({id:t,...e}){t==null||t.set_text(e)}set_left({id:t,...e}){t==null||t.set_left(e)}set_right({id:t,...e}){t==null||t.set_right(e)}set_extend({id:t,...e},r){t==null||t.set_extend(e,r)}set_bgcolor({id:t,...e}){t==null||t.set_bgcolor(e)}set_border_color({id:t,...e}){t==null||t.set_border_color(e)}set_border_width({id:t,...e}){t==null||t.set_border_width(e)}set_border_style({id:t,...e},r){t==null||t.set_border_style(e,r)}set_lefttop({id:t,...e}){t==null||t.set_lefttop(e)}set_rightbottom({id:t,...e}){t==null||t.set_rightbottom(e)}set_text_size({id:t,...e},r){t==null||t.set_text_size(e,r)}set_text_wrap({id:t,...e},r){t==null||t.set_text_wrap(e,r)}set_text_color({id:t,...e}){t==null||t.set_text_color(e)}set_text_halign({id:t,...e},r){t==null||t.set_text_halign(e,r)}set_text_valign({id:t,...e},r){t==null||t.set_text_valign(e,r)}set_top_left_point({id:t,...e}){t==null||t.set_top_left_point(e)}set_bottom_right_point({id:t,...e}){t==null||t.set_bottom_right_point(e)}set_text_font_family({id:t,...e},r){t==null||t.set_text_font_family(e,r)}}class wo{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");this._variables=t,this._id=e,this._errorListener=r}get type(){return te.BOX}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.box.get(this._id)}copy(t){const{bar_index:e}=this._variables,r=`box_${t}_${e}`,n=this._getBox(),s=new wo(this._variables,r,this._errorListener);return n&&this._variables.box.add(r,{...n,id:r,bar_index:e},s),s}delete(){this._variables.box.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}get_top(){const t=this._getBox();return t&&t.top}set_top({top:t}){const e=this._getBox();e&&(e.top=t)}get_left(){const t=this._getBox();return t&&t.left}set_left({left:t}){const e=this._getBox();e&&(e.left=t)}set_text({text:t}){const e=this._getBox();e&&(e.text=t)}get_right(){const t=this._getBox();return t&&t.right}set_right({right:t}){const e=this._getBox();e&&(e.right=t)}get_bottom(){const t=this._getBox();return t&&t.bottom}set_bottom({bottom:t}){const e=this._getBox();e&&(e.bottom=t)}set_extend({extend:t},e){const r=this._getBox();r&&(r.extend=t,this._paramVerfiy(t,e,"box.set_extend",Object.values(Yr),"extend"))}set_bgcolor({color:t}){const e=this._getBox();e&&(e.bgcolor=t,ve(e,["bgcolor"]))}set_lefttop({left:t,top:e}){const r=this._getBox();r&&(r.left=t,r.top=e)}set_text_size({text_size:t},e){const r=this._getBox();r&&(r.text_size=t,this._paramVerfiy(t,e,"box.set_text_size",Object.values(ir),"text_size"))}set_text_wrap({text_wrap:t},e){const r=this._getBox();r&&(r.text_wrap=t,this._paramVerfiy(t,e,"box.set_text_wrap",[jt.wrapAuto,jt.wrapNone],"text_wrap"))}set_text_color({text_color:t}){const e=this._getBox();e&&(e.text_color=t,ve(e,["text_color"]))}set_rightbottom({right:t,bottom:e}){const r=this._getBox();r&&(r.right=t,r.bottom=e)}set_text_halign({text_halign:t},e){const r=this._getBox();r&&(r.text_halign=t,this._paramVerfiy(t,e,"box.set_text_halign",[jt.alignLeft,jt.alignCenter,jt.alignRight],"text_halign"))}set_text_valign({text_valign:t},e){const r=this._getBox();r&&(r.text_valign=t,this._paramVerfiy(t,e,"box.set_text_valign",[jt.alignBottom,jt.alignCenter,jt.alignTop],"text_valign"))}set_top_left_point({point:t}){const e=this._getBox();if(e){const{index:r,price:n,time:s}=t||{};e.top=n,e.left=e.xloc===be.bar_index?r:s}}set_border_color({color:t}){const e=this._getBox();e&&(e.border_color=t,ve(e,["border_color"]))}set_border_style({style:t},e){const r=this._getBox();r&&(r.border_style=t,this._paramVerfiy(t,e,"box.set_border_style",[Re.styleDashed,Re.styleDotted,Re.styleSolid],"style"))}set_border_width({width:t}){const e=this._getBox();e&&(e.border_width=t)}set_bottom_right_point({point:t}){const e=this._getBox();if(e){const{index:r,price:n,time:s}=t||{};e.bottom=n,e.right=e.xloc===be.bar_index?r:s}}set_text_font_family({text_font_family:t},e){const r=this._getBox();r&&(r.text_font_family=t,this._paramVerfiy(t,e,"box.set_text_font_family",Object.values(Jn),"text_font_family"))}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getBox(){return this._variables.box.get(this._id)}}class Rw{constructor(t,e){$(this,"_variables");$(this,"_errorListener");$(this,"_defaultTable",{position:vr.topLeft,columns:0,rows:0,frame_width:0,border_width:0});this._variables=t,this._errorListener=e}table({x:t}){return t}new(t,e){const{bar_index:r}=this._variables,n=`table_${e}_${r}`,{rows:s}=t;ve(t,["text_color","bgcolor","border_color"]);const a=Array.from(Array(s),()=>[]),u=e.split("_"),c=u.pop(),f=u.pop(),d={...this._defaultTable,...t,cell:a,id:n,bar_index:r,line:f,col:c},h=new Mh(this._variables,n,this._errorListener);return this._paramVerfiy(t.position,e,"table.new",Object.values(vr),"position"),e.startsWith("export")||this._variables.table.add(n,d,h),h}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}cell({table_id:t,...e}){t==null||t.cell(e)}cell_set_bgcolor({table_id:t,...e}){t==null||t.cell_set_bgcolor(e)}cell_set_height({table_id:t,...e}){t==null||t.cell_set_height(e)}cell_set_text({table_id:t,...e}){t==null||t.cell_set_text(e)}cell_set_text_color({table_id:t,...e}){t==null||t.cell_set_text_color(e)}cell_set_text_font_family({table_id:t,...e}){t==null||t.cell_set_text_font_family(e)}cell_set_text_halign({table_id:t,...e}){t==null||t.cell_set_text_halign(e)}cell_set_text_valign({table_id:t,...e}){t==null||t.cell_set_text_valign(e)}cell_set_text_size({table_id:t,...e}){t==null||t.cell_set_text_size(e)}cell_set_tooltip({table_id:t,...e}){t==null||t.cell_set_tooltip(e)}cell_set_width({table_id:t,...e}){t==null||t.cell_set_width(e)}clear({table_id:t,...e}){t==null||t.clear(e)}delete({table_id:t}){t==null||t.delete()}merge_cells({table_id:t,...e},r){t==null||t.merge_cells(e,r)}set_bgcolor({table_id:t,...e}){t==null||t.set_bgcolor(e)}set_border_color({table_id:t,...e}){t==null||t.set_border_color(e)}set_border_width({table_id:t,...e}){t==null||t.set_border_width(e)}set_frame_color({table_id:t,...e}){t==null||t.set_frame_color(e)}set_frame_width({table_id:t,...e}){t==null||t.set_frame_width(e)}set_position({table_id:t,...e},r){t==null||t.set_position(e,r)}}class Mh{constructor(t,e,r){$(this,"_id");$(this,"_variables");$(this,"_errorListener");$(this,"_suffix","");$(this,"_defaultCell",{column:0,row:0,text:"",text_color:Ti.black,text_halign:jt.alignCenter,text_valign:jt.alignCenter,text_size:ir.normal});this._variables=t,this._id=e,this._errorListener=r}get type(){return te.TABLE}get id(){return this._id}updateId(){const{bar_index:t}=this._variables;if(!this._suffix)this._suffix=`_${t}`,this._id=`${this._id}${this._suffix}`;else{const e=this._id.split("_");e.pop(),this._id=`${e.join("_")}_${t}`}return this._id}get data(){return this._variables.table.get(this._id)}cell(t){const e={...this._defaultCell,...t},{column:r=0,row:n=0}=e,s=this._variables.table.get(this._id);if(s){const a=s.cell||[],u=a[n]||[];u[r]=e,a[n]=u,s.cell=a}}cell_set_bgcolor({column:t=0,row:e=0,bgcolor:r}){const n=this._getTableItem(t,e);n&&(n.bgcolor=r)}cell_set_height({column:t=0,row:e=0,height:r}){const n=this._getTableItem(t,e);n&&(n.height=r)}cell_set_text({column:t=0,row:e=0,text:r}){const n=this._getTableItem(t,e);n&&(n.text=r)}cell_set_text_color({column:t=0,row:e=0,text_color:r}){const n=this._getTableItem(t,e);n&&(n.text_color=r,ve(n,["text_color"]))}cell_set_text_font_family({column:t=0,row:e=0,text_font_family:r}){const n=this._getTableItem(t,e);n&&(n.text_font_family=r)}cell_set_text_halign({column:t=0,row:e=0,text_halign:r}){const n=this._getTableItem(t,e);n&&(n.text_halign=r)}cell_set_text_valign({column:t=0,row:e=0,text_valign:r}){const n=this._getTableItem(t,e);n&&(n.text_valign=r)}cell_set_text_size({column:t=0,row:e=0,text_size:r}){const n=this._getTableItem(t,e);n&&(n.text_size=r)}cell_set_tooltip({column:t=0,row:e=0,tooltip:r}){const n=this._getTableItem(t,e);n&&(n.tooltip=r)}cell_set_width({column:t=0,row:e=0,width:r}){const n=this._getTableItem(t,e);n&&(n.width=r)}clear({start_column:t=0,start_row:e=0,end_column:r=0,end_row:n=0}){const s=this._variables.table.get(this._id);if(s){const a=s.cell;if(a)for(let u=e;u<=n;u++)for(let c=t;c<=r;c++){const f=a[u];f&&(f[c]=void 0)}}}delete(){this._variables.table.delete(this._id,this._variables._isRealTimeBar?void 0:this._variables.bar_index)}merge_cells({start_column:t=0,start_row:e=0,end_column:r=0,end_row:n=0},s){if(t>r||e>n){this._errorListener.addError(ie.mergeCellErr,s,Rt.Error);return}const a=this._variables.table.get(this._id);if(!a)return;const u=a.merge_cells||[];u.push({start_column:t,start_row:e,end_column:r,end_row:n}),a.merge_cells=u}set_bgcolor({bgcolor:t}){const e=this._variables.table.get(this._id);e&&(e.bgcolor=t,ve(e,["bgcolor"]))}set_border_color({border_color:t}){const e=this._variables.table.get(this._id);e&&(e.border_color=t,ve(e,["border_color"]))}set_border_width({border_width:t}){const e=this._variables.table.get(this._id);e&&(e.border_width=t)}set_frame_color({frame_color:t}){const e=this._variables.table.get(this._id);e&&(e.frame_color=t)}set_frame_width({frame_width:t}){const e=this._variables.table.get(this._id);e&&(e.frame_width=t)}set_position({position:t},e){const r=this._variables.table.get(this._id);r&&(r.position=t,this._paramVerfiy(t,e,"table.set_position",Object.values(vr),"position"))}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_getTableItem(t,e){const r=this._variables.table.get(this._id);if(r){const n=r.cell;return n?n[e][t]:void 0}}}class Pw{constructor(t){$(this,"_strategy");this._strategy=t}commission({trade_num:t}){return this._verifyTradeNum(t)&&this._strategy.historyOrders[t].commission||0}entry_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].in_index}entry_comment({trade_num:t}){if(!this._verifyTradeNum(t))return"";const{comment:e,id:r}=this._strategy.historyOrders[t];return e||r}entry_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].id:""}entry_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].in_price}entry_time({trade_num:t}){if(!this._verifyTradeNum(t))return;const{in_time:e,entry_time:r}=this._strategy.historyOrders[t];return r||e}exit_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_index}exit_comment({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].out_comment:""}exit_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].out_id:""}exit_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_price}exit_time({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.historyOrders[t].out_time}max_drawdown({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].trading_loss:0}max_drawdown_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].trading_loss_percent:0}max_runup({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].max_profit:0}max_runup_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].max_profit_percent:0}profit({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].profit:0}profit_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.historyOrders[t].profit_percent:0}size({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{out_qty:e=0,direction:r}=this._strategy.historyOrders[t];return r===fe.long?e:-e}_verifyTradeNum(t){if(typeof t!="number"||t<0)return!1;const e=this._strategy.historyOrders.length;return!(t>=e)}}class kw{constructor(t){$(this,"_strategy");this._strategy=t}commission({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{qty:e=0,original_qty:r=0,commission:n=0}=this._strategy.orders[t];return n*e/r}entry_bar_index({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.orders[t].in_index}entry_comment({trade_num:t}){if(!this._verifyTradeNum(t))return"";const{comment:e,id:r}=this._strategy.orders[t];return e||r}entry_id({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].id:""}entry_price({trade_num:t}){if(this._verifyTradeNum(t))return this._strategy.orders[t].in_price}entry_time({trade_num:t}){if(!this._verifyTradeNum(t))return;const{in_time:e,entry_time:r}=this._strategy.orders[t];return r||e}max_drawdown({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].trading_loss:0}max_drawdown_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].trading_loss_percent:0}max_runup({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].max_profit:0}max_runup_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].max_profit_percent:0}profit({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].profit:0}profit_percent({trade_num:t}){return this._verifyTradeNum(t)?this._strategy.orders[t].profit_percent:0}size({trade_num:t}){if(!this._verifyTradeNum(t))return 0;const{qty:e=0,direction:r}=this._strategy.orders[t];return r===fe.long?e:-e}_verifyTradeNum(t){if(typeof t!="number"||t<0)return!1;const e=this._strategy.orders.length;return!(t>=e)}}class zw{constructor(t,e){$(this,"_strategy");$(this,"_errorListener");this._strategy=t,this._errorListener=e}allow_entry_in({value:t},e){this._paramVerfiy(t,e,"strategy.risk.allow_entry_in",Object.values(fe),"value"),this._strategy.updateRisk({allow_entry_in:t})}max_cons_loss_days({count:t}){this._strategy.updateRisk({max_cons_loss_days:t})}max_drawdown({value:t,type:e},r){this._paramVerfiy(e,r,"strategy.risk.max_drawdown",[Pe.percentOfEquity,Pe.cash],"type"),e===Pe.percentOfEquity&&(t=t>100?100:t),this._strategy.updateRisk({max_drawdown:t,max_drawdown_type:e})}max_intraday_filled_orders({count:t}){this._strategy.updateRisk({max_intraday_filled_orders:t})}max_intraday_loss({value:t,type:e},r){this._paramVerfiy(e,r,"strategy.risk.max_intraday_loss",[Pe.percentOfEquity,Pe.cash],"type"),e===Pe.percentOfEquity&&(t=t>100?100:t),this._strategy.updateRisk({max_intraday_loss:t,max_intraday_loss_type:e})}max_position_size({contracts:t}){this._strategy.updateRisk({max_position_size:t})}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}}var qw=20,Uw=1,ni=1e6,Fh=1e6,Ww=-7,jw=21,Yw=!1,us="[big.js] ",ii=us+"Invalid ",Do=ii+"decimal places",Vw=ii+"rounding mode",Nh=us+"Division by zero",le={},sn=void 0,Hw=/^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i;function Sh(){function i(t){var e=this;if(!(e instanceof i))return t===sn?Sh():new i(t);if(t instanceof i)e.s=t.s,e.e=t.e,e.c=t.c.slice();else{if(typeof t!="string"){if(i.strict===!0&&typeof t!="bigint")throw TypeError(ii+"value");t=t===0&&1/t<0?"-0":String(t)}Zw(e,t)}e.constructor=i}return i.prototype=le,i.DP=qw,i.RM=Uw,i.NE=Ww,i.PE=jw,i.strict=Yw,i.roundDown=0,i.roundHalfUp=1,i.roundHalfEven=2,i.roundUp=3,i}function Zw(i,t){var e,r,n;if(!Hw.test(t))throw Error(ii+"number");for(i.s=t.charAt(0)=="-"?(t=t.slice(1),-1):1,(e=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(e<0&&(e=r),e+=+t.slice(r+1),t=t.substring(0,r)):e<0&&(e=t.length),n=t.length,r=0;r<n&&t.charAt(r)=="0";)++r;if(r==n)i.c=[i.e=0];else{for(;n>0&&t.charAt(--n)=="0";);for(i.e=e-r-1,i.c=[],e=0;r<=n;)i.c[e++]=+t.charAt(r++)}return i}function si(i,t,e,r){var n=i.c;if(e===sn&&(e=i.constructor.RM),e!==0&&e!==1&&e!==2&&e!==3)throw Error(Vw);if(t<1)r=e===3&&(r||!!n[0])||t===0&&(e===1&&n[0]>=5||e===2&&(n[0]>5||n[0]===5&&(r||n[1]!==sn))),n.length=1,r?(i.e=i.e-t+1,n[0]=1):n[0]=i.e=0;else if(t<n.length){if(r=e===1&&n[t]>=5||e===2&&(n[t]>5||n[t]===5&&(r||n[t+1]!==sn||n[t-1]&1))||e===3&&(r||!!n[0]),n.length=t,r){for(;++n[--t]>9;)if(n[t]=0,t===0){++i.e,n.unshift(1);break}}for(t=n.length;!n[--t];)n.pop()}return i}function oi(i,t,e){var r=i.e,n=i.c.join(""),s=n.length;if(t)n=n.charAt(0)+(s>1?"."+n.slice(1):"")+(r<0?"e":"e+")+r;else if(r<0){for(;++r;)n="0"+n;n="0."+n}else if(r>0)if(++r>s)for(r-=s;r--;)n+="0";else r<s&&(n=n.slice(0,r)+"."+n.slice(r));else s>1&&(n=n.charAt(0)+"."+n.slice(1));return i.s<0&&e?"-"+n:n}le.abs=function(){var i=new this.constructor(this);return i.s=1,i},le.cmp=function(i){var t,e=this,r=e.c,n=(i=new e.constructor(i)).c,s=e.s,a=i.s,u=e.e,c=i.e;if(!r[0]||!n[0])return r[0]?s:n[0]?-a:0;if(s!=a)return s;if(t=s<0,u!=c)return u>c^t?1:-1;for(a=(u=r.length)<(c=n.length)?u:c,s=-1;++s<a;)if(r[s]!=n[s])return r[s]>n[s]^t?1:-1;return u==c?0:u>c^t?1:-1},le.div=function(i){var t=this,e=t.constructor,r=t.c,n=(i=new e(i)).c,s=t.s==i.s?1:-1,a=e.DP;if(a!==~~a||a<0||a>ni)throw Error(Do);if(!n[0])throw Error(Nh);if(!r[0])return i.s=s,i.c=[i.e=0],i;var u,c,f,d,h,_=n.slice(),g=u=n.length,y=r.length,p=r.slice(0,u),w=p.length,v=i,x=v.c=[],b=0,C=a+(v.e=t.e-i.e)+1;for(v.s=s,s=C<0?0:C,_.unshift(0);w++<u;)p.push(0);do{for(f=0;f<10;f++){if(u!=(w=p.length))d=u>w?1:-1;else for(h=-1,d=0;++h<u;)if(n[h]!=p[h]){d=n[h]>p[h]?1:-1;break}if(d<0){for(c=w==u?n:_;w;){if(p[--w]<c[w]){for(h=w;h&&!p[--h];)p[h]=9;--p[h],p[w]+=10}p[w]-=c[w]}for(;!p[0];)p.shift()}else break}x[b++]=d?f:++f,p[0]&&d?p[w]=r[g]||0:p=[r[g]]}while((g++<y||p[0]!==sn)&&s--);return!x[0]&&b!=1&&(x.shift(),v.e--,C--),b>C&&si(v,C,e.RM,p[0]!==sn),v},le.eq=function(i){return this.cmp(i)===0},le.gt=function(i){return this.cmp(i)>0},le.gte=function(i){return this.cmp(i)>-1},le.lt=function(i){return this.cmp(i)<0},le.lte=function(i){return this.cmp(i)<1},le.minus=le.sub=function(i){var t,e,r,n,s=this,a=s.constructor,u=s.s,c=(i=new a(i)).s;if(u!=c)return i.s=-c,s.plus(i);var f=s.c.slice(),d=s.e,h=i.c,_=i.e;if(!f[0]||!h[0])return h[0]?i.s=-c:f[0]?i=new a(s):i.s=1,i;if(u=d-_){for((n=u<0)?(u=-u,r=f):(_=d,r=h),r.reverse(),c=u;c--;)r.push(0);r.reverse()}else for(e=((n=f.length<h.length)?f:h).length,u=c=0;c<e;c++)if(f[c]!=h[c]){n=f[c]<h[c];break}if(n&&(r=f,f=h,h=r,i.s=-i.s),(c=(e=h.length)-(t=f.length))>0)for(;c--;)f[t++]=0;for(c=t;e>u;){if(f[--e]<h[e]){for(t=e;t&&!f[--t];)f[t]=9;--f[t],f[e]+=10}f[e]-=h[e]}for(;f[--c]===0;)f.pop();for(;f[0]===0;)f.shift(),--_;return f[0]||(i.s=1,f=[_=0]),i.c=f,i.e=_,i},le.mod=function(i){var t,e=this,r=e.constructor,n=e.s,s=(i=new r(i)).s;if(!i.c[0])throw Error(Nh);return e.s=i.s=1,t=i.cmp(e)==1,e.s=n,i.s=s,t?new r(e):(n=r.DP,s=r.RM,r.DP=r.RM=0,e=e.div(i),r.DP=n,r.RM=s,this.minus(e.times(i)))},le.neg=function(){var i=new this.constructor(this);return i.s=-i.s,i},le.plus=le.add=function(i){var t,e,r,n=this,s=n.constructor;if(i=new s(i),n.s!=i.s)return i.s=-i.s,n.minus(i);var a=n.e,u=n.c,c=i.e,f=i.c;if(!u[0]||!f[0])return f[0]||(u[0]?i=new s(n):i.s=n.s),i;if(u=u.slice(),t=a-c){for(t>0?(c=a,r=f):(t=-t,r=u),r.reverse();t--;)r.push(0);r.reverse()}for(u.length-f.length<0&&(r=f,f=u,u=r),t=f.length,e=0;t;u[t]%=10)e=(u[--t]=u[t]+f[t]+e)/10|0;for(e&&(u.unshift(e),++c),t=u.length;u[--t]===0;)u.pop();return i.c=u,i.e=c,i},le.pow=function(i){var t=this,e=new t.constructor("1"),r=e,n=i<0;if(i!==~~i||i<-Fh||i>Fh)throw Error(ii+"exponent");for(n&&(i=-i);i&1&&(r=r.times(t)),i>>=1,!!i;)t=t.times(t);return n?e.div(r):r},le.prec=function(i,t){if(i!==~~i||i<1||i>ni)throw Error(ii+"precision");return si(new this.constructor(this),i,t)},le.round=function(i,t){if(i===sn)i=0;else if(i!==~~i||i<-ni||i>ni)throw Error(Do);return si(new this.constructor(this),i+this.e+1,t)},le.sqrt=function(){var i,t,e,r=this,n=r.constructor,s=r.s,a=r.e,u=new n("0.5");if(!r.c[0])return new n(r);if(s<0)throw Error(us+"No square root");s=Math.sqrt(+oi(r,!0,!0)),s===0||s===1/0?(t=r.c.join(""),t.length+a&1||(t+="0"),s=Math.sqrt(t),a=((a+1)/2|0)-(a<0||a&1),i=new n((s==1/0?"5e":(s=s.toExponential()).slice(0,s.indexOf("e")+1))+a)):i=new n(s+""),a=i.e+(n.DP+=4);do e=i,i=u.times(e.plus(r.div(e)));while(e.c.slice(0,a).join("")!==i.c.slice(0,a).join(""));return si(i,(n.DP-=4)+i.e+1,n.RM)},le.times=le.mul=function(i){var t,e=this,r=e.constructor,n=e.c,s=(i=new r(i)).c,a=n.length,u=s.length,c=e.e,f=i.e;if(i.s=e.s==i.s?1:-1,!n[0]||!s[0])return i.c=[i.e=0],i;for(i.e=c+f,a<u&&(t=n,n=s,s=t,f=a,a=u,u=f),t=new Array(f=a+u);f--;)t[f]=0;for(c=u;c--;){for(u=0,f=a+c;f>c;)u=t[f]+s[c]*n[f-c-1]+u,t[f--]=u%10,u=u/10|0;t[f]=u}for(u?++i.e:t.shift(),c=t.length;!t[--c];)t.pop();return i.c=t,i},le.toExponential=function(i,t){var e=this,r=e.c[0];if(i!==sn){if(i!==~~i||i<0||i>ni)throw Error(Do);for(e=si(new e.constructor(e),++i,t);e.c.length<i;)e.c.push(0)}return oi(e,!0,!!r)},le.toFixed=function(i,t){var e=this,r=e.c[0];if(i!==sn){if(i!==~~i||i<0||i>ni)throw Error(Do);for(e=si(new e.constructor(e),i+e.e+1,t),i=i+e.e+1;e.c.length<i;)e.c.push(0)}return oi(e,!1,!!r)},le[Symbol.for("nodejs.util.inspect.custom")]=le.toJSON=le.toString=function(){var i=this,t=i.constructor;return oi(i,i.e<=t.NE||i.e>=t.PE,!!i.c[0])},le.toNumber=function(){var i=+oi(this,!0,!0);if(this.constructor.strict===!0&&!this.eq(i.toString()))throw Error(us+"Imprecise conversion");return i},le.toPrecision=function(i,t){var e=this,r=e.constructor,n=e.c[0];if(i!==sn){if(i!==~~i||i<1||i>ni)throw Error(ii+"precision");for(e=si(new r(e),i,t);e.c.length<i;)e.c.push(0)}return oi(e,i<=e.e||e.e<=r.NE||e.e>=r.PE,!!n)},le.valueOf=function(){var i=this,t=i.constructor;if(t.strict===!0)throw Error(us+"valueOf disallowed");return oi(i,i.e<=t.NE||i.e>=t.PE,!0)};var iu=Sh();function Oh(i,t){return iu(i).plus(t).toNumber()}function bo(i,t){return iu(i).minus(t).toNumber()}function Ii(i,t){return iu(i).mul(t).toNumber()}let Kw=class{constructor(t,e,r,n,s){$(this,"_variables");$(this,"_options");$(this,"_totalChangeCapital");$(this,"_historyOrder");$(this,"_orders");$(this,"_exitOrders");$(this,"_pendingOrders");$(this,"_mintick");$(this,"_funcOptions");$(this,"_pendingCloseOrders");$(this,"_errorListener");$(this,"_risk");$(this,"_opentrades");$(this,"_closedtrades");$(this,"_riskNamespace");$(this,"_updateOptions",{});$(this,"_id");$(this,"_maxDrawdownVerifyIndex",0);$(this,"calcOnOrderFillsData",{index:-1});this._variables=t,this._errorListener=n,this._options={overlay:!1,format:Gt.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:Pe.fixed,default_qty_value:1,initial_capital:1e6,currency:xh.NONE,slippage:0,commission_type:je.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=e,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 kw(this),this._closedtrades=new Pw(this),this._riskNamespace=new zw(this,n),this._id=`strategy_${s}`}get orders(){return[...this._orders]}get historyOrders(){return[...this._historyOrder]}get _freezeCapital(){const{close:t}=this.calcOnOrderFillsData.data||this._variables;return this._orders.reduce((e,r)=>e+t*(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(t){this._updateOptions=t||{},Object.assign(this._options,this._updateOptions)}update(){this._maxConsLossDaysVerify(),this._ordersHandle(),this._pendingOrderHandle(),this._exitOrdersHandle(),this._maxIntradayFilledOrdersVerify(),this._maxDrawdownVerify();const{open:t,high:e,low:r}=this.calcOnOrderFillsData.data||this._variables;let n=this._variables.close;this.calcOnOrderFillsData.tradeData&&(n=this.calcOnOrderFillsData.tradeData.open),this._variables.strategy.update({open:t,close:n,high:e,low:r}),!this._options.process_orders_on_close&&this._calcLiquidate(),this._calcProfitAndLoss()}calcCurrentOrder(){this._ordersHandle(),this._pendingOrderHandle(),this._calcProfitAndLoss()}updateRisk(t){Object.assign(this._risk,t)}endExecution(){this._maxIntradayLoss(),this._pendingCloseOrderHandle(),this._options.process_orders_on_close&&this._calcLiquidate()}_maxIntradayLoss(){var g;const{max_intraday_loss:t,max_intraday_loss_type:e,isDisabledOpen:r}=this._risk;if(t===void 0||!e||r)return;const{time_tradingday:n,time:s,strategy:{netprofit:a,initial_capital:u}}=this._variables,{high:c,low:f}=this.calcOnOrderFillsData.data||this._variables;let{preNetprofit:d=0}=this._risk;s===n&&(d=a,this._risk.preNetprofit=a,this._risk.isTemporaryBan=!1);let h=d-a;h+=this._orders.reduce((y,p)=>{const{in_price:w,direction:v,qty:x=0,commission:b=0,original_qty:C=0}=p,E=v===fe.long?1:-1,A=(c-w)*x,N=(f-w)*x,S=E===1?N:-A;return y+S+x/C*b},0);let _=!1;switch(e){case Pe.cash:_=t<h;break;case Pe.percentOfEquity:const y=h/(u+a)*100;_=t<y;break}if(_){this._risk.isTemporaryBan=!0;const y=(g=this._orders[0])==null?void 0:g.direction;this._closeOrders(this._orders,y===fe.long?f:c,"Close Position (Max intraday Loss)",void 0,"close"),this._pendingOrders=[]}}_maxIntradayFilledOrdersVerify(){const{max_intraday_filled_orders:t,intradayOrders:e=0,isDisabledOpen:r}=this._risk;if(t===void 0||r)return;const{time:n,time_tradingday:s}=this._variables,{open:a}=this.calcOnOrderFillsData.data||this._variables;n===s&&(this._risk.intradayOrders=0,this._risk.isTemporaryBan=!1),t<=e&&(this._risk.isTemporaryBan=!0,this._closeOrders(this._orders,a,"Close Position (Max number of filled orders in one day)",void 0,"close"),this._pendingOrders=[])}_maxConsLossDaysVerify(){const{max_cons_loss_days:t,lossDays:e=0,isDisabledOpen:r,totalProfit:n=0}=this._risk;if(t===void 0||r)return;const{time:s,time_tradingday:a,strategy:u}=this._variables,{open:c}=this.calcOnOrderFillsData.data||this._variables;let f=e;if(s===a){const d=u.netprofit+u.openprofit;d<n?f=0:f++,Object.assign(this._risk,{lossDays:f,totalProfit:d})}t<=f&&this._riskTouchOff(c,"Close Position (Max consecutive loss days)")}_maxDrawdownVerify(){const{max_drawdown:t,max_drawdown_type:e,isDisabledOpen:r}=this._risk;if(r)return;const{bar_index:n}=this._variables,{open:s}=this.calcOnOrderFillsData.data||this._variables;if(t!==void 0&&e&&this._maxDrawdownVerifyIndex===n){const{initial_capital:a}=this._options,c=this._orders.reduce((d,h)=>{const{in_price:_,commission:g=0,qty:y=0,original_qty:p=0,direction:w}=h,v=w===fe.long?1:-1,x=(s-_)*v*y;return d+x+g*y/p},0)+this._totalChangeCapital;let f=!1;switch(e){case Pe.percentOfEquity:f=c/a*100<=-t;break;case Pe.cash:f=c<=-t;break}f&&this._riskTouchOff(s,"Close Position (Max Drawdown)")}}_riskTouchOff(t,e){this._risk.isDisabledOpen=!0,this._orders.length&&this._closeOrders(this._orders,t,e,"close"),this._pendingOrders=[]}strategy(t,e){if(!this._variables.bar_index){this._paramVerfiy(t.format,e,"strategy",[Gt.inherit,Gt.price,Gt.percent,Gt.volume],"format"),this._paramVerfiy(t.default_qty_type,e,"strategy",Object.values(Pe),"default_qty_type"),this._paramVerfiy(t.commission_type,e,"strategy",Object.values(je),"commission_type");const r=self==null?void 0:self.workerStorage.get(this._id),n={...this._updateOptions};if(r)for(const s of Object.keys({...r,...t}))t[s]!==r[s]&&delete n[s];self==null||self.workerStorage.set(this._id,t),Object.assign(this._options,t,n),this._variables.updateMaxLength(t),Object.assign(this._funcOptions,{strategy:this._options,userSetStrategyConfig:n,scriptType:"strategy"})}}order(t,e){this._risk.isDisabledOpen||(this._paramVerfiy(t.oca_type,e,"strategy.order",Object.values(fn),"oca_type"),this._orderHandle(t))}entry(t,e){this._risk.isDisabledOpen||(this._paramVerfiy(t.oca_type,e,"strategy.entry",Object.values(fn),"oca_type"),this._entryHandle(t))}close(t){if(!this._orders.filter(r=>!this._options.process_orders_on_close||r.in_index!==this._variables.bar_index).length)return;const{immediately:e}=t;if(e||this._options.process_orders_on_close){const r=this._pendingCloseOrders.find(n=>n.id===t.id&&n.place_order_type==="close");if(r){Object.assign(r,t);return}this._pendingCloseOrders.push({...t,place_order_type:"close"})}else{const r=this._pendingOrders.find(n=>n.id===t.id&&n.place_order_type==="close");if(r){Object.assign(r,t);return}this._pendingOrders.push({...t,place_order_type:"close"})}}close_all(t){if(typeof t=="string"&&(t={}),!this._orders.length)return;const{immediately:e}=t;e||this._options.process_orders_on_close?this._pendingCloseOrders.push({...t,place_order_type:"close_all"}):this._pendingOrders.push({...t,place_order_type:"close_all"})}cancel({id:t}){this._pendingOrders=this._pendingOrders.filter(e=>!(e.id===t&&e.place_order_type!=="close"))}cancel_all(){this._pendingOrders=this._pendingOrders.filter(t=>t.place_order_type==="close_all")}exit(t,e){this._exit(t,e)}convert_to_account({value:t}){return t}convert_to_symbol({value:t}){return t}default_entry_qty({fill_price:t}){return t?this._calcDefaultQty(t):0}_calcDefaultQty(t){const{default_qty_type:e=Pe.fixed,default_qty_value:r=1,initial_capital:n,commission_value:s}=this._options;let a=r;switch(e){case Pe.cash:a=r/t;break;case Pe.percentOfEquity:const u=this._getOrderProfit(t),c=n+u+this._totalChangeCapital;s?a=this._getCommQty(c,t):a=c*r/100/t;break}return Ql(a,this._getLen(t))}_getCommQty(t,e){const{commission_type:r,commission_value:n=0,default_qty_value:s=0}=this._options;let a=0;switch(r){case je.percent:a=t*s/(100*e+n*e);break;case je.cashPerContract:a=t*s/(100*e+n);break;case je.cashPerOrder:a=(t-n)*s/100/e}return a}_getLen(t){const e=String(Math.floor(t)).length-3;return e<0?0:e}_getCapital(t,e){const{margin_long:r=0,margin_short:n=0}=this._options;return r<100&&r>0&&t===1?e=e*100/r:n<=100&&n>0&&t===-1&&(e=e*100/n),e}_calcProfitAndLoss(){const{close:t}=this.calcOnOrderFillsData.data||this._variables;for(const e of this._orders){const{in_price:r,qty:n=0,direction:s}=e,a=s===fe.long?1:-1,u=(t-r)*a*n,[c,f]=this._calcProfitAndLossHandle(r,n,a);this._calcOrderPercent(e,u,c,f)}}_calcProfitAndLossHandle(t,e,r,n){const{high:s,low:a}=this.calcOnOrderFillsData.data||this._variables,u=((n||s)-t)*e,c=((n||a)-t)*e;let f=r===1?u:-c,d=r===1?c:-u;return[f,d]}_calcOrderPercent(t,e,r,n){const{commission_value:s}=this._options,{close:a}=this.calcOnOrderFillsData.data||this._variables,{original_qty:u=0,qty:c=0,in_price:f,max_profit:d=0,trading_loss:h=0}=t;let{commission:_=0}=t,g=f*c;if(s){const y=this._getCommission(a,c);_=_*c/u,r-=_,n-=_,g+=_,e=e-y-_}r=Math.max(r,d,0),n=Math.min(n,h,0),Object.assign(t,{profit:e,total_profit:this._totalChangeCapital+e,total_profit_percent:e/(this._options.initial_capital+this._totalChangeCapital)*100,max_profit:r,trading_loss:n,profit_percent:e/g*100,max_profit_percent:r/g*100,trading_loss_percent:n/g*100})}_calcLiquidate(){if(!this._orders.length)return;const{time:t}=this._variables,{high:e,low:r}=this.calcOnOrderFillsData.data||this._variables,{initial_capital:n,margin_long:s=0,margin_short:a=0}=this._options,u=this._orders[0].direction===fe.long?1:-1;let c=u===1?r:e;if(u===1&&s===100)return;const f=(u===1?s:a)/100;if(f<=0)return;let d=!1;const[h,_]=this._orders.reduce((w,v)=>{let[x,b]=w;const{in_price:C,qty:E=0,in_time:A}=v;A===t&&(d=!0);const N=C*E,S=c*E;return x+=N,b+=S,[x,b]},[0,0]);let g=0,y=0;const p=n+this._totalChangeCapital;if(d&&(g=p-h*f,g<0&&(c=this._orders[0].in_price,y=Math.abs(Math.trunc(g/f/c)*4),y=Math.max(y,1))),g>=0){const w=u*(_-h);if(g=p+w-_*f,g>=0)return;y=Math.abs(Math.trunc(g/f/c)*4)}y<=0||this._marginCallOrders(c,y,"Margin Call")}_marginCallOrders(t,e,r){const{close_entries_rule:n="FIFO"}=this._options;if(n==="FIFO"){this._processOrders(this._orders,t,e*this._orders.length,r,r,!0);return}for(const s of this.orders)s.position_close_type=s.place_order_type,s.isTiggerClose=!0,this._processOrder(s,t,e,r,r,!0);this._orders=this._orders.filter(s=>!s.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_orderHandle(t){const{process_orders_on_close:e,slippage:r=0}=this._options,{orders:n,isMarketPrice:s,quantities:a,close:u,price:c,activePrice:f,isTouch:d}=this._orderArgsParse(t),h=t.direction===fe.long?1:-1;if(a<=0)return;let _=a;if((s||d)&&e){const y=d?c:u;if(n.length){const E=this._processOrders(n,y,_,t.id,t.comment,!1,"order");if(E<=0)return;_=E}const p=y-h*r*this._mintick;if(!this._judgeCapitalEnough(_,p,h))return;this._ocaGroupVerify(_,t.oca_name,t.oca_type);const{bar_index:v,time:x}=this._variables,{high:b,low:C}=this.calcOnOrderFillsData.data||this._variables;this._calcCurrentOrder({...t,in_price:p,in_high:b,in_low:C,in_index:v,in_time:x,qty:_,place_order_type:"order"});return}this._judgeCapitalEnough(a,c,h)&&this._addPendingOrders(t,c,_,s,f)}_judgeCapitalEnough(t,e,r){let n=this._freezeCapital;if(this._orders.some(d=>(d.direction===fe.long?1:-1)!==r)&&(n=0),t<=0)return!1;const{margin_long:s=0,margin_short:a=0}=this._options;if(s===0&&r===1||a===0&&r===-1)return!0;const u=this._getOrderProfit(e),f=this._getCapital(r,this._options.initial_capital+u+this._totalChangeCapital)-n;return t*e<=f}_getOrderProfit(t){return this._orders.reduce((e,r)=>{const{in_price:n,qty:s=0,direction:a}=r,u=a===fe.long?1:-1;return e+(t-n)*s*u},0)}_ocaGroupVerify(t,e,r){if(!e||!r||r===fn.none)return!1;let n=!1;switch(r){case fn.cancel:this._pendingOrders=this._pendingOrders.filter(s=>{if(s.oca_name===e)s.isCancel=!0,n=!0;else return!0});break;case fn.reduce:this._pendingOrders=this._pendingOrders.filter(s=>{const{qty:a=0,oca_name:u}=s;if(e===u){const c=a-t;return n=!0,c<=0?(s.isCancel=!0,!1):(s.qty=c,!0)}else return!0});break}return n}_processOrders(t,e,r,n,s,a=!1,u,c){let f=r;for(const d of t)if(d.position_close_type=u||d.place_order_type,d.immediately=c,d.isTiggerClose=a||d.position_close_type==="close",f=this._processOrder(d,e,f,n,s,a),f<=0)break;return this._orders=this._orders.filter(d=>!d.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),f}_addPendingOrders(t,e,r,n,s){const a=this._pendingOrders.find(u=>u.id===t.id&&!u.isMarketPrice);if(a)Object.assign(a,{...t,in_price:e,isMarketPrice:n,qty:r,active_price:s});else{const u={...t,in_price:e,isMarketPrice:n,qty:r,active_price:s,entry_time:this._variables.time,place_order_type:"order"};this._pendingOrders.push(u)}}_orderArgsParse(t){const{direction:e,qty:r,stop:n}=t;let s=t.limit||0;const{close:a}=this.calcOnOrderFillsData.data||this._variables;let u=a,c=!1,f;const d=e===fe.long?1:-1,h=n&&(n-a)*d>=0,{backtest_fill_limits_assumption:_=0}=this._options;_>0&&s&&(s-=_*this._mintick*d);const g=s&&(s-a)*d<=0;let y=!1;h&&g?(n!==a&&(f=n),u=s):h?(u=n,y=n===a):g?(u=s,y=s===a):c=!0;const p=r!==void 0?Ql(r,this._getLen(u)):this._calcDefaultQty(u);return{orders:this._orders.filter(v=>v.direction!==e),isMarketPrice:c,activePrice:f,quantities:p,close:a,price:u,isTouch:y}}_entryHandle(t){const{process_orders_on_close:e}=this._options,{orders:r,isMarketPrice:n,quantities:s,close:a,price:u,activePrice:c,isTouch:f}=this._orderArgsParse(t);if(s<=0)return;if((n||f)&&e){this._entryOrder(r,f?u:a,s,t);return}this._judgeCapitalEnough(s,a,t.direction===fe.long?1:-1)&&this._addPendingEntry(t,u,s,n,c)}_entryOrder(t,e,r,n){const{time:s,bar_index:a}=this._variables,{high:u,low:c}=this.calcOnOrderFillsData.data||this._variables,{slippage:f=0}=this._options,{oca_name:d,oca_type:h,direction:_,comment:g,id:y}=n,p=_===fe.long?1:-1;if(r=this._getAvailablePositionSize(r,_),r<=0)return;const w=e;if(e=e+f*this._mintick*p,!this._judgeCapitalEnough(r,e,p))return;this._closeOrders(t,w,y,g,"entry",void 0,!0);const x={...n,in_price:e,qty:r,in_index:a,in_high:u,in_low:c,in_time:s,place_order_type:"entry"},{orders:b}=this._getEntryOrders(_),C=b.length;C&&C>=(this._options.pyramiding||1)||(this._ocaGroupVerify(r,d,h),this._calcCurrentOrder(x))}_getAvailablePositionSize(t,e){const{max_position_size:r,allow_entry_in:n}=this._risk;if(n&&n!==fe.all&&n!==e)return 0;if(r===void 0)return t;const s=this._orders.reduce((a,u)=>a+(u.qty||0),0);return s?s+t>r?0:t:t>r?t-r:0}_getEntryOrders(t){const e=this._pendingOrders.filter(n=>["entry","order"].includes(n.place_order_type)&&n.direction===t),r=this._orders.filter(n=>n.direction===t);return{pendingOrders:e,orders:r}}_addPendingEntry(t,e,r,n,s){if(r=this._getAvailablePositionSize(r,t.direction),r<=0)return;const{pendingOrders:a,orders:u}=this._getEntryOrders(t.direction),c=a.find(f=>f.id===t.id&&f.place_order_type==="entry");if(c)Object.assign(c,{...t,in_price:e,isMarketPrice:n,qty:r,active_price:s});else{const f={...t,in_price:e,isMarketPrice:n,qty:r,active_price:s,entry_time:this._variables.time,place_order_type:"entry"};this._pendingOrders.push(f)}}_closeAllOrders(t,e){const{comment:r,immediately:n}=t,{bar_index:s}=this._variables,a=this._orders.filter(u=>u.in_index!==s);a.length&&(this._closeOrders(a,e,"Close position order",r,"close",n),this._orders=[],this._variables.strategy.updateOrders(this._orders))}_closeOrders(t,e,r,n,s,a,u){for(const c of t)c.position_close_type=s,c.immediately=a,c.isTiggerClose=!0,this._closeOrder(c,e,r,n,u);this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder)}_closeOrder(t,e,r,n,s){const{time:a,bar_index:u}=this._variables,{high:c,low:f}=this.calcOnOrderFillsData.data||this._variables,{slippage:d=0}=this._options,{in_price:h,qty:_=0,direction:g}=t,y=g===fe.long?1:-1;e=e-y*d*this._mintick,t.isDeal=!0;const p=(e-h)*y*_,w={...t,out_price:e,out_id:r,out_index:u,out_high:c,out_low:f,out_time:a,out_comment:n,out_qty:_,profit:p};this._calcPercent(w,s)}_exitOrdersHandle(){if(!this._exitOrders.length)return;let{open:t,low:e,high:r,close:n}=this.calcOnOrderFillsData.data||this._variables;const s=[],a=Math.abs(r-t),u=Math.abs(e-t),c=[],f=this._variables.precision;t=Number(t.toFixed(f)),e=Number(e.toFixed(f)),r=Number(r.toFixed(f)),n=Number(n.toFixed(f));for(const d of this._exitOrders){const{directionNum:h,id:_,comment:g,qty:y,comment_loss:p,comment_profit:w,comment_trailing:v,order:x}=d;if(x.isTiggerClose)continue;let b=a<u||a===u&&h===1;const C=[],[E,A]=this._getLimitPrice(d,t,e,r,b);E&&C.push({order:x,price:E,index:A,isHighFront:b,exitInfo:{id:_,comment:w||g,qty:y}});const[N,S]=this._getStopPrice(d,t,e,r,b);N&&C.push({order:x,price:N,index:S,isHighFront:b,exitInfo:{id:_,comment:p||g,qty:y}});const[I,F]=this._getTrailStopPrice(d,t,e,r,n,b);if(I&&C.push({order:x,price:I,index:F,isHighFront:b,exitInfo:{id:_,comment:v||g,qty:y}}),C.length){this._executesSort(C),s.push(C[0]);continue}c.push(d)}this._exitOrders=c,this._executesSort(s);for(const d of s){const{order:h,price:_,exitInfo:g,isHighFront:y,index:p}=d;y?(r=p===1?_:r,e=p===1?t:_):(r=p===1?t:_,e=p===1?_:e),this._variables.strategy.update({open:_,high:r,low:e,close:n}),this._processExitOnClose(h,_,g)}}_executesSort(t){return t.sort(({price:e,index:r,isHighFront:n},{price:s,index:a})=>r!==a?r-a:n?r===1?e-s:s-e:r===1?s-e:e-s),t}_getLimitPrice(t,e,r,n,s){const{limit:a,directionNum:u}=t;let c,f=1;return a&&((e-a)*u>=0?(c=e,f=1):r<=a&&n>=a&&(c=a,s&&a>e||!s&&a<e?f=1:f=2)),[c,f]}_getStopPrice(t,e,r,n,s){const{stop:a,directionNum:u}=t;let c,f=1;return a&&((e-a)*u<=0?(c=e,f=1):r<=a&&n>=a&&(c=a,s&&a>e||!s&&a<e?f=1:f=2)),[c,f]}_getTrailStopPrice(t,e,r,n,s,a){const{trail_stop_price:u,directionNum:c,active_price:f,trail_offset:d=0}=t;let h=u,_,g=1;if(h)if((h-e)*c>=0)_=e,g=1;else{const[y,p,w]=this._calcTrailStopPrice(h,n,r,s,d,c,a);_=p,g=w||1,t.trail_stop_price=y}if(f&&!_&&f<=n&&f>=r)if(d===0)_=f,a&&f>e||!a&&f<e?g=1:g=2;else{h=bo(f,Ii(d*c,this._mintick));let y=n,p=r;a?f>=e&&f<=n?(y=n,g=1):(a=!1,y=s,g=2):f<e&&f>=r?(p=r,g=1):(a=!0,p=s,g=2);const[w,v,x=1]=this._calcTrailStopPrice(h,y,p,s,d,c,a);delete t.active_price,g<x&&(g=x),t.trail_stop_price=w,_=v}return[_,g]}_ordersHandle(t){const e=this._orders.filter(a=>a.isMarketPriceLimit||a.isMarketPriceStop);if(!e.length)return;const{open:r,close:n}=this.calcOnOrderFillsData.data||this._variables,s=t?n:r;for(const a of e){const{out_comment:u,out_qty:c,out_id:f}=a;this._processExitOnClose(a,s,{id:f,comment:u,qty:c})}}_calcTrailStopPrice(t,e,r,n,s,a,u){let c=t,f;const d=bo(a===1?e:r,Ii(s*a,this._mintick));let h=1;return a===1?u?(c<d&&(c=d),c>=r&&(h=2,f=c)):c>=r?(h=1,f=c):d>c&&(c=d,d>=n&&(h=3,f=d)):u?c<=e?(h=1,f=c):d<c&&(c=d,d<=n&&(h=3,f=d)):(d<c&&(c=d),c<=e&&(h=2,f=c)),[c,f,h]}_pendingOrderHandle(){if(!this._pendingOrders.length)return;const t=[],e=this._pendingOrders.filter(r=>r.place_order_type==="exit");for(const r of this._pendingOrders){const{isCancel:n,place_order_type:s}=r;if(n)continue;let a;switch(s){case"entry":a=this._entryOrderHandle(r);break;case"order":a=this._orderOrderHandle(r);break;case"close":a=this._closeOrderHandle(r);break;case"close_all":const{open:u}=this.calcOnOrderFillsData.data||this._variables;this._closeAllOrders(r,u);break}a&&t.push(a)}for(const r of e){const n=this._exitOrderHandle(r);n&&t.push(n)}this._pendingOrders=t}_pendingCloseOrderHandle(){if(!this._pendingCloseOrders.length)return;const t=this._pendingCloseOrders.filter(r=>["close","close_all"].includes(r.place_order_type||"")),{close:e}=this.calcOnOrderFillsData.data||this._variables;this._pendingCloseOrders=[];for(const r of t)switch(r.place_order_type){case"close":const n=this._closeOrderHandle(r,!0);n&&this._pendingCloseOrders.push(n);break;case"close_all":this._closeAllOrders(r,e);break}this._ordersHandle(!0)}_entryOrderHandle(t){const{open:e,low:r,high:n}=this.calcOnOrderFillsData.data||this._variables,{isMarketPrice:s,qty:a=0,in_price:u,direction:c,active_price:f}=t;if(f&&n>=f&&r<=f)return delete t.active_price,t;let d=u;if(s&&(d=e),d<=n&&d>=r){const h=this._orders.filter(_=>_.direction!==c);this._entryOrder(h,d,a,t)}else return t}_orderOrderHandle(t){const{time:e,bar_index:r}=this._variables,{open:n,low:s,high:a}=this.calcOnOrderFillsData.data||this._variables,{slippage:u=0}=this._options,{isMarketPrice:c,qty:f=0,in_price:d,direction:h,comment:_,oca_name:g,oca_type:y,active_price:p,id:w}=t;if(p&&a>=p&&s<=p)return delete t.active_price,t;let v=d,x=f;if(c&&(v=n),v<=a&&v>=s){const b=this._orders.filter(E=>E.direction!==h);if(b.length&&(x=this._processOrders(b,v,f,w,_,!1,"order"),x<=0))return;const C=h===fe.long?1:-1;this._ocaGroupVerify(x,g,y),this._calcCurrentOrder({...t,in_price:v-C*u*this._mintick,in_index:r,in_time:e,in_high:a,in_low:s,qty:x});return}else return t}_closeOrderHandle(t,e){const{id:r,qty:n,qty_percent:s=100,comment:a,immediately:u}=t,{close_entries_rule:c="FIFO"}=this._options;let f=[];if(c==="FIFO"?f=this._orders.filter(g=>g.id===r):f=this._orders.filter(g=>g.id===r&&!g.close_qty),!f.length)return;let d=0;if(n?d=n:(d=f.reduce((g,y)=>g+(y.qty||0),d),d=s/100*d),d<=0)return;const{open:h,close:_}=this.calcOnOrderFillsData.data||this._variables;if(c==="FIFO")this._processOrders(f,e?_:h,d,`Close entry(s) order ${r}`,a,!1,"close",u);else if(this._processCloseOrders(f,e?_:h,d,`Close entry(s) order ${r}`,a,u))return t}_processCloseOrders(t,e,r,n,s,a){let u=!1;for(const c of t)c.close_qty=r,(c.qty||0)>r&&(u=!0),c.immediately=a,c.position_close_type="close",c.isTiggerClose=!0,this._processOrder(c,e,r,n,s);return this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),u}_exitOrderHandle(t){const{from_entry:e}=t,r=this._orders.filter(n=>(!e||e===n.id)&&!n.hasExit);if(!(r.length&&!this._ordersToExit(r,t,!0)))return t}_exit(t,e){if(!t.hasOwnProperty("profit")&&!t.hasOwnProperty("loss")&&!t.hasOwnProperty("stop")&&!t.hasOwnProperty("limit")&&(!t.hasOwnProperty("trail_offset")||!t.hasOwnProperty("trail_price")&&!t.hasOwnProperty("trail_points"))){this._errorListener.addError(ie.strategyExitErr,e,Rt.Error);return}const{profit:r,loss:n,stop:s,limit:a,trail_offset:u,trail_price:c,trail_points:f,from_entry:d="",id:h}=t;if(this._isNaN(r)&&this._isNaN(n)&&this._isNaN(s)&&this._isNaN(a)&&(this._isNaN(u)||this._isNaN(f)&&this._isNaN(c)))return;const _={...t,place_order_type:"exit"},g=this._orders.filter(v=>(!d||d===v.id)&&!v.hasExit),y=this._updateExitOrders(_),p=this._pendingOrders.filter(v=>(!d||d===v.id)&&["order","entry"].includes(v.place_order_type||""));if(g.length){if(!this._ordersToExit(g,_,!1))return}else if(!p.length||y)return;const w=this._pendingOrders.find(v=>v.id===h&&v.place_order_type==="exit");w?Object.assign(w,{...t}):this._pendingOrders.push(_)}_updateExitOrders(t){let e=!1;const r=this._exitOrders.filter(n=>n.id===t.id&&(n.from_entry===t.from_entry||!t.from_entry));for(const n of r){const{directionNum:s,order:a}=n;if(a.isTiggerClose){n.isClose=!0;continue}e=!0;const u={...t};if(this._stopProfit(a,s,u)){n.isClose=!0;continue}if(this._stopLoss(a,s,u)){n.isClose=!0;continue}if(this._trailStopLoss(a,s,u)){n.isClose=!0;continue}Object.assign(n,u)}return this._exitOrders=this._exitOrders.filter(n=>!n.isClose),e}_ordersToExit(t,e,r){const{qty:n,qty_percent:s=100,id:a,comment:u}=e;let c=n,f=!1;e.comment=u||a;const d=t[0],h={...e},{qty:_=0}=d,g=d.direction===fe.long?1:-1;return c=n?n>=_?_:n:s/100*_,h.qty=c,c<_&&(f=!0),this._stopProfit(d,g,h,r)||this._stopLoss(d,g,h,r)||this._trailStopLoss(d,g,h,r)||(this._exitOrders.push({...h,directionNum:g,order:d}),d.hasExit=!0),f}_addExitPendingCloseOrders(t){const e=this._pendingCloseOrders.find(r=>r.id===t.id);e?Object.assign(e,{...t}):this._pendingCloseOrders.push(t)}_stopProfit(t,e,r,n){const{limit:s,profit:a,comment_profit:u,comment:c,id:f,qty:d}=r;let h=s;const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;if(!this._isNaN(a)&&this._isNaN(s)&&(h=Oh(g,Ii(a*e,this._mintick))),r.limit=e===1?ec(h,this._variables.precision):rc(h,this._variables.precision),!n&&h!==void 0&&(h-_)*e<=0)return t.isMarketPriceLimit=!0,r.comment=u||c,Object.assign(t,{out_comment:r.comment,out_id:f,out_qty:d}),y&&this._addExitPendingCloseOrders(r),!0}_stopLoss(t,e,r,n){const{stop:s,loss:a,comment_loss:u,comment:c,id:f,qty:d}=r;let h=s;const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;if(!this._isNaN(a)&&this._isNaN(s)&&(h=bo(g,Ii(a*e,this._mintick))),r.stop=e===1?rc(h,this._variables.precision):ec(h,this._variables.precision),!n&&h!==void 0&&(h-_)*e>=0)return t.isMarketPriceStop=!0,r.comment=u||c,Object.assign(t,{out_comment:r.comment,out_id:f,out_qty:d}),y&&this._addExitPendingCloseOrders(r),!0}_trailStopLoss(t,e,r,n){const{trail_offset:s,trail_price:a,trail_points:u,comment_trailing:c,comment:f,id:d,qty:h}=r;if(!this._isNaN(s)){const{close:_}=this.calcOnOrderFillsData.data||this._variables,{in_price:g}=t,{process_orders_on_close:y}=this._options;let p;if(this._isNaN(a)?this._isNaN(u)||(p=Oh(g,Ii(u*e,this._mintick))):p=a,r.active_price=p,n)return;if(p!==void 0&&(p-_)*e<=0){const w=bo(_,Ii(s*e,this._mintick));if((w-_)*e>=0)return t.isMarketPriceStop=!0,r.comment=c||f,Object.assign(t,{out_comment:r.comment,out_id:d,out_qty:h}),y&&this._addExitPendingCloseOrders(r),!0;r.trail_stop_price=w}}}_processExitOnClose(t,e,r){const{qty:n=0,comment:s,id:a}=r,{close_entries_rule:u="FIFO"}=this._options;if(n)if(t.isTiggerClose=!0,u==="FIFO")this._processExitOrders(this._orders,e,n,a,s);else{if(t.isDeal)return;this._processOrders([t],e,n,a,s,!1,"exit")}}_processExitOrders(t,e,r,n,s){let a=r,u;for(const c of t)if(u=c,c.position_close_type="exit",a=this._processOrder(c,e,a,n,s),a<=0)break;return this._orders=this._orders.filter(c=>!c.isDeal),this._variables.strategy.updateOrders(this._orders),this._variables.strategy.updateHistoryOrders(this._historyOrder),u}_processOrder(t,e,r,n,s,a=!1){const{time:u,bar_index:c}=this._variables,{low:f,high:d}=this.calcOnOrderFillsData.data||this._variables,{slippage:h=0}=this._options,{in_price:_,qty:g=0,max_profit:y,trading_loss:p,direction:w,commission:v=0,original_qty:x=0}=t,b=w===fe.long?1:-1;if(e=e-b*h*this._mintick,r<g){const C=g-r,E=(e-_)*b*r,A=y!==void 0?y/g*r:void 0,N=p!==void 0?p/g*r:void 0,S=v*C/x;this._calcPercent({...t,out_price:e,last_commission:S,out_id:n,out_index:c,out_high:d,out_low:f,out_time:u,out_comment:s,profit:E,out_qty:r,max_profit:A,trading_loss:N});const I=(e-_)*b*C-S;Object.assign(t,{qty:C,profit:I,max_profit:y!==void 0?y-(A||0):void 0,trading_loss:p!==void 0?p-(N||0):void 0,total_profit:this._totalChangeCapital+I}),r=0}else{t.isDeal=!0;const C=(e-_)*b*g;this._calcPercent({...t,out_price:e,out_id:n,out_index:c,out_high:d,out_low:f,out_time:u,out_comment:s,out_qty:g,profit:C}),r-=g}return a&&(b===1?this._variables.strategy.marginCallLong++:this._variables.strategy.marginCallShort++),r}_calcPercent(t,e){const{commission_value:r,process_orders_on_close:n}=this._options,{in_price:s,out_qty:a=0,out_price:u=0,original_qty:c=0,direction:f,last_commission:d=0,immediately:h}=t;let{profit:_=0,max_profit:g,trading_loss:y,commission:p=0}=t,w=s*a,v=this._totalChangeCapital+this._options.initial_capital;if(this._totalChangeCapital+=_,r){const E=this._getCommission(u,a);this._totalChangeCapital-=E;let A=p*a/c;w+=A,A+=E,_=_-A,Object.assign(t,{commission:A});const N=this._orders.reduce((S,I)=>{const{qty:F=0,original_qty:O=0,commission:L=0}=I;return S+L*F/O},0);v+=N-d}const x=f===fe.long?1:-1;let[b,C]=this._calcProfitAndLossHandle(s,a,x,u);if(r){const E=p*a/c;b-=E,C-=E}g=Math.max(b,g||0),y=Math.min(C,y||0),_=parseFloat(String(_)),Object.assign(t,{max_profit:g,profit:_,trading_loss:y,total_profit:this._totalChangeCapital,total_profit_percent:_/v*100,profit_percent:_/w*100,max_profit_percent:g/w*100,trading_loss_percent:y/w*100}),this._maxDrawdownVerifyIndex=this._variables.bar_index+(n?1:0),this._risk.intradayOrders+=1,this._historyOrder.push(t),!e&&this._calcOrderFillsHandle(u,f,h)}_getCommission(t,e){const{commission_value:r=0,commission_type:n}=this._options,s=t*e;let a=0;switch(n){case je.percent:a=s*r/100;break;case je.cashPerContract:a=e*r;break;case je.cashPerOrder:a=r;break}return a}_calcCurrentOrder(t){const{commission_value:e}=this._options,{in_price:r,qty:n=0,max_profit:s=0,trading_loss:a=0,direction:u,immediately:c}=t;let{profit:f=0}=t,d=r*n;const h=this._totalChangeCapital+this._options.initial_capital;if(e){const _=this._getCommission(r,n);this._totalChangeCapital-=_,f=f-_,d+=_,Object.assign(t,{commission:_,total_profit:this._totalChangeCapital})}f=parseFloat(String(f)),Object.assign(t,{original_qty:n,profit:f,total_profit_percent:f/h*100,profit_percent:f/d*100,max_profit_percent:s/d*100,trading_loss_percent:a/d*100,stop:void 0,limit:void 0}),this._risk.intradayOrders+=1,this._orders.push(t),this._variables.strategy.updateOrders(this._orders),e&&this._variables.strategy.updateHistoryOrders(this._historyOrder),this._calcOrderFillsHandle(r,u,c)}_calcOrderFillsHandle(t,e,r=!1){const{calc_on_order_fills:n,process_orders_on_close:s,slippage:a=0}=this._options;if(n){const{open:u,high:c,low:f,close:d}=this._variables,h=e===fe.long?1:-1,_=d-h*a*this._mintick;if((r||s)&&t===_)return;const g=u-h*a*this._mintick;let y={open:u,high:c,low:f,close:d},p=this.calcOnOrderFillsData.index;const w=Math.abs(c-u)<=Math.abs(f-u);switch(p){case-1:t===g?p=0:t>g?w?(p=1,y={open:c,high:c,low:f,close:d}):(p=2,y={open:c,high:c,low:d,close:d}):w?(p=2,y={open:f,high:d,low:f,close:d}):(p=1,y={open:f,high:c,low:f,close:d});break;case 0:t===g?(p=1,w?y={open:c,high:c,low:f,close:d}:y={open:f,high:c,low:f,close:d}):t>g?w?(p=1,y={open:c,high:c,low:f,close:d}):(p=2,y={open:c,high:c,low:d,close:d}):w?(p=2,y={open:f,high:d,low:f,close:d}):(p=1,y={open:f,high:c,low:f,close:d});break;case 1:p=2,w?y={open:f,high:d,low:f,close:d}:y={open:c,high:c,low:d,close:d};break;case 2:p=-1,y=void 0;break}this.calcOnOrderFillsData={tradeData:y,index:p}}}_isNaN(t){return t===void 0||isNaN(t)}_paramVerfiy(t="",e,r,n,s){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}};var Bh={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){return function(e,r,n){r.prototype.isBetween=function(s,a,u,c){var f=n(s),d=n(a),h=(c=c||"()")[0]==="(",_=c[1]===")";return(h?this.isAfter(f,u):!this.isBefore(f,u))&&(_?this.isBefore(d,u):!this.isAfter(d,u))||(h?this.isBefore(f,u):!this.isAfter(f,u))&&(_?this.isAfter(d,u):!this.isBefore(d,u))}}})})(Bh);var Gw=Bh.exports,Jw=Kt(Gw),Th={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){return function(e,r,n){var s=r.prototype,a=function(_){var g,y=_.date,p=_.utc,w={};if(!((g=y)===null||g instanceof Date||g instanceof Array||s.$utils().u(g)||g.constructor.name!=="Object")){if(!Object.keys(y).length)return new Date;var v=p?n.utc():n();Object.keys(y).forEach(function(I){var F,O;w[F=I,O=s.$utils().p(F),O==="date"?"day":O]=y[I]});var x=w.day||(w.year||w.month>=0?1:v.date()),b=w.year||v.year(),C=w.month>=0?w.month:w.year||w.day?0:v.month(),E=w.hour||0,A=w.minute||0,N=w.second||0,S=w.millisecond||0;return p?new Date(Date.UTC(b,C,x,E,A,N,S)):new Date(b,C,x,E,A,N,S)}return y},u=s.parse;s.parse=function(_){_.date=a.bind(this)(_),u.bind(this)(_)};var c=s.set,f=s.add,d=s.subtract,h=function(_,g,y,p){p===void 0&&(p=1);var w=Object.keys(g),v=this;return w.forEach(function(x){v=_.bind(v)(g[x]*p,x)}),v};s.set=function(_,g){return g=g===void 0?_:g,_.constructor.name==="Object"?h.bind(this)(function(y,p){return c.bind(this)(p,y)},g,_):c.bind(this)(_,g)},s.add=function(_,g){return _.constructor.name==="Object"?h.bind(this)(f,_,g):f.bind(this)(_,g)},s.subtract=function(_,g){return _.constructor.name==="Object"?h.bind(this)(f,_,g,-1):d.bind(this)(_,g)}}})})(Th);var Xw=Th.exports,Qw=Kt(Xw),Ih={exports:{}};(function(i,t){(function(e,r){i.exports=r()})(Vt,function(){var e,r,n=1e3,s=6e4,a=36e5,u=864e5,c=/\[([^\]]+)]|Y{1,4}|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,f=31536e6,d=2628e6,h=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/,_={years:f,months:d,days:u,hours:a,minutes:s,seconds:n,milliseconds:1,weeks:6048e5},g=function(A){return A instanceof C},y=function(A,N,S){return new C(A,S,N.$l)},p=function(A){return r.p(A)+"s"},w=function(A){return A<0},v=function(A){return w(A)?Math.ceil(A):Math.floor(A)},x=function(A){return Math.abs(A)},b=function(A,N){return A?w(A)?{negative:!0,format:""+x(A)+N}:{negative:!1,format:""+A+N}:{negative:!1,format:""}},C=function(){function A(S,I,F){var O=this;if(this.$d={},this.$l=F,S===void 0&&(this.$ms=0,this.parseFromMilliseconds()),I)return y(S*_[p(I)],this);if(typeof S=="number")return this.$ms=S,this.parseFromMilliseconds(),this;if(typeof S=="object")return Object.keys(S).forEach(function(q){O.$d[p(q)]=S[q]}),this.calMilliseconds(),this;if(typeof S=="string"){var L=S.match(h);if(L){var z=L.slice(2).map(function(q){return q!=null?Number(q):0});return this.$d.years=z[0],this.$d.months=z[1],this.$d.weeks=z[2],this.$d.days=z[3],this.$d.hours=z[4],this.$d.minutes=z[5],this.$d.seconds=z[6],this.calMilliseconds(),this}}return this}var N=A.prototype;return N.calMilliseconds=function(){var S=this;this.$ms=Object.keys(this.$d).reduce(function(I,F){return I+(S.$d[F]||0)*_[F]},0)},N.parseFromMilliseconds=function(){var S=this.$ms;this.$d.years=v(S/f),S%=f,this.$d.months=v(S/d),S%=d,this.$d.days=v(S/u),S%=u,this.$d.hours=v(S/a),S%=a,this.$d.minutes=v(S/s),S%=s,this.$d.seconds=v(S/n),S%=n,this.$d.milliseconds=S},N.toISOString=function(){var S=b(this.$d.years,"Y"),I=b(this.$d.months,"M"),F=+this.$d.days||0;this.$d.weeks&&(F+=7*this.$d.weeks);var O=b(F,"D"),L=b(this.$d.hours,"H"),z=b(this.$d.minutes,"M"),q=this.$d.seconds||0;this.$d.milliseconds&&(q+=this.$d.milliseconds/1e3,q=Math.round(1e3*q)/1e3);var W=b(q,"S"),P=S.negative||I.negative||O.negative||L.negative||z.negative||W.negative,Z=L.format||z.format||W.format?"T":"",Y=(P?"-":"")+"P"+S.format+I.format+O.format+Z+L.format+z.format+W.format;return Y==="P"||Y==="-P"?"P0D":Y},N.toJSON=function(){return this.toISOString()},N.format=function(S){var I=S||"YYYY-MM-DDTHH:mm:ss",F={Y:this.$d.years,YY:r.s(this.$d.years,2,"0"),YYYY:r.s(this.$d.years,4,"0"),M:this.$d.months,MM:r.s(this.$d.months,2,"0"),D:this.$d.days,DD:r.s(this.$d.days,2,"0"),H:this.$d.hours,HH:r.s(this.$d.hours,2,"0"),m:this.$d.minutes,mm:r.s(this.$d.minutes,2,"0"),s:this.$d.seconds,ss:r.s(this.$d.seconds,2,"0"),SSS:r.s(this.$d.milliseconds,3,"0")};return I.replace(c,function(O,L){return L||String(F[O])})},N.as=function(S){return this.$ms/_[p(S)]},N.get=function(S){var I=this.$ms,F=p(S);return F==="milliseconds"?I%=1e3:I=F==="weeks"?v(I/_[F]):this.$d[F],I||0},N.add=function(S,I,F){var O;return O=I?S*_[p(I)]:g(S)?S.$ms:y(S,this).$ms,y(this.$ms+O*(F?-1:1),this)},N.subtract=function(S,I){return this.add(S,I,!0)},N.locale=function(S){var I=this.clone();return I.$l=S,I},N.clone=function(){return y(this.$ms,this)},N.humanize=function(S){return e().add(this.$ms,"ms").locale(this.$l).fromNow(!S)},N.valueOf=function(){return this.asMilliseconds()},N.milliseconds=function(){return this.get("milliseconds")},N.asMilliseconds=function(){return this.as("milliseconds")},N.seconds=function(){return this.get("seconds")},N.asSeconds=function(){return this.as("seconds")},N.minutes=function(){return this.get("minutes")},N.asMinutes=function(){return this.as("minutes")},N.hours=function(){return this.get("hours")},N.asHours=function(){return this.as("hours")},N.days=function(){return this.get("days")},N.asDays=function(){return this.as("days")},N.weeks=function(){return this.get("weeks")},N.asWeeks=function(){return this.as("weeks")},N.months=function(){return this.get("months")},N.asMonths=function(){return this.as("months")},N.years=function(){return this.get("years")},N.asYears=function(){return this.as("years")},A}(),E=function(A,N,S){return A.add(N.years()*S,"y").add(N.months()*S,"M").add(N.days()*S,"d").add(N.hours()*S,"h").add(N.minutes()*S,"m").add(N.seconds()*S,"s").add(N.milliseconds()*S,"ms")};return function(A,N,S){e=S,r=S().$utils(),S.duration=function(O,L){var z=S.locale();return y(O,{$l:z},L)},S.isDuration=g;var I=N.prototype.add,F=N.prototype.subtract;N.prototype.add=function(O,L){return g(O)?E(this,O,1):I.bind(this)(O,L)},N.prototype.subtract=function(O,L){return g(O)?E(this,O,-1):F.bind(this)(O,L)}}})})(Ih);var tD=Ih.exports,eD=Kt(tD);Wt.extend(xa),Wt.extend(Ea),Wt.extend(Jw),Wt.extend(Qw),Wt.extend(eD);class $h{constructor(t,e,r){$(this,"array");$(this,"color");$(this,"math");$(this,"str");$(this,"map");$(this,"matrix");$(this,"timeframe");$(this,"ta");$(this,"input");$(this,"_variables");$(this,"_cacheData");$(this,"_options");$(this,"_errorListener");$(this,"_plots");$(this,"_plotshapes");$(this,"_plotbars");$(this,"_plotchars");$(this,"_plotarrows");$(this,"_plotcandles");$(this,"_alerts");$(this,"_bgColors");$(this,"_hlines");$(this,"_fills");$(this,"chart");$(this,"line");$(this,"label");$(this,"polyline");$(this,"box");$(this,"table");$(this,"linefill");$(this,"log");$(this,"runtime");$(this,"strategy");$(this,"request");$(this,"syminfo");$(this,"_count",0);var s;const n=((s=t.toString().split(".")[1])==null?void 0:s.length)||5;this._variables=e,this._errorListener=new aD,this.array=new I_(this._errorListener),this.math=new $_(n,this._errorListener),this.color=new oy,this.str=new lw(this._errorListener,n),this.map=new cw(this._errorListener),this.timeframe=new ow(e),this.matrix=new sw(this._errorListener),this.ta=new iy(e,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 sy(e,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 fw(e)},this.line=new Iw(e,this._errorListener),this.label=new hw(e,this._errorListener),this.polyline=new Tw(e,this._errorListener),this.box=new Lw(e,this._errorListener),this.table=new Rw(e,this._errorListener),this.linefill=new $w(e),this.log=new sD(e,this.str),this.runtime=new oD(this._errorListener),this.strategy=new Kw(this._variables,this._options,t,this._errorListener,r),this.request=new nD(this._variables,r),this.syminfo=new iD}get errors(){return this._errorListener.errors}get scriptType(){return this._options.scriptType}options(t){if(t.length)return this._getDataOfBarindex(t);const e=this.input.getInputs(),r=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const n=Object.keys(this._bgColors);let s;if(n.length){s={};for(const v of n)s[v]=[...this._bgColors[v].values()]}const a=this._hlines.size?[...this._hlines.values()]:void 0,u=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 f=this._plots.size>0?[...this._plots.values()]:void 0,d=this._plotbars.size>0?[...this._plotbars.values()]:void 0,h=this._plotshapes.size>0?[...this._plotshapes.values()]:void 0,_=this._plotarrows.size>0?[...this._plotarrows.values()]:void 0,g=this._plotcandles.size>0?[...this._plotcandles.values()]:void 0,y=this._plotchars.size>0?[...this._plotchars.values()]:void 0,p=this._getDraws(),w=this._variables.chart.isUseBgColor;return Object.assign(this._options,{inputs:e,plots:f,draws:p,alerts:r,colors:s,hlines:a,fills:u,logs:c,plotshapes:h,plotarrows:_,plotcandles:g,plotchars:y,plotbars:d,isUseBgColor:w})}_getDataOfBarindex(t){const e=this._alerts.size?[...this._alerts.values()]:void 0;this._alerts.clear();const r=Object.keys(this._bgColors);let n;if(r.length){n={};for(const v of r)n[v]=[...this._bgColors[v].values()].map(x=>{const b=[];for(const C of t){const E=x.data[C];E&&b.push(E)}return x.data=b,x})}const s=this._hlines.size?[...this._hlines.values()]:void 0,a=this._fills.size?this._getDataFromBarindex(t,[...this._fills.values()]):void 0,u=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 c=this._getDataFromBarindex(t,[...this._plots.values()]),f=this._plotbars.size>0?this._getDataFromBarindex(t,[...this._plotbars.values()]):void 0,d=this._plotarrows.size>0?this._getDataFromBarindex(t,[...this._plotarrows.values()]):void 0,h=this._plotcandles.size>0?this._getDataFromBarindex(t,[...this._plotcandles.values()]):void 0,_=this._plotchars.size>0?this._getDataFromBarindex(t,[...this._plotchars.values()]):void 0,g=this._plotshapes.size>0?this._getDataFromBarindex(t,[...this._plotshapes.values()]):void 0,y=this._getDrawsFromBarindex(t),p=this._getDrawDeletes(t),w=this._variables.chart.isUseBgColor;return Object.assign(this._options,{plots:c,plotarrows:d,plotcandles:h,plotchars:_,plotbars:f,draws:y,drawDeletes:p,alerts:e,colors:n,hlines:s,fills:a,logs:u,plotshapes:g,isUseBgColor:w})}_getDataFromBarindex(t,e){return e.map(r=>{const n=[];for(const s of t){const a=r.data[s];a&&n.push(a)}return r.data=n,{...r}})}_getDraws(){const{line:t,linefill:e,table:r,box:n,polyline:s,label:a}=this._variables,u={};return t.data.length&&(u.lines=t.data),e.data.length&&(u.linefills=e.data),r.data.length&&(u.tables=r.data),n.data.length&&(u.boxes=n.data),s.data.length&&(u.polylines=s.data),a.data.length&&(u.labels=a.data),Object.keys(u).length?u:void 0}_getDrawsFromBarindex(t){const{line:e,linefill:r,table:n,box:s,polyline:a,label:u}=this._variables,c={};return e.data.length&&(c.lines=e.getValOfBarIndex(t)),r.data.length&&(c.linefills=r.getValOfBarIndex(t)),n.data.length&&(c.tables=n.getValOfBarIndex(t)),s.data.length&&(c.boxes=s.getValOfBarIndex(t)),a.data.length&&(c.polylines=a.getValOfBarIndex(t)),u.data.length&&(c.labels=u.getValOfBarIndex(t)),Object.keys(c).length?c:void 0}_getDrawDeletes(t){const{line:e,linefill:r,table:n,box:s,polyline:a,label:u}=this._variables,c={},f=e.getDeleteIds(t),d=r.getDeleteIds(t),h=n.getDeleteIds(t),_=s.getDeleteIds(t),g=a.getDeleteIds(t),y=u.getDeleteIds(t);return f.length&&(c.lines=f),d.length&&(c.linefills=d),h.length&&(c.tables=h),_.length&&(c.boxes=_),g.length&&(c.polylines=g),y.length&&(c.labels=y),c}updateOptions(t){var n;const{inputs:e,strategy:r}=t;this.input.update(e),r&&((n=this.strategy)==null||n.updateOptions(r))}update(t){const{barIndex:e}=t;this.strategy.update(),this.math.update(e)}endExecution(){this.strategy.endExecution()}library(t,e){if(!this._variables.bar_index){const r=/^[^\W\d\s][^\W\s]*$/,{title:n}=t;r.test(n)?(T_.includes(n)||B_.includes(n))&&this._errorListener.addError(He(ie.libraryTitleIsKeywordErr,{name:n}),e,Rt.Error):this._errorListener.addError(ie.libraryTitleErr,e,Rt.Error),this._options.scriptType="library",this._options.library=t}}indicator(t,e){if(!this._variables.bar_index){const{format:r}=t;this._paramVerfiy(r,e,"indicator",[Gt.inherit,Gt.percent,Gt.price,Gt.volume]),this._variables.updateMaxLength(t),this._options.scriptType="indicator",this._options.indicator=t}}_paramVerfiy(t="",e,r,n,s="format"){t&&!n.includes(t)&&this._errorListener.addError(He(ie.paramsErr,{value:t,func:r,param:s,targetVal:`[${n.join(", ")}]`}),e,Rt.Error)}_lineWidthVerify(t,e){const{linewidth:r=1}=t;r<1&&(this._errorListener.addError(S_.lineWidthWarning,e,Rt.Warning),t.linewidth=1)}plot(t,e){const r=["color"];ve(t,r);const{series:n,color:s,...a}=t,{bar_index:u,time:c}=this._variables,f=`plot_${e}`,d=this._plots.get(f),h=(d==null?void 0:d.data)||[],_=n!==void 0&&isNaN(n)?void 0:n;if(h[u]={value:[c,_],barIndex:u,itemStyle:{color:s}},this._seriesColorHandle(t,r,d),!d){this._count++,this._lineWidthVerify(a,e),this._paramVerfiy(t.format,e,"plot",[Gt.percent,Gt.price,Gt.volume]);const g=s?[s]:void 0;this._plots.set(f,{editable:!0,...a,colors:g,data:h,id:f,zIndex:this._count})}return{type:"plot",key:f}}plotbar(t,e){const r=["color"];ve(t,r);const{open:n,close:s,low:a,high:u,color:c,...f}=t,{bar_index:d,time:h}=this._variables,_=`plotbar_${e}`,g=this._plotbars.get(_),y=(g==null?void 0:g.data)||[],p=s!==void 0&&isNaN(s)?void 0:s,w=n!==void 0&&isNaN(n)?void 0:n,v=a!==void 0&&isNaN(a)?void 0:a,x=u!==void 0&&isNaN(u)?void 0:u,b=[h,w,p,v,x];if(y[d]={value:b,barIndex:d,itemStyle:{color:c}},this._seriesColorHandle(t,r,g),!g){this._count++,this._paramVerfiy(t.format,e,"plotbar",[Gt.percent,Gt.price,Gt.volume]);const C=c?[c]:void 0;this._plotbars.set(_,{editable:!0,...f,colors:C,data:y,id:_,zIndex:this._count})}}_verfiyArgs(t,e,r){const{size:n,format:s,location:a,style:u}=t;this._paramVerfiy(u,r,e,Object.values(lr),"style"),this._paramVerfiy(a,r,e,Object.values(cn),"location"),this._paramVerfiy(n,r,e,Object.values(ir),"size"),this._paramVerfiy(s,r,e,[Gt.percent,Gt.price,Gt.volume],"format")}plotchar(t,e){const r=["color","textcolor"];ve(t,r);const{series:n,color:s,textcolor:a,location:u=cn.abovebar,...c}=t,{bar_index:f,time:d,high:h,low:_}=this._variables,g=`plotchar_${e}`,y=this._plotchars.get(g),p=(y==null?void 0:y.data)||[],w={value:[d,n],barIndex:f,itemStyle:{color:s,textcolor:a},low:_,high:h};p[f]=w,this._seriesColorHandle(t,r,y),y||(this._count++,this._verfiyArgs(t,"plotchar",e),this._plotchars.set(g,{editable:!0,...c,location:u,data:p,id:g,zIndex:this._count}))}plotarrow(t,e){const r=["colorup","colordown"];ve(t,r);const{series:n,colorup:s,colordown:a,...u}=t,{bar_index:c,time:f,low:d,high:h}=this._variables,_=`plotarrow_${e}`,g=this._plotarrows.get(_),y=(g==null?void 0:g.data)||[];y[c]={value:[f,n!==void 0&&isNaN(n)?void 0:n],barIndex:c,itemStyle:{colorup:s,colordown:a},low:d,high:h},this._seriesColorHandle(t,r,g),g||(this._count++,this._paramVerfiy(t.format,e,"plotarrow",[Gt.percent,Gt.price,Gt.volume]),this._plotarrows.set(_,{editable:!0,...u,data:y,id:_,zIndex:this._count}))}plotshape(t,e){const r=["color","textcolor"];ve(t,r);const{series:n,color:s,textcolor:a,location:u=cn.abovebar,...c}=t,{bar_index:f,time:d,low:h,high:_}=this._variables,g=`plotshape_${e}`,y=this._plotshapes.get(g),p=(y==null?void 0:y.data)||[],w={value:n,barIndex:f,color:s,textcolor:a,time:d,low:h,high:_};if(p[f]=w,this._seriesColorHandle(t,r,y),!y){this._count++;const v=s?[s]:void 0;this._verfiyArgs(t,"plotshape",e),this._plotshapes.set(g,{editable:!0,...c,data:p,location:u,id:g,colors:v,zIndex:this._count})}}plotcandle(t,e){const r=["wickcolor","bordercolor","color"];ve(t,r);const{wickcolor:n,bordercolor:s,color:a,close:u,open:c,low:f,high:d,...h}=t,{bar_index:_,time:g}=this._variables,y=`plotcandle_${e}`,p=this._plotcandles.get(y),w=(p==null?void 0:p.data)||[],v=u!==void 0&&isNaN(u)?void 0:u,x=c!==void 0&&isNaN(c)?void 0:c,b=f!==void 0&&isNaN(f)?void 0:f,C=d!==void 0&&isNaN(d)?void 0:d,E=[g,x,v,b,C];w[_]={value:E,barIndex:_,wickcolor:n,bordercolor:s,color:a},this._seriesColorHandle(t,r,p),p||(this._count++,this._paramVerfiy(t.format,e,"plotcandle",[Gt.percent,Gt.price,Gt.volume]),this._plotcandles.set(y,{editable:!0,...h,data:w,id:y,zIndex:this._count}))}hline(t,e){const r=`hline_${e}`;ve(t,["color"]),this._verifyDisplay(t.display,"hline",e);const s=t.display&&!t.display.length?Ze.none:Ze.all;return this._hlines.has(r)||(this._count++,this._lineWidthVerify(t,e),this._hlines.set(r,{id:r,linewidth:1,editable:!0,display:s,...t,zIndex:this._count})),{type:"hline",key:r}}fill(t,e){var S,I,F,O,L,z,q,W,P,Z;const r=["color","top_color","bottom_color"];ve(t,r);const{color:n,top_color:s,bottom_color:a,seriesColors:u,hline1:c,hline2:f,plot1:d,plot2:h,top_value:_,bottom_value:g,...y}=t,{bar_index:p,time:w}=this._variables,v=`fill_${e}`,x=this._fills.get(v),b=(x==null?void 0:x.data)||[];this._verifyDisplay(t.display,"fill",e);const C=t.display&&!t.display.length?Ze.none:Ze.all;let E,A,N="plot";if(c&&f)E=(S=this._hlines.get(c==null?void 0:c.key))==null?void 0:S.price,A=(I=this._hlines.get(f==null?void 0:f.key))==null?void 0:I.price,N="hline";else{const Y=((F=this._plots.get(d==null?void 0:d.key))==null?void 0:F.data)||[],G=((O=this._plots.get(h==null?void 0:h.key))==null?void 0:O.data)||[];E=(z=(L=Y[p])==null?void 0:L.value)==null?void 0:z[1],A=(W=(q=G[p])==null?void 0:q.value)==null?void 0:W[1]}if(b[p]={time:w,color:n,top_color:s,bottom_color:a,plot1:E,plot2:A,top_value:_,bottom_value:g},this._seriesColorHandle(t,r,x),!x){this._count++;const Y=((P=this._options.indicator)==null?void 0:P.explicit_plot_zorder)||((Z=this._options.strategy)==null?void 0:Z.explicit_plot_zorder),G=n?[n]:void 0,X=s?[s]:void 0,ut=a?[a]:void 0;this._fills.set(v,{id:v,colors:G,top_colors:X,bottom_colors:ut,display:C,data:b,type:N,editable:!0,fillgaps:!1,hline1:c,hline2:f,plot1:d,plot2:h,...y,zIndex:Y?this._count:void 0})}}alert({message:t,freq:e=jr.freqOncePerBar},r){const{bar_index:n,_isRealTimeBar:s,last_bar_index:a}=this._variables,u=`alert_${r}`,c=this._cacheData[u]||{},f=c.barIndex;if(this._paramVerfiy(e,r,"alert",[jr.freqAll,jr.freqOncePerBar,jr.freqOncePerBarClose]),e===jr.freqOncePerBar&&n===f){this._alerts.delete(u);return}this._cacheData[u]=c;const d={message:t,freq:e,id:u,type:"alert"};if(s){e!==jr.freqOncePerBarClose&&this._alerts.set(u,d),c.barIndex=n;return}if(!s&&e===jr.freqOncePerBarClose&&n===f&&a===n-1){this._alerts.set(u,d),c.barIndex=n;return}this._alerts.delete(u)}alertcondition({condition:t,message:e,title:r},n){const{_isRealTimeBar:s}=this._variables,a=`alertcondition_${n}`;s&&t?this._alerts.set(a,{message:e,title:r,id:a,type:"alertcondition"}):this._alerts.delete(a)}barcolor(t,e){this._setColors(t,"barcolor",e)}bgcolor(t,e){this._setColors(t,"bgcolor",e)}_verifyDisplay(t=Eh.all,e,r){t.length&&t.length<4&&this._errorListener.addError(He(ie.displayErr,{func:e,values:"[display.none, display.all]"}),r,Rt.Error)}_setColors(t,e,r){ve(t,["color"]);const{color:s,...a}=t;this._verifyDisplay(a.display,e,r);const u=t.display&&!t.display.length?Ze.none:Ze.all,{bar_index:c,time:f}=this._variables,d=`${e}_${r}`;this._bgColors[e]||(this._bgColors[e]=new Map);const h=this._bgColors[e].get(d),_=(h==null?void 0:h.data)||[],g=(h==null?void 0:h.setColors)||[];s&&!g.includes(s)&&g.push(s),_[c]={color:s,time:f,barIndex:c},h||this._bgColors[e].set(d,{...a,display:u,data:_,setColors:g,id:d})}max_bars_back({var:t,num:e,var_name:r}){console.log(t,e,r)}float({x:t}){return t}bool({x:t}){return t||!1}string({x:t}){return t}int({x:t}){return t&&Math.trunc(t)}na({x:t}){return!!(t===void 0||typeof t=="number"&&isNaN(t))}fixnan({source:t},e){return t===void 0||typeof t=="number"&&isNaN(t)?this._cacheData[`fixnan_${e}`]:(this._cacheData[`fixnan_${e}`]=t,t)}nz({source:t,replacement:e}){return t!==void 0&&!(typeof t=="number"&&isNaN(t))?t:e||0}time({timeframe:t="",session:e,timezone:r,bars_back:n=0},s){return this._timeHandle(this._variables.time,s,t,e,r,n)}time_close({timeframe:t="",session:e,timezone:r,bars_back:n=0},s){return this._timeHandle(this._variables.time,s,t,e,r,n,!0)}timestamp(t){const{dateString:e,timezone:r,year:n,month:s,day:a,hour:u=0,minute:c=0,second:f=0}=t;if(e)return Wt(e).utc(!/GMT|UTC/.test(e)).valueOf();let d=s-1,h=n;if(d<0){const _=Math.ceil(Math.abs(d/12));d=12*_+d,h=n-_}return mr({year:h,month:d,day:a,hour:u,minute:c,second:f},r).valueOf()}weekofyear({time:t,timezone:e}){return mr(t,e).week()}year({time:t,timezone:e}){return mr(t,e).year()}second({time:t,timezone:e}){return mr(t,e).second()}month({time:t,timezone:e}){return mr(t,e).month()+1}minute({time:t,timezone:e}){return mr(t,e).minute()}hour({time:t,timezone:e}){return mr(t,e).hour()}dayofweek({time:t,timezone:e}){return mr(t,e).day()+1}dayofmonth({time:t,timezone:e}){return mr(t,e).date()}_calcTimeOffset(t,e){const r=this._variables.getTimeTradingday(t,this._variables.timeframe.period),n=gr(e,t)*1e3;return t-r-Math.floor((t-r)/n)*n}_timeHandle(t,e,r="",n,s,a=0,u=!1){const c=r||this._variables.__period,f=gr(c,t),d=gr(this._variables.__period,t);let h;if(f<=d)h=t,u&&(h+=d*1e3);else{const _=`time_${e}`,g=this._cacheData[_];if(g)g.currentTime+f*1e3-g.offset<=t?(h=t,this._cacheData[_]={currentTime:t,offset:0}):h=g.currentTime;else{const y=this._calcTimeOffset(t,c);this._cacheData[_]={currentTime:t,offset:y},h=t}u&&(h+=f*1e3)}if(n&&n!==Mn.regular&&n!==Mn.extended){const{timePeriods:_,weeks:g}=this._parserSession(n,e),y=mr(t,s),p=y.format("YYYY-MM-DD HH:mm"),w=y.format("YYYY-MM-DD"),v=h,x=mr(h,s).format("YYYY-MM-DD HH:mm");h=void 0;for(const C of _){const[E,A]=C;let N;if(E===A&&(N=y.add(1,"day").format("YYYY-MM-DD")),Wt(p).isBetween(`${w} ${E}`,`${N||w} ${A}`,"hour","[)")){Wt(x).isBetween(`${w} ${E}`,`${N||w} ${A}`,"hour","[)")?h=v:h=mr(`${w} ${E}`,s).valueOf();break}}const b=this._variables.dayofweek;h&&!g.includes(b)&&(h=void 0)}return h&&h-a*d*1e3}_seriesColorHandle(t,e,r){var n;if(r&&e!=null&&e.length)for(const s of e){if((n=r.gradientColorKeys)!=null&&n.includes(s))continue;const a=t[s];if(!a)continue;const u=r[`${s}s`]||[];u.includes(a)||(u.push(a),r[`${s}s`]=u,u.length>5&&(r[`${s}s`]=[],r.gradientColorKeys=r.gradientColorKeys||[],r.gradientColorKeys.push(s)))}}_parserSession(t,e){const r=t.split(":"),n=r[0],a=(r[1]||"1234567").split("").map(c=>{const f=parseInt(c,10);if(f<1||f>7){this._errorListener.addError(`Invalid day of week: ${c}`,e,Rt.Error);return}return f});return{timePeriods:n.split(",").map(c=>{c===""||c===Mn.regular?c="0930-1500":c===Mn.extended&&(c="1500-1830");const f=c.split("-");return f.length!==2?[]:[this._processTime(f[0],e),this._processTime(f[1],e)]}),weeks:a}}_processTime(t,e){const r=parseInt(t.slice(0,2),10),n=parseInt(t.slice(2),10);if(!(r>=0&&r<=23)&&n>=0&&n<=59){this._errorListener.addError("Invalid time: Time must be within 00:00 to 23:59",e,Rt.Error);return}return`${r}:${n}`}}const rD={1:"1M",3:"3M",5:"5M",15:"15M",30:"30M",45:"45M",60:"1H",120:"2H",180:"3H",240:"4H",D:"1D",W:"1W",M:"1MTH","3M":"3MTH","6M":"6MTH","12M":"12MTH"};let nD=class{constructor(t,e){$(this,"_variables");$(this,"_scriptId");$(this,"_cacheData");this._variables=t,this._scriptId=e,this._cacheData=new Map}security(t,e){const r=self.workerStorage.get(`request_${this._scriptId}`),{paramsExpr:n=[]}=t,s=this._getRequestData(t,e);if(r!=null&&r.has(e)){if(!s)return;const c=r.get(e);return this._runScripts(c,e,!1,n,s)}const a=this._parseExprCode(t),u=this._runScripts(a,e,!0,n,s);return r==null||r.set(e,a),u}_parseExprCode(t){let{expression:e,paramsExpr:r=[]}=t,n=[],s=1;e=Xl(e);const a=JSON.parse(e),u=a.pop();let c=(u==null?void 0:u.memberCodes)||{},f=(u==null?void 0:u.depends)||[];if(!f.length)return`return ${u==null?void 0:u.code}`;let d=[],h=[];const _=[];if(this._getDependCodes(f,a,n,d,h,_),n.push(..._),h.length){const p=r.length;let w=[];for(let v=p-1;v>=0;v--){const x=r[v];let b=JSON.parse(Xl(x));const C=[];s!==0&&h.length&&(w.unshift("{"),s++),b=b.map(S=>{const{scope:I,code:F,varNames:O,dependSelf:L}=S;return I===2&&!C.includes(O)&&!L&&(S.code=`let ${F}`),O&&C.push(...O.split(", ")),S.memberCodes&&Object.assign(c,{...S.memberCodes}),S});const E=[],A=[];let N=h.map(S=>({...S,isArg:!1,isPreArg:!0}));h=[],this._getDependCodes(N,b,A,d,h,E),w.unshift(...A,...E),n=w.concat(n),w=[]}}for(n.push(`return ${u==null?void 0:u.code}`);s>1;)n.push("}"),s--;n=d.concat(n);let g=n.join(`
63
63
  `);const y=[];for(const p of Object.keys(c))g.includes(`$_var.getCacheData("${p}"`)&&y.push(c[p]);return y.length&&(g=`${y.join(`
64
64
  `)}
65
- ${g}`),g}_getRequestData(t,e){var C,E,A,N,S;let{symbol:r,timeframe:n,calc_bars_count:s,gaps:a,lookahead:u,ignore_invalid_symbol:c}=t;const{__period:f,syminfo:{ticker:d,tickerid:h},mintick:_,time:g,nextBarTime:y}=this._variables;if(n=nc(n),(f===n||n==="")&&(r===d||r===h)){const{close:I,open:F,high:O,low:L,bar_index:z,last_bar_index:q,last_bar_time:W,_isRealTimeBar:P,volume:Z,time:Y,time_tradingday:G}=this._variables;return{barIndex:z,c:I,o:F,h:O,l:L,volume:Z,lastBarIndex:q,lastBarTime:W/1e3,nextBarTime:y,isrealtime:P,time_tradingday:G,time:Y/1e3,interval:f,mintick:_}}const p=`${r}--${n||f}`,w=self.workerStorage.get(`request_${this._scriptId}_data`),v=self.workerStorage.get(`request_${this._scriptId}_list`),x=self.workerStorage.get(`request_${this._scriptId}_tmp`),b={id:p,calc_bars_count:s,ignore_invalid_symbol:c,symbol:r,timeframe:rD[n||f]||n};if(w!=null&&w.has(p)){let I=gr(n,g)*1e3;const F=gr(f,g)*1e3;x==null||x.delete(p),e=`${e}_${p}`;const{index:O=0,periodStamp:L=F}=this._cacheData.get(e)||{},z=w==null?void 0:w.get(p);if(!z.length)return;const q=z.slice(O);let W=g,P=L+W;const Z=z.length-1;if(Z<0)return;const Y={lastBarIndex:z[Z].barindex||Z,lastBarTime:z[Z].time,interval:n,mintick:_};if(I>L){let G;if(u===ln.lookaheadOn?G=this._lookaheadOnHandle(q,n,P,I,Y,O,L,e,W,a):G=this._lookaheadOffHandle(q,n,P,I,Y,O,L,e,W,y||P,a),G)return G;if(G===null)return}else if(u===ln.lookaheadOn)for(const[G,X]of q.entries()){let{time:ut,barindex:_t}=X;ut=ut*1e3;const at=((C=q[G+1])==null?void 0:C.time)*1e3||ut+I;let vt=O+G;if(ut>=P){this._cacheData.set(e,{index:vt,periodStamp:L});return}if(ut<=W&&at>W){const wt=O+G;return this._cacheData.set(e,{index:wt,periodStamp:L}),{...X,barIndex:_t||wt,nextBarTime:(E=q[G+1])==null?void 0:E.time,...Y}}}else for(const[G,X]of q.entries()){let{time:ut,barindex:_t}=X;ut=ut*1e3;const at=((A=q[G+1])==null?void 0:A.time)*1e3||ut+I;let vt=O+G;if(ut>P){this._cacheData.set(e,{index:vt,periodStamp:L});return}if(ut<=P&&P<at)return this._cacheData.set(e,{index:vt,periodStamp:L}),{...X,barIndex:_t||vt,nextBarTime:(N=q[G+1])==null?void 0:N.time,...Y};if(ut>=W&&ut<=P&&(_t||vt)===Y.lastBarIndex)return this._cacheData.set(e,{index:vt,periodStamp:L}),{...X,barIndex:_t||vt,nextBarTime:(S=q[G+1])==null?void 0:S.time,...Y}}this._cacheData.set(e,{index:z.length,periodStamp:L})}else(v==null?void 0:v.get(p))||x==null||x.set(p,b);v==null||v.set(p,b)}_lookaheadOnHandle(t,e,r,n,s,a,u,c,f,d){var h;for(const[_,g]of t.entries()){let{time:y,barindex:p}=g;y=y*1e3,e.includes("M")&&(n=gr(e,y)*1e3-(Wt(y).date()-1)*864e5);const w=y,v=n+w;let x=a+_;if(r<=w)return this._cacheData.set(c,{index:x,periodStamp:u}),null;let b={...g,barIndex:p||x,nextBarTime:(h=t[_+1])==null?void 0:h.time,...s};if(d===ln.gapsOn){if(r>w&&f<=w)return this._cacheData.set(c,{index:x,periodStamp:u}),b}else{if(r>v)continue;if(r>w)return this._cacheData.set(c,{index:x,periodStamp:u}),b}}}_lookaheadOffHandle(t,e,r,n,s,a,u,c,f,d,h){var _,g;for(const[y,p]of t.entries()){let{time:w,barindex:v}=p;w=w*1e3,e.includes("M")&&(n=gr(e,w)*1e3-(Wt(w).date()-1)*864e5);const x=w,b=n+x,C=a+y;if(r<x)return this._cacheData.set(c,{index:C,periodStamp:u}),null;const E={...p,barIndex:v||C,nextBarTime:(_=t[y+1])==null?void 0:_.time,...s};if(r>=b&&f<b||r<b&&d>=b)return h===ln.gapsOn?(this._cacheData.set(c,{index:C,periodStamp:u}),E):(this._cacheData.set(c,{index:C,data:E,periodStamp:u}),E);if(!(f>b)&&f>=x){let A=(g=this._cacheData.get(c))==null?void 0:g.data;if(!A){const N=t[C-1];if(!N)return null;A={...N,barIndex:N.barindex||C-1,nextBarTime:E.time,...s},this._cacheData.set(c,{index:C,data:A,periodStamp:u})}return A}}}_getDependCodes(t,e,r,n,s,a){for(const u of t){if(!u.isArg){const c=e.filter(d=>{var h;return(h=d==null?void 0:d.depends)==null?void 0:h.some(_=>_.name===u.name&&_.scope===u.scope&&_.isAgainAssign)});for(const d of c){const{code:h,depends:_}=d;if(!r.includes(h)&&(r.unshift(h),_!=null&&_.length)){for(const g of _)g.memberCode&&a.push(g.memberCode);this._getDependCodes(_,e,r,n,s,a)}}const f=e.find(d=>{var h;return((h=d.varNames)==null?void 0:h.split(", ").includes(u.name))&&(!u.isPreArg||u.isPreArg&&d.methodName===u.functionName)||d.funcName===u.name});if(f){const{code:d,depends:h}=f,_=r.findIndex(g=>g===d);if(_!==-1&&r.splice(_,1),r.unshift(d),h!=null&&h.length){for(const g of h)g.memberCode&&a.push(g.memberCode);this._getDependCodes(h,e,r,n,s,a)}continue}}s.some(c=>c.name===u.name)||s.push(u)}}_runScripts(t,e,r,n,s){const a=`${this._scriptId}_${e}`;let{builtInGather:u,buildinConstants:c,buildInFunctions:f,tradingvueFunc:d}=self.workerStorage.get(a)||{};const{interval:h,mintick:_,...g}=s||{};r&&(u=new Lh(a),c=new Ch,f=new $h(this._variables.mintick||1e-5,u,this._scriptId),d=new Function("$_var","$_const","$_func","$paramsExpr","$posStr",t),u.updateOptions({interval:h,mintick:_||1e-5}),self.workerStorage.set(a,{builtInGather:u,buildinConstants:c,buildInFunctions:f,tradingvueFunc:d})),u.updateData(g),f.update({barIndex:(g==null?void 0:g.barindex)||0});const y=d(u,c,f,n||[],e);return f.endExecution(),y}},iD=class{constructor(){}prefix(t){var r;const{symbol:e}=t;return((r=e==null?void 0:e.split("."))==null?void 0:r[0])||""}ticker(t){var r;const{symbol:e}=t;return((r=e==null?void 0:e.split("."))==null?void 0:r[1])||""}};class sD{constructor(t,e){$(this,"_logs");$(this,"_variables");$(this,"_str");$(this,"_preBar",{barIndex:-1,isrealtime:!1});this._variables=t,this._logs=[],this._str=e}get logs(){return this._logs}clearLogs(){this._logs=[]}info(t,e,r){this._addLog(t,e,"info",r)}error(t,e,r){this._addLog(t,e,"error",r)}warning(t,e,r){this._addLog(t,e,"warning",r)}_addLog(t,e,r,n){if(typeof e=="string"&&(n=e),n.startsWith("export"))return;const{message:s,formatString:a}=t,{time:u,bar_index:c,_isRealTimeBar:f,_isRepeated:d}=this._variables;let h=s;a&&Array.isArray(e)&&e.length&&(e=e.map(p=>(typeof p=="object"&&(p.isArray?p=JSON.stringify(p._value):p=p.toString()),p!==void 0?p:"na")),h=this._str.strformat({formatString:a},e,!0));const{barIndex:_,isrealtime:g}=this._preBar;this._preBar={barIndex:c,isrealtime:f};const y=Date.now();h&&this._logs.push({message:`[${Wt(g||f?y:u).format("YYYY-MM-DDTHH:mm:ss.SSSZ")}]: ${h}`,time:u,id:M_(6),barIndex:c,type:r})}}class oD{constructor(t){$(this,"_errorListener");this._errorListener=t}error({message:t},e){e.startsWith("export")||this._errorListener.addError(t,e,Rt.Error)}}class aD{constructor(){$(this,"_errors");this._errors=new Map}clear(){this._errors.clear()}get errors(){return Wr.flatMap([...this._errors.values()])}addError(t,e,r,n=0){const[s,a]=e.split("_").slice(-2),u=this._errors.get(e),c={message:t,endLineNumber:Number(s),startColumn:Number(a)+1,endColumn:Number(a)+n+1,startLineNumber:Number(s),type:r};u?u.push(c):this._errors.set(e,[c])}}class uD{constructor(){$(this,"_isMarketOpen");$(this,"_currentBarIndex");$(this,"_totalBarIndex");$(this,"_isRealTimeBar");$(this,"_preBarIndex");this._currentBarIndex=0,this._totalBarIndex=0,this._isRealTimeBar=!1,this._preBarIndex=0,this._isMarketOpen=!0}update(t,e,r,n){this._preBarIndex=this._currentBarIndex,this._currentBarIndex=t,this._totalBarIndex=e,this._isRealTimeBar=r,this._isMarketOpen=n}get isnew(){return!this._isRealTimeBar||this._preBarIndex!==this._currentBarIndex}get islast(){return this._currentBarIndex===this._totalBarIndex}get isfirst(){return this._currentBarIndex===0}get ishistory(){return!this._isRealTimeBar}get isrealtime(){return this._isRealTimeBar}get isconfirmed(){return!this._isRealTimeBar}get islastconfirmedhistory(){return this._isMarketOpen?this._currentBarIndex===this._totalBarIndex-1||this._currentBarIndex===this._totalBarIndex&&!this._isRealTimeBar:this._currentBarIndex===this._totalBarIndex}}class lD{constructor(t){$(this,"_variables");this._variables=t}get isfirstbar(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday}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:t,__period:e}=this._variables,r=gr(e,t);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:t,__period:e}=this._variables,r=gr(e,t);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 cD{constructor(t){$(this,"_orders");$(this,"_historyOrders");$(this,"_options");$(this,"_max_contracts_held_all",0);$(this,"_max_contracts_held_long",0);$(this,"_max_contracts_held_short",0);$(this,"_max_drawdown",0);$(this,"_max_runup",0);$(this,"_max_runup_percent",0);$(this,"_max_drawdown_percent",0);$(this,"_variables");$(this,"_netprofit",0);$(this,"_eventrades",0);$(this,"_avg_trade_percent");$(this,"_avg_losing_trade_percent");$(this,"_avg_winning_trade_percent");$(this,"_closedtrades",0);$(this,"_losstrades",0);$(this,"_grossloss",0);$(this,"_grossprofit",0);$(this,"_wintrades",0);$(this,"_opentrades_capital_held",0);$(this,"_position_avg_price",0);$(this,"_position_size",0);$(this,"_openprofit",0);$(this,"_preMaxNetValue",0);$(this,"_preMinNetValue",0);$(this,"marginCallLong",0);$(this,"marginCallShort",0);this._orders=[],this._historyOrders=[],this._variables=t}update(t){this._calcMaxDrawdownAndMaxRunup(t)}_calcMaxDrawdownAndMaxRunup(t){if(!this._orders.length&&!this._historyOrders.length)return;let e=0,r=0;const{high:n,low:s,close:a}=t;let u=0;for(const[d,h]of this._orders.entries()){const{in_price:_,qty:g=0,direction:y,commission:p,original_qty:w=1}=h,v=y===fe.long?1:-1,x=(n-_)*g,b=(s-_)*g,C=v===1?x:-b,E=v===1?-b:x;u+=(a-_)*v*g,e+=E,d>0&&p&&(r-=p*g/w),r+=C}this._openprofit=u;const c=this.initial_capital,f=c+this._netprofit;this._preMinNetValue=this._preMinNetValue||c,this._preMaxNetValue=this._preMaxNetValue||c,e=this._preMaxNetValue-f+Math.max(e,0),r=f-this._preMinNetValue+r,this._max_drawdown<e&&(this._max_drawdown=e,this._max_drawdown_percent=e/this._preMaxNetValue*100),r>this._max_runup&&(this._max_runup=r,this._max_runup_percent=r/(this._preMinNetValue+r)*100)}updateOrders(t){this._orders=t,this._calcMaxContracts()}_calcMaxContracts(){const t=this._orders.length;if(!t){this._position_size=0,this._position_avg_price=void 0,this._opentrades_capital_held=0;return}const[e,r,n,s,a,u,c]=this._orders.reduce(([f,d,h,_,g,y,p],w)=>{const{direction:v,qty:x=0,in_price:b,commission:C=0}=w;return v===fe.long?(f+=x,d+=x,y+=x):(f+=x,h+=x,y-=x),_+=x*b,g+=b,p+=C,[f,d,h,_,g,y,p]},[0,0,0,0,0,0,0]);this._historyOrders.length||(this._netprofit=-c,this._grossloss=c),this._position_size=u,this._position_avg_price=a/t,this._opentrades_capital_held=s,this._max_contracts_held_all=Math.max(e,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(n,this._max_contracts_held_short)}updateHistoryOrders(t){this._historyOrders=t;const e=this._historyOrders.length;this._closedtrades=e;const[r,n,s,a,u,c,f,d]=this._historyOrders.reduce((g,y)=>{let[p,w,v,x,b,C,E,A]=g;const{profit:N=0,profit_percent:S=0}=y;return p+=N,w+=S,N<0?(v+=N,x+=S,E+=1):N>0&&(b+=N,C+=S,A+=1),[p,w,v,x,b,C,E,A]},[0,0,0,0,0,0,0,0]),h=this._orders.reduce((g,y)=>{const{commission:p=0,qty:w=0,original_qty:v=0}=y,x=p*w/v;return g+x},0);this._avg_trade_percent=e?n/e:void 0,this._avg_losing_trade_percent=e?Math.abs(a)/f:void 0,this._avg_winning_trade_percent=e?c/d:void 0,this._netprofit=r-h;const _=this.initial_capital+this._netprofit;this._preMaxNetValue=Math.max(this._preMaxNetValue||this.initial_capital,_),this._preMinNetValue=Math.min(this._preMinNetValue||this.initial_capital,_),this._grossloss=Math.abs(s-h),this._grossprofit=u,this._eventrades=e-f-d,this._losstrades=f,this._wintrades=d}updateStrategyOptions(t){this._options=t}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 t=this._losstrades;return t?Math.abs(this._grossloss/t):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 t=this._wintrades;return t?Math.abs(this._grossprofit/t):void 0}get avg_winning_trade_percent(){return this._avg_winning_trade_percent}get initial_capital(){var t;return((t=this._options)==null?void 0:t.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:t,margin_long:e=0,margin_short:r=0,commission_type:n,commission_value:s=0}=this._options,a=this._orders[0].direction===fe.long?1:-1,u=(a===1?e:r)/100;if(u<=0)return;const{close:c}=this._variables,[f,d]=this._orders.reduce((h,_)=>{let[g,y]=h;const{in_price:p,qty:w=0,original_qty:v=0}=_,x=p*w;if(g+=x,s){let b=0;switch(n){case je.percent:b=(x+w*c)*s/100;break;case je.cashPerContract:b=w*s*2;break;case je.cashPerOrder:b=w/v*s+s;break}y+=b}return[g,y]},[0,0]);return(f-(t+this._netprofit-d))*a/this._position_size/(1-a*u)}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(t,e){if(!this._options)return 0;const{commission_value:r=0,commission_type:n}=this._options,s=t*e;let a=0;switch(n){case je.percent:a=s*r/100;break;case je.cashPerContract:a=e*r;break;case je.cashPerOrder:a=r;break}return a}}class fD{constructor(t){$(this,"_preAccdist");$(this,"_preNvi");$(this,"_prePvi");$(this,"_preObv");$(this,"_prePvt");$(this,"_preWad");$(this,"_preVwap");$(this,"_preValue");$(this,"_currentData");$(this,"_preData");$(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=t}update(t){this._preValue={},t.barIndex!==this._currentData.barIndex&&(this._preData={...this._currentData}),this._currentData={...t}}get isRealTime(){return this._preData.barIndex===this._currentData.barIndex}get accdist(){if(this._preValue.accdist)return this._preValue.accdist;const{close:t,low:e,high:r,volume:n}=this._currentData;if(r===e)return this._preAccdist;const s=(t-e-(r-t))/(r-e)*n+this._preAccdist;return!this.isRealTime&&(this._preAccdist=s),this._preValue.accdist=s,s}get iii(){if(this._preValue.iii)return this._preValue.iii;const{close:t,low:e,high:r,volume:n}=this._currentData,s=(2*t-r-e)/((r-e)*n);return this._preValue.iii=s,s}get nvi(){return this._preValue.nvi?this._preValue.nvi:this._getNvi()}get wvad(){if(this._preValue.wvad)return this._preValue.wvad;const{close:t,low:e,high:r,volume:n,open:s}=this._currentData,a=(t-s)/(r-e)*n;return this._preValue.wvad=a,a}get obv(){if(this._preValue.obv)return this._preValue.obv;const{close:t,volume:e}=this._currentData,{close:r}=this._preData;if(r===void 0){this._preObv=0;return}const n=Math.sign(t-r)*e+this._preObv;return!this.isRealTime&&(this._preObv=n),this._preValue.obv=n,n}get pvi(){return this._preValue.pvi?this._preValue.pvi:this._getPvi()}get tr(){if(this._preValue.tr)return this._preValue.tr;const{low:t,high:e}=this._currentData,{close:r}=this._preData;if(r===void 0)return;const n=Math.max(e-t,Math.abs(e-r),Math.abs(t-r));return this._preValue.tr=n,n}get pvt(){if(this._preValue.pvt)return this._preValue.pvt;const{close:t,volume:e}=this._currentData,{close:r}=this._preData;if(r===void 0){this._prePvt=0;return}const n=(t-r)/r*e+this._prePvt;return!this.isRealTime&&(this._prePvt=n),this._preValue.pvt=n,n}get wad(){if(this._preValue.wad)return this._preValue.wad;const{close:t,high:e,low:r}=this._currentData,{close:n}=this._preData;if(n===void 0)return this._preWad=0,0;const s=Math.max(e,n),a=Math.min(r,n),u=t-n,f=(u>0?t-a:u<0?t-s:0)+this._preWad;return!this.isRealTime&&(this._preWad=f),this._preValue.wad=f,f}get vwap(){var d,h;if(this._preValue.vwap)return this._preValue.vwap;const{hlc3:t,volume:e}=this._currentData;let{sum:r=0,sumV:n=0,isReset:s}=this._preVwap;if(((h=(d=self.workerStorage)==null?void 0:d.get(this._id))==null?void 0:h.buildInFunctions.timeframe.change({timeframe:"1D"},"vwap_buildin"))&&(s=!0,r=n=0),!s)return;const u=t*e+r,c=e+n;!this.isRealTime&&(this._preVwap={sum:u,sumV:c,isReset:s});const f=u/c;return this._preValue.vwap=f,f}_getNvi(){const t=this._preNvi||1,{close:e=0,volume:r=0}=this._preData,{close:n,volume:s}=this._currentData;let a=1;const u=t||1;return n&&e?a=s<r?u+(n-e)/e*u:u:a=u,!this.isRealTime&&(this._preNvi=a),this._preValue.nvi=a,a}_getPvi(){const t=this._prePvi||1,{close:e=0,volume:r=0}=this._preData,{close:n,volume:s}=this._currentData;let a=1;const u=t||1;return n&&e?a=s>r?u+(n-e)/e*u:u:a=u,!this.isRealTime&&(this._prePvi=a),this._preValue.pvi=a,a}}class hD{constructor(){$(this,"_period");$(this,"_multiplier");$(this,"_unit");this._period="1",this._multiplier=1,this._unit="m"}update(t){if(!t)return;this._period=t;const[e,r]=Fs(t);this._multiplier=e,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 dD{constructor(t){$(this,"_variables");$(this,"_bgColor");$(this,"_fgColor");$(this,"isUseBgColor",!1);this._variables=t}updateOptions(t){t!=null&&t.bg_color&&(this._bgColor=t.bg_color,this._fgColor=this._contrastColor(t.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(){return this._variables.time}get right_visible_bar_time(){return this._variables.time}_parseColor(t){let e,r,n,s;if(t.startsWith("#")){e=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16);const a=t.substring(7);a?s=parseInt(a,16)/255:s=1}else{const a=this._parserRgbColor(t);e=a[0]||0,r=a[1]||0,n=a[2]||0,s=a[3]||1}return{r:e,g:r,b:n,a:s}}_parserRgbColor(t){var e;return((e=t.match(/\d+/g))==null?void 0:e.map(Number))||[]}_contrastColor(t){const{r:e,g:r,b:n}=this._parseColor(t);return(299*e+587*r+114*n)/1e3>128?"#000000":"#ffffff"}}class _D{constructor(){$(this,"_syminfo",{})}update(t){this._syminfo=t}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||Mn.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}get volumetype(){return this._syminfo.volumetype||"n/a"}}class pD{constructor(t){$(this,"_variables");this._variables=t}get future_amount(){}get future_ex_date(){}get future_pay_date(){}}class mD{constructor(t){$(this,"_variables");this._variables=t}get future_eps(){}get future_period_end_time(){}get future_revenue(){}get future_time(){}}Wt.extend(A_),Wt.extend(xa),Wt.extend(Ea);class Lh{constructor(t){$(this,"_cacheData");$(this,"_barIndex");$(this,"_isRealTimeBar");$(this,"_barstate");$(this,"_priceVariables");$(this,"_lastBarIndex");$(this,"_currentBarTime");$(this,"_lastBarTime");$(this,"_period");$(this,"_offsetTime");$(this,"_timeframe");$(this,"_ta");$(this,"_polyline");$(this,"_label");$(this,"_line");$(this,"_linefill");$(this,"_box");$(this,"_table");$(this,"_strategy");$(this,"_session");$(this,"syminfo");$(this,"chart");$(this,"earnings");$(this,"dividends");$(this,"_timeTradingday");$(this,"_mintick");$(this,"_cacheSpace");$(this,"_precision");$(this,"_nextBarTime");$(this,"_isRepeated");$(this,"_preCacheData");this._cacheData={varData:{},varNewData:{},varipData:{}},this._preCacheData={varData:{},varNewData:{},varipData:{}},this._barIndex=0,this._lastBarIndex=0,this._currentBarTime=0,this._lastBarTime=0,this._offsetTime=0,this._period="",this._isRealTimeBar=!1,this._barstate=new uD,this._timeframe=new hD,this._priceVariables={close:0,open:0,low:0,high:0,volume:0},this._ta=new fD(t),this._polyline=new $i,this._label=new $i,this._line=new $i,this._linefill=new $i,this._box=new $i,this._table=new $i,this._strategy=new cD(this),this._session=new lD(this),this.syminfo=new _D,this.chart=new dD(this),this.earnings=new mD(this),this.dividends=new pD(this),this._cacheSpace=new Map}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:t,open:e,high:r,low:n}=this._priceVariables;return(t+e+r+n)/4}get hl2(){const{high:t,low:e}=this._priceVariables;return(t+e)/2}get hlc3(){const{close:t,high:e,low:r}=this._priceVariables;return(t+e+r)/3}get hlcc4(){const{close:t,high:e,low:r}=this._priceVariables;return(t*2+e+r)/4}get hour(){return Wt(this._currentBarTime).hour()}get minute(){return Wt(this._currentBarTime).minute()}get second(){return Wt(this._currentBarTime).second()}get month(){return Wt(this._currentBarTime).month()+1}get year(){return Wt(this._currentBarTime).year()}get dayofweek(){return Wt(this._currentBarTime).day()}get dayofmonth(){return Wt(this._currentBarTime).date()}get weekofyear(){return Wt(this._currentBarTime).week()}get last_bar_time(){return this._lastBarTime}get time(){return this._currentBarTime}get time_close(){const[t,e]=Fs(this._period);return this._isRealTimeBar?void 0:Wt(this._currentBarTime).add(t,e).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}updateMaxLength(t){const{max_lines_count:e,max_labels_count:r,max_boxes_count:n,max_polylines_count:s}=t;n&&this._box.setMaxLen(n),r&&this._label.setMaxLen(r),e&&this._line.setMaxLen(e),s&&this._polyline.setMaxLen(s)}getTimeTradingday(t,e){const[r,n]=Fs(e),s=Wt(t);return["M","w","y","d"].includes(n)?s.valueOf():(s.subtract(this._offsetTime,"h"),s.startOf("d").add(this._offsetTime,"h").valueOf())}updateOptions(t){var f;const{interval:e="1D",offsetTime:r=5,mintick:n,chart:s,syminfo:a}=t,u=((f=n.toString().split(".")[1])==null?void 0:f.length)||5;this._precision=u;const c=this._transformPeriod(e);this._period=c,this._mintick=n,this._offsetTime=r,this._timeframe.update(c),this.chart.updateOptions(s),this.syminfo.update(a)}updateData(t,e){const{barIndex:r,c:n,o:s,h:a,l:u,volume:c,time:f,lastBarIndex:d,lastBarTime:h,isrealtime:_,time_tradingday:g,nextBarTime:y}=t;if(this._priceVariables={close:Number(n),open:Number(s),high:Number(a),low:Number(u),volume:Number(c)},this._isRealTimeBar=_,r>this._barIndex){const{varData:p,varNewData:w,varipData:v}=this._cacheData;this._preCacheData={varData:{...p},varNewData:{...w},varipData:{...v}},this._isRealTimeBar&&(this._cacheData.varNewData={})}this._isRepeated=e,this._timeTradingday=g,this._currentBarTime=f*1e3,this._lastBarIndex=d,this._barIndex=r,this._lastBarTime=h*1e3,this._nextBarTime=y*1e3,this._barstate.update(r,d,_,!0),this.ta.update({...this._priceVariables,hlc3:this.hlc3,barIndex:r})}getCacheData(t,e,r){const n=this.setCacheData(t,r),s=this._cacheSpace.get(t)||0;return e=Math.floor(e),s<e&&this._cacheSpace.set(t,e),n[n.length-1-e]}setCacheData(t,e){let r=this._cacheData[t]||{barIndex:-1,data:[]};if(r.barIndex>this._barIndex)return r.data;r.barIndex===this._barIndex?r.data[r.data.length-1]=e:r.data.push(e);const n=this._cacheSpace.get(t);return n&&r.data.length>n+5&&r.data.shift(),r.barIndex=this._barIndex,this._cacheData[t]=r,r.data}getTypeInstance(t,e){return new D_(t,e)}verifyVarAndVarip(t,e,r){const n=`${t}_${e}`;return r==="var"&&this._cacheData.varData.hasOwnProperty(n)?(this._upadteChartDraws(this._cacheData.varData[n]),!0):r==="varip"&&this._cacheData.varipData.hasOwnProperty(n)?(this._upadteChartDraws(this._cacheData.varipData[n]),!0):!1}getVarValue(t,e,r){const n=`${t}_${e}`,s=this._isRepeated?this._preCacheData:this._cacheData;return r==="var"?this._isRealTimeBar&&s.varNewData.hasOwnProperty(n)?s.varNewData[n]:s.varData[n]:this._cacheData.varipData[n]}setVarValue(t,e,r,n){var u;if(this._isRepeated&&n==="var")return this.getVarValue(t,e,n);const s=`${t}_${e}`;let a;switch(typeof r=="object"&&((u=r==null?void 0:r.varipKeys)!=null&&u.length)&&(n="var",a=r.varipKeys),this._chartDrawsHandle(r,this._cacheData.varData[s]||this._cacheData.varipData[s]),n){case"var":if(this._isRealTimeBar){if(this._cacheData.varNewData[s]=r,a&&a.length)for(const c of a)this._cacheData.varData[s][c]=r[c]}else this._cacheData.varData[s]=r;break;case"varip":this._cacheData.varipData[s]=r;break}return r}_upadteChartDraws(t){const e=t==null?void 0:t.id;if(e)switch(t==null?void 0:t.type){case te.BOX:this._setChartDraw(e,this._box);break;case te.LINE:this._setChartDraw(e,this._line);break;case te.POLYLINE:this._setChartDraw(e,this._polyline);break;case te.LABEL:this._setChartDraw(e,this._label);break;case te.LINEFILL:this._setChartDraw(e,this._linefill);break;case te.TABLE:this._setChartDraw(e,this._table);break}}_setChartDraw(t,e){const r=e.getInstance(t),n=e.get(t);if(!n||!r)return;const s=(r==null?void 0:r.updateId())||t;e.delete(t),e.set(s,n,r)}_chartDrawsHandle(t,e){const r=e==null?void 0:e.id;let n=t==null?void 0:t.id;r!==n&&(n&&t.data&&(t.data.isVar=!0),r&&e.data&&(e.data.isVar=!1))}add(t,e){return Array.isArray(t)&&Array.isArray(e)?Wr.uniq([...t,...e]):typeof t=="number"||typeof e=="number"?Number(t)+Number(e):t+e}sub(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter(r=>!e.includes(r)):Number(t)-Number(e)}equal(t,e,r,n){if(t!==void 0&&e!==void 0)return t==e;if(!(r.endsWith(te.BOOL)&&t===void 0))return(r.endsWith(te.FLOAT)||r.endsWith(te.INT)||n.endsWith(te.FLOAT)||n.endsWith(te.INT))&&t===void 0&&e===void 0?!1:r.endsWith(te.STRING)&&t===""&&e===void 0||n.endsWith(te.STRING)&&e===""&&t===void 0?!0:r.endsWith(te.NA)&&n.endsWith(te.NA)?!1:t==e}againAssignParse(t,e){var n;if(e)return;const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;if(r)switch(r){case go.name:case Ah.name:case wo.name:case Mh.name:case vo.name:case yo.name:t==null||t.delete();break}}_transformPeriod(t){return t.includes("MTH")?t=t.replace("MTH","M"):t.includes("M")&&(t=t.replace("M","")),nc(t)}}class $i{constructor(t=50){$(this,"_all");$(this,"_allInstance");$(this,"_pseudoArrayAll");$(this,"_maxLength");$(this,"_deleteIds");this._all=new Map,this._allInstance=new Map,this._pseudoArrayAll=new ee,this._maxLength=t,this._deleteIds=new Map}setMaxLen(t){this._maxLength=t}get data(){return[...this._all.values()].slice(-this._maxLength)}get all(){return this._pseudoArrayAll._value=[...this._allInstance.values()],this._pseudoArrayAll}add(t,e,r){if(this.set(t,e,r),this._all.size>this._maxLength){const{bar_index:n}=e;for(const[s,a]of this._all){const{isVar:u,id:c,bar_index:f}=a;if(f===n)break;if(u)continue;this.delete(c);break}}}getValOfBarIndex(t){let e=[];const r=[...this._all.keys()];for(const n of t){const s=r.filter(a=>a.endsWith(`_${n}`));for(const a of s){const u=this._all.get(a);u&&e.push(u)}}return e.length?e:void 0}getDeleteIds(t){let e=[];for(const r of t)e=e.concat(this._deleteIds.get(r)||[]);return this._deleteIds.clear(),Wr.uniq(e)}set(t,e,r){this._all.set(t,e),this._allInstance.set(t,r)}get(t){return this._all.get(t)}getInstance(t){return this._allInstance.get(t)}delete(t,e){if(this._all.delete(t),this._allInstance.delete(t),typeof e=="number"){const r=this._deleteIds.get(e)||[];r.push(t),this._deleteIds.set(e,r)}}}/**
65
+ ${g}`),g}_getRequestData(t,e){var C,E,A,N,S;let{symbol:r,timeframe:n,calc_bars_count:s,gaps:a,lookahead:u,ignore_invalid_symbol:c}=t;const{__period:f,syminfo:{ticker:d,tickerid:h},mintick:_,time:g,nextBarTime:y}=this._variables;if(n=nc(n),(f===n||n==="")&&(r===d||r===h)){const{close:I,open:F,high:O,low:L,bar_index:z,last_bar_index:q,last_bar_time:W,_isRealTimeBar:P,volume:Z,time:Y,time_tradingday:G}=this._variables;return{barIndex:z,c:I,o:F,h:O,l:L,volume:Z,lastBarIndex:q,lastBarTime:W/1e3,nextBarTime:y,isrealtime:P,time_tradingday:G,time:Y/1e3,interval:f,mintick:_}}const p=`${r}--${n||f}`,w=self.workerStorage.get(`request_${this._scriptId}_data`),v=self.workerStorage.get(`request_${this._scriptId}_list`),x=self.workerStorage.get(`request_${this._scriptId}_tmp`),b={id:p,calc_bars_count:s,ignore_invalid_symbol:c,symbol:r,timeframe:rD[n||f]||n};if(w!=null&&w.has(p)){let I=gr(n,g)*1e3;const F=gr(f,g)*1e3;x==null||x.delete(p),e=`${e}_${p}`;const{index:O=0,periodStamp:L=F}=this._cacheData.get(e)||{},z=w==null?void 0:w.get(p);if(!z.length)return;const q=z.slice(O);let W=g,P=L+W;const Z=z.length-1;if(Z<0)return;const Y={lastBarIndex:z[Z].barindex||Z,lastBarTime:z[Z].time,interval:n,mintick:_};if(I>L){let G;if(u===ln.lookaheadOn?G=this._lookaheadOnHandle(q,n,P,I,Y,O,L,e,W,a):G=this._lookaheadOffHandle(q,n,P,I,Y,O,L,e,W,y||P,a),G)return G;if(G===null)return}else if(u===ln.lookaheadOn)for(const[G,X]of q.entries()){let{time:ut,barindex:_t}=X;ut=ut*1e3;const at=((C=q[G+1])==null?void 0:C.time)*1e3||ut+I;let vt=O+G;if(ut>=P){this._cacheData.set(e,{index:vt,periodStamp:L});return}if(ut<=W&&at>W){const wt=O+G;return this._cacheData.set(e,{index:wt,periodStamp:L}),{...X,barIndex:_t||wt,nextBarTime:(E=q[G+1])==null?void 0:E.time,...Y}}}else for(const[G,X]of q.entries()){let{time:ut,barindex:_t}=X;ut=ut*1e3;const at=((A=q[G+1])==null?void 0:A.time)*1e3||ut+I;let vt=O+G;if(ut>P){this._cacheData.set(e,{index:vt,periodStamp:L});return}if(ut<=P&&P<at)return this._cacheData.set(e,{index:vt,periodStamp:L}),{...X,barIndex:_t||vt,nextBarTime:(N=q[G+1])==null?void 0:N.time,...Y};if(ut>=W&&ut<=P&&(_t||vt)===Y.lastBarIndex)return this._cacheData.set(e,{index:vt,periodStamp:L}),{...X,barIndex:_t||vt,nextBarTime:(S=q[G+1])==null?void 0:S.time,...Y}}this._cacheData.set(e,{index:z.length,periodStamp:L})}else(v==null?void 0:v.get(p))||x==null||x.set(p,b);v==null||v.set(p,b)}_lookaheadOnHandle(t,e,r,n,s,a,u,c,f,d){var h;for(const[_,g]of t.entries()){let{time:y,barindex:p}=g;y=y*1e3,e.includes("M")&&(n=gr(e,y)*1e3-(Wt(y).date()-1)*864e5);const w=y,v=n+w;let x=a+_;if(r<=w)return this._cacheData.set(c,{index:x,periodStamp:u}),null;let b={...g,barIndex:p||x,nextBarTime:(h=t[_+1])==null?void 0:h.time,...s};if(d===ln.gapsOn){if(r>w&&f<=w)return this._cacheData.set(c,{index:x,periodStamp:u}),b}else{if(r>v)continue;if(r>w)return this._cacheData.set(c,{index:x,periodStamp:u}),b}}}_lookaheadOffHandle(t,e,r,n,s,a,u,c,f,d,h){var _,g;for(const[y,p]of t.entries()){let{time:w,barindex:v}=p;w=w*1e3,e.includes("M")&&(n=gr(e,w)*1e3-(Wt(w).date()-1)*864e5);const x=w,b=n+x,C=a+y;if(r<x)return this._cacheData.set(c,{index:C,periodStamp:u}),null;const E={...p,barIndex:v||C,nextBarTime:(_=t[y+1])==null?void 0:_.time,...s};if(r>=b&&f<b||r<b&&d>=b)return h===ln.gapsOn?(this._cacheData.set(c,{index:C,periodStamp:u}),E):(this._cacheData.set(c,{index:C,data:E,periodStamp:u}),E);if(!(f>b)&&f>=x){let A=(g=this._cacheData.get(c))==null?void 0:g.data;if(!A){const N=t[C-1];if(!N)return null;A={...N,barIndex:N.barindex||C-1,nextBarTime:E.time,...s},this._cacheData.set(c,{index:C,data:A,periodStamp:u})}return A}}}_getDependCodes(t,e,r,n,s,a){for(const u of t){if(!u.isArg){const c=e.filter(d=>{var h;return(h=d==null?void 0:d.depends)==null?void 0:h.some(_=>_.name===u.name&&_.scope===u.scope&&_.isAgainAssign)});for(const d of c){const{code:h,depends:_}=d;if(!r.includes(h)&&(r.unshift(h),_!=null&&_.length)){for(const g of _)g.memberCode&&a.push(g.memberCode);this._getDependCodes(_,e,r,n,s,a)}}const f=e.find(d=>{var h;return((h=d.varNames)==null?void 0:h.split(", ").includes(u.name))&&(!u.isPreArg||u.isPreArg&&d.methodName===u.functionName)||d.funcName===u.name});if(f){const{code:d,depends:h}=f,_=r.findIndex(g=>g===d);if(_!==-1&&r.splice(_,1),r.unshift(d),h!=null&&h.length){for(const g of h)g.memberCode&&a.push(g.memberCode);this._getDependCodes(h,e,r,n,s,a)}continue}}s.some(c=>c.name===u.name)||s.push(u)}}_runScripts(t,e,r,n,s){const a=`${this._scriptId}_${e}`;let{builtInGather:u,buildinConstants:c,buildInFunctions:f,tradingvueFunc:d}=self.workerStorage.get(a)||{};const{interval:h,mintick:_,...g}=s||{};r&&(u=new Lh(a),c=new Ch,f=new $h(this._variables.mintick||1e-5,u,this._scriptId),d=new Function("$_var","$_const","$_func","$paramsExpr","$posStr",t),u.updateOptions({interval:h,mintick:_||1e-5}),self.workerStorage.set(a,{builtInGather:u,buildinConstants:c,buildInFunctions:f,tradingvueFunc:d})),u.updateData(g),f.update({barIndex:(g==null?void 0:g.barindex)||0});const y=d(u,c,f,n||[],e);return f.endExecution(),y}},iD=class{constructor(){}prefix(t){var r;const{symbol:e}=t;return((r=e==null?void 0:e.split("."))==null?void 0:r[0])||""}ticker(t){var r;const{symbol:e}=t;return((r=e==null?void 0:e.split("."))==null?void 0:r[1])||""}};class sD{constructor(t,e){$(this,"_logs");$(this,"_variables");$(this,"_str");$(this,"_preBar",{barIndex:-1,isrealtime:!1});this._variables=t,this._logs=[],this._str=e}get logs(){return this._logs}clearLogForIndex(t){this._logs=this._logs.filter(e=>e.barIndex!==t)}clearLogs(){this._logs=[]}info(t,e,r){this._addLog(t,e,"info",r)}error(t,e,r){this._addLog(t,e,"error",r)}warning(t,e,r){this._addLog(t,e,"warning",r)}_addLog(t,e,r,n){if(typeof e=="string"&&(n=e),n.startsWith("export"))return;const{message:s,formatString:a}=t,{time:u,bar_index:c,_isRealTimeBar:f}=this._variables;let d=s;a&&Array.isArray(e)&&e.length&&(e=e.map(g=>(typeof g=="object"&&(g.isArray?g=JSON.stringify(g._value):g=g.toString()),g!==void 0?g:"na")),d=this._str.strformat({formatString:a},e,!0));const{isrealtime:h}=this._preBar;this._preBar={barIndex:c,isrealtime:f};const _=Date.now();d&&this._logs.push({message:`[${Wt(h||f?_:u).format("YYYY-MM-DDTHH:mm:ss.SSSZ")}]: ${d}`,time:u,id:M_(6),barIndex:c,type:r})}}class oD{constructor(t){$(this,"_errorListener");this._errorListener=t}error({message:t},e){e.startsWith("export")||this._errorListener.addError(t,e,Rt.Error)}}class aD{constructor(){$(this,"_errors");this._errors=new Map}clear(){this._errors.clear()}get errors(){return Wr.flatMap([...this._errors.values()])}addError(t,e,r,n=0){const[s,a]=e.split("_").slice(-2),u=this._errors.get(e),c={message:t,endLineNumber:Number(s),startColumn:Number(a)+1,endColumn:Number(a)+n+1,startLineNumber:Number(s),type:r};u?u.push(c):this._errors.set(e,[c])}}class uD{constructor(){$(this,"_isMarketOpen");$(this,"_currentBarIndex");$(this,"_totalBarIndex");$(this,"_isRealTimeBar");$(this,"_preBarIndex");this._currentBarIndex=0,this._totalBarIndex=0,this._isRealTimeBar=!1,this._preBarIndex=0,this._isMarketOpen=!0}update(t,e,r,n){this._preBarIndex=this._currentBarIndex,this._currentBarIndex=t,this._totalBarIndex=e,this._isRealTimeBar=r,this._isMarketOpen=n}get isnew(){return!this._isRealTimeBar||this._preBarIndex!==this._currentBarIndex}get islast(){return this._currentBarIndex===this._totalBarIndex}get isfirst(){return this._currentBarIndex===0}get ishistory(){return!this._isRealTimeBar}get isrealtime(){return this._isRealTimeBar}get isconfirmed(){return!this._isRealTimeBar}get islastconfirmedhistory(){return this._isMarketOpen?this._currentBarIndex===this._totalBarIndex-1||this._currentBarIndex===this._totalBarIndex&&!this._isRealTimeBar:this._currentBarIndex===this._totalBarIndex}}class lD{constructor(t){$(this,"_variables");this._variables=t}get isfirstbar(){return this._variables.timeframe.isdwm?!0:this._variables.time===this._variables.time_tradingday}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:t,__period:e}=this._variables,r=gr(e,t);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:t,__period:e}=this._variables,r=gr(e,t);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 cD{constructor(t){$(this,"_orders");$(this,"_historyOrders");$(this,"_options");$(this,"_max_contracts_held_all",0);$(this,"_max_contracts_held_long",0);$(this,"_max_contracts_held_short",0);$(this,"_max_drawdown",0);$(this,"_max_runup",0);$(this,"_max_runup_percent",0);$(this,"_max_drawdown_percent",0);$(this,"_variables");$(this,"_netprofit",0);$(this,"_eventrades",0);$(this,"_avg_trade_percent");$(this,"_avg_losing_trade_percent");$(this,"_avg_winning_trade_percent");$(this,"_closedtrades",0);$(this,"_losstrades",0);$(this,"_grossloss",0);$(this,"_grossprofit",0);$(this,"_wintrades",0);$(this,"_opentrades_capital_held",0);$(this,"_position_avg_price",0);$(this,"_position_size",0);$(this,"_openprofit",0);$(this,"_preMaxNetValue",0);$(this,"_preMinNetValue",0);$(this,"marginCallLong",0);$(this,"marginCallShort",0);this._orders=[],this._historyOrders=[],this._variables=t}update(t){this._calcMaxDrawdownAndMaxRunup(t)}_calcMaxDrawdownAndMaxRunup(t){if(!this._orders.length&&!this._historyOrders.length)return;let e=0,r=0;const{high:n,low:s,close:a}=t;let u=0;for(const[d,h]of this._orders.entries()){const{in_price:_,qty:g=0,direction:y,commission:p,original_qty:w=1}=h,v=y===fe.long?1:-1,x=(n-_)*g,b=(s-_)*g,C=v===1?x:-b,E=v===1?-b:x;u+=(a-_)*v*g,e+=E,d>0&&p&&(r-=p*g/w),r+=C}this._openprofit=u;const c=this.initial_capital,f=c+this._netprofit;this._preMinNetValue=this._preMinNetValue||c,this._preMaxNetValue=this._preMaxNetValue||c,e=this._preMaxNetValue-f+Math.max(e,0),r=f-this._preMinNetValue+r,this._max_drawdown<e&&(this._max_drawdown=e,this._max_drawdown_percent=e/this._preMaxNetValue*100),r>this._max_runup&&(this._max_runup=r,this._max_runup_percent=r/(this._preMinNetValue+r)*100)}updateOrders(t){this._orders=t,this._calcMaxContracts()}_calcMaxContracts(){const t=this._orders.length;if(!t){this._position_size=0,this._position_avg_price=void 0,this._opentrades_capital_held=0;return}const[e,r,n,s,a,u,c]=this._orders.reduce(([f,d,h,_,g,y,p],w)=>{const{direction:v,qty:x=0,in_price:b,commission:C=0}=w;return v===fe.long?(f+=x,d+=x,y+=x):(f+=x,h+=x,y-=x),_+=x*b,g+=b,p+=C,[f,d,h,_,g,y,p]},[0,0,0,0,0,0,0]);this._historyOrders.length||(this._netprofit=-c,this._grossloss=c),this._position_size=u,this._position_avg_price=a/t,this._opentrades_capital_held=s,this._max_contracts_held_all=Math.max(e,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(n,this._max_contracts_held_short)}updateHistoryOrders(t){this._historyOrders=t;const e=this._historyOrders.length;this._closedtrades=e;const[r,n,s,a,u,c,f,d]=this._historyOrders.reduce((g,y)=>{let[p,w,v,x,b,C,E,A]=g;const{profit:N=0,profit_percent:S=0}=y;return p+=N,w+=S,N<0?(v+=N,x+=S,E+=1):N>0&&(b+=N,C+=S,A+=1),[p,w,v,x,b,C,E,A]},[0,0,0,0,0,0,0,0]),h=this._orders.reduce((g,y)=>{const{commission:p=0,qty:w=0,original_qty:v=0}=y,x=p*w/v;return g+x},0);this._avg_trade_percent=e?n/e:void 0,this._avg_losing_trade_percent=e?Math.abs(a)/f:void 0,this._avg_winning_trade_percent=e?c/d:void 0,this._netprofit=r-h;const _=this.initial_capital+this._netprofit;this._preMaxNetValue=Math.max(this._preMaxNetValue||this.initial_capital,_),this._preMinNetValue=Math.min(this._preMinNetValue||this.initial_capital,_),this._grossloss=Math.abs(s-h),this._grossprofit=u,this._eventrades=e-f-d,this._losstrades=f,this._wintrades=d}updateStrategyOptions(t){this._options=t}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 t=this._losstrades;return t?Math.abs(this._grossloss/t):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 t=this._wintrades;return t?Math.abs(this._grossprofit/t):void 0}get avg_winning_trade_percent(){return this._avg_winning_trade_percent}get initial_capital(){var t;return((t=this._options)==null?void 0:t.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:t,margin_long:e=0,margin_short:r=0,commission_type:n,commission_value:s=0}=this._options,a=this._orders[0].direction===fe.long?1:-1,u=(a===1?e:r)/100;if(u<=0)return;const{close:c}=this._variables,[f,d]=this._orders.reduce((h,_)=>{let[g,y]=h;const{in_price:p,qty:w=0,original_qty:v=0}=_,x=p*w;if(g+=x,s){let b=0;switch(n){case je.percent:b=(x+w*c)*s/100;break;case je.cashPerContract:b=w*s*2;break;case je.cashPerOrder:b=w/v*s+s;break}y+=b}return[g,y]},[0,0]);return(f-(t+this._netprofit-d))*a/this._position_size/(1-a*u)}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(t,e){if(!this._options)return 0;const{commission_value:r=0,commission_type:n}=this._options,s=t*e;let a=0;switch(n){case je.percent:a=s*r/100;break;case je.cashPerContract:a=e*r;break;case je.cashPerOrder:a=r;break}return a}}class fD{constructor(t){$(this,"_preAccdist");$(this,"_preNvi");$(this,"_prePvi");$(this,"_preObv");$(this,"_prePvt");$(this,"_preWad");$(this,"_preVwap");$(this,"_preValue");$(this,"_currentData");$(this,"_preData");$(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=t}update(t){this._preValue={},t.barIndex!==this._currentData.barIndex&&(this._preData={...this._currentData}),this._currentData={...t}}get isRealTime(){return this._preData.barIndex===this._currentData.barIndex}get accdist(){if(this._preValue.accdist)return this._preValue.accdist;const{close:t,low:e,high:r,volume:n}=this._currentData;if(r===e)return this._preAccdist;const s=(t-e-(r-t))/(r-e)*n+this._preAccdist;return!this.isRealTime&&(this._preAccdist=s),this._preValue.accdist=s,s}get iii(){if(this._preValue.iii)return this._preValue.iii;const{close:t,low:e,high:r,volume:n}=this._currentData,s=(2*t-r-e)/((r-e)*n);return this._preValue.iii=s,s}get nvi(){return this._preValue.nvi?this._preValue.nvi:this._getNvi()}get wvad(){if(this._preValue.wvad)return this._preValue.wvad;const{close:t,low:e,high:r,volume:n,open:s}=this._currentData,a=(t-s)/(r-e)*n;return this._preValue.wvad=a,a}get obv(){if(this._preValue.obv)return this._preValue.obv;const{close:t,volume:e}=this._currentData,{close:r}=this._preData;if(r===void 0){this._preObv=0;return}const n=Math.sign(t-r)*e+this._preObv;return!this.isRealTime&&(this._preObv=n),this._preValue.obv=n,n}get pvi(){return this._preValue.pvi?this._preValue.pvi:this._getPvi()}get tr(){if(this._preValue.tr)return this._preValue.tr;const{low:t,high:e}=this._currentData,{close:r}=this._preData;if(r===void 0)return;const n=Math.max(e-t,Math.abs(e-r),Math.abs(t-r));return this._preValue.tr=n,n}get pvt(){if(this._preValue.pvt)return this._preValue.pvt;const{close:t,volume:e}=this._currentData,{close:r}=this._preData;if(r===void 0){this._prePvt=0;return}const n=(t-r)/r*e+this._prePvt;return!this.isRealTime&&(this._prePvt=n),this._preValue.pvt=n,n}get wad(){if(this._preValue.wad)return this._preValue.wad;const{close:t,high:e,low:r}=this._currentData,{close:n}=this._preData;if(n===void 0)return this._preWad=0,0;const s=Math.max(e,n),a=Math.min(r,n),u=t-n,f=(u>0?t-a:u<0?t-s:0)+this._preWad;return!this.isRealTime&&(this._preWad=f),this._preValue.wad=f,f}get vwap(){var d,h;if(this._preValue.vwap)return this._preValue.vwap;const{hlc3:t,volume:e}=this._currentData;let{sum:r=0,sumV:n=0,isReset:s}=this._preVwap;if(((h=(d=self.workerStorage)==null?void 0:d.get(this._id))==null?void 0:h.buildInFunctions.timeframe.change({timeframe:"1D"},"vwap_buildin"))&&(s=!0,r=n=0),!s)return;const u=t*e+r,c=e+n;!this.isRealTime&&(this._preVwap={sum:u,sumV:c,isReset:s});const f=u/c;return this._preValue.vwap=f,f}_getNvi(){const t=this._preNvi||1,{close:e=0,volume:r=0}=this._preData,{close:n,volume:s}=this._currentData;let a=1;const u=t||1;return n&&e?a=s<r?u+(n-e)/e*u:u:a=u,!this.isRealTime&&(this._preNvi=a),this._preValue.nvi=a,a}_getPvi(){const t=this._prePvi||1,{close:e=0,volume:r=0}=this._preData,{close:n,volume:s}=this._currentData;let a=1;const u=t||1;return n&&e?a=s>r?u+(n-e)/e*u:u:a=u,!this.isRealTime&&(this._prePvi=a),this._preValue.pvi=a,a}}class hD{constructor(){$(this,"_period");$(this,"_multiplier");$(this,"_unit");this._period="1",this._multiplier=1,this._unit="m"}update(t){if(!t)return;this._period=t;const[e,r]=Fs(t);this._multiplier=e,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 dD{constructor(t){$(this,"_variables");$(this,"_bgColor");$(this,"_fgColor");$(this,"isUseBgColor",!1);this._variables=t}updateOptions(t){t!=null&&t.bg_color&&(this._bgColor=t.bg_color,this._fgColor=this._contrastColor(t.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(){return this._variables.time}get right_visible_bar_time(){return this._variables.time}_parseColor(t){let e,r,n,s;if(t.startsWith("#")){e=parseInt(t.substring(1,3),16),r=parseInt(t.substring(3,5),16),n=parseInt(t.substring(5,7),16);const a=t.substring(7);a?s=parseInt(a,16)/255:s=1}else{const a=this._parserRgbColor(t);e=a[0]||0,r=a[1]||0,n=a[2]||0,s=a[3]||1}return{r:e,g:r,b:n,a:s}}_parserRgbColor(t){var e;return((e=t.match(/\d+/g))==null?void 0:e.map(Number))||[]}_contrastColor(t){const{r:e,g:r,b:n}=this._parseColor(t);return(299*e+587*r+114*n)/1e3>128?"#000000":"#ffffff"}}class _D{constructor(){$(this,"_syminfo",{})}update(t){this._syminfo=t}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||Mn.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}get volumetype(){return this._syminfo.volumetype||"n/a"}}class pD{constructor(t){$(this,"_variables");this._variables=t}get future_amount(){}get future_ex_date(){}get future_pay_date(){}}class mD{constructor(t){$(this,"_variables");this._variables=t}get future_eps(){}get future_period_end_time(){}get future_revenue(){}get future_time(){}}Wt.extend(A_),Wt.extend(xa),Wt.extend(Ea);class Lh{constructor(t){$(this,"_cacheData");$(this,"_barIndex");$(this,"_isRealTimeBar");$(this,"_barstate");$(this,"_priceVariables");$(this,"_lastBarIndex");$(this,"_currentBarTime");$(this,"_lastBarTime");$(this,"_period");$(this,"_offsetTime");$(this,"_timeframe");$(this,"_ta");$(this,"_polyline");$(this,"_label");$(this,"_line");$(this,"_linefill");$(this,"_box");$(this,"_table");$(this,"_strategy");$(this,"_session");$(this,"syminfo");$(this,"chart");$(this,"earnings");$(this,"dividends");$(this,"_timeTradingday");$(this,"_mintick");$(this,"_cacheSpace");$(this,"_precision");$(this,"_nextBarTime");$(this,"_isRepeated");$(this,"_preCacheData");this._cacheData={varData:{},varNewData:{},varipData:{}},this._preCacheData={varData:{},varNewData:{},varipData:{}},this._barIndex=0,this._lastBarIndex=0,this._currentBarTime=0,this._lastBarTime=0,this._offsetTime=0,this._period="",this._isRealTimeBar=!1,this._barstate=new uD,this._timeframe=new hD,this._priceVariables={close:0,open:0,low:0,high:0,volume:0},this._ta=new fD(t),this._polyline=new $i,this._label=new $i,this._line=new $i,this._linefill=new $i,this._box=new $i,this._table=new $i,this._strategy=new cD(this),this._session=new lD(this),this.syminfo=new _D,this.chart=new dD(this),this.earnings=new mD(this),this.dividends=new pD(this),this._cacheSpace=new Map}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:t,open:e,high:r,low:n}=this._priceVariables;return(t+e+r+n)/4}get hl2(){const{high:t,low:e}=this._priceVariables;return(t+e)/2}get hlc3(){const{close:t,high:e,low:r}=this._priceVariables;return(t+e+r)/3}get hlcc4(){const{close:t,high:e,low:r}=this._priceVariables;return(t*2+e+r)/4}get hour(){return Wt(this._currentBarTime).hour()}get minute(){return Wt(this._currentBarTime).minute()}get second(){return Wt(this._currentBarTime).second()}get month(){return Wt(this._currentBarTime).month()+1}get year(){return Wt(this._currentBarTime).year()}get dayofweek(){return Wt(this._currentBarTime).day()}get dayofmonth(){return Wt(this._currentBarTime).date()}get weekofyear(){return Wt(this._currentBarTime).week()}get last_bar_time(){return this._lastBarTime}get time(){return this._currentBarTime}get time_close(){const[t,e]=Fs(this._period);return this._isRealTimeBar?void 0:Wt(this._currentBarTime).add(t,e).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}updateMaxLength(t){const{max_lines_count:e,max_labels_count:r,max_boxes_count:n,max_polylines_count:s}=t;n&&this._box.setMaxLen(n),r&&this._label.setMaxLen(r),e&&this._line.setMaxLen(e),s&&this._polyline.setMaxLen(s)}getTimeTradingday(t,e){const[r,n]=Fs(e),s=Wt(t);return["M","w","y","d"].includes(n)?s.valueOf():(s.subtract(this._offsetTime,"h"),s.startOf("d").add(this._offsetTime,"h").valueOf())}updateOptions(t){var f;const{interval:e="1D",offsetTime:r=5,mintick:n,chart:s,syminfo:a}=t,u=((f=n.toString().split(".")[1])==null?void 0:f.length)||5;this._precision=u;const c=this._transformPeriod(e);this._period=c,this._mintick=n,this._offsetTime=r,this._timeframe.update(c),this.chart.updateOptions(s),this.syminfo.update(a)}updateData(t,e){const{barIndex:r,c:n,o:s,h:a,l:u,volume:c,time:f,lastBarIndex:d,lastBarTime:h,isrealtime:_,time_tradingday:g,nextBarTime:y}=t;if(this._priceVariables={close:Number(n),open:Number(s),high:Number(a),low:Number(u),volume:Number(c)},this._isRealTimeBar=_,r>this._barIndex){const{varData:p,varNewData:w,varipData:v}=this._cacheData;this._preCacheData={varData:{...p},varNewData:{...w},varipData:{...v}},this._isRealTimeBar&&(this._cacheData.varNewData={})}this._isRepeated=e,this._timeTradingday=g,this._currentBarTime=f*1e3,this._lastBarIndex=d,this._barIndex=r,this._lastBarTime=h*1e3,this._nextBarTime=y*1e3,this._barstate.update(r,d,_,!0),this.ta.update({...this._priceVariables,hlc3:this.hlc3,barIndex:r})}getCacheData(t,e,r){const n=this.setCacheData(t,r),s=this._cacheSpace.get(t)||0;return e=Math.floor(e),s<e&&this._cacheSpace.set(t,e),n[n.length-1-e]}setCacheData(t,e){let r=this._cacheData[t]||{barIndex:-1,data:[]};if(r.barIndex>this._barIndex)return r.data;r.barIndex===this._barIndex?r.data[r.data.length-1]=e:r.data.push(e);const n=this._cacheSpace.get(t);return n&&r.data.length>n+5&&r.data.shift(),r.barIndex=this._barIndex,this._cacheData[t]=r,r.data}getTypeInstance(t,e){return new D_(t,e)}verifyVarAndVarip(t,e,r){const n=`${t}_${e}`;return r==="var"&&this._cacheData.varData.hasOwnProperty(n)?(this._upadteChartDraws(this._cacheData.varData[n]),!0):r==="varip"&&this._cacheData.varipData.hasOwnProperty(n)?(this._upadteChartDraws(this._cacheData.varipData[n]),!0):!1}getVarValue(t,e,r){const n=`${t}_${e}`,s=this._isRepeated?this._preCacheData:this._cacheData;return r==="var"?this._isRealTimeBar&&s.varNewData.hasOwnProperty(n)?s.varNewData[n]:s.varData[n]:this._cacheData.varipData[n]}setVarValue(t,e,r,n){var u;if(this._isRepeated&&n==="var")return this.getVarValue(t,e,n);const s=`${t}_${e}`;let a;switch(typeof r=="object"&&((u=r==null?void 0:r.varipKeys)!=null&&u.length)&&(n="var",a=r.varipKeys),this._chartDrawsHandle(r,this._cacheData.varData[s]||this._cacheData.varipData[s]),n){case"var":if(this._isRealTimeBar){if(this._cacheData.varNewData[s]=r,a&&a.length)for(const c of a)this._cacheData.varData[s][c]=r[c]}else this._cacheData.varData[s]=r;break;case"varip":this._cacheData.varipData[s]=r;break}return r}_upadteChartDraws(t){const e=t==null?void 0:t.id;if(e)switch(t==null?void 0:t.type){case te.BOX:this._setChartDraw(e,this._box);break;case te.LINE:this._setChartDraw(e,this._line);break;case te.POLYLINE:this._setChartDraw(e,this._polyline);break;case te.LABEL:this._setChartDraw(e,this._label);break;case te.LINEFILL:this._setChartDraw(e,this._linefill);break;case te.TABLE:this._setChartDraw(e,this._table);break}}_setChartDraw(t,e){const r=e.getInstance(t),n=e.get(t);if(!n||!r)return;const s=(r==null?void 0:r.updateId())||t;e.delete(t),e.set(s,n,r)}_chartDrawsHandle(t,e){const r=e==null?void 0:e.id;let n=t==null?void 0:t.id;r!==n&&(n&&t.data&&(t.data.isVar=!0),r&&e.data&&(e.data.isVar=!1))}add(t,e){return Array.isArray(t)&&Array.isArray(e)?Wr.uniq([...t,...e]):typeof t=="number"||typeof e=="number"?Number(t)+Number(e):t+e}sub(t,e){return Array.isArray(t)&&Array.isArray(e)?t.filter(r=>!e.includes(r)):Number(t)-Number(e)}equal(t,e,r,n){if(t!==void 0&&e!==void 0)return t==e;if(!(r.endsWith(te.BOOL)&&t===void 0))return(r.endsWith(te.FLOAT)||r.endsWith(te.INT)||n.endsWith(te.FLOAT)||n.endsWith(te.INT))&&t===void 0&&e===void 0?!1:r.endsWith(te.STRING)&&t===""&&e===void 0||n.endsWith(te.STRING)&&e===""&&t===void 0?!0:r.endsWith(te.NA)&&n.endsWith(te.NA)?!1:t==e}againAssignParse(t,e){var n;if(e)return;const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;if(r)switch(r){case go.name:case Ah.name:case wo.name:case Mh.name:case vo.name:case yo.name:t==null||t.delete();break}}_transformPeriod(t){return t.includes("MTH")?t=t.replace("MTH","M"):t.includes("M")&&(t=t.replace("M","")),nc(t)}}class $i{constructor(t=50){$(this,"_all");$(this,"_allInstance");$(this,"_pseudoArrayAll");$(this,"_maxLength");$(this,"_deleteIds");this._all=new Map,this._allInstance=new Map,this._pseudoArrayAll=new ee,this._maxLength=t,this._deleteIds=new Map}setMaxLen(t){this._maxLength=t}get data(){return[...this._all.values()].slice(-this._maxLength)}get all(){return this._pseudoArrayAll._value=[...this._allInstance.values()],this._pseudoArrayAll}add(t,e,r){if(this.set(t,e,r),this._all.size>this._maxLength){const{bar_index:n}=e;for(const[s,a]of this._all){const{isVar:u,id:c,bar_index:f}=a;if(f===n)break;if(u)continue;this.delete(c);break}}}getValOfBarIndex(t){let e=[];const r=[...this._all.keys()];for(const n of t){const s=r.filter(a=>a.endsWith(`_${n}`));for(const a of s){const u=this._all.get(a);u&&e.push(u)}}return e.length?e:void 0}getDeleteIds(t){let e=[];for(const r of t)e=e.concat(this._deleteIds.get(r)||[]);return this._deleteIds.clear(),Wr.uniq(e)}set(t,e,r){this._all.set(t,e),this._allInstance.set(t,r)}get(t){return this._all.get(t)}getInstance(t){return this._allInstance.get(t)}delete(t,e){if(this._all.delete(t),this._allInstance.delete(t),typeof e=="number"){const r=this._deleteIds.get(e)||[];r.push(t),this._deleteIds.set(e,r)}}}/**
66
66
  * @license
67
67
  * Copyright 2019 Google LLC
68
68
  * SPDX-License-Identifier: Apache-2.0
69
- */const Rh=Symbol("Comlink.proxy"),gD=Symbol("Comlink.endpoint"),vD=Symbol("Comlink.releaseProxy"),su=Symbol("Comlink.finalizer"),xo=Symbol("Comlink.thrown"),Ph=i=>typeof i=="object"&&i!==null||typeof i=="function",yD={canHandle:i=>Ph(i)&&i[Rh],serialize(i){const{port1:t,port2:e}=new MessageChannel;return ou(i,t),[e,[e]]},deserialize(i){return i.start(),xD(i)}},wD={canHandle:i=>Ph(i)&&xo in i,serialize({value:i}){let t;return i instanceof Error?t={isError:!0,value:{message:i.message,name:i.name,stack:i.stack}}:t={isError:!1,value:i},[t,[]]},deserialize(i){throw i.isError?Object.assign(new Error(i.value.message),i.value):i.value}},kh=new Map([["proxy",yD],["throw",wD]]);function DD(i,t){for(const e of i)if(t===e||e==="*"||e instanceof RegExp&&e.test(t))return!0;return!1}function ou(i,t=globalThis,e=["*"]){t.addEventListener("message",function r(n){if(!n||!n.data)return;if(!DD(e,n.origin)){console.warn(`Invalid origin '${n.origin}' for comlink proxy`);return}const{id:s,type:a,path:u}=Object.assign({path:[]},n.data),c=(n.data.argumentList||[]).map(ai);let f;try{const d=u.slice(0,-1).reduce((_,g)=>_[g],i),h=u.reduce((_,g)=>_[g],i);switch(a){case"GET":f=h;break;case"SET":d[u.slice(-1)[0]]=ai(n.data.value),f=!0;break;case"APPLY":f=h.apply(d,c);break;case"CONSTRUCT":{const _=new h(...c);f=FD(_)}break;case"ENDPOINT":{const{port1:_,port2:g}=new MessageChannel;ou(i,g),f=MD(_,[_])}break;case"RELEASE":f=void 0;break;default:return}}catch(d){f={value:d,[xo]:0}}Promise.resolve(f).catch(d=>({value:d,[xo]:0})).then(d=>{const[h,_]=Mo(d);t.postMessage(Object.assign(Object.assign({},h),{id:s}),_),a==="RELEASE"&&(t.removeEventListener("message",r),zh(t),su in i&&typeof i[su]=="function"&&i[su]())}).catch(d=>{const[h,_]=Mo({value:new TypeError("Unserializable return value"),[xo]:0});t.postMessage(Object.assign(Object.assign({},h),{id:s}),_)})}),t.start&&t.start()}function bD(i){return i.constructor.name==="MessagePort"}function zh(i){bD(i)&&i.close()}function xD(i,t){return au(i,[],t)}function Eo(i){if(i)throw new Error("Proxy has been released and is not useable")}function qh(i){return Li(i,{type:"RELEASE"}).then(()=>{zh(i)})}const Co=new WeakMap,Ao="FinalizationRegistry"in globalThis&&new FinalizationRegistry(i=>{const t=(Co.get(i)||0)-1;Co.set(i,t),t===0&&qh(i)});function ED(i,t){const e=(Co.get(t)||0)+1;Co.set(t,e),Ao&&Ao.register(i,t,i)}function CD(i){Ao&&Ao.unregister(i)}function au(i,t=[],e=function(){}){let r=!1;const n=new Proxy(e,{get(s,a){if(Eo(r),a===vD)return()=>{CD(n),qh(i),r=!0};if(a==="then"){if(t.length===0)return{then:()=>n};const u=Li(i,{type:"GET",path:t.map(c=>c.toString())}).then(ai);return u.then.bind(u)}return au(i,[...t,a])},set(s,a,u){Eo(r);const[c,f]=Mo(u);return Li(i,{type:"SET",path:[...t,a].map(d=>d.toString()),value:c},f).then(ai)},apply(s,a,u){Eo(r);const c=t[t.length-1];if(c===gD)return Li(i,{type:"ENDPOINT"}).then(ai);if(c==="bind")return au(i,t.slice(0,-1));const[f,d]=Uh(u);return Li(i,{type:"APPLY",path:t.map(h=>h.toString()),argumentList:f},d).then(ai)},construct(s,a){Eo(r);const[u,c]=Uh(a);return Li(i,{type:"CONSTRUCT",path:t.map(f=>f.toString()),argumentList:u},c).then(ai)}});return ED(n,i),n}function AD(i){return Array.prototype.concat.apply([],i)}function Uh(i){const t=i.map(Mo);return[t.map(e=>e[0]),AD(t.map(e=>e[1]))]}const Wh=new WeakMap;function MD(i,t){return Wh.set(i,t),i}function FD(i){return Object.assign(i,{[Rh]:!0})}function Mo(i){for(const[t,e]of kh)if(e.canHandle(i)){const[r,n]=e.serialize(i);return[{type:"HANDLER",name:t,value:r},n]}return[{type:"RAW",value:i},Wh.get(i)||[]]}function ai(i){switch(i.type){case"HANDLER":return kh.get(i.name).deserialize(i.value);case"RAW":return i.value}}function Li(i,t,e){return new Promise(r=>{const n=ND();i.addEventListener("message",function s(a){!a.data||!a.data.id||a.data.id!==n||(i.removeEventListener("message",s),r(a.data))}),i.start&&i.start(),i.postMessage(Object.assign({id:n},t),e)})}function ND(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}class SD{constructor(){$(this,"_cache");this._cache=new Map}set(t,e){this._cache.set(t,e)}setValue(t,e,r){const n=this._cache.get(t)||{};n[e]=r,this._cache.set(t,n)}updateValue(t,e,r){const n=this._cache.get(t)||{};this._cache.set(t,Object.assign(n[e]||{},r))}get(t){return this._cache.get(t)}has(t){return this._cache.has(t)}deleteStartwidthKey(t){for(const e of this._cache.keys())e.startsWith(t)&&this._cache.delete(e)}delete(t){this._cache.delete(t)}clear(){this._cache.clear()}}class jh extends Error{constructor(e,r,n){const s=e.status||e.status===0?e.status:"",a=e.statusText||"",u=`${s} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`);$(this,"response");$(this,"request");$(this,"options");this.name="HTTPError",this.response=e,this.request=r,this.options=n}}class Yh extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`);$(this,"request");this.name="TimeoutError",this.request=e}}const ls=i=>i!==null&&typeof i=="object",Fo=(...i)=>{for(const t of i)if((!ls(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return uu({},...i)},Vh=(i={},t={})=>{const e=new globalThis.Headers(i),r=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[s,a]of n.entries())r&&a==="undefined"||a===void 0?e.delete(s):e.set(s,a);return e};function No(i,t,e){return Object.hasOwn(t,e)&&t[e]===void 0?[]:uu(i[e]??[],t[e]??[])}const Hh=(i={},t={})=>({beforeRequest:No(i,t,"beforeRequest"),beforeRetry:No(i,t,"beforeRetry"),afterResponse:No(i,t,"afterResponse"),beforeError:No(i,t,"beforeError")}),uu=(...i)=>{let t={},e={},r={};for(const n of i)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(ls(n)){for(let[s,a]of Object.entries(n))ls(a)&&s in t&&(a=uu(t[s],a)),t={...t,[s]:a};ls(n.hooks)&&(r=Hh(r,n.hooks),t.hooks=r),ls(n.headers)&&(e=Vh(e,n.headers),t.headers=e)}return t},OD=(()=>{let i=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(e&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return i=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return i&&!t})(),BD=typeof globalThis.AbortController=="function",TD=typeof globalThis.ReadableStream=="function",ID=typeof globalThis.FormData=="function",Zh=["get","post","put","patch","head","delete"],$D={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},lu=2147483647,Kh=Symbol("stop"),LD={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},RD={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},PD=i=>Zh.includes(i)?i.toUpperCase():i,Gh={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:i=>.3*2**(i-1)*1e3},kD=(i={})=>{if(typeof i=="number")return{...Gh,limit:i};if(i.methods&&!Array.isArray(i.methods))throw new Error("retry.methods must be an array");if(i.statusCodes&&!Array.isArray(i.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Gh,...i}};async function zD(i,t,e,r){return new Promise((n,s)=>{const a=setTimeout(()=>{e&&e.abort(),s(new Yh(i))},r.timeout);r.fetch(i,t).then(n).catch(s).then(()=>{clearTimeout(a)})})}async function qD(i,{signal:t}){return new Promise((e,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(s),r(t.reason)}const s=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},i)})}const UD=(i,t)=>{const e={};for(const r in t)!(r in RD)&&!(r in LD)&&!(r in i)&&(e[r]=t[r]);return e};class So{constructor(t,e={}){$(this,"request");$(this,"abortController");$(this,"_retryCount",0);$(this,"_input");$(this,"_options");var r,n;if(this._input=t,this._options={...e,headers:Vh(this._input.headers,e.headers),hooks:Hh({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:PD(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:kD(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(BD){this.abortController=new globalThis.AbortController;const s=this._options.signal??this._input.signal;s==null||s.addEventListener("abort",()=>{this.abortController.abort(s.reason)}),this._options.signal=this.abortController.signal}if(OD&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((n=(r=this._options).stringifyJson)==null?void 0:n.call(r,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const a="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),u=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,a);(ID&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(u,{...this.request}),this._options)}}static create(t,e){const r=new So(t,e),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>lu)throw new RangeError(`The \`timeout\` option cannot be greater than ${lu}`);await Promise.resolve();let u=await r._fetch();for(const c of r._options.hooks.afterResponse){const f=await c(r.request,r._options,r._decorateResponse(u.clone()));f instanceof globalThis.Response&&(u=f)}if(r._decorateResponse(u),!u.ok&&r._options.throwHttpErrors){let c=new jh(u,r.request,r._options);for(const f of r._options.hooks.beforeError)c=await f(c);throw c}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!TD)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(u.clone(),r._options.onDownloadProgress)}return u},a=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[u,c]of Object.entries($D))a[u]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||c);const d=(await a).clone();if(u==="json"){if(d.status===204||(await d.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await d.text())}return d[u]()};return a}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof Yh)throw t;if(t instanceof jh){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;const r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(r)*1e3;Number.isNaN(n)?n=Date.parse(r)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());const s=this._options.retry.maxRetryAfter??n;return n<s?n:s}if(t.response.status===413)throw t}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),lu);if(this._retryCount<1)throw e;await qD(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===Kh)return;return this._retry(t)}}async _fetch(){for(const r of this._options.hooks.beforeRequest){const n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}const t=UD(this.request,this._options),e=this.request;return this.request=e.clone(),this._options.timeout===!1?this._options.fetch(e,t):zD(e,t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(s){const a=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){const{done:c,value:f}=await a.read();if(c){s.close();return}if(e){n+=f.byteLength;const d=r===0?0:n/r;e({percent:d,transferredBytes:n,totalBytes:r},f)}s.enqueue(f),await u()}await u()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const cu=i=>{const t=(e,r)=>So.create(e,Fo(i,r));for(const e of Zh)t[e]=(r,n)=>So.create(r,Fo(i,n,{method:e}));return t.create=e=>cu(Fo(e)),t.extend=e=>(typeof e=="function"&&(e=e(i??{})),cu(Fo(i,e))),t.stop=Kh,t},WD=cu().create({prefixUrl:"https://data.tradingvue.com/",retry:0});function jD(i){return WD.post("symbol/data/v1/",{json:i})}async function YD(i,t,e){var A,N,S;const{data:r,isPreParser:n,id:s="default",syminfo:a={},interval:u,inputs:c,chart:f,strategy:d,scriptType:h,isManuallyAdd:_,subscribeData:g}=t;self.workerStorage||(self.workerStorage=new SD);let{builtInGather:y,buildinConstants:p,buildInFunctions:w,tradingvueFunc:v}=self.workerStorage.get(s)||{},x=[];const b=a.mintick?Number(a.mintick):1e-5;a.mintick=b,e&&(y=new Lh(s),p=new Ch,w=new $h(b,y,s),v=new Function("$_var","$_const","$_func",i),self.workerStorage.set(s,{builtInGather:y,buildinConstants:p,buildInFunctions:w,tradingvueFunc:v}),self.workerStorage.set(`request_${s}`,new Map),(_||!self.workerStorage.has(`request_${s}_data`))&&self.workerStorage.set(`request_${s}_data`,new Map),self.workerStorage.set(`request_${s}_list`,new Map),self.workerStorage.set(`request_${s}_tmp`,new Map));let C=[];if(VD(g,s),n)v(y,p,w);else if(r&&r.length){const I=r.length-1;y.updateOptions({interval:u,mintick:b,chart:f,syminfo:a}),w.updateOptions({inputs:c,strategy:d});const F=self.workerStorage.get(`request_${s}_tmp`),O=self.workerStorage.get(`request_${s}_data`);try{let L;for(const[q,W]of r.entries()){const{barindex:P}=W;if(!e&&(P||P===0)&&x.push(P),F!=null&&F.size){const Y=[],G=[];for(const[ut,_t]of F){const{symbol:at,timeframe:vt,id:wt,calc_bars_count:Ct,ignore_invalid_symbol:bt}=_t,re=`${at}:${vt}`;G.push({id:wt,key:re,ignore_invalid_symbol:bt});const[Bt,Nt]=at.split(":");Y.push(jD({params:[{exchange:Bt,symbol:Nt,limit:Ct||5e3,start:0,end:0,period:vt}]}).json())}const X=await Promise.all(Y);for(const[ut,_t]of X.entries()){const{code:at,data:vt,msg:wt}=_t,Ct=G[ut];if(at!==200&&!Ct.ignore_invalid_symbol)return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:wt,type:Rt.Error}]};O==null||O.set(Ct.id,((N=(A=vt[Ct.key])==null?void 0:A.list)==null?void 0:N.reverse())||[])}F==null||F.clear(),L&&Jh(y,w,p,v,h,L)}L=Object.assign(W,{barIndex:P||q,lastBarIndex:r[I].barindex||I,lastBarTime:r[I].time,nextBarTime:(S=r[q+1])==null?void 0:S.time}),Jh(y,w,p,v,h,L);const Z=w.errors;if(Z.length&&Z.some(Y=>Y.type===Rt.Error))return{status:1,errors:Z}}const z=self.workerStorage.get(`request_${s}_list`);if((z==null?void 0:z.size)>40)return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:ie.requestsNumErr,type:Rt.Error}]};if(z!=null&&z.size){const q=new Map;for(const[W,P]of z)C.push(P),e&&(O!=null&&O.has(W))&&q.set(W,O.get(W));e&&self.workerStorage.set(`request_${s}_data`,q)}C.length&&(z==null||z.clear()),e&&self.workerStorage.delete(`request_${s}_tmp`)}catch(L){return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:L==null?void 0:L.message,type:Rt.Error}]}}}const E=w.errors;return E.length&&E.some(I=>I.type===Rt.Error)?{status:1,errors:E}:{status:0,requestList:C,errors:E,options:{...w.options(x),id:s}}}function VD(i,t){if(!i)return;const e=self.workerStorage.get(`request_${t}_data`),r=Object.keys(i);if(r.length)for(const n of r){let s=i[n]||[];if(e!=null&&e.has(n)){const a=(e==null?void 0:e.get(n))||[];if(a.length){const u=a[a.length-1].time;s=s.filter(c=>c.time>=u),s[0].time===u&&a.pop()}e==null||e.set(n,a.concat(s))}}}function Jh(i,t,e,r,n,s){if(i.updateData(s),t.update({barIndex:s.barIndex}),n=n||t.scriptType,s.isrealtime&&n===ic.strategy&&!t.strategy.isCalcOnEveryTick){t.strategy.calcCurrentOrder();return}if(r(i,e,t),t.endExecution(),t.strategy.calcOnOrderFillsData.tradeData){for(;t.strategy.calcOnOrderFillsData.tradeData;)t.strategy.calcOnOrderFillsData.data=t.strategy.calcOnOrderFillsData.tradeData,t.strategy.calcOnOrderFillsData.tradeData=void 0,i.updateData(s,!0),t.update({barIndex:s==null?void 0:s.barIndex}),r(i,e,t),t.endExecution();t.strategy.calcOnOrderFillsData={index:-1}}}function HD(i){var t,e,r,n,s,a;(t=self==null?void 0:self.workerStorage)==null||t.deleteStartwidthKey(i),(e=self==null?void 0:self.workerStorage)==null||e.delete(`inputs_${i}`),(r=self==null?void 0:self.workerStorage)==null||r.delete(`strategy_${i}`),(n=self==null?void 0:self.workerStorage)==null||n.delete(`request_${i}`),(s=self==null?void 0:self.workerStorage)==null||s.delete(`request_${i}_data`),(a=self==null?void 0:self.workerStorage)==null||a.delete(`request_${i}_list`)}ou({runScript:YD,removeScript:HD})})();
69
+ */const Rh=Symbol("Comlink.proxy"),gD=Symbol("Comlink.endpoint"),vD=Symbol("Comlink.releaseProxy"),su=Symbol("Comlink.finalizer"),xo=Symbol("Comlink.thrown"),Ph=i=>typeof i=="object"&&i!==null||typeof i=="function",yD={canHandle:i=>Ph(i)&&i[Rh],serialize(i){const{port1:t,port2:e}=new MessageChannel;return ou(i,t),[e,[e]]},deserialize(i){return i.start(),xD(i)}},wD={canHandle:i=>Ph(i)&&xo in i,serialize({value:i}){let t;return i instanceof Error?t={isError:!0,value:{message:i.message,name:i.name,stack:i.stack}}:t={isError:!1,value:i},[t,[]]},deserialize(i){throw i.isError?Object.assign(new Error(i.value.message),i.value):i.value}},kh=new Map([["proxy",yD],["throw",wD]]);function DD(i,t){for(const e of i)if(t===e||e==="*"||e instanceof RegExp&&e.test(t))return!0;return!1}function ou(i,t=globalThis,e=["*"]){t.addEventListener("message",function r(n){if(!n||!n.data)return;if(!DD(e,n.origin)){console.warn(`Invalid origin '${n.origin}' for comlink proxy`);return}const{id:s,type:a,path:u}=Object.assign({path:[]},n.data),c=(n.data.argumentList||[]).map(ai);let f;try{const d=u.slice(0,-1).reduce((_,g)=>_[g],i),h=u.reduce((_,g)=>_[g],i);switch(a){case"GET":f=h;break;case"SET":d[u.slice(-1)[0]]=ai(n.data.value),f=!0;break;case"APPLY":f=h.apply(d,c);break;case"CONSTRUCT":{const _=new h(...c);f=FD(_)}break;case"ENDPOINT":{const{port1:_,port2:g}=new MessageChannel;ou(i,g),f=MD(_,[_])}break;case"RELEASE":f=void 0;break;default:return}}catch(d){f={value:d,[xo]:0}}Promise.resolve(f).catch(d=>({value:d,[xo]:0})).then(d=>{const[h,_]=Mo(d);t.postMessage(Object.assign(Object.assign({},h),{id:s}),_),a==="RELEASE"&&(t.removeEventListener("message",r),zh(t),su in i&&typeof i[su]=="function"&&i[su]())}).catch(d=>{const[h,_]=Mo({value:new TypeError("Unserializable return value"),[xo]:0});t.postMessage(Object.assign(Object.assign({},h),{id:s}),_)})}),t.start&&t.start()}function bD(i){return i.constructor.name==="MessagePort"}function zh(i){bD(i)&&i.close()}function xD(i,t){return au(i,[],t)}function Eo(i){if(i)throw new Error("Proxy has been released and is not useable")}function qh(i){return Li(i,{type:"RELEASE"}).then(()=>{zh(i)})}const Co=new WeakMap,Ao="FinalizationRegistry"in globalThis&&new FinalizationRegistry(i=>{const t=(Co.get(i)||0)-1;Co.set(i,t),t===0&&qh(i)});function ED(i,t){const e=(Co.get(t)||0)+1;Co.set(t,e),Ao&&Ao.register(i,t,i)}function CD(i){Ao&&Ao.unregister(i)}function au(i,t=[],e=function(){}){let r=!1;const n=new Proxy(e,{get(s,a){if(Eo(r),a===vD)return()=>{CD(n),qh(i),r=!0};if(a==="then"){if(t.length===0)return{then:()=>n};const u=Li(i,{type:"GET",path:t.map(c=>c.toString())}).then(ai);return u.then.bind(u)}return au(i,[...t,a])},set(s,a,u){Eo(r);const[c,f]=Mo(u);return Li(i,{type:"SET",path:[...t,a].map(d=>d.toString()),value:c},f).then(ai)},apply(s,a,u){Eo(r);const c=t[t.length-1];if(c===gD)return Li(i,{type:"ENDPOINT"}).then(ai);if(c==="bind")return au(i,t.slice(0,-1));const[f,d]=Uh(u);return Li(i,{type:"APPLY",path:t.map(h=>h.toString()),argumentList:f},d).then(ai)},construct(s,a){Eo(r);const[u,c]=Uh(a);return Li(i,{type:"CONSTRUCT",path:t.map(f=>f.toString()),argumentList:u},c).then(ai)}});return ED(n,i),n}function AD(i){return Array.prototype.concat.apply([],i)}function Uh(i){const t=i.map(Mo);return[t.map(e=>e[0]),AD(t.map(e=>e[1]))]}const Wh=new WeakMap;function MD(i,t){return Wh.set(i,t),i}function FD(i){return Object.assign(i,{[Rh]:!0})}function Mo(i){for(const[t,e]of kh)if(e.canHandle(i)){const[r,n]=e.serialize(i);return[{type:"HANDLER",name:t,value:r},n]}return[{type:"RAW",value:i},Wh.get(i)||[]]}function ai(i){switch(i.type){case"HANDLER":return kh.get(i.name).deserialize(i.value);case"RAW":return i.value}}function Li(i,t,e){return new Promise(r=>{const n=ND();i.addEventListener("message",function s(a){!a.data||!a.data.id||a.data.id!==n||(i.removeEventListener("message",s),r(a.data))}),i.start&&i.start(),i.postMessage(Object.assign({id:n},t),e)})}function ND(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}class SD{constructor(){$(this,"_cache");this._cache=new Map}set(t,e){this._cache.set(t,e)}setValue(t,e,r){const n=this._cache.get(t)||{};n[e]=r,this._cache.set(t,n)}updateValue(t,e,r){const n=this._cache.get(t)||{};this._cache.set(t,Object.assign(n[e]||{},r))}get(t){return this._cache.get(t)}has(t){return this._cache.has(t)}deleteStartwidthKey(t){for(const e of this._cache.keys())e.startsWith(t)&&this._cache.delete(e)}delete(t){this._cache.delete(t)}clear(){this._cache.clear()}}class jh extends Error{constructor(e,r,n){const s=e.status||e.status===0?e.status:"",a=e.statusText||"",u=`${s} ${a}`.trim(),c=u?`status code ${u}`:"an unknown error";super(`Request failed with ${c}: ${r.method} ${r.url}`);$(this,"response");$(this,"request");$(this,"options");this.name="HTTPError",this.response=e,this.request=r,this.options=n}}class Yh extends Error{constructor(e){super(`Request timed out: ${e.method} ${e.url}`);$(this,"request");this.name="TimeoutError",this.request=e}}const ls=i=>i!==null&&typeof i=="object",Fo=(...i)=>{for(const t of i)if((!ls(t)||Array.isArray(t))&&t!==void 0)throw new TypeError("The `options` argument must be an object");return uu({},...i)},Vh=(i={},t={})=>{const e=new globalThis.Headers(i),r=t instanceof globalThis.Headers,n=new globalThis.Headers(t);for(const[s,a]of n.entries())r&&a==="undefined"||a===void 0?e.delete(s):e.set(s,a);return e};function No(i,t,e){return Object.hasOwn(t,e)&&t[e]===void 0?[]:uu(i[e]??[],t[e]??[])}const Hh=(i={},t={})=>({beforeRequest:No(i,t,"beforeRequest"),beforeRetry:No(i,t,"beforeRetry"),afterResponse:No(i,t,"afterResponse"),beforeError:No(i,t,"beforeError")}),uu=(...i)=>{let t={},e={},r={};for(const n of i)if(Array.isArray(n))Array.isArray(t)||(t=[]),t=[...t,...n];else if(ls(n)){for(let[s,a]of Object.entries(n))ls(a)&&s in t&&(a=uu(t[s],a)),t={...t,[s]:a};ls(n.hooks)&&(r=Hh(r,n.hooks),t.hooks=r),ls(n.headers)&&(e=Vh(e,n.headers),t.headers=e)}return t},OD=(()=>{let i=!1,t=!1;const e=typeof globalThis.ReadableStream=="function",r=typeof globalThis.Request=="function";if(e&&r)try{t=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return i=!0,"half"}}).headers.has("Content-Type")}catch(n){if(n instanceof Error&&n.message==="unsupported BodyInit type")return!1;throw n}return i&&!t})(),BD=typeof globalThis.AbortController=="function",TD=typeof globalThis.ReadableStream=="function",ID=typeof globalThis.FormData=="function",Zh=["get","post","put","patch","head","delete"],$D={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*"},lu=2147483647,Kh=Symbol("stop"),LD={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,prefixUrl:!0,retry:!0,timeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,fetch:!0},RD={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,dispatcher:!0,duplex:!0,priority:!0},PD=i=>Zh.includes(i)?i.toUpperCase():i,Gh={limit:2,methods:["get","put","head","delete","options","trace"],statusCodes:[408,413,429,500,502,503,504],afterStatusCodes:[413,429,503],maxRetryAfter:Number.POSITIVE_INFINITY,backoffLimit:Number.POSITIVE_INFINITY,delay:i=>.3*2**(i-1)*1e3},kD=(i={})=>{if(typeof i=="number")return{...Gh,limit:i};if(i.methods&&!Array.isArray(i.methods))throw new Error("retry.methods must be an array");if(i.statusCodes&&!Array.isArray(i.statusCodes))throw new Error("retry.statusCodes must be an array");return{...Gh,...i}};async function zD(i,t,e,r){return new Promise((n,s)=>{const a=setTimeout(()=>{e&&e.abort(),s(new Yh(i))},r.timeout);r.fetch(i,t).then(n).catch(s).then(()=>{clearTimeout(a)})})}async function qD(i,{signal:t}){return new Promise((e,r)=>{t&&(t.throwIfAborted(),t.addEventListener("abort",n,{once:!0}));function n(){clearTimeout(s),r(t.reason)}const s=setTimeout(()=>{t==null||t.removeEventListener("abort",n),e()},i)})}const UD=(i,t)=>{const e={};for(const r in t)!(r in RD)&&!(r in LD)&&!(r in i)&&(e[r]=t[r]);return e};class So{constructor(t,e={}){$(this,"request");$(this,"abortController");$(this,"_retryCount",0);$(this,"_input");$(this,"_options");var r,n;if(this._input=t,this._options={...e,headers:Vh(this._input.headers,e.headers),hooks:Hh({beforeRequest:[],beforeRetry:[],beforeError:[],afterResponse:[]},e.hooks),method:PD(e.method??this._input.method),prefixUrl:String(e.prefixUrl||""),retry:kD(e.retry),throwHttpErrors:e.throwHttpErrors!==!1,timeout:e.timeout??1e4,fetch:e.fetch??globalThis.fetch.bind(globalThis)},typeof this._input!="string"&&!(this._input instanceof URL||this._input instanceof globalThis.Request))throw new TypeError("`input` must be a string, URL, or Request");if(this._options.prefixUrl&&typeof this._input=="string"){if(this._input.startsWith("/"))throw new Error("`input` must not begin with a slash when using `prefixUrl`");this._options.prefixUrl.endsWith("/")||(this._options.prefixUrl+="/"),this._input=this._options.prefixUrl+this._input}if(BD){this.abortController=new globalThis.AbortController;const s=this._options.signal??this._input.signal;s==null||s.addEventListener("abort",()=>{this.abortController.abort(s.reason)}),this._options.signal=this.abortController.signal}if(OD&&(this._options.duplex="half"),this._options.json!==void 0&&(this._options.body=((n=(r=this._options).stringifyJson)==null?void 0:n.call(r,this._options.json))??JSON.stringify(this._options.json),this._options.headers.set("content-type",this._options.headers.get("content-type")??"application/json")),this.request=new globalThis.Request(this._input,this._options),this._options.searchParams){const a="?"+(typeof this._options.searchParams=="string"?this._options.searchParams.replace(/^\?/,""):new URLSearchParams(this._options.searchParams).toString()),u=this.request.url.replace(/(?:\?.*?)?(?=#|$)/,a);(ID&&this._options.body instanceof globalThis.FormData||this._options.body instanceof URLSearchParams)&&!(this._options.headers&&this._options.headers["content-type"])&&this.request.headers.delete("content-type"),this.request=new globalThis.Request(new globalThis.Request(u,{...this.request}),this._options)}}static create(t,e){const r=new So(t,e),n=async()=>{if(typeof r._options.timeout=="number"&&r._options.timeout>lu)throw new RangeError(`The \`timeout\` option cannot be greater than ${lu}`);await Promise.resolve();let u=await r._fetch();for(const c of r._options.hooks.afterResponse){const f=await c(r.request,r._options,r._decorateResponse(u.clone()));f instanceof globalThis.Response&&(u=f)}if(r._decorateResponse(u),!u.ok&&r._options.throwHttpErrors){let c=new jh(u,r.request,r._options);for(const f of r._options.hooks.beforeError)c=await f(c);throw c}if(r._options.onDownloadProgress){if(typeof r._options.onDownloadProgress!="function")throw new TypeError("The `onDownloadProgress` option must be a function");if(!TD)throw new Error("Streams are not supported in your environment. `ReadableStream` is missing.");return r._stream(u.clone(),r._options.onDownloadProgress)}return u},a=r._options.retry.methods.includes(r.request.method.toLowerCase())?r._retry(n):n();for(const[u,c]of Object.entries($D))a[u]=async()=>{r.request.headers.set("accept",r.request.headers.get("accept")||c);const d=(await a).clone();if(u==="json"){if(d.status===204||(await d.clone().arrayBuffer()).byteLength===0)return"";if(e.parseJson)return e.parseJson(await d.text())}return d[u]()};return a}_calculateRetryDelay(t){if(this._retryCount++,this._retryCount>this._options.retry.limit||t instanceof Yh)throw t;if(t instanceof jh){if(!this._options.retry.statusCodes.includes(t.response.status))throw t;const r=t.response.headers.get("Retry-After")??t.response.headers.get("RateLimit-Reset")??t.response.headers.get("X-RateLimit-Reset")??t.response.headers.get("X-Rate-Limit-Reset");if(r&&this._options.retry.afterStatusCodes.includes(t.response.status)){let n=Number(r)*1e3;Number.isNaN(n)?n=Date.parse(r)-Date.now():n>=Date.parse("2024-01-01")&&(n-=Date.now());const s=this._options.retry.maxRetryAfter??n;return n<s?n:s}if(t.response.status===413)throw t}const e=this._options.retry.delay(this._retryCount);return Math.min(this._options.retry.backoffLimit,e)}_decorateResponse(t){return this._options.parseJson&&(t.json=async()=>this._options.parseJson(await t.text())),t}async _retry(t){try{return await t()}catch(e){const r=Math.min(this._calculateRetryDelay(e),lu);if(this._retryCount<1)throw e;await qD(r,{signal:this._options.signal});for(const n of this._options.hooks.beforeRetry)if(await n({request:this.request,options:this._options,error:e,retryCount:this._retryCount})===Kh)return;return this._retry(t)}}async _fetch(){for(const r of this._options.hooks.beforeRequest){const n=await r(this.request,this._options);if(n instanceof Request){this.request=n;break}if(n instanceof Response)return n}const t=UD(this.request,this._options),e=this.request;return this.request=e.clone(),this._options.timeout===!1?this._options.fetch(e,t):zD(e,t,this.abortController,this._options)}_stream(t,e){const r=Number(t.headers.get("content-length"))||0;let n=0;return t.status===204?(e&&e({percent:1,totalBytes:r,transferredBytes:n},new Uint8Array),new globalThis.Response(null,{status:t.status,statusText:t.statusText,headers:t.headers})):new globalThis.Response(new globalThis.ReadableStream({async start(s){const a=t.body.getReader();e&&e({percent:0,transferredBytes:0,totalBytes:r},new Uint8Array);async function u(){const{done:c,value:f}=await a.read();if(c){s.close();return}if(e){n+=f.byteLength;const d=r===0?0:n/r;e({percent:d,transferredBytes:n,totalBytes:r},f)}s.enqueue(f),await u()}await u()}}),{status:t.status,statusText:t.statusText,headers:t.headers})}}/*! MIT License © Sindre Sorhus */const cu=i=>{const t=(e,r)=>So.create(e,Fo(i,r));for(const e of Zh)t[e]=(r,n)=>So.create(r,Fo(i,n,{method:e}));return t.create=e=>cu(Fo(e)),t.extend=e=>(typeof e=="function"&&(e=e(i??{})),cu(Fo(i,e))),t.stop=Kh,t},WD=cu().create({prefixUrl:"https://data.tradingvue.com/",retry:0});function jD(i){return WD.post("symbol/data/v1/",{json:i})}async function YD(i,t,e){var A,N,S;const{data:r,isPreParser:n,id:s="default",syminfo:a={},interval:u,inputs:c,chart:f,strategy:d,scriptType:h,isManuallyAdd:_,subscribeData:g}=t;self.workerStorage||(self.workerStorage=new SD);let{builtInGather:y,buildinConstants:p,buildInFunctions:w,tradingvueFunc:v}=self.workerStorage.get(s)||{},x=[];const b=a.mintick?Number(a.mintick):1e-5;a.mintick=b,e&&(y=new Lh(s),p=new Ch,w=new $h(b,y,s),v=new Function("$_var","$_const","$_func",i),self.workerStorage.set(s,{builtInGather:y,buildinConstants:p,buildInFunctions:w,tradingvueFunc:v}),self.workerStorage.set(`request_${s}`,new Map),(_||!self.workerStorage.has(`request_${s}_data`))&&self.workerStorage.set(`request_${s}_data`,new Map),self.workerStorage.set(`request_${s}_list`,new Map),self.workerStorage.set(`request_${s}_tmp`,new Map));let C=[];if(VD(g,s),n)v(y,p,w);else if(r&&r.length){const I=r.length-1;y.updateOptions({interval:u,mintick:b,chart:f,syminfo:a}),w.updateOptions({inputs:c,strategy:d});const F=self.workerStorage.get(`request_${s}_tmp`),O=self.workerStorage.get(`request_${s}_data`);try{let L;for(const[q,W]of r.entries()){const{barindex:P}=W;if(!e&&(P||P===0)&&x.push(P),F!=null&&F.size){const Y=[],G=[];for(const[ut,_t]of F){const{symbol:at,timeframe:vt,id:wt,calc_bars_count:Ct,ignore_invalid_symbol:bt}=_t,re=`${at}:${vt}`;G.push({id:wt,key:re,ignore_invalid_symbol:bt});const[Bt,Nt]=at.split(":");Y.push(jD({params:[{exchange:Bt,symbol:Nt,limit:Ct||5e3,start:0,end:0,period:vt}]}).json())}const X=await Promise.all(Y);for(const[ut,_t]of X.entries()){const{code:at,data:vt,msg:wt}=_t,Ct=G[ut];if(at!==200&&!Ct.ignore_invalid_symbol)return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:wt,type:Rt.Error}]};O==null||O.set(Ct.id,((N=(A=vt[Ct.key])==null?void 0:A.list)==null?void 0:N.reverse())||[])}F==null||F.clear(),L&&(w.log.clearLogForIndex(L.barIndex),Jh(y,w,p,v,h,L))}L=Object.assign(W,{barIndex:P||q,lastBarIndex:r[I].barindex||I,lastBarTime:r[I].time,nextBarTime:(S=r[q+1])==null?void 0:S.time}),Jh(y,w,p,v,h,L);const Z=w.errors;if(Z.length&&Z.some(Y=>Y.type===Rt.Error))return{status:1,errors:Z}}const z=self.workerStorage.get(`request_${s}_list`);if((z==null?void 0:z.size)>40)return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:ie.requestsNumErr,type:Rt.Error}]};if(z!=null&&z.size){const q=new Map;for(const[W,P]of z)C.push(P),e&&(O!=null&&O.has(W))&&q.set(W,O.get(W));e&&self.workerStorage.set(`request_${s}_data`,q)}C.length&&(z==null||z.clear()),e&&self.workerStorage.delete(`request_${s}_tmp`)}catch(L){return{status:1,errors:[{endLineNumber:0,startColumn:0,endColumn:0,startLineNumber:0,message:L==null?void 0:L.message,type:Rt.Error}]}}}const E=w.errors;return E.length&&E.some(I=>I.type===Rt.Error)?{status:1,errors:E}:{status:0,requestList:C,errors:E,options:{...w.options(x),id:s}}}function VD(i,t){if(!i)return;const e=self.workerStorage.get(`request_${t}_data`),r=Object.keys(i);if(r.length)for(const n of r){let s=i[n]||[];if(e!=null&&e.has(n)){const a=(e==null?void 0:e.get(n))||[];if(a.length){const u=a[a.length-1].time;s=s.filter(c=>c.time>=u),s[0].time===u&&a.pop()}e==null||e.set(n,a.concat(s))}}}function Jh(i,t,e,r,n,s){if(i.updateData(s),t.update({barIndex:s.barIndex}),n=n||t.scriptType,s.isrealtime&&n===ic.strategy&&!t.strategy.isCalcOnEveryTick){t.strategy.calcCurrentOrder();return}if(r(i,e,t),t.endExecution(),t.strategy.calcOnOrderFillsData.tradeData){for(;t.strategy.calcOnOrderFillsData.tradeData;)t.strategy.calcOnOrderFillsData.data=t.strategy.calcOnOrderFillsData.tradeData,t.strategy.calcOnOrderFillsData.tradeData=void 0,i.updateData(s,!0),t.update({barIndex:s==null?void 0:s.barIndex}),r(i,e,t),t.endExecution();t.strategy.calcOnOrderFillsData={index:-1}}}function HD(i){var t,e,r,n,s,a;(t=self==null?void 0:self.workerStorage)==null||t.deleteStartwidthKey(i),(e=self==null?void 0:self.workerStorage)==null||e.delete(`inputs_${i}`),(r=self==null?void 0:self.workerStorage)==null||r.delete(`strategy_${i}`),(n=self==null?void 0:self.workerStorage)==null||n.delete(`request_${i}`),(s=self==null?void 0:self.workerStorage)==null||s.delete(`request_${i}_data`),(a=self==null?void 0:self.workerStorage)==null||a.delete(`request_${i}_list`)}ou({runScript:YD,removeScript:HD})})();
@@ -20,6 +20,7 @@ export declare class Log {
20
20
  private _preBar;
21
21
  constructor(variables: BuiltInVariables, str: BuildInStr);
22
22
  get logs(): ILog[];
23
+ clearLogForIndex(index: number): void;
23
24
  clearLogs(): void;
24
25
  info(args: ILogArgs, replaces: (string | number | PseudoArray)[], posStr: string): void;
25
26
  error(args: ILogArgs, replaces: (string | number | PseudoArray)[], posStr: string): void;
@@ -69138,7 +69138,7 @@ function br(a, s, r) {
69138
69138
  function Nw() {
69139
69139
  return new Array(4).fill(0).map(() => Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString(16)).join("-");
69140
69140
  }
69141
- const Cd = new Worker(new URL("" + new URL("assets/scriptsRunWorker-DQMD5E5G.js", import.meta.url).href, import.meta.url), { type: "module", name: "Run TccScript Server" });
69141
+ const Cd = new Worker(new URL("" + new URL("assets/scriptsRunWorker-CdpsYJcD.js", import.meta.url).href, import.meta.url), { type: "module", name: "Run TccScript Server" });
69142
69142
  Cd.onerror = (a) => {
69143
69143
  console.error(a);
69144
69144
  };
@@ -141,7 +141,7 @@ function print() { __p += __j.call(arguments, '') }
141
141
  * @license
142
142
  * Copyright 2019 Google LLC
143
143
  * SPDX-License-Identifier: Apache-2.0
144
- */const tl=Symbol("Comlink.proxy"),Dm=Symbol("Comlink.endpoint"),Im=Symbol("Comlink.releaseProxy"),Bn=Symbol("Comlink.finalizer"),ba=Symbol("Comlink.thrown"),sl=a=>typeof a=="object"&&a!==null||typeof a=="function",Am={canHandle:a=>sl(a)&&a[tl],serialize(a){const{port1:s,port2:r}=new MessageChannel;return al(a,s),[r,[r]]},deserialize(a){return a.start(),Un(a)}},qm={canHandle:a=>sl(a)&&ba in a,serialize({value:a}){let s;return a instanceof Error?s={isError:!0,value:{message:a.message,name:a.name,stack:a.stack}}:s={isError:!1,value:a},[s,[]]},deserialize(a){throw a.isError?Object.assign(new Error(a.value.message),a.value):a.value}},rl=new Map([["proxy",Am],["throw",qm]]);function Cm(a,s){for(const r of a)if(s===r||r==="*"||r instanceof RegExp&&r.test(s))return!0;return!1}function al(a,s=globalThis,r=["*"]){s.addEventListener("message",function n(o){if(!o||!o.data)return;if(!Cm(r,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}const{id:l,type:c,path:d}=Object.assign({path:[]},o.data),m=(o.data.argumentList||[]).map(Is);let _;try{const g=d.slice(0,-1).reduce((h,D)=>h[D],a),x=d.reduce((h,D)=>h[D],a);switch(c){case"GET":_=x;break;case"SET":g[d.slice(-1)[0]]=Is(o.data.value),_=!0;break;case"APPLY":_=x.apply(g,m);break;case"CONSTRUCT":{const h=new x(...m);_=Kn(h)}break;case"ENDPOINT":{const{port1:h,port2:D}=new MessageChannel;al(a,D),_=Lm(h,[h])}break;case"RELEASE":_=void 0;break;default:return}}catch(g){_={value:g,[ba]:0}}Promise.resolve(_).catch(g=>({value:g,[ba]:0})).then(g=>{const[x,h]=va(g);s.postMessage(Object.assign(Object.assign({},x),{id:l}),h),c==="RELEASE"&&(s.removeEventListener("message",n),nl(s),Bn in a&&typeof a[Bn]=="function"&&a[Bn]())}).catch(g=>{const[x,h]=va({value:new TypeError("Unserializable return value"),[ba]:0});s.postMessage(Object.assign(Object.assign({},x),{id:l}),h)})}),s.start&&s.start()}function Sm(a){return a.constructor.name==="MessagePort"}function nl(a){Sm(a)&&a.close()}function Un(a,s){return $n(a,[],s)}function xa(a){if(a)throw new Error("Proxy has been released and is not useable")}function il(a){return Hs(a,{type:"RELEASE"}).then(()=>{nl(a)})}const ha=new WeakMap,wa="FinalizationRegistry"in globalThis&&new FinalizationRegistry(a=>{const s=(ha.get(a)||0)-1;ha.set(a,s),s===0&&il(a)});function zm(a,s){const r=(ha.get(s)||0)+1;ha.set(s,r),wa&&wa.register(a,s,a)}function Nm(a){wa&&wa.unregister(a)}function $n(a,s=[],r=function(){}){let n=!1;const o=new Proxy(r,{get(l,c){if(xa(n),c===Im)return()=>{Nm(o),il(a),n=!0};if(c==="then"){if(s.length===0)return{then:()=>o};const d=Hs(a,{type:"GET",path:s.map(m=>m.toString())}).then(Is);return d.then.bind(d)}return $n(a,[...s,c])},set(l,c,d){xa(n);const[m,_]=va(d);return Hs(a,{type:"SET",path:[...s,c].map(g=>g.toString()),value:m},_).then(Is)},apply(l,c,d){xa(n);const m=s[s.length-1];if(m===Dm)return Hs(a,{type:"ENDPOINT"}).then(Is);if(m==="bind")return $n(a,s.slice(0,-1));const[_,g]=ol(d);return Hs(a,{type:"APPLY",path:s.map(x=>x.toString()),argumentList:_},g).then(Is)},construct(l,c){xa(n);const[d,m]=ol(c);return Hs(a,{type:"CONSTRUCT",path:s.map(_=>_.toString()),argumentList:d},m).then(Is)}});return zm(o,a),o}function Em(a){return Array.prototype.concat.apply([],a)}function ol(a){const s=a.map(va);return[s.map(r=>r[0]),Em(s.map(r=>r[1]))]}const ll=new WeakMap;function Lm(a,s){return ll.set(a,s),a}function Kn(a){return Object.assign(a,{[tl]:!0})}function va(a){for(const[s,r]of rl)if(r.canHandle(a)){const[n,o]=r.serialize(a);return[{type:"HANDLER",name:s,value:n},o]}return[{type:"RAW",value:a},ll.get(a)||[]]}function Is(a){switch(a.type){case"HANDLER":return rl.get(a.name).deserialize(a.value);case"RAW":return a.value}}function Hs(a,s,r){return new Promise(n=>{const o=Mm();a.addEventListener("message",function l(c){!c.data||!c.data.id||c.data.id!==o||(a.removeEventListener("message",l),n(c.data))}),a.start&&a.start(),a.postMessage(Object.assign({id:o},s),r)})}function Mm(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}const cl=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/scriptsRunWorker-DQMD5E5G.js").href:new URL("assets/scriptsRunWorker-DQMD5E5G.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ra&&ra.src||new URL("trading-vue-editor.umd.cjs",document.baseURI).href),{type:"module",name:"Run TccScript Server"});cl.onerror=a=>{console.error(a)};async function pl(a){return await _a.setInlayHints(a)}const dl=Un(cl),ul=Un(new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/parserTccWorker-Cj4qsUGd.js").href:new URL("assets/parserTccWorker-Cj4qsUGd.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ra&&ra.src||new URL("trading-vue-editor.umd.cjs",document.baseURI).href),{type:"module",name:"Parser TccScript Server"}));async function ml(a,s=!1){const{functions:r,types:n,constants:o,variables:l,methods:c}=nt;return await ul.parseTcc(a,s,Kn(pl),{functions:Object.fromEntries(r),methods:Object.fromEntries(c),types:Object.fromEntries(n),constants:Object.fromEntries(o),variables:Object.fromEntries(l)})}async function Om(a,s){const{functions:r,types:n,constants:o,variables:l,methods:c}=nt;return await ul.parseLibraryCode(a,s,Kn(pl),{functions:Object.fromEntries(r),methods:Object.fromEntries(c),types:Object.fromEntries(n),constants:Object.fromEntries(o),variables:Object.fromEntries(l)})}async function Pm(a,s,r=!0){return await dl.runScript(a,s,r)}async function Rm(a){return await dl.removeScript(a)}function Fm(a){return new Worker(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/editor.worker-CT5Cb1wO.js").href:new URL("assets/editor.worker-CT5Cb1wO.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),{name:a==null?void 0:a.name})}const{slice:Bm,forEach:Um}=[];function $m(a){return Um.call(Bm.call(arguments,1),s=>{if(s)for(const r in s)a[r]===void 0&&(a[r]=s[r])}),a}const yl=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Km=(a,s,r)=>{const n=r||{};n.path=n.path||"/";const o=encodeURIComponent(s);let l=`${a}=${o}`;if(n.maxAge>0){const c=n.maxAge-0;if(Number.isNaN(c))throw new Error("maxAge should be a Number");l+=`; Max-Age=${Math.floor(c)}`}if(n.domain){if(!yl.test(n.domain))throw new TypeError("option domain is invalid");l+=`; Domain=${n.domain}`}if(n.path){if(!yl.test(n.path))throw new TypeError("option path is invalid");l+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");l+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(l+="; HttpOnly"),n.secure&&(l+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"strict":l+="; SameSite=Strict";break;case"none":l+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return l},_l={create(a,s,r,n){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(o.expires=new Date,o.expires.setTime(o.expires.getTime()+r*60*1e3)),n&&(o.domain=n),document.cookie=Km(a,encodeURIComponent(s),o)},read(a){const s=`${a}=`,r=document.cookie.split(";");for(let n=0;n<r.length;n++){let o=r[n];for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(s)===0)return o.substring(s.length,o.length)}return null},remove(a){this.create(a,"",-1)}};var jm={name:"cookie",lookup(a){let{lookupCookie:s}=a;if(s&&typeof document<"u")return _l.read(s)||void 0},cacheUserLanguage(a,s){let{lookupCookie:r,cookieMinutes:n,cookieDomain:o,cookieOptions:l}=s;r&&typeof document<"u"&&_l.create(r,a,n,o,l)}},Hm={name:"querystring",lookup(a){var n;let{lookupQuerystring:s}=a,r;if(typeof window<"u"){let{search:o}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(o=window.location.hash.substring(window.location.hash.indexOf("?")));const c=o.substring(1).split("&");for(let d=0;d<c.length;d++){const m=c[d].indexOf("=");m>0&&c[d].substring(0,m)===s&&(r=c[d].substring(m+1))}}return r}};let Cr=null;const fl=()=>{if(Cr!==null)return Cr;try{Cr=window!=="undefined"&&window.localStorage!==null;const a="i18next.translate.boo";window.localStorage.setItem(a,"foo"),window.localStorage.removeItem(a)}catch{Cr=!1}return Cr};var Wm={name:"localStorage",lookup(a){let{lookupLocalStorage:s}=a;if(s&&fl())return window.localStorage.getItem(s)||void 0},cacheUserLanguage(a,s){let{lookupLocalStorage:r}=s;r&&fl()&&window.localStorage.setItem(r,a)}};let Sr=null;const gl=()=>{if(Sr!==null)return Sr;try{Sr=window!=="undefined"&&window.sessionStorage!==null;const a="i18next.translate.boo";window.sessionStorage.setItem(a,"foo"),window.sessionStorage.removeItem(a)}catch{Sr=!1}return Sr};var Vm={name:"sessionStorage",lookup(a){let{lookupSessionStorage:s}=a;if(s&&gl())return window.sessionStorage.getItem(s)||void 0},cacheUserLanguage(a,s){let{lookupSessionStorage:r}=s;r&&gl()&&window.sessionStorage.setItem(r,a)}},Gm={name:"navigator",lookup(a){const s=[];if(typeof navigator<"u"){const{languages:r,userLanguage:n,language:o}=navigator;if(r)for(let l=0;l<r.length;l++)s.push(r[l]);n&&s.push(n),o&&s.push(o)}return s.length>0?s:void 0}},Xm={name:"htmlTag",lookup(a){let{htmlTag:s}=a,r;const n=s||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(r=n.getAttribute("lang")),r}},Ym={name:"path",lookup(a){var o;let{lookupFromPathIndex:s}=a;if(typeof window>"u")return;const r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(r)?(o=r[typeof s=="number"?s:0])==null?void 0:o.replace("/",""):void 0}},Qm={name:"subdomain",lookup(a){var o,l;let{lookupFromSubdomainIndex:s}=a;const r=typeof s=="number"?s+1:1,n=typeof window<"u"&&((l=(o=window.location)==null?void 0:o.hostname)==null?void 0:l.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[r]}};function Zm(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:a=>a}}class bl{constructor(s){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(s,r)}init(s){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=s||{languageUtils:{}},this.options=$m(r,this.options||{},Zm()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=o=>o.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(jm),this.addDetector(Hm),this.addDetector(Wm),this.addDetector(Vm),this.addDetector(Gm),this.addDetector(Xm),this.addDetector(Ym),this.addDetector(Qm)}addDetector(s){return this.detectors[s.name]=s,this}detect(s){s||(s=this.options.order);let r=[];return s.forEach(n=>{if(this.detectors[n]){let o=this.detectors[n].lookup(this.options);o&&typeof o=="string"&&(o=[o]),o&&(r=r.concat(o))}}),r=r.map(n=>this.options.convertDetectedLanguage(n)),this.services.languageUtils.getBestMatchFromCodes?r:r.length>0?r[0]:null}cacheUserLanguage(s,r){r||(r=this.options.caches),r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(s)>-1||r.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(s,this.options)}))}}bl.type="languageDetector";const Jm=(...a)=>{console!=null&&console.warn&&(As(a[0])&&(a[0]=`react-i18next:: ${a[0]}`),console.warn(...a))},xl={},jn=(...a)=>{As(a[0])&&xl[a[0]]||(As(a[0])&&(xl[a[0]]=new Date),Jm(...a))},hl=(a,s)=>()=>{if(a.isInitialized)s();else{const r=()=>{setTimeout(()=>{a.off("initialized",r)},0),s()};a.on("initialized",r)}},Hn=(a,s,r)=>{a.loadNamespaces(s,hl(a,r))},wl=(a,s,r,n)=>{if(As(r)&&(r=[r]),a.options.preload&&a.options.preload.indexOf(s)>-1)return Hn(a,r,n);r.forEach(o=>{a.options.ns.indexOf(o)<0&&a.options.ns.push(o)}),a.loadLanguages(s,hl(a,n))},ey=(a,s,r={})=>!s.languages||!s.languages.length?(jn("i18n.languages were undefined or empty",s.languages),!0):s.hasLoadedNamespace(a,{lng:r.lng,precheck:(n,o)=>{var l;if(((l=r.bindI18n)==null?void 0:l.indexOf("languageChanging"))>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,a))return!1}}),As=a=>typeof a=="string",ty=a=>typeof a=="object"&&a!==null,sy=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,ry={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},ay=a=>ry[a];let Wn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:a=>a.replace(sy,ay)};const ny=(a={})=>{Wn={...Wn,...a}},iy=()=>Wn;let vl;const oy=a=>{vl=a},ly=()=>vl,cy={type:"3rdParty",init(a){ny(a.options.react),oy(a)}},py=S.createContext();class dy{constructor(){this.usedNamespaces={}}addUsedNamespaces(s){s.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const uy=(a,s)=>{const r=S.useRef();return S.useEffect(()=>{r.current=s?r.current:a},[a,s]),r.current},Tl=(a,s,r,n)=>a.getFixedT(s,r,n),my=(a,s,r,n)=>S.useCallback(Tl(a,s,r,n),[a,s,r,n]),Ws=(a,s={})=>{var V,Q,q,C;const{i18n:r}=s,{i18n:n,defaultNS:o}=S.useContext(py)||{},l=r||n||ly();if(l&&!l.reportNamespaces&&(l.reportNamespaces=new dy),!l){jn("You will need to pass in an i18next instance by using initReactI18next");const R=(A,O)=>As(O)?O:ty(O)&&As(O.defaultValue)?O.defaultValue:Array.isArray(A)?A[A.length-1]:A,E=[R,{},!1];return E.t=R,E.i18n={},E.ready=!1,E}(V=l.options.react)!=null&&V.wait&&jn("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const c={...iy(),...l.options.react,...s},{useSuspense:d,keyPrefix:m}=c;let _=a||o||((Q=l.options)==null?void 0:Q.defaultNS);_=As(_)?[_]:_||["translation"],(C=(q=l.reportNamespaces).addUsedNamespaces)==null||C.call(q,_);const g=(l.isInitialized||l.initializedStoreOnce)&&_.every(R=>ey(R,l,c)),x=my(l,s.lng||null,c.nsMode==="fallback"?_:_[0],m),h=()=>x,D=()=>Tl(l,s.lng||null,c.nsMode==="fallback"?_:_[0],m),[z,P]=S.useState(h);let $=_.join();s.lng&&($=`${s.lng}${$}`);const j=uy($),W=S.useRef(!0);S.useEffect(()=>{const{bindI18n:R,bindI18nStore:E}=c;W.current=!0,!g&&!d&&(s.lng?wl(l,s.lng,_,()=>{W.current&&P(D)}):Hn(l,_,()=>{W.current&&P(D)})),g&&j&&j!==$&&W.current&&P(D);const A=()=>{W.current&&P(D)};return R&&(l==null||l.on(R,A)),E&&(l==null||l.store.on(E,A)),()=>{W.current=!1,l&&(R==null||R.split(" ").forEach(O=>l.off(O,A))),E&&l&&E.split(" ").forEach(O=>l.store.off(O,A))}},[l,$]),S.useEffect(()=>{W.current&&g&&P(h)},[l,m,g]);const re=[z,l,g];if(re.t=z,re.i18n=l,re.ready=g,g||!g&&!d)return re;throw new Promise(R=>{s.lng?wl(l,s.lng,_,()=>R()):Hn(l,_,()=>R())})},yy={type:"type",syntax:"syntax",overloads:"overloads",arguments:"arguments",fields:"fields",example:"example",returns:"returns",remarks:"remarks","see also":"see also","Copy code":"Copy code","Copy link":"Copy link",Copied:"Copied","Link copied":"Link copied",variables:"Variables",constants:"Constants",functions:"Functions",keywords:"Keywords",types:"Types",operators:"Operators",annotations:"Annotations",search:"Search","Mine Script® v1 Reference Manual":"Mine Script® v1 Reference Manual","This script is read-only. It cannot be edited.":"This script is read-only. It cannot be edited.","save script":"Save script","open script":"Open script","find/replace":"Find/Replace","toggle console":"Toggle console","open editor in new tab":"Open editor in new tab","open editor in new window":"Open editor in new window",keyword:"keyword","built-in function":"built-in function","built-in variable":"built-in variable","built-in method":"built-in method","built-in type":"built-in type",annotation:"annotation","built-in constant":"built-in constant",namespace:"namespace","user-defined variable":"user-defined variable","user-defined type":"user-defined type",field:"field",enum:"enum","user-defined method":"user-defined method","user-defined function":"user-defined function",parameter:"parameter","**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Tcc functions, variables, and methods.":"**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Mine functions, variables, and methods.","to trigger parameters hint":"to trigger parameters hint",library:"library","enum member":"enum member",Returns:"Returns",Syntax:"Syntax",Remarks:"Remarks",Fields:"Fields",Description:"Description",Example:"Example","Enum members":"Enum members",statement:"statement",loop:"loop","`click` on keyword for more help":"`click` on keyword for more help"},_y={type:"类型",syntax:"语法",overloads:"重载",arguments:"参数",fields:"字段",example:"例子",returns:"返回值",remarks:"备注","see also":"另见","Copy code":"复制代码","Copy link":"复制链接",Copied:"已复制","Link copied":"链接已复制",variables:"内置变量",constants:"常量",functions:"函数",keywords:"关键词",types:"类型",operators:"运算符",annotations:"注释",search:"搜索","Mine Script® v1 Reference Manual":"Mine Script™ v1参考手册","This script is read-only. It cannot be edited.":"该脚本是只读的。它无法被编辑。","save script":"保存脚本","open script":"打开脚本","find/replace":"寻找/替换","toggle console":"切换控制台","open editor in new tab":"在新标签页中打开","open editor in new window":"在新窗口中打开",keyword:"关键词","built-in function":"内置函数","built-in variable":"内置变量","built-in method":"内置方法","built-in type":"内置类型",annotation:"注释","built-in constant":"内置常量",namespace:"命名空间","user-defined variable":"用户自定义变量","user-defined type":"用户自定义类型",field:"字段",enum:"枚举","user-defined method":"用户自定义方法","user-defined function":"用户自定义函数",parameter:"参数","**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Tcc functions, variables, and methods.":"命名空间是不可变的术语,充当标识符组的前缀。在命名Mine函数、变量和方法时,点和另一个术语始终遵循命名空间。","to trigger parameters hint":"触发参数提示",library:"脚本库","enum member":"枚举成员",Returns:"返回值",Syntax:"语法",Remarks:"备注",Fields:"字段",Description:"描述",Example:"例子","Enum members":"枚举成员",statement:"声明",loop:"循环","`click` on keyword for more help":"“点击”关键词以获得更多帮助"};Me.use(bl).use(cy).init({debug:!1,fallbackLng:"zh",interpolation:{escapeValue:!1},resources:{en:{translation:yy},zh:{translation:_y}}}),self.MonacoEnvironment={getWorker(){return new Fm({name:"Editor Worker"})}},In.config({paths:{vs:"https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs"},"vs/nls":{availableLanguages:{"*":"zh-cn"}}});const fy=(a,s)=>{const{height:r,width:n,theme:o,options:l,hasDiff:c,readOnly:d,defaultValue:m,language:_,onChange:g,onLinkOpen:x,onCursorPositionChange:h,onActionTrigger:D,onEditorDidMount:z}=a,{t:P,i18n:$}=Ws(),j=S.useRef(null),W=S.useRef(null),re=S.useRef(!1),V=S.useRef(!1);S.useImperativeHandle(s,()=>({setOriginalScript(A){var O;(O=j.current)==null||O.setOriginalScript(A)},setScript(A){var O;(O=j.current)==null||O.setValue(A)},gotoLine(){var A;(A=j.current)==null||A.gotoLine()},getEditorLayout(){var A;return(A=j.current)==null?void 0:A.getEditorLayout()},setPosition(A,O){var J;(J=j.current)==null||J.setPosition({column:A,lineNumber:O})},setModelMarkers(A){var O;V.current=!0,(O=j.current)==null||O.setModelMarkers(A),setTimeout(()=>{V.current=!1},2e3)},focus(){var A;(A=j.current)==null||A.focus()}})),S.useEffect(()=>{var A,O;c?(O=j.current)==null||O.addDiffDecorations():(A=j.current)==null||A.removeDiffDecorations()},[c]),S.useEffect(()=>{o&&Ne.editor.setTheme(o)},[o]),S.useEffect(()=>{_&&$.changeLanguage(_)},[_]),S.useEffect(()=>{var A;(A=j.current)==null||A.updateActionTrigger(D)},[D]),S.useEffect(()=>{var A;x&&((A=j.current)==null||A.addLinkOpenFunc(x))},[x]);function Q(A,O){var se,le;Pt.initBuiltinsTrees(),_a.setEditor(A),j.current=new km(A,O,D),x&&((se=j.current)==null||se.addLinkOpenFunc(x)),c&&((le=j.current)==null||le.addDiffDecorations()),Gu(A),requestAnimationFrame(E);const J=A.getValue();j.current.onChangeCursorPosition(h),g&&g(J),!d&&q(J),z&&z()}const q=S.useCallback(async A=>{var Rt;re.current=!1;const{errors:O,functions:J,methods:se,types:le,variables:Y,overloadsFuncs:oe,imports:xe,enums:pe}=await ml(A),_e=new Map(Object.entries(J)),Ee=new Map(Object.entries(se)),ee=new Map(Object.entries(le)),de=new Map(Object.entries(Y)),Oe=new Map(Object.entries(xe)),Ge=new Map(Object.entries(pe));Ds.setUserDefined({functions:_e,methods:Ee,types:ee,variables:de,imports:Oe,enums:Ge},oe),Pt.setUserDefind(_e,ee,de,Ee,Ge);const Qe=O.map(us=>({...us,severity:us.type||Ne.MarkerSeverity.Error}));d||!re.current&&!V.current&&Qe.length&&((Rt=j.current)==null||Rt.setModelMarkers(Qe))},[d]),C=S.useMemo(()=>Qu.debounce(q,1500),[q]);function R(A){var O;if(d){q(A||"");return}re.current=!0,_a.clearInlayHints(),(O=j.current)==null||O.setModelMarkers([]),A!==void 0&&(g&&g(A),C(A))}const E=S.useCallback(()=>{var O,J;const A=(O=W.current)==null?void 0:O.getBoundingClientRect();(J=j.current)==null||J.setEditorLayout((A==null?void 0:A.height)||0,A==null?void 0:A.width)},[]);return S.useEffect(()=>{const A=()=>{window.requestAnimationFrame(E)},O=new ResizeObserver(A);return W.current&&O.observe(W.current),()=>{var J;W.current&&O.unobserve(W.current),O.disconnect(),(J=j.current)==null||J.dispose()}},[]),T.jsx("div",{ref:W,children:T.jsx(mu,{height:r,width:n||"100%",defaultLanguage:Ke,defaultValue:m||`indicator("我的脚本")
144
+ */const tl=Symbol("Comlink.proxy"),Dm=Symbol("Comlink.endpoint"),Im=Symbol("Comlink.releaseProxy"),Bn=Symbol("Comlink.finalizer"),ba=Symbol("Comlink.thrown"),sl=a=>typeof a=="object"&&a!==null||typeof a=="function",Am={canHandle:a=>sl(a)&&a[tl],serialize(a){const{port1:s,port2:r}=new MessageChannel;return al(a,s),[r,[r]]},deserialize(a){return a.start(),Un(a)}},qm={canHandle:a=>sl(a)&&ba in a,serialize({value:a}){let s;return a instanceof Error?s={isError:!0,value:{message:a.message,name:a.name,stack:a.stack}}:s={isError:!1,value:a},[s,[]]},deserialize(a){throw a.isError?Object.assign(new Error(a.value.message),a.value):a.value}},rl=new Map([["proxy",Am],["throw",qm]]);function Cm(a,s){for(const r of a)if(s===r||r==="*"||r instanceof RegExp&&r.test(s))return!0;return!1}function al(a,s=globalThis,r=["*"]){s.addEventListener("message",function n(o){if(!o||!o.data)return;if(!Cm(r,o.origin)){console.warn(`Invalid origin '${o.origin}' for comlink proxy`);return}const{id:l,type:c,path:d}=Object.assign({path:[]},o.data),m=(o.data.argumentList||[]).map(Is);let _;try{const g=d.slice(0,-1).reduce((h,D)=>h[D],a),x=d.reduce((h,D)=>h[D],a);switch(c){case"GET":_=x;break;case"SET":g[d.slice(-1)[0]]=Is(o.data.value),_=!0;break;case"APPLY":_=x.apply(g,m);break;case"CONSTRUCT":{const h=new x(...m);_=Kn(h)}break;case"ENDPOINT":{const{port1:h,port2:D}=new MessageChannel;al(a,D),_=Lm(h,[h])}break;case"RELEASE":_=void 0;break;default:return}}catch(g){_={value:g,[ba]:0}}Promise.resolve(_).catch(g=>({value:g,[ba]:0})).then(g=>{const[x,h]=va(g);s.postMessage(Object.assign(Object.assign({},x),{id:l}),h),c==="RELEASE"&&(s.removeEventListener("message",n),nl(s),Bn in a&&typeof a[Bn]=="function"&&a[Bn]())}).catch(g=>{const[x,h]=va({value:new TypeError("Unserializable return value"),[ba]:0});s.postMessage(Object.assign(Object.assign({},x),{id:l}),h)})}),s.start&&s.start()}function Sm(a){return a.constructor.name==="MessagePort"}function nl(a){Sm(a)&&a.close()}function Un(a,s){return $n(a,[],s)}function xa(a){if(a)throw new Error("Proxy has been released and is not useable")}function il(a){return Hs(a,{type:"RELEASE"}).then(()=>{nl(a)})}const ha=new WeakMap,wa="FinalizationRegistry"in globalThis&&new FinalizationRegistry(a=>{const s=(ha.get(a)||0)-1;ha.set(a,s),s===0&&il(a)});function zm(a,s){const r=(ha.get(s)||0)+1;ha.set(s,r),wa&&wa.register(a,s,a)}function Nm(a){wa&&wa.unregister(a)}function $n(a,s=[],r=function(){}){let n=!1;const o=new Proxy(r,{get(l,c){if(xa(n),c===Im)return()=>{Nm(o),il(a),n=!0};if(c==="then"){if(s.length===0)return{then:()=>o};const d=Hs(a,{type:"GET",path:s.map(m=>m.toString())}).then(Is);return d.then.bind(d)}return $n(a,[...s,c])},set(l,c,d){xa(n);const[m,_]=va(d);return Hs(a,{type:"SET",path:[...s,c].map(g=>g.toString()),value:m},_).then(Is)},apply(l,c,d){xa(n);const m=s[s.length-1];if(m===Dm)return Hs(a,{type:"ENDPOINT"}).then(Is);if(m==="bind")return $n(a,s.slice(0,-1));const[_,g]=ol(d);return Hs(a,{type:"APPLY",path:s.map(x=>x.toString()),argumentList:_},g).then(Is)},construct(l,c){xa(n);const[d,m]=ol(c);return Hs(a,{type:"CONSTRUCT",path:s.map(_=>_.toString()),argumentList:d},m).then(Is)}});return zm(o,a),o}function Em(a){return Array.prototype.concat.apply([],a)}function ol(a){const s=a.map(va);return[s.map(r=>r[0]),Em(s.map(r=>r[1]))]}const ll=new WeakMap;function Lm(a,s){return ll.set(a,s),a}function Kn(a){return Object.assign(a,{[tl]:!0})}function va(a){for(const[s,r]of rl)if(r.canHandle(a)){const[n,o]=r.serialize(a);return[{type:"HANDLER",name:s,value:n},o]}return[{type:"RAW",value:a},ll.get(a)||[]]}function Is(a){switch(a.type){case"HANDLER":return rl.get(a.name).deserialize(a.value);case"RAW":return a.value}}function Hs(a,s,r){return new Promise(n=>{const o=Mm();a.addEventListener("message",function l(c){!c.data||!c.data.id||c.data.id!==o||(a.removeEventListener("message",l),n(c.data))}),a.start&&a.start(),a.postMessage(Object.assign({id:o},s),r)})}function Mm(){return new Array(4).fill(0).map(()=>Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16)).join("-")}const cl=new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/scriptsRunWorker-CdpsYJcD.js").href:new URL("assets/scriptsRunWorker-CdpsYJcD.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ra&&ra.src||new URL("trading-vue-editor.umd.cjs",document.baseURI).href),{type:"module",name:"Run TccScript Server"});cl.onerror=a=>{console.error(a)};async function pl(a){return await _a.setInlayHints(a)}const dl=Un(cl),ul=Un(new Worker(new URL(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/parserTccWorker-Cj4qsUGd.js").href:new URL("assets/parserTccWorker-Cj4qsUGd.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__filename).href:typeof document>"u"?location.href:ra&&ra.src||new URL("trading-vue-editor.umd.cjs",document.baseURI).href),{type:"module",name:"Parser TccScript Server"}));async function ml(a,s=!1){const{functions:r,types:n,constants:o,variables:l,methods:c}=nt;return await ul.parseTcc(a,s,Kn(pl),{functions:Object.fromEntries(r),methods:Object.fromEntries(c),types:Object.fromEntries(n),constants:Object.fromEntries(o),variables:Object.fromEntries(l)})}async function Om(a,s){const{functions:r,types:n,constants:o,variables:l,methods:c}=nt;return await ul.parseLibraryCode(a,s,Kn(pl),{functions:Object.fromEntries(r),methods:Object.fromEntries(c),types:Object.fromEntries(n),constants:Object.fromEntries(o),variables:Object.fromEntries(l)})}async function Pm(a,s,r=!0){return await dl.runScript(a,s,r)}async function Rm(a){return await dl.removeScript(a)}function Fm(a){return new Worker(""+(typeof document>"u"&&typeof location>"u"?require("url").pathToFileURL(__dirname+"/assets/editor.worker-CT5Cb1wO.js").href:new URL("assets/editor.worker-CT5Cb1wO.js",typeof document>"u"?location.href:document.currentScript&&document.currentScript.src||document.baseURI).href),{name:a==null?void 0:a.name})}const{slice:Bm,forEach:Um}=[];function $m(a){return Um.call(Bm.call(arguments,1),s=>{if(s)for(const r in s)a[r]===void 0&&(a[r]=s[r])}),a}const yl=/^[\u0009\u0020-\u007e\u0080-\u00ff]+$/,Km=(a,s,r)=>{const n=r||{};n.path=n.path||"/";const o=encodeURIComponent(s);let l=`${a}=${o}`;if(n.maxAge>0){const c=n.maxAge-0;if(Number.isNaN(c))throw new Error("maxAge should be a Number");l+=`; Max-Age=${Math.floor(c)}`}if(n.domain){if(!yl.test(n.domain))throw new TypeError("option domain is invalid");l+=`; Domain=${n.domain}`}if(n.path){if(!yl.test(n.path))throw new TypeError("option path is invalid");l+=`; Path=${n.path}`}if(n.expires){if(typeof n.expires.toUTCString!="function")throw new TypeError("option expires is invalid");l+=`; Expires=${n.expires.toUTCString()}`}if(n.httpOnly&&(l+="; HttpOnly"),n.secure&&(l+="; Secure"),n.sameSite)switch(typeof n.sameSite=="string"?n.sameSite.toLowerCase():n.sameSite){case!0:l+="; SameSite=Strict";break;case"lax":l+="; SameSite=Lax";break;case"strict":l+="; SameSite=Strict";break;case"none":l+="; SameSite=None";break;default:throw new TypeError("option sameSite is invalid")}return l},_l={create(a,s,r,n){let o=arguments.length>4&&arguments[4]!==void 0?arguments[4]:{path:"/",sameSite:"strict"};r&&(o.expires=new Date,o.expires.setTime(o.expires.getTime()+r*60*1e3)),n&&(o.domain=n),document.cookie=Km(a,encodeURIComponent(s),o)},read(a){const s=`${a}=`,r=document.cookie.split(";");for(let n=0;n<r.length;n++){let o=r[n];for(;o.charAt(0)===" ";)o=o.substring(1,o.length);if(o.indexOf(s)===0)return o.substring(s.length,o.length)}return null},remove(a){this.create(a,"",-1)}};var jm={name:"cookie",lookup(a){let{lookupCookie:s}=a;if(s&&typeof document<"u")return _l.read(s)||void 0},cacheUserLanguage(a,s){let{lookupCookie:r,cookieMinutes:n,cookieDomain:o,cookieOptions:l}=s;r&&typeof document<"u"&&_l.create(r,a,n,o,l)}},Hm={name:"querystring",lookup(a){var n;let{lookupQuerystring:s}=a,r;if(typeof window<"u"){let{search:o}=window.location;!window.location.search&&((n=window.location.hash)==null?void 0:n.indexOf("?"))>-1&&(o=window.location.hash.substring(window.location.hash.indexOf("?")));const c=o.substring(1).split("&");for(let d=0;d<c.length;d++){const m=c[d].indexOf("=");m>0&&c[d].substring(0,m)===s&&(r=c[d].substring(m+1))}}return r}};let Cr=null;const fl=()=>{if(Cr!==null)return Cr;try{Cr=window!=="undefined"&&window.localStorage!==null;const a="i18next.translate.boo";window.localStorage.setItem(a,"foo"),window.localStorage.removeItem(a)}catch{Cr=!1}return Cr};var Wm={name:"localStorage",lookup(a){let{lookupLocalStorage:s}=a;if(s&&fl())return window.localStorage.getItem(s)||void 0},cacheUserLanguage(a,s){let{lookupLocalStorage:r}=s;r&&fl()&&window.localStorage.setItem(r,a)}};let Sr=null;const gl=()=>{if(Sr!==null)return Sr;try{Sr=window!=="undefined"&&window.sessionStorage!==null;const a="i18next.translate.boo";window.sessionStorage.setItem(a,"foo"),window.sessionStorage.removeItem(a)}catch{Sr=!1}return Sr};var Vm={name:"sessionStorage",lookup(a){let{lookupSessionStorage:s}=a;if(s&&gl())return window.sessionStorage.getItem(s)||void 0},cacheUserLanguage(a,s){let{lookupSessionStorage:r}=s;r&&gl()&&window.sessionStorage.setItem(r,a)}},Gm={name:"navigator",lookup(a){const s=[];if(typeof navigator<"u"){const{languages:r,userLanguage:n,language:o}=navigator;if(r)for(let l=0;l<r.length;l++)s.push(r[l]);n&&s.push(n),o&&s.push(o)}return s.length>0?s:void 0}},Xm={name:"htmlTag",lookup(a){let{htmlTag:s}=a,r;const n=s||(typeof document<"u"?document.documentElement:null);return n&&typeof n.getAttribute=="function"&&(r=n.getAttribute("lang")),r}},Ym={name:"path",lookup(a){var o;let{lookupFromPathIndex:s}=a;if(typeof window>"u")return;const r=window.location.pathname.match(/\/([a-zA-Z-]*)/g);return Array.isArray(r)?(o=r[typeof s=="number"?s:0])==null?void 0:o.replace("/",""):void 0}},Qm={name:"subdomain",lookup(a){var o,l;let{lookupFromSubdomainIndex:s}=a;const r=typeof s=="number"?s+1:1,n=typeof window<"u"&&((l=(o=window.location)==null?void 0:o.hostname)==null?void 0:l.match(/^(\w{2,5})\.(([a-z0-9-]{1,63}\.[a-z]{2,6})|localhost)/i));if(n)return n[r]}};function Zm(){return{order:["querystring","cookie","localStorage","sessionStorage","navigator","htmlTag"],lookupQuerystring:"lng",lookupCookie:"i18next",lookupLocalStorage:"i18nextLng",lookupSessionStorage:"i18nextLng",caches:["localStorage"],excludeCacheFor:["cimode"],convertDetectedLanguage:a=>a}}class bl{constructor(s){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.type="languageDetector",this.detectors={},this.init(s,r)}init(s){let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};this.services=s||{languageUtils:{}},this.options=$m(r,this.options||{},Zm()),typeof this.options.convertDetectedLanguage=="string"&&this.options.convertDetectedLanguage.indexOf("15897")>-1&&(this.options.convertDetectedLanguage=o=>o.replace("-","_")),this.options.lookupFromUrlIndex&&(this.options.lookupFromPathIndex=this.options.lookupFromUrlIndex),this.i18nOptions=n,this.addDetector(jm),this.addDetector(Hm),this.addDetector(Wm),this.addDetector(Vm),this.addDetector(Gm),this.addDetector(Xm),this.addDetector(Ym),this.addDetector(Qm)}addDetector(s){return this.detectors[s.name]=s,this}detect(s){s||(s=this.options.order);let r=[];return s.forEach(n=>{if(this.detectors[n]){let o=this.detectors[n].lookup(this.options);o&&typeof o=="string"&&(o=[o]),o&&(r=r.concat(o))}}),r=r.map(n=>this.options.convertDetectedLanguage(n)),this.services.languageUtils.getBestMatchFromCodes?r:r.length>0?r[0]:null}cacheUserLanguage(s,r){r||(r=this.options.caches),r&&(this.options.excludeCacheFor&&this.options.excludeCacheFor.indexOf(s)>-1||r.forEach(n=>{this.detectors[n]&&this.detectors[n].cacheUserLanguage(s,this.options)}))}}bl.type="languageDetector";const Jm=(...a)=>{console!=null&&console.warn&&(As(a[0])&&(a[0]=`react-i18next:: ${a[0]}`),console.warn(...a))},xl={},jn=(...a)=>{As(a[0])&&xl[a[0]]||(As(a[0])&&(xl[a[0]]=new Date),Jm(...a))},hl=(a,s)=>()=>{if(a.isInitialized)s();else{const r=()=>{setTimeout(()=>{a.off("initialized",r)},0),s()};a.on("initialized",r)}},Hn=(a,s,r)=>{a.loadNamespaces(s,hl(a,r))},wl=(a,s,r,n)=>{if(As(r)&&(r=[r]),a.options.preload&&a.options.preload.indexOf(s)>-1)return Hn(a,r,n);r.forEach(o=>{a.options.ns.indexOf(o)<0&&a.options.ns.push(o)}),a.loadLanguages(s,hl(a,n))},ey=(a,s,r={})=>!s.languages||!s.languages.length?(jn("i18n.languages were undefined or empty",s.languages),!0):s.hasLoadedNamespace(a,{lng:r.lng,precheck:(n,o)=>{var l;if(((l=r.bindI18n)==null?void 0:l.indexOf("languageChanging"))>-1&&n.services.backendConnector.backend&&n.isLanguageChangingTo&&!o(n.isLanguageChangingTo,a))return!1}}),As=a=>typeof a=="string",ty=a=>typeof a=="object"&&a!==null,sy=/&(?:amp|#38|lt|#60|gt|#62|apos|#39|quot|#34|nbsp|#160|copy|#169|reg|#174|hellip|#8230|#x2F|#47);/g,ry={"&amp;":"&","&#38;":"&","&lt;":"<","&#60;":"<","&gt;":">","&#62;":">","&apos;":"'","&#39;":"'","&quot;":'"',"&#34;":'"',"&nbsp;":" ","&#160;":" ","&copy;":"©","&#169;":"©","&reg;":"®","&#174;":"®","&hellip;":"…","&#8230;":"…","&#x2F;":"/","&#47;":"/"},ay=a=>ry[a];let Wn={bindI18n:"languageChanged",bindI18nStore:"",transEmptyNodeValue:"",transSupportBasicHtmlNodes:!0,transWrapTextNodes:"",transKeepBasicHtmlNodesFor:["br","strong","i","p"],useSuspense:!0,unescape:a=>a.replace(sy,ay)};const ny=(a={})=>{Wn={...Wn,...a}},iy=()=>Wn;let vl;const oy=a=>{vl=a},ly=()=>vl,cy={type:"3rdParty",init(a){ny(a.options.react),oy(a)}},py=S.createContext();class dy{constructor(){this.usedNamespaces={}}addUsedNamespaces(s){s.forEach(r=>{this.usedNamespaces[r]||(this.usedNamespaces[r]=!0)})}getUsedNamespaces(){return Object.keys(this.usedNamespaces)}}const uy=(a,s)=>{const r=S.useRef();return S.useEffect(()=>{r.current=s?r.current:a},[a,s]),r.current},Tl=(a,s,r,n)=>a.getFixedT(s,r,n),my=(a,s,r,n)=>S.useCallback(Tl(a,s,r,n),[a,s,r,n]),Ws=(a,s={})=>{var V,Q,q,C;const{i18n:r}=s,{i18n:n,defaultNS:o}=S.useContext(py)||{},l=r||n||ly();if(l&&!l.reportNamespaces&&(l.reportNamespaces=new dy),!l){jn("You will need to pass in an i18next instance by using initReactI18next");const R=(A,O)=>As(O)?O:ty(O)&&As(O.defaultValue)?O.defaultValue:Array.isArray(A)?A[A.length-1]:A,E=[R,{},!1];return E.t=R,E.i18n={},E.ready=!1,E}(V=l.options.react)!=null&&V.wait&&jn("It seems you are still using the old wait option, you may migrate to the new useSuspense behaviour.");const c={...iy(),...l.options.react,...s},{useSuspense:d,keyPrefix:m}=c;let _=a||o||((Q=l.options)==null?void 0:Q.defaultNS);_=As(_)?[_]:_||["translation"],(C=(q=l.reportNamespaces).addUsedNamespaces)==null||C.call(q,_);const g=(l.isInitialized||l.initializedStoreOnce)&&_.every(R=>ey(R,l,c)),x=my(l,s.lng||null,c.nsMode==="fallback"?_:_[0],m),h=()=>x,D=()=>Tl(l,s.lng||null,c.nsMode==="fallback"?_:_[0],m),[z,P]=S.useState(h);let $=_.join();s.lng&&($=`${s.lng}${$}`);const j=uy($),W=S.useRef(!0);S.useEffect(()=>{const{bindI18n:R,bindI18nStore:E}=c;W.current=!0,!g&&!d&&(s.lng?wl(l,s.lng,_,()=>{W.current&&P(D)}):Hn(l,_,()=>{W.current&&P(D)})),g&&j&&j!==$&&W.current&&P(D);const A=()=>{W.current&&P(D)};return R&&(l==null||l.on(R,A)),E&&(l==null||l.store.on(E,A)),()=>{W.current=!1,l&&(R==null||R.split(" ").forEach(O=>l.off(O,A))),E&&l&&E.split(" ").forEach(O=>l.store.off(O,A))}},[l,$]),S.useEffect(()=>{W.current&&g&&P(h)},[l,m,g]);const re=[z,l,g];if(re.t=z,re.i18n=l,re.ready=g,g||!g&&!d)return re;throw new Promise(R=>{s.lng?wl(l,s.lng,_,()=>R()):Hn(l,_,()=>R())})},yy={type:"type",syntax:"syntax",overloads:"overloads",arguments:"arguments",fields:"fields",example:"example",returns:"returns",remarks:"remarks","see also":"see also","Copy code":"Copy code","Copy link":"Copy link",Copied:"Copied","Link copied":"Link copied",variables:"Variables",constants:"Constants",functions:"Functions",keywords:"Keywords",types:"Types",operators:"Operators",annotations:"Annotations",search:"Search","Mine Script® v1 Reference Manual":"Mine Script® v1 Reference Manual","This script is read-only. It cannot be edited.":"This script is read-only. It cannot be edited.","save script":"Save script","open script":"Open script","find/replace":"Find/Replace","toggle console":"Toggle console","open editor in new tab":"Open editor in new tab","open editor in new window":"Open editor in new window",keyword:"keyword","built-in function":"built-in function","built-in variable":"built-in variable","built-in method":"built-in method","built-in type":"built-in type",annotation:"annotation","built-in constant":"built-in constant",namespace:"namespace","user-defined variable":"user-defined variable","user-defined type":"user-defined type",field:"field",enum:"enum","user-defined method":"user-defined method","user-defined function":"user-defined function",parameter:"parameter","**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Tcc functions, variables, and methods.":"**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Mine functions, variables, and methods.","to trigger parameters hint":"to trigger parameters hint",library:"library","enum member":"enum member",Returns:"Returns",Syntax:"Syntax",Remarks:"Remarks",Fields:"Fields",Description:"Description",Example:"Example","Enum members":"Enum members",statement:"statement",loop:"loop","`click` on keyword for more help":"`click` on keyword for more help"},_y={type:"类型",syntax:"语法",overloads:"重载",arguments:"参数",fields:"字段",example:"例子",returns:"返回值",remarks:"备注","see also":"另见","Copy code":"复制代码","Copy link":"复制链接",Copied:"已复制","Link copied":"链接已复制",variables:"内置变量",constants:"常量",functions:"函数",keywords:"关键词",types:"类型",operators:"运算符",annotations:"注释",search:"搜索","Mine Script® v1 Reference Manual":"Mine Script™ v1参考手册","This script is read-only. It cannot be edited.":"该脚本是只读的。它无法被编辑。","save script":"保存脚本","open script":"打开脚本","find/replace":"寻找/替换","toggle console":"切换控制台","open editor in new tab":"在新标签页中打开","open editor in new window":"在新窗口中打开",keyword:"关键词","built-in function":"内置函数","built-in variable":"内置变量","built-in method":"内置方法","built-in type":"内置类型",annotation:"注释","built-in constant":"内置常量",namespace:"命名空间","user-defined variable":"用户自定义变量","user-defined type":"用户自定义类型",field:"字段",enum:"枚举","user-defined method":"用户自定义方法","user-defined function":"用户自定义函数",parameter:"参数","**Namespaces** are immutable terms that act as prefixes for groups of identifiers. A dot and another term always follow a namespace when naming Tcc functions, variables, and methods.":"命名空间是不可变的术语,充当标识符组的前缀。在命名Mine函数、变量和方法时,点和另一个术语始终遵循命名空间。","to trigger parameters hint":"触发参数提示",library:"脚本库","enum member":"枚举成员",Returns:"返回值",Syntax:"语法",Remarks:"备注",Fields:"字段",Description:"描述",Example:"例子","Enum members":"枚举成员",statement:"声明",loop:"循环","`click` on keyword for more help":"“点击”关键词以获得更多帮助"};Me.use(bl).use(cy).init({debug:!1,fallbackLng:"zh",interpolation:{escapeValue:!1},resources:{en:{translation:yy},zh:{translation:_y}}}),self.MonacoEnvironment={getWorker(){return new Fm({name:"Editor Worker"})}},In.config({paths:{vs:"https://cdnjs.cloudflare.com/ajax/libs/monaco-editor/0.45.0/min/vs"},"vs/nls":{availableLanguages:{"*":"zh-cn"}}});const fy=(a,s)=>{const{height:r,width:n,theme:o,options:l,hasDiff:c,readOnly:d,defaultValue:m,language:_,onChange:g,onLinkOpen:x,onCursorPositionChange:h,onActionTrigger:D,onEditorDidMount:z}=a,{t:P,i18n:$}=Ws(),j=S.useRef(null),W=S.useRef(null),re=S.useRef(!1),V=S.useRef(!1);S.useImperativeHandle(s,()=>({setOriginalScript(A){var O;(O=j.current)==null||O.setOriginalScript(A)},setScript(A){var O;(O=j.current)==null||O.setValue(A)},gotoLine(){var A;(A=j.current)==null||A.gotoLine()},getEditorLayout(){var A;return(A=j.current)==null?void 0:A.getEditorLayout()},setPosition(A,O){var J;(J=j.current)==null||J.setPosition({column:A,lineNumber:O})},setModelMarkers(A){var O;V.current=!0,(O=j.current)==null||O.setModelMarkers(A),setTimeout(()=>{V.current=!1},2e3)},focus(){var A;(A=j.current)==null||A.focus()}})),S.useEffect(()=>{var A,O;c?(O=j.current)==null||O.addDiffDecorations():(A=j.current)==null||A.removeDiffDecorations()},[c]),S.useEffect(()=>{o&&Ne.editor.setTheme(o)},[o]),S.useEffect(()=>{_&&$.changeLanguage(_)},[_]),S.useEffect(()=>{var A;(A=j.current)==null||A.updateActionTrigger(D)},[D]),S.useEffect(()=>{var A;x&&((A=j.current)==null||A.addLinkOpenFunc(x))},[x]);function Q(A,O){var se,le;Pt.initBuiltinsTrees(),_a.setEditor(A),j.current=new km(A,O,D),x&&((se=j.current)==null||se.addLinkOpenFunc(x)),c&&((le=j.current)==null||le.addDiffDecorations()),Gu(A),requestAnimationFrame(E);const J=A.getValue();j.current.onChangeCursorPosition(h),g&&g(J),!d&&q(J),z&&z()}const q=S.useCallback(async A=>{var Rt;re.current=!1;const{errors:O,functions:J,methods:se,types:le,variables:Y,overloadsFuncs:oe,imports:xe,enums:pe}=await ml(A),_e=new Map(Object.entries(J)),Ee=new Map(Object.entries(se)),ee=new Map(Object.entries(le)),de=new Map(Object.entries(Y)),Oe=new Map(Object.entries(xe)),Ge=new Map(Object.entries(pe));Ds.setUserDefined({functions:_e,methods:Ee,types:ee,variables:de,imports:Oe,enums:Ge},oe),Pt.setUserDefind(_e,ee,de,Ee,Ge);const Qe=O.map(us=>({...us,severity:us.type||Ne.MarkerSeverity.Error}));d||!re.current&&!V.current&&Qe.length&&((Rt=j.current)==null||Rt.setModelMarkers(Qe))},[d]),C=S.useMemo(()=>Qu.debounce(q,1500),[q]);function R(A){var O;if(d){q(A||"");return}re.current=!0,_a.clearInlayHints(),(O=j.current)==null||O.setModelMarkers([]),A!==void 0&&(g&&g(A),C(A))}const E=S.useCallback(()=>{var O,J;const A=(O=W.current)==null?void 0:O.getBoundingClientRect();(J=j.current)==null||J.setEditorLayout((A==null?void 0:A.height)||0,A==null?void 0:A.width)},[]);return S.useEffect(()=>{const A=()=>{window.requestAnimationFrame(E)},O=new ResizeObserver(A);return W.current&&O.observe(W.current),()=>{var J;W.current&&O.unobserve(W.current),O.disconnect(),(J=j.current)==null||J.dispose()}},[]),T.jsx("div",{ref:W,children:T.jsx(mu,{height:r,width:n||"100%",defaultLanguage:Ke,defaultValue:m||`indicator("我的脚本")
145
145
  plot(close)
146
146
  `,theme:o||"vs-dark",className:`tvue-script ${o||"vs-dark"}`,options:{colorDecorators:!0,useShadowDOM:!1,matchOnWordStartOnly:!0,automaticLayout:!1,unicodeHighlight:{allowedCharacters:{" ":!0}},suggest:{filterGraceful:!0},fontSize:13,...d?am:{},readOnlyMessage:{value:P("This script is read-only. It cannot be edited.")},...l},onMount:Q,onChange:R})})},gy=S.forwardRef(fy),by=a=>{const{theme:s,modified:r,original:n,height:o,width:l,renderSideBySide:c=!0}=a,d=S.useCallback((m,_)=>{_.languages.register({id:Ke}),_.editor.defineTheme("vs-dark",Mn),_.editor.defineTheme("vs",Ln),_.languages.setMonarchTokensProvider(Ke,js),_.languages.setLanguageConfiguration(Ke,En)},[]);return T.jsx(lu,{height:o||"90vh",width:l||"100%",theme:s||"vs-dark",options:{readOnly:!0,renderSideBySide:c,scrollBeyondLastLine:!1},language:Ke,modified:r,original:n,onMount:d})};L.VMarkerSeverity=void 0,function(a){a[a.Hint=1]="Hint",a[a.Info=2]="Info",a[a.Warning=4]="Warning",a[a.Error=8]="Error"}(L.VMarkerSeverity||(L.VMarkerSeverity={}));var Ta={},xy=function(){var a=document.getSelection();if(!a.rangeCount)return function(){};for(var s=document.activeElement,r=[],n=0;n<a.rangeCount;n++)r.push(a.getRangeAt(n));switch(s.tagName.toUpperCase()){case"INPUT":case"TEXTAREA":s.blur();break;default:s=null;break}return a.removeAllRanges(),function(){a.type==="Caret"&&a.removeAllRanges(),a.rangeCount||r.forEach(function(o){a.addRange(o)}),s&&s.focus()}},hy=xy,kl={"text/plain":"Text","text/html":"Url",default:"Text"},wy="Copy to clipboard: #{key}, Enter";function vy(a){var s=(/mac os x/i.test(navigator.userAgent)?"⌘":"Ctrl")+"+C";return a.replace(/#{\s*key\s*}/g,s)}function Ty(a,s){var r,n,o,l,c,d,m=!1;s||(s={}),r=s.debug||!1;try{o=hy(),l=document.createRange(),c=document.getSelection(),d=document.createElement("span"),d.textContent=a,d.ariaHidden="true",d.style.all="unset",d.style.position="fixed",d.style.top=0,d.style.clip="rect(0, 0, 0, 0)",d.style.whiteSpace="pre",d.style.webkitUserSelect="text",d.style.MozUserSelect="text",d.style.msUserSelect="text",d.style.userSelect="text",d.addEventListener("copy",function(g){if(g.stopPropagation(),s.format)if(g.preventDefault(),typeof g.clipboardData>"u"){r&&console.warn("unable to use e.clipboardData"),r&&console.warn("trying IE specific stuff"),window.clipboardData.clearData();var x=kl[s.format]||kl.default;window.clipboardData.setData(x,a)}else g.clipboardData.clearData(),g.clipboardData.setData(s.format,a);s.onCopy&&(g.preventDefault(),s.onCopy(g.clipboardData))}),document.body.appendChild(d),l.selectNodeContents(d),c.addRange(l);var _=document.execCommand("copy");if(!_)throw new Error("copy command was unsuccessful");m=!0}catch(g){r&&console.error("unable to copy using execCommand: ",g),r&&console.warn("trying IE specific stuff");try{window.clipboardData.setData(s.format||"text",a),s.onCopy&&s.onCopy(window.clipboardData),m=!0}catch(x){r&&console.error("unable to copy using clipboardData: ",x),r&&console.error("falling back to prompt"),n=vy("message"in s?s.message:wy),window.prompt(n,a)}}finally{c&&(typeof c.removeRange=="function"?c.removeRange(l):c.removeAllRanges()),d&&document.body.removeChild(d),o()}return m}var ky=Ty;function Vn(a){"@babel/helpers - typeof";return Vn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},Vn(a)}Object.defineProperty(Ta,"__esModule",{value:!0}),Ta.CopyToClipboard=void 0;var ka=Dl(S),Dy=Dl(ky),Iy=["text","onCopy","options","children"];function Dl(a){return a&&a.__esModule?a:{default:a}}function Il(a,s){var r=Object.keys(a);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(a);s&&(n=n.filter(function(o){return Object.getOwnPropertyDescriptor(a,o).enumerable})),r.push.apply(r,n)}return r}function Al(a){for(var s=1;s<arguments.length;s++){var r=arguments[s]!=null?arguments[s]:{};s%2?Il(Object(r),!0).forEach(function(n){Xn(a,n,r[n])}):Object.getOwnPropertyDescriptors?Object.defineProperties(a,Object.getOwnPropertyDescriptors(r)):Il(Object(r)).forEach(function(n){Object.defineProperty(a,n,Object.getOwnPropertyDescriptor(r,n))})}return a}function Ay(a,s){if(a==null)return{};var r=qy(a,s),n,o;if(Object.getOwnPropertySymbols){var l=Object.getOwnPropertySymbols(a);for(o=0;o<l.length;o++)n=l[o],!(s.indexOf(n)>=0)&&Object.prototype.propertyIsEnumerable.call(a,n)&&(r[n]=a[n])}return r}function qy(a,s){if(a==null)return{};var r={},n=Object.keys(a),o,l;for(l=0;l<n.length;l++)o=n[l],!(s.indexOf(o)>=0)&&(r[o]=a[o]);return r}function Cy(a,s){if(!(a instanceof s))throw new TypeError("Cannot call a class as a function")}function ql(a,s){for(var r=0;r<s.length;r++){var n=s[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(a,n.key,n)}}function Sy(a,s,r){return s&&ql(a.prototype,s),r&&ql(a,r),Object.defineProperty(a,"prototype",{writable:!1}),a}function zy(a,s){if(typeof s!="function"&&s!==null)throw new TypeError("Super expression must either be null or a function");a.prototype=Object.create(s&&s.prototype,{constructor:{value:a,writable:!0,configurable:!0}}),Object.defineProperty(a,"prototype",{writable:!1}),s&&Gn(a,s)}function Gn(a,s){return Gn=Object.setPrototypeOf||function(n,o){return n.__proto__=o,n},Gn(a,s)}function Ny(a){var s=Ly();return function(){var n=Da(a),o;if(s){var l=Da(this).constructor;o=Reflect.construct(n,arguments,l)}else o=n.apply(this,arguments);return Ey(this,o)}}function Ey(a,s){if(s&&(Vn(s)==="object"||typeof s=="function"))return s;if(s!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Cl(a)}function Cl(a){if(a===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return a}function Ly(){if(typeof Reflect>"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Da(a){return Da=Object.setPrototypeOf?Object.getPrototypeOf:function(r){return r.__proto__||Object.getPrototypeOf(r)},Da(a)}function Xn(a,s,r){return s in a?Object.defineProperty(a,s,{value:r,enumerable:!0,configurable:!0,writable:!0}):a[s]=r,a}var Sl=function(a){zy(r,a);var s=Ny(r);function r(){var n;Cy(this,r);for(var o=arguments.length,l=new Array(o),c=0;c<o;c++)l[c]=arguments[c];return n=s.call.apply(s,[this].concat(l)),Xn(Cl(n),"onClick",function(d){var m=n.props,_=m.text,g=m.onCopy,x=m.children,h=m.options,D=ka.default.Children.only(x),z=(0,Dy.default)(_,h);g&&g(_,z),D&&D.props&&typeof D.props.onClick=="function"&&D.props.onClick(d)}),n}return Sy(r,[{key:"render",value:function(){var o=this.props;o.text,o.onCopy,o.options;var l=o.children,c=Ay(o,Iy),d=ka.default.Children.only(l);return ka.default.cloneElement(d,Al(Al({},c),{},{onClick:this.onClick}))}}]),r}(ka.default.PureComponent);Ta.CopyToClipboard=Sl,Xn(Sl,"defaultProps",{onCopy:void 0,options:void 0});var My=Ta,Yn=My.CopyToClipboard;Yn.CopyToClipboard=Yn;var Oy=Yn;const Vs=nd(Oy);Ne.languages.register({id:Ke}),Ne.editor.defineTheme("vs-dark",Mn),Ne.editor.defineTheme("vs",Ln),Ne.languages.setMonarchTokensProvider(Ke,js),Ne.languages.setLanguageConfiguration(Ke,En);async function zl(a,s){return s&&Ne.editor.setTheme(s.includes("dark")?"vs-dark":"light"),await Ne.editor.colorize(a,Ke,{tabSize:4})}async function Qn(a,s=0){const r=a[s];if(!r)return;const{name:n,args:o,type:l,desc:c,examples:d,remarks:m,seeAlso:_,syntax:g,detailedDesc:x,fields:h,returns:D}=r,z={name:n,orirginalName:n};if(a.length>1&&(z.overloads=`${a.length} ${Me.t("overloads")}`),l&&(z.type=l),o&&(z.name=`${n}()`,z.args=o.map(P=>{const{name:$,desc:j,displayType:W}=P;return{label:`${$} (${W})`,desc:j&&qs(j)}})),c&&(z.desc=c.map(P=>qs(P))),d&&(z.originalExample=d.join(`
147
147
  `),z.examples=await Ne.editor.colorize(z.originalExample,Ke,{tabSize:4})),x){z.detailedDesc=[];for(const P of x){const{desc:$,examples:j}=P;let W=$.map(Q=>qs(Q)),re,V;j&&(V=j.join(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@guihz/trading-vue-editor-tes",
3
- "version": "0.0.236",
3
+ "version": "0.0.238",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "lib"