coinrayjs 2.0.24 → 2.0.26
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/coinrayjs.es.js +157 -141
- package/dist/coinrayjs.es.js.map +1 -1
- package/dist/coinrayjs.js +2 -2
- package/dist/coinrayjs.js.map +1 -1
- package/dist/types/coinray.d.ts +2 -1
- package/dist/types/coinray.d.ts.map +1 -1
- package/dist/types/current-market.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/coinrayjs.js
CHANGED
|
@@ -30,6 +30,6 @@ function print() { __p += __j.call(arguments, '') }
|
|
|
30
30
|
[`+a+`] `,arguments[0])z(arguments[0],o)&&(i+=o+`: `+arguments[0][o]+`, `);i=i.slice(0,-2)}else i=arguments[a];r.push(i)}Io(e+`
|
|
31
31
|
Arguments: `+Array.prototype.slice.call(r).join(``)+`
|
|
32
32
|
`+Error().stack),n=!1}return t.apply(this,arguments)},t)}var Ro={};function V(e,t){R.deprecationHandler!=null&&R.deprecationHandler(e,t),Ro[e]||(Io(t),Ro[e]=!0)}R.suppressDeprecationWarnings=!1,R.deprecationHandler=null;function zo(e){return typeof Function<`u`&&e instanceof Function||Object.prototype.toString.call(e)===`[object Function]`}function Bo(e){var t,n;for(n in e)z(e,n)&&(t=e[n],zo(t)?this[n]=t:this[`_`+n]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+`|\\d{1,2}`)}function Vo(e,t){var n=To({},e),r;for(r in t)z(t,r)&&(yo(e[r])&&yo(t[r])?(n[r]={},To(n[r],e[r]),To(n[r],t[r])):t[r]==null?delete n[r]:n[r]=t[r]);for(r in e)z(e,r)&&!z(t,r)&&yo(e[r])&&(n[r]=To({},n[r]));return n}function Ho(e){e!=null&&this.set(e)}var Uo=Object.keys?Object.keys:function(e){var t,n=[];for(t in e)z(e,t)&&n.push(t);return n},Wo={sameDay:`[Today at] LT`,nextDay:`[Tomorrow at] LT`,nextWeek:`dddd [at] LT`,lastDay:`[Yesterday at] LT`,lastWeek:`[Last] dddd [at] LT`,sameElse:`L`};function Go(e,t,n){var r=this._calendar[e]||this._calendar.sameElse;return zo(r)?r.call(t,n):r}function Ko(e,t,n){var r=``+Math.abs(e),i=t-r.length;return(e>=0?n?`+`:``:`-`)+(10**Math.max(0,i)).toString().substr(1)+r}var qo=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Jo=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Yo={},Xo={};function H(e,t,n,r){var i=r;typeof r==`string`&&(i=function(){return this[r]()}),e&&(Xo[e]=i),t&&(Xo[t[0]]=function(){return Ko(i.apply(this,arguments),t[1],t[2])}),n&&(Xo[n]=function(){return this.localeData().ordinal(i.apply(this,arguments),e)})}function Zo(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,``):e.replace(/\\/g,``)}function Qo(e){for(var t=e.match(qo),n=0,r=t.length;n<r;n++)Xo[t[n]]?t[n]=Xo[t[n]]:t[n]=Zo(t[n]);return function(n){for(var i=``,a=0;a<r;a++)i+=zo(t[a])?t[a].call(n,e):t[a];return i}}function $o(e,t){return e.isValid()?(t=es(t,e.localeData()),Yo[t]=Yo[t]||Qo(t),Yo[t](e)):e.localeData().invalidDate()}function es(e,t){var n=5;function r(e){return t.longDateFormat(e)||e}for(Jo.lastIndex=0;n>=0&&Jo.test(e);)e=e.replace(Jo,r),Jo.lastIndex=0,--n;return e}var ts={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`};function ns(e){var t=this._longDateFormat[e],n=this._longDateFormat[e.toUpperCase()];return t||!n?t:(this._longDateFormat[e]=n.match(qo).map(function(e){return e===`MMMM`||e===`MM`||e===`DD`||e===`dddd`?e.slice(1):e}).join(``),this._longDateFormat[e])}var rs=`Invalid date`;function is(){return this._invalidDate}var as=`%d`,os=/\d{1,2}/;function ss(e){return this._ordinal.replace(`%d`,e)}var cs={future:`in %s`,past:`%s ago`,s:`a few seconds`,ss:`%d seconds`,m:`a minute`,mm:`%d minutes`,h:`an hour`,hh:`%d hours`,d:`a day`,dd:`%d days`,w:`a week`,ww:`%d weeks`,M:`a month`,MM:`%d months`,y:`a year`,yy:`%d years`};function ls(e,t,n,r){var i=this._relativeTime[n];return zo(i)?i(e,t,n,r):i.replace(/%d/i,e)}function us(e,t){var n=this._relativeTime[e>0?`future`:`past`];return zo(n)?n(t):n.replace(/%s/i,t)}var ds={D:`date`,dates:`date`,date:`date`,d:`day`,days:`day`,day:`day`,e:`weekday`,weekdays:`weekday`,weekday:`weekday`,E:`isoWeekday`,isoweekdays:`isoWeekday`,isoweekday:`isoWeekday`,DDD:`dayOfYear`,dayofyears:`dayOfYear`,dayofyear:`dayOfYear`,h:`hour`,hours:`hour`,hour:`hour`,ms:`millisecond`,milliseconds:`millisecond`,millisecond:`millisecond`,m:`minute`,minutes:`minute`,minute:`minute`,M:`month`,months:`month`,month:`month`,Q:`quarter`,quarters:`quarter`,quarter:`quarter`,s:`second`,seconds:`second`,second:`second`,gg:`weekYear`,weekyears:`weekYear`,weekyear:`weekYear`,GG:`isoWeekYear`,isoweekyears:`isoWeekYear`,isoweekyear:`isoWeekYear`,w:`week`,weeks:`week`,week:`week`,W:`isoWeek`,isoweeks:`isoWeek`,isoweek:`isoWeek`,y:`year`,years:`year`,year:`year`};function fs(e){return typeof e==`string`?ds[e]||ds[e.toLowerCase()]:void 0}function ps(e){var t={},n,r;for(r in e)z(e,r)&&(n=fs(r),n&&(t[n]=e[r]));return t}var ms={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};function hs(e){var t=[],n;for(n in e)z(e,n)&&t.push({unit:n,priority:ms[n]});return t.sort(function(e,t){return e.priority-t.priority}),t}var gs=/\d/,_s=/\d\d/,vs=/\d{3}/,ys=/\d{4}/,bs=/[+-]?\d{6}/,xs=/\d\d?/,Ss=/\d\d\d\d?/,Cs=/\d\d\d\d\d\d?/,ws=/\d{1,3}/,Ts=/\d{1,4}/,Es=/[+-]?\d{1,6}/,Ds=/\d+/,Os=/[+-]?\d+/,ks=/Z|[+-]\d\d:?\d\d/gi,As=/Z|[+-]\d\d(?::?\d\d)?/gi,js=/[+-]?\d+(\.\d{1,3})?/,Ms=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,Ns=/^[1-9]\d?/,Ps=/^([1-9]\d|\d)/,Fs={};function U(e,t,n){Fs[e]=zo(t)?t:function(e,r){return e&&n?n:t}}function Is(e,t){return z(Fs,e)?Fs[e](t._strict,t._locale):new RegExp(Ls(e))}function Ls(e){return Rs(e.replace(`\\`,``).replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(e,t,n,r,i){return t||n||r||i}))}function Rs(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,`\\$&`)}function zs(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function W(e){var t=+e,n=0;return t!==0&&isFinite(t)&&(n=zs(t)),n}var Bs={};function Vs(e,t){var n,r=t,i;for(typeof e==`string`&&(e=[e]),So(t)&&(r=function(e,n){n[t]=W(e)}),i=e.length,n=0;n<i;n++)Bs[e[n]]=r}function Hs(e,t){Vs(e,function(e,n,r,i){r._w=r._w||{},t(e,r._w,r,i)})}function Us(e,t,n){t!=null&&z(Bs,e)&&Bs[e](t,n._a,n,e)}function Ws(e){return e%4==0&&e%100!=0||e%400==0}var Gs=0,Ks=1,qs=2,Js=3,Ys=4,Xs=5,Zs=6,Qs=7,$s=8;H(`Y`,0,0,function(){var e=this.year();return e<=9999?Ko(e,4):`+`+e}),H(0,[`YY`,2],0,function(){return this.year()%100}),H(0,[`YYYY`,4],0,`year`),H(0,[`YYYYY`,5],0,`year`),H(0,[`YYYYYY`,6,!0],0,`year`),U(`Y`,Os),U(`YY`,xs,_s),U(`YYYY`,Ts,ys),U(`YYYYY`,Es,bs),U(`YYYYYY`,Es,bs),Vs([`YYYYY`,`YYYYYY`],Gs),Vs(`YYYY`,function(e,t){t[Gs]=e.length===2?R.parseTwoDigitYear(e):W(e)}),Vs(`YY`,function(e,t){t[Gs]=R.parseTwoDigitYear(e)}),Vs(`Y`,function(e,t){t[Gs]=parseInt(e,10)});function ec(e){return Ws(e)?366:365}R.parseTwoDigitYear=function(e){return W(e)+(W(e)>68?1900:2e3)};var tc=rc(`FullYear`,!0);function nc(){return Ws(this.year())}function rc(e,t){return function(n){return n==null?ic(this,e):(ac(this,e,n),R.updateOffset(this,t),this)}}function ic(e,t){if(!e.isValid())return NaN;var n=e._d,r=e._isUTC;switch(t){case`Milliseconds`:return r?n.getUTCMilliseconds():n.getMilliseconds();case`Seconds`:return r?n.getUTCSeconds():n.getSeconds();case`Minutes`:return r?n.getUTCMinutes():n.getMinutes();case`Hours`:return r?n.getUTCHours():n.getHours();case`Date`:return r?n.getUTCDate():n.getDate();case`Day`:return r?n.getUTCDay():n.getDay();case`Month`:return r?n.getUTCMonth():n.getMonth();case`FullYear`:return r?n.getUTCFullYear():n.getFullYear();default:return NaN}}function ac(e,t,n){var r,i,a,o,s;if(e.isValid()&&!isNaN(n)){switch(r=e._d,i=e._isUTC,t){case`Milliseconds`:i?r.setUTCMilliseconds(n):r.setMilliseconds(n);return;case`Seconds`:i?r.setUTCSeconds(n):r.setSeconds(n);return;case`Minutes`:i?r.setUTCMinutes(n):r.setMinutes(n);return;case`Hours`:i?r.setUTCHours(n):r.setHours(n);return;case`Date`:i?r.setUTCDate(n):r.setDate(n);return;case`FullYear`:break;default:return}a=n,o=e.month(),s=e.date(),s=s===29&&o===1&&!Ws(a)?28:s,i?r.setUTCFullYear(a,o,s):r.setFullYear(a,o,s)}}function oc(e){return e=fs(e),zo(this[e])?this[e]():this}function sc(e,t){if(typeof e==`object`){e=ps(e);var n=hs(e),r,i=n.length;for(r=0;r<i;r++)this[n[r].unit](e[n[r].unit])}else if(e=fs(e),zo(this[e]))return this[e](t);return this}function cc(e,t){return(e%t+t)%t}var lc=Array.prototype.indexOf?Array.prototype.indexOf:function(e){for(var t=0;t<this.length;++t)if(this[t]===e)return t;return-1};function uc(e,t){if(isNaN(e)||isNaN(t))return NaN;var n=cc(t,12);return e+=(t-n)/12,n===1?Ws(e)?29:28:31-n%7%2}H(`M`,[`MM`,2],`Mo`,function(){return this.month()+1}),H(`MMM`,0,0,function(e){return this.localeData().monthsShort(this,e)}),H(`MMMM`,0,0,function(e){return this.localeData().months(this,e)}),U(`M`,xs,Ns),U(`MM`,xs,_s),U(`MMM`,function(e,t){return t.monthsShortRegex(e)}),U(`MMMM`,function(e,t){return t.monthsRegex(e)}),Vs([`M`,`MM`],function(e,t){t[Ks]=W(e)-1}),Vs([`MMM`,`MMMM`],function(e,t,n,r){var i=n._locale.monthsParse(e,r,n._strict);i==null?B(n).invalidMonth=e:t[Ks]=i});var dc=`January_February_March_April_May_June_July_August_September_October_November_December`.split(`_`),fc=`Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec`.split(`_`),pc=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,mc=Ms,hc=Ms;function gc(e,t){return e?vo(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||pc).test(t)?`format`:`standalone`][e.month()]:vo(this._months)?this._months:this._months.standalone}function _c(e,t){return e?vo(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[pc.test(t)?`format`:`standalone`][e.month()]:vo(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function vc(e,t,n){var r,i,a,o=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)a=Eo([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(a,``).toLocaleLowerCase(),this._longMonthsParse[r]=this.months(a,``).toLocaleLowerCase();return n?t===`MMM`?(i=lc.call(this._shortMonthsParse,o),i===-1?null:i):(i=lc.call(this._longMonthsParse,o),i===-1?null:i):t===`MMM`?(i=lc.call(this._shortMonthsParse,o),i===-1?(i=lc.call(this._longMonthsParse,o),i===-1?null:i):i):(i=lc.call(this._longMonthsParse,o),i===-1?(i=lc.call(this._shortMonthsParse,o),i===-1?null:i):i)}function yc(e,t,n){var r,i,a;if(this._monthsParseExact)return vc.call(this,e,t,n);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++)if(i=Eo([2e3,r]),n&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=RegExp(`^`+this.months(i,``).replace(`.`,``)+`$`,`i`),this._shortMonthsParse[r]=RegExp(`^`+this.monthsShort(i,``).replace(`.`,``)+`$`,`i`)),!n&&!this._monthsParse[r]&&(a=`^`+this.months(i,``)+`|^`+this.monthsShort(i,``),this._monthsParse[r]=new RegExp(a.replace(`.`,``),`i`)),n&&t===`MMMM`&&this._longMonthsParse[r].test(e)||n&&t===`MMM`&&this._shortMonthsParse[r].test(e)||!n&&this._monthsParse[r].test(e))return r}function bc(e,t){if(!e.isValid())return e;if(typeof t==`string`){if(/^\d+$/.test(t))t=W(t);else if(t=e.localeData().monthsParse(t),!So(t))return e}var n=t,r=e.date();return r=r<29?r:Math.min(r,uc(e.year(),n)),e._isUTC?e._d.setUTCMonth(n,r):e._d.setMonth(n,r),e}function xc(e){return e==null?ic(this,`Month`):(bc(this,e),R.updateOffset(this,!0),this)}function Sc(){return uc(this.year(),this.month())}function Cc(e){return this._monthsParseExact?(z(this,`_monthsRegex`)||Tc.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(z(this,`_monthsShortRegex`)||(this._monthsShortRegex=mc),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function wc(e){return this._monthsParseExact?(z(this,`_monthsRegex`)||Tc.call(this),e?this._monthsStrictRegex:this._monthsRegex):(z(this,`_monthsRegex`)||(this._monthsRegex=hc),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function Tc(){function e(e,t){return t.length-e.length}for(var t=[],n=[],r=[],i=0,a,o,s;i<12;i++)a=Eo([2e3,i]),o=Rs(this.monthsShort(a,``)),s=Rs(this.months(a,``)),t.push(o),n.push(s),r.push(s),r.push(o);t.sort(e),n.sort(e),r.sort(e),this._monthsRegex=RegExp(`^(`+r.join(`|`)+`)`,`i`),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=RegExp(`^(`+n.join(`|`)+`)`,`i`),this._monthsShortStrictRegex=RegExp(`^(`+t.join(`|`)+`)`,`i`)}function Ec(e,t,n,r,i,a,o){var s;return e<100&&e>=0?(s=new Date(e+400,t,n,r,i,a,o),isFinite(s.getFullYear())&&s.setFullYear(e)):s=new Date(e,t,n,r,i,a,o),s}function Dc(e){var t,n;return e<100&&e>=0?(n=Array.prototype.slice.call(arguments),n[0]=e+400,t=new Date(Date.UTC.apply(null,n)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Oc(e,t,n){var r=7+t-n;return-((7+Dc(e,0,r).getUTCDay()-t)%7)+r-1}function kc(e,t,n,r,i){var a=(7+n-r)%7,o=Oc(e,r,i),s=1+7*(t-1)+a+o,c,l;return s<=0?(c=e-1,l=ec(c)+s):s>ec(e)?(c=e+1,l=s-ec(e)):(c=e,l=s),{year:c,dayOfYear:l}}function Ac(e,t,n){var r=Oc(e.year(),t,n),i=Math.floor((e.dayOfYear()-r-1)/7)+1,a,o;return i<1?(o=e.year()-1,a=i+jc(o,t,n)):i>jc(e.year(),t,n)?(a=i-jc(e.year(),t,n),o=e.year()+1):(o=e.year(),a=i),{week:a,year:o}}function jc(e,t,n){var r=Oc(e,t,n),i=Oc(e+1,t,n);return(ec(e)-r+i)/7}H(`w`,[`ww`,2],`wo`,`week`),H(`W`,[`WW`,2],`Wo`,`isoWeek`),U(`w`,xs,Ns),U(`ww`,xs,_s),U(`W`,xs,Ns),U(`WW`,xs,_s),Hs([`w`,`ww`,`W`,`WW`],function(e,t,n,r){t[r.substr(0,1)]=W(e)});function Mc(e){return Ac(e,this._week.dow,this._week.doy).week}var Nc={dow:0,doy:6};function Pc(){return this._week.dow}function Fc(){return this._week.doy}function Ic(e){var t=this.localeData().week(this);return e==null?t:this.add((e-t)*7,`d`)}function Lc(e){var t=Ac(this,1,4).week;return e==null?t:this.add((e-t)*7,`d`)}H(`d`,0,`do`,`day`),H(`dd`,0,0,function(e){return this.localeData().weekdaysMin(this,e)}),H(`ddd`,0,0,function(e){return this.localeData().weekdaysShort(this,e)}),H(`dddd`,0,0,function(e){return this.localeData().weekdays(this,e)}),H(`e`,0,0,`weekday`),H(`E`,0,0,`isoWeekday`),U(`d`,xs),U(`e`,xs),U(`E`,xs),U(`dd`,function(e,t){return t.weekdaysMinRegex(e)}),U(`ddd`,function(e,t){return t.weekdaysShortRegex(e)}),U(`dddd`,function(e,t){return t.weekdaysRegex(e)}),Hs([`dd`,`ddd`,`dddd`],function(e,t,n,r){var i=n._locale.weekdaysParse(e,r,n._strict);i==null?B(n).invalidWeekday=e:t.d=i}),Hs([`d`,`e`,`E`],function(e,t,n,r){t[r]=W(e)});function Rc(e,t){return typeof e==`string`?isNaN(e)?(e=t.weekdaysParse(e),typeof e==`number`?e:null):parseInt(e,10):e}function zc(e,t){return typeof e==`string`?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Bc(e,t){return e.slice(t,7).concat(e.slice(0,t))}var Vc=`Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday`.split(`_`),Hc=`Sun_Mon_Tue_Wed_Thu_Fri_Sat`.split(`_`),Uc=`Su_Mo_Tu_We_Th_Fr_Sa`.split(`_`),Wc=Ms,Gc=Ms,Kc=Ms;function qc(e,t){var n=vo(this._weekdays)?this._weekdays:this._weekdays[e&&e!==!0&&this._weekdays.isFormat.test(t)?`format`:`standalone`];return e===!0?Bc(n,this._week.dow):e?n[e.day()]:n}function Jc(e){return e===!0?Bc(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function Yc(e){return e===!0?Bc(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function Xc(e,t,n){var r,i,a,o=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)a=Eo([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(a,``).toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(a,``).toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(a,``).toLocaleLowerCase();return n?t===`dddd`?(i=lc.call(this._weekdaysParse,o),i===-1?null:i):t===`ddd`?(i=lc.call(this._shortWeekdaysParse,o),i===-1?null:i):(i=lc.call(this._minWeekdaysParse,o),i===-1?null:i):t===`dddd`?(i=lc.call(this._weekdaysParse,o),i!==-1||(i=lc.call(this._shortWeekdaysParse,o),i!==-1)?i:(i=lc.call(this._minWeekdaysParse,o),i===-1?null:i)):t===`ddd`?(i=lc.call(this._shortWeekdaysParse,o),i!==-1||(i=lc.call(this._weekdaysParse,o),i!==-1)?i:(i=lc.call(this._minWeekdaysParse,o),i===-1?null:i)):(i=lc.call(this._minWeekdaysParse,o),i!==-1||(i=lc.call(this._weekdaysParse,o),i!==-1)?i:(i=lc.call(this._shortWeekdaysParse,o),i===-1?null:i))}function Zc(e,t,n){var r,i,a;if(this._weekdaysParseExact)return Xc.call(this,e,t,n);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++)if(i=Eo([2e3,1]).day(r),n&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=RegExp(`^`+this.weekdays(i,``).replace(`.`,`\\.?`)+`$`,`i`),this._shortWeekdaysParse[r]=RegExp(`^`+this.weekdaysShort(i,``).replace(`.`,`\\.?`)+`$`,`i`),this._minWeekdaysParse[r]=RegExp(`^`+this.weekdaysMin(i,``).replace(`.`,`\\.?`)+`$`,`i`)),this._weekdaysParse[r]||(a=`^`+this.weekdays(i,``)+`|^`+this.weekdaysShort(i,``)+`|^`+this.weekdaysMin(i,``),this._weekdaysParse[r]=new RegExp(a.replace(`.`,``),`i`)),n&&t===`dddd`&&this._fullWeekdaysParse[r].test(e)||n&&t===`ddd`&&this._shortWeekdaysParse[r].test(e)||n&&t===`dd`&&this._minWeekdaysParse[r].test(e)||!n&&this._weekdaysParse[r].test(e))return r}function Qc(e){if(!this.isValid())return e==null?NaN:this;var t=ic(this,`Day`);return e==null?t:(e=Rc(e,this.localeData()),this.add(e-t,`d`))}function $c(e){if(!this.isValid())return e==null?NaN:this;var t=(this.day()+7-this.localeData()._week.dow)%7;return e==null?t:this.add(e-t,`d`)}function el(e){if(!this.isValid())return e==null?NaN:this;if(e!=null){var t=zc(e,this.localeData());return this.day(this.day()%7?t:t-7)}return this.day()||7}function tl(e){return this._weekdaysParseExact?(z(this,`_weekdaysRegex`)||il.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(z(this,`_weekdaysRegex`)||(this._weekdaysRegex=Wc),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function nl(e){return this._weekdaysParseExact?(z(this,`_weekdaysRegex`)||il.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(z(this,`_weekdaysShortRegex`)||(this._weekdaysShortRegex=Gc),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function rl(e){return this._weekdaysParseExact?(z(this,`_weekdaysRegex`)||il.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(z(this,`_weekdaysMinRegex`)||(this._weekdaysMinRegex=Kc),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function il(){function e(e,t){return t.length-e.length}for(var t=[],n=[],r=[],i=[],a=0,o,s,c,l;a<7;a++)o=Eo([2e3,1]).day(a),s=Rs(this.weekdaysMin(o,``)),c=Rs(this.weekdaysShort(o,``)),l=Rs(this.weekdays(o,``)),t.push(s),n.push(c),r.push(l),i.push(s),i.push(c),i.push(l);t.sort(e),n.sort(e),r.sort(e),i.sort(e),this._weekdaysRegex=RegExp(`^(`+i.join(`|`)+`)`,`i`),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=RegExp(`^(`+r.join(`|`)+`)`,`i`),this._weekdaysShortStrictRegex=RegExp(`^(`+n.join(`|`)+`)`,`i`),this._weekdaysMinStrictRegex=RegExp(`^(`+t.join(`|`)+`)`,`i`)}function al(){return this.hours()%12||12}function ol(){return this.hours()||24}H(`H`,[`HH`,2],0,`hour`),H(`h`,[`hh`,2],0,al),H(`k`,[`kk`,2],0,ol),H(`hmm`,0,0,function(){return``+al.apply(this)+Ko(this.minutes(),2)}),H(`hmmss`,0,0,function(){return``+al.apply(this)+Ko(this.minutes(),2)+Ko(this.seconds(),2)}),H(`Hmm`,0,0,function(){return``+this.hours()+Ko(this.minutes(),2)}),H(`Hmmss`,0,0,function(){return``+this.hours()+Ko(this.minutes(),2)+Ko(this.seconds(),2)});function sl(e,t){H(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}sl(`a`,!0),sl(`A`,!1);function cl(e,t){return t._meridiemParse}U(`a`,cl),U(`A`,cl),U(`H`,xs,Ps),U(`h`,xs,Ns),U(`k`,xs,Ns),U(`HH`,xs,_s),U(`hh`,xs,_s),U(`kk`,xs,_s),U(`hmm`,Ss),U(`hmmss`,Cs),U(`Hmm`,Ss),U(`Hmmss`,Cs),Vs([`H`,`HH`],Js),Vs([`k`,`kk`],function(e,t,n){var r=W(e);t[Js]=r===24?0:r}),Vs([`a`,`A`],function(e,t,n){n._isPm=n._locale.isPM(e),n._meridiem=e}),Vs([`h`,`hh`],function(e,t,n){t[Js]=W(e),B(n).bigHour=!0}),Vs(`hmm`,function(e,t,n){var r=e.length-2;t[Js]=W(e.substr(0,r)),t[Ys]=W(e.substr(r)),B(n).bigHour=!0}),Vs(`hmmss`,function(e,t,n){var r=e.length-4,i=e.length-2;t[Js]=W(e.substr(0,r)),t[Ys]=W(e.substr(r,2)),t[Xs]=W(e.substr(i)),B(n).bigHour=!0}),Vs(`Hmm`,function(e,t,n){var r=e.length-2;t[Js]=W(e.substr(0,r)),t[Ys]=W(e.substr(r))}),Vs(`Hmmss`,function(e,t,n){var r=e.length-4,i=e.length-2;t[Js]=W(e.substr(0,r)),t[Ys]=W(e.substr(r,2)),t[Xs]=W(e.substr(i))});function ll(e){return(e+``).toLowerCase().charAt(0)===`p`}var ul=/[ap]\.?m?\.?/i,dl=rc(`Hours`,!0);function fl(e,t,n){return e>11?n?`pm`:`PM`:n?`am`:`AM`}var pl={calendar:Wo,longDateFormat:ts,invalidDate:rs,ordinal:as,dayOfMonthOrdinalParse:os,relativeTime:cs,months:dc,monthsShort:fc,week:Nc,weekdays:Vc,weekdaysMin:Uc,weekdaysShort:Hc,meridiemParse:ul},ml={},hl={},gl;function _l(e,t){var n,r=Math.min(e.length,t.length);for(n=0;n<r;n+=1)if(e[n]!==t[n])return n;return r}function vl(e){return e&&e.toLowerCase().replace(`_`,`-`)}function yl(e){for(var t=0,n,r,i,a;t<e.length;){for(a=vl(e[t]).split(`-`),n=a.length,r=vl(e[t+1]),r=r?r.split(`-`):null;n>0;){if(i=xl(a.slice(0,n).join(`-`)),i)return i;if(r&&r.length>=n&&_l(a,r)>=n-1)break;n--}t++}return gl}function bl(e){return!!(e&&e.match(`^[^/\\\\]*$`))}function xl(e){var t=null,n;if(ml[e]===void 0&&typeof module<`u`&&module&&module.exports&&bl(e))try{t=gl._abbr,n=require,n(`./locale/`+e),Sl(t)}catch{ml[e]=null}return ml[e]}function Sl(e,t){var n;return e&&(n=xo(t)?Tl(e):Cl(e,t),n?gl=n:typeof console<`u`&&console.warn&&console.warn(`Locale `+e+` not found. Did you forget to load it?`)),gl._abbr}function Cl(e,t){if(t!==null){var n,r=pl;if(t.abbr=e,ml[e]!=null)V(`defineLocaleOverride`,`use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info.`),r=ml[e]._config;else if(t.parentLocale!=null){if(ml[t.parentLocale]!=null)r=ml[t.parentLocale]._config;else if(n=xl(t.parentLocale),n!=null)r=n._config;else return hl[t.parentLocale]||(hl[t.parentLocale]=[]),hl[t.parentLocale].push({name:e,config:t}),null}return ml[e]=new Ho(Vo(r,t)),hl[e]&&hl[e].forEach(function(e){Cl(e.name,e.config)}),Sl(e),ml[e]}return delete ml[e],null}function wl(e,t){if(t!=null){var n,r,i=pl;ml[e]!=null&&ml[e].parentLocale!=null?ml[e].set(Vo(ml[e]._config,t)):(r=xl(e),r!=null&&(i=r._config),t=Vo(i,t),r??(t.abbr=e),n=new Ho(t),n.parentLocale=ml[e],ml[e]=n),Sl(e)}else ml[e]!=null&&(ml[e].parentLocale==null?ml[e]!=null&&delete ml[e]:(ml[e]=ml[e].parentLocale,e===Sl()&&Sl(e)));return ml[e]}function Tl(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return gl;if(!vo(e)){if(t=xl(e),t)return t;e=[e]}return yl(e)}function El(){return Uo(ml)}function Dl(e){var t,n=e._a;return n&&B(e).overflow===-2&&(t=n[Ks]<0||n[Ks]>11?Ks:n[qs]<1||n[qs]>uc(n[Gs],n[Ks])?qs:n[Js]<0||n[Js]>24||n[Js]===24&&(n[Ys]!==0||n[Xs]!==0||n[Zs]!==0)?Js:n[Ys]<0||n[Ys]>59?Ys:n[Xs]<0||n[Xs]>59?Xs:n[Zs]<0||n[Zs]>999?Zs:-1,B(e)._overflowDayOfYear&&(t<Gs||t>qs)&&(t=qs),B(e)._overflowWeeks&&t===-1&&(t=Qs),B(e)._overflowWeekday&&t===-1&&(t=$s),B(e).overflow=t),e}var Ol=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,kl=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,Al=/Z|[+-]\d\d(?::?\d\d)?/,jl=[[`YYYYYY-MM-DD`,/[+-]\d{6}-\d\d-\d\d/],[`YYYY-MM-DD`,/\d{4}-\d\d-\d\d/],[`GGGG-[W]WW-E`,/\d{4}-W\d\d-\d/],[`GGGG-[W]WW`,/\d{4}-W\d\d/,!1],[`YYYY-DDD`,/\d{4}-\d{3}/],[`YYYY-MM`,/\d{4}-\d\d/,!1],[`YYYYYYMMDD`,/[+-]\d{10}/],[`YYYYMMDD`,/\d{8}/],[`GGGG[W]WWE`,/\d{4}W\d{3}/],[`GGGG[W]WW`,/\d{4}W\d{2}/,!1],[`YYYYDDD`,/\d{7}/],[`YYYYMM`,/\d{6}/,!1],[`YYYY`,/\d{4}/,!1]],Ml=[[`HH:mm:ss.SSSS`,/\d\d:\d\d:\d\d\.\d+/],[`HH:mm:ss,SSSS`,/\d\d:\d\d:\d\d,\d+/],[`HH:mm:ss`,/\d\d:\d\d:\d\d/],[`HH:mm`,/\d\d:\d\d/],[`HHmmss.SSSS`,/\d\d\d\d\d\d\.\d+/],[`HHmmss,SSSS`,/\d\d\d\d\d\d,\d+/],[`HHmmss`,/\d\d\d\d\d\d/],[`HHmm`,/\d\d\d\d/],[`HH`,/\d\d/]],Nl=/^\/?Date\((-?\d+)/i,Pl=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,Fl={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function Il(e){var t,n,r=e._i,i=Ol.exec(r)||kl.exec(r),a,o,s,c,l=jl.length,u=Ml.length;if(i){for(B(e).iso=!0,t=0,n=l;t<n;t++)if(jl[t][1].exec(i[1])){o=jl[t][0],a=jl[t][2]!==!1;break}if(o==null){e._isValid=!1;return}if(i[3]){for(t=0,n=u;t<n;t++)if(Ml[t][1].exec(i[3])){s=(i[2]||` `)+Ml[t][0];break}if(s==null){e._isValid=!1;return}}if(!a&&s!=null){e._isValid=!1;return}if(i[4]){if(Al.exec(i[4]))c=`Z`;else{e._isValid=!1;return}}e._f=o+(s||``)+(c||``),Jl(e)}else e._isValid=!1}function Ll(e,t,n,r,i,a){var o=[Rl(e),fc.indexOf(t),parseInt(n,10),parseInt(r,10),parseInt(i,10)];return a&&o.push(parseInt(a,10)),o}function Rl(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function zl(e){return e.replace(/\([^()]*\)|[\n\t]/g,` `).replace(/(\s\s+)/g,` `).replace(/^\s\s*/,``).replace(/\s\s*$/,``)}function Bl(e,t,n){return e&&Hc.indexOf(e)!==new Date(t[0],t[1],t[2]).getDay()?(B(n).weekdayMismatch=!0,n._isValid=!1,!1):!0}function Vl(e,t,n){if(e)return Fl[e];if(t)return 0;var r=parseInt(n,10),i=r%100;return(r-i)/100*60+i}function Hl(e){var t=Pl.exec(zl(e._i)),n;if(t){if(n=Ll(t[4],t[3],t[2],t[5],t[6],t[7]),!Bl(t[1],n,e))return;e._a=n,e._tzm=Vl(t[8],t[9],t[10]),e._d=Dc.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),B(e).rfc2822=!0}else e._isValid=!1}function Ul(e){var t=Nl.exec(e._i);if(t!==null){e._d=new Date(+t[1]);return}if(Il(e),e._isValid===!1)delete e._isValid;else return;if(Hl(e),e._isValid===!1)delete e._isValid;else return;e._strict?e._isValid=!1:R.createFromInputFallback(e)}R.createFromInputFallback=Lo(`value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.`,function(e){e._d=new Date(e._i+(e._useUTC?` UTC`:``))});function Wl(e,t,n){return e??t??n}function Gl(e){var t=new Date(R.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function Kl(e){var t,n,r=[],i,a,o;if(!e._d){for(i=Gl(e),e._w&&e._a[qs]==null&&e._a[Ks]==null&&ql(e),e._dayOfYear!=null&&(o=Wl(e._a[Gs],i[Gs]),(e._dayOfYear>ec(o)||e._dayOfYear===0)&&(B(e)._overflowDayOfYear=!0),n=Dc(o,0,e._dayOfYear),e._a[Ks]=n.getUTCMonth(),e._a[qs]=n.getUTCDate()),t=0;t<3&&e._a[t]==null;++t)e._a[t]=r[t]=i[t];for(;t<7;t++)e._a[t]=r[t]=e._a[t]==null?+(t===2):e._a[t];e._a[Js]===24&&e._a[Ys]===0&&e._a[Xs]===0&&e._a[Zs]===0&&(e._nextDay=!0,e._a[Js]=0),e._d=(e._useUTC?Dc:Ec).apply(null,r),a=e._useUTC?e._d.getUTCDay():e._d.getDay(),e._tzm!=null&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[Js]=24),e._w&&e._w.d!==void 0&&e._w.d!==a&&(B(e).weekdayMismatch=!0)}}function ql(e){var t=e._w,n,r,i,a,o,s,c,l;t.GG!=null||t.W!=null||t.E!=null?(a=1,o=4,n=Wl(t.GG,e._a[Gs],Ac(K(),1,4).year),r=Wl(t.W,1),i=Wl(t.E,1),(i<1||i>7)&&(c=!0)):(a=e._locale._week.dow,o=e._locale._week.doy,l=Ac(K(),a,o),n=Wl(t.gg,e._a[Gs],l.year),r=Wl(t.w,l.week),t.d==null?t.e==null?i=a:(i=t.e+a,(t.e<0||t.e>6)&&(c=!0)):(i=t.d,(i<0||i>6)&&(c=!0))),r<1||r>jc(n,a,o)?B(e)._overflowWeeks=!0:c==null?(s=kc(n,r,i,a,o),e._a[Gs]=s.year,e._dayOfYear=s.dayOfYear):B(e)._overflowWeekday=!0}R.ISO_8601=function(){},R.RFC_2822=function(){};function Jl(e){if(e._f===R.ISO_8601){Il(e);return}if(e._f===R.RFC_2822){Hl(e);return}e._a=[],B(e).empty=!0;var t=``+e._i,n,r,i,a,o,s=t.length,c=0,l,u;for(i=es(e._f,e._locale).match(qo)||[],u=i.length,n=0;n<u;n++)a=i[n],r=(t.match(Is(a,e))||[])[0],r&&(o=t.substr(0,t.indexOf(r)),o.length>0&&B(e).unusedInput.push(o),t=t.slice(t.indexOf(r)+r.length),c+=r.length),Xo[a]?(r?B(e).empty=!1:B(e).unusedTokens.push(a),Us(a,r,e)):e._strict&&!r&&B(e).unusedTokens.push(a);B(e).charsLeftOver=s-c,t.length>0&&B(e).unusedInput.push(t),e._a[Js]<=12&&B(e).bigHour===!0&&e._a[Js]>0&&(B(e).bigHour=void 0),B(e).parsedDateParts=e._a.slice(0),B(e).meridiem=e._meridiem,e._a[Js]=Yl(e._locale,e._a[Js],e._meridiem),l=B(e).era,l!==null&&(e._a[Gs]=e._locale.erasConvertYear(l,e._a[Gs])),Kl(e),Dl(e)}function Yl(e,t,n){var r;return n==null?t:e.meridiemHour==null?e.isPM==null?t:(r=e.isPM(n),r&&t<12&&(t+=12),!r&&t===12&&(t=0),t):e.meridiemHour(t,n)}function Xl(e){var t,n,r,i,a,o,s=!1,c=e._f.length;if(c===0){B(e).invalidFormat=!0,e._d=new Date(NaN);return}for(i=0;i<c;i++)a=0,o=!1,t=No({},e),e._useUTC!=null&&(t._useUTC=e._useUTC),t._f=e._f[i],Jl(t),ko(t)&&(o=!0),a+=B(t).charsLeftOver,a+=B(t).unusedTokens.length*10,B(t).score=a,s?a<r&&(r=a,n=t):(r==null||a<r||o)&&(r=a,n=t,o&&(s=!0));To(e,n||t)}function Zl(e){if(!e._d){var t=ps(e._i),n=t.day===void 0?t.date:t.day;e._a=wo([t.year,t.month,n,t.hour,t.minute,t.second,t.millisecond],function(e){return e&&parseInt(e,10)}),Kl(e)}}function Ql(e){var t=new Po(Dl(G(e)));return t._nextDay&&=(t.add(1,`d`),void 0),t}function G(e){var t=e._i,n=e._f;return e._locale=e._locale||Tl(e._l),t===null||n===void 0&&t===``?Ao({nullInput:!0}):(typeof t==`string`&&(e._i=t=e._locale.preparse(t)),Fo(t)?new Po(Dl(t)):(Co(t)?e._d=t:vo(n)?Xl(e):n?Jl(e):$l(e),ko(e)||(e._d=null),e))}function $l(e){var t=e._i;xo(t)?e._d=new Date(R.now()):Co(t)?e._d=new Date(t.valueOf()):typeof t==`string`?Ul(e):vo(t)?(e._a=wo(t.slice(0),function(e){return parseInt(e,10)}),Kl(e)):yo(t)?Zl(e):So(t)?e._d=new Date(t):R.createFromInputFallback(e)}function eu(e,t,n,r,i){var a={};return(t===!0||t===!1)&&(r=t,t=void 0),(n===!0||n===!1)&&(r=n,n=void 0),(yo(e)&&bo(e)||vo(e)&&e.length===0)&&(e=void 0),a._isAMomentObject=!0,a._useUTC=a._isUTC=i,a._l=n,a._i=e,a._f=t,a._strict=r,Ql(a)}function K(e,t,n,r){return eu(e,t,n,r,!1)}var tu=Lo(`moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/`,function(){var e=K.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:Ao()}),nu=Lo(`moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/`,function(){var e=K.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:Ao()});function ru(e,t){var n,r;if(t.length===1&&vo(t[0])&&(t=t[0]),!t.length)return K();for(n=t[0],r=1;r<t.length;++r)(!t[r].isValid()||t[r][e](n))&&(n=t[r]);return n}function iu(){return ru(`isBefore`,[].slice.call(arguments,0))}function au(){return ru(`isAfter`,[].slice.call(arguments,0))}var ou=function(){return Date.now?Date.now():+new Date},su=[`year`,`quarter`,`month`,`week`,`day`,`hour`,`minute`,`second`,`millisecond`];function cu(e){var t,n=!1,r,i=su.length;for(t in e)if(z(e,t)&&(lc.call(su,t)===-1||e[t]!=null&&isNaN(e[t])))return!1;for(r=0;r<i;++r)if(e[su[r]]){if(n)return!1;parseFloat(e[su[r]])!==W(e[su[r]])&&(n=!0)}return!0}function lu(){return this._isValid}function uu(){return Nu(NaN)}function du(e){var t=ps(e),n=t.year||0,r=t.quarter||0,i=t.month||0,a=t.week||t.isoWeek||0,o=t.day||0,s=t.hour||0,c=t.minute||0,l=t.second||0,u=t.millisecond||0;this._isValid=cu(t),this._milliseconds=+u+l*1e3+c*6e4+s*1e3*60*60,this._days=+o+a*7,this._months=+i+r*3+n*12,this._data={},this._locale=Tl(),this._bubble()}function fu(e){return e instanceof du}function pu(e){return e<0?Math.round(-1*e)*-1:Math.round(e)}function mu(e,t,n){for(var r=Math.min(e.length,t.length),i=Math.abs(e.length-t.length),a=0,o=0;o<r;o++)(n&&e[o]!==t[o]||!n&&W(e[o])!==W(t[o]))&&a++;return a+i}function hu(e,t){H(e,0,0,function(){var e=this.utcOffset(),n=`+`;return e<0&&(e=-e,n=`-`),n+Ko(~~(e/60),2)+t+Ko(~~e%60,2)})}hu(`Z`,`:`),hu(`ZZ`,``),U(`Z`,As),U(`ZZ`,As),Vs([`Z`,`ZZ`],function(e,t,n){n._useUTC=!0,n._tzm=_u(As,e)});var gu=/([\+\-]|\d\d)/gi;function _u(e,t){var n=(t||``).match(e),r,i,a;return n===null?null:(r=n[n.length-1]||[],i=(r+``).match(gu)||[`-`,0,0],a=+(i[1]*60)+W(i[2]),a===0?0:i[0]===`+`?a:-a)}function vu(e,t){var n,r;return t._isUTC?(n=t.clone(),r=(Fo(e)||Co(e)?e.valueOf():K(e).valueOf())-n.valueOf(),n._d.setTime(n._d.valueOf()+r),R.updateOffset(n,!1),n):K(e).local()}function yu(e){return-Math.round(e._d.getTimezoneOffset())}R.updateOffset=function(){};function bu(e,t,n){var r=this._offset||0,i;if(!this.isValid())return e==null?NaN:this;if(e!=null){if(typeof e==`string`){if(e=_u(As,e),e===null)return this}else Math.abs(e)<16&&!n&&(e*=60);return!this._isUTC&&t&&(i=yu(this)),this._offset=e,this._isUTC=!0,i!=null&&this.add(i,`m`),r!==e&&(!t||this._changeInProgress?Lu(this,Nu(e-r,`m`),1,!1):this._changeInProgress||=(this._changeInProgress=!0,R.updateOffset(this,!0),null)),this}return this._isUTC?r:yu(this)}function xu(e,t){return e==null?-this.utcOffset():(typeof e!=`string`&&(e=-e),this.utcOffset(e,t),this)}function Su(e){return this.utcOffset(0,e)}function Cu(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(yu(this),`m`)),this}function wu(){if(this._tzm!=null)this.utcOffset(this._tzm,!1,!0);else if(typeof this._i==`string`){var e=_u(ks,this._i);e==null?this.utcOffset(0,!0):this.utcOffset(e)}return this}function Tu(e){return this.isValid()?(e=e?K(e).utcOffset():0,(this.utcOffset()-e)%60==0):!1}function Eu(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Du(){if(!xo(this._isDSTShifted))return this._isDSTShifted;var e={},t;return No(e,this),e=G(e),e._a?(t=e._isUTC?Eo(e._a):K(e._a),this._isDSTShifted=this.isValid()&&mu(e._a,t.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function Ou(){return this.isValid()?!this._isUTC:!1}function ku(){return this.isValid()?this._isUTC:!1}function Au(){return this.isValid()?this._isUTC&&this._offset===0:!1}var ju=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Mu=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Nu(e,t){var n=e,r=null,i,a,o;return fu(e)?n={ms:e._milliseconds,d:e._days,M:e._months}:So(e)||!isNaN(+e)?(n={},t?n[t]=+e:n.milliseconds=+e):(r=ju.exec(e))?(i=r[1]===`-`?-1:1,n={y:0,d:W(r[qs])*i,h:W(r[Js])*i,m:W(r[Ys])*i,s:W(r[Xs])*i,ms:W(pu(r[Zs]*1e3))*i}):(r=Mu.exec(e))?(i=r[1]===`-`?-1:1,n={y:Pu(r[2],i),M:Pu(r[3],i),w:Pu(r[4],i),d:Pu(r[5],i),h:Pu(r[6],i),m:Pu(r[7],i),s:Pu(r[8],i)}):n==null?n={}:typeof n==`object`&&(`from`in n||`to`in n)&&(o=Iu(K(n.from),K(n.to)),n={},n.ms=o.milliseconds,n.M=o.months),a=new du(n),fu(e)&&z(e,`_locale`)&&(a._locale=e._locale),fu(e)&&z(e,`_isValid`)&&(a._isValid=e._isValid),a}Nu.fn=du.prototype,Nu.invalid=uu;function Pu(e,t){var n=e&&parseFloat(e.replace(`,`,`.`));return(isNaN(n)?0:n)*t}function Fu(e,t){var n={};return n.months=t.month()-e.month()+(t.year()-e.year())*12,e.clone().add(n.months,`M`).isAfter(t)&&--n.months,n.milliseconds=+t-e.clone().add(n.months,`M`),n}function Iu(e,t){var n;return e.isValid()&&t.isValid()?(t=vu(t,e),e.isBefore(t)?n=Fu(e,t):(n=Fu(t,e),n.milliseconds=-n.milliseconds,n.months=-n.months),n):{milliseconds:0,months:0}}function q(e,t){return function(n,r){var i,a;return r!==null&&!isNaN(+r)&&(V(t,`moment().`+t+`(period, number) is deprecated. Please use moment().`+t+`(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info.`),a=n,n=r,r=a),i=Nu(n,r),Lu(this,i,e),this}}function Lu(e,t,n,r){var i=t._milliseconds,a=pu(t._days),o=pu(t._months);e.isValid()&&(r??=!0,o&&bc(e,ic(e,`Month`)+o*n),a&&ac(e,`Date`,ic(e,`Date`)+a*n),i&&e._d.setTime(e._d.valueOf()+i*n),r&&R.updateOffset(e,a||o))}var Ru=q(1,`add`),zu=q(-1,`subtract`);function Bu(e){return typeof e==`string`||e instanceof String}function J(e){return Fo(e)||Co(e)||Bu(e)||So(e)||Hu(e)||Vu(e)||e==null}function Vu(e){var t=yo(e)&&!bo(e),n=!1,r=[`years`,`year`,`y`,`months`,`month`,`M`,`days`,`day`,`d`,`dates`,`date`,`D`,`hours`,`hour`,`h`,`minutes`,`minute`,`m`,`seconds`,`second`,`s`,`milliseconds`,`millisecond`,`ms`],i,a,o=r.length;for(i=0;i<o;i+=1)a=r[i],n||=z(e,a);return t&&n}function Hu(e){var t=vo(e),n=!1;return t&&(n=e.filter(function(t){return!So(t)&&Bu(e)}).length===0),t&&n}function Uu(e){for(var t=yo(e)&&!bo(e),n=!1,r=[`sameDay`,`nextDay`,`lastDay`,`nextWeek`,`lastWeek`,`sameElse`],i=0,a;i<r.length;i+=1)a=r[i],n||=z(e,a);return t&&n}function Wu(e,t){var n=e.diff(t,`days`,!0);return n<-6?`sameElse`:n<-1?`lastWeek`:n<0?`lastDay`:n<1?`sameDay`:n<2?`nextDay`:n<7?`nextWeek`:`sameElse`}function Gu(e,t){arguments.length===1&&(arguments[0]?J(arguments[0])?(e=arguments[0],t=void 0):Uu(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var n=e||K(),r=vu(n,this).startOf(`day`),i=R.calendarFormat(this,r)||`sameElse`,a=t&&(zo(t[i])?t[i].call(this,n):t[i]);return this.format(a||this.localeData().calendar(i,this,K(n)))}function Ku(){return new Po(this)}function qu(e,t){var n=Fo(e)?e:K(e);return this.isValid()&&n.isValid()?(t=fs(t)||`millisecond`,t===`millisecond`?this.valueOf()>n.valueOf():n.valueOf()<this.clone().startOf(t).valueOf()):!1}function Ju(e,t){var n=Fo(e)?e:K(e);return this.isValid()&&n.isValid()?(t=fs(t)||`millisecond`,t===`millisecond`?this.valueOf()<n.valueOf():this.clone().endOf(t).valueOf()<n.valueOf()):!1}function Yu(e,t,n,r){var i=Fo(e)?e:K(e),a=Fo(t)?t:K(t);return this.isValid()&&i.isValid()&&a.isValid()?(r||=`()`,(r[0]===`(`?this.isAfter(i,n):!this.isBefore(i,n))&&(r[1]===`)`?this.isBefore(a,n):!this.isAfter(a,n))):!1}function Xu(e,t){var n=Fo(e)?e:K(e),r;return this.isValid()&&n.isValid()?(t=fs(t)||`millisecond`,t===`millisecond`?this.valueOf()===n.valueOf():(r=n.valueOf(),this.clone().startOf(t).valueOf()<=r&&r<=this.clone().endOf(t).valueOf())):!1}function Zu(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function Qu(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function $u(e,t,n){var r,i,a;if(!this.isValid()||(r=vu(e,this),!r.isValid()))return NaN;switch(i=(r.utcOffset()-this.utcOffset())*6e4,t=fs(t),t){case`year`:a=ed(this,r)/12;break;case`month`:a=ed(this,r);break;case`quarter`:a=ed(this,r)/3;break;case`second`:a=(this-r)/1e3;break;case`minute`:a=(this-r)/6e4;break;case`hour`:a=(this-r)/36e5;break;case`day`:a=(this-r-i)/864e5;break;case`week`:a=(this-r-i)/6048e5;break;default:a=this-r}return n?a:zs(a)}function ed(e,t){if(e.date()<t.date())return-ed(t,e);var n=(t.year()-e.year())*12+(t.month()-e.month()),r=e.clone().add(n,`months`),i,a;return t-r<0?(i=e.clone().add(n-1,`months`),a=(t-r)/(r-i)):(i=e.clone().add(n+1,`months`),a=(t-r)/(i-r)),-(n+a)||0}R.defaultFormat=`YYYY-MM-DDTHH:mm:ssZ`,R.defaultFormatUtc=`YYYY-MM-DDTHH:mm:ss[Z]`;function td(){return this.clone().locale(`en`).format(`ddd MMM DD YYYY HH:mm:ss [GMT]ZZ`)}function nd(e){if(!this.isValid())return null;var t=e!==!0,n=t?this.clone().utc():this;return n.year()<0||n.year()>9999?$o(n,t?`YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]`:`YYYYYY-MM-DD[T]HH:mm:ss.SSSZ`):zo(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace(`Z`,$o(n,`Z`)):$o(n,t?`YYYY-MM-DD[T]HH:mm:ss.SSS[Z]`:`YYYY-MM-DD[T]HH:mm:ss.SSSZ`)}function rd(){if(!this.isValid())return`moment.invalid(/* `+this._i+` */)`;var e=`moment`,t=``,n,r,i,a;return this.isLocal()||(e=this.utcOffset()===0?`moment.utc`:`moment.parseZone`,t=`Z`),n=`[`+e+`("]`,r=0<=this.year()&&this.year()<=9999?`YYYY`:`YYYYYY`,i=`-MM-DD[T]HH:mm:ss.SSS`,a=t+`[")]`,this.format(n+r+i+a)}function id(e){e||=this.isUtc()?R.defaultFormatUtc:R.defaultFormat;var t=$o(this,e);return this.localeData().postformat(t)}function ad(e,t){return this.isValid()&&(Fo(e)&&e.isValid()||K(e).isValid())?Nu({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function od(e){return this.from(K(),e)}function sd(e,t){return this.isValid()&&(Fo(e)&&e.isValid()||K(e).isValid())?Nu({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function cd(e){return this.to(K(),e)}function ld(e){var t;return e===void 0?this._locale._abbr:(t=Tl(e),t!=null&&(this._locale=t),this)}var ud=Lo(`moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.`,function(e){return e===void 0?this.localeData():this.locale(e)});function dd(){return this._locale}var fd=1e3,pd=60*fd,md=60*pd,hd=3506328*md;function gd(e,t){return(e%t+t)%t}function _d(e,t,n){return e<100&&e>=0?new Date(e+400,t,n)-hd:new Date(e,t,n).valueOf()}function vd(e,t,n){return e<100&&e>=0?Date.UTC(e+400,t,n)-hd:Date.UTC(e,t,n)}function yd(e){var t,n;if(e=fs(e),e===void 0||e===`millisecond`||!this.isValid())return this;switch(n=this._isUTC?vd:_d,e){case`year`:t=n(this.year(),0,1);break;case`quarter`:t=n(this.year(),this.month()-this.month()%3,1);break;case`month`:t=n(this.year(),this.month(),1);break;case`week`:t=n(this.year(),this.month(),this.date()-this.weekday());break;case`isoWeek`:t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case`day`:case`date`:t=n(this.year(),this.month(),this.date());break;case`hour`:t=this._d.valueOf(),t-=gd(t+(this._isUTC?0:this.utcOffset()*pd),md);break;case`minute`:t=this._d.valueOf(),t-=gd(t,pd);break;case`second`:t=this._d.valueOf(),t-=gd(t,fd)}return this._d.setTime(t),R.updateOffset(this,!0),this}function bd(e){var t,n;if(e=fs(e),e===void 0||e===`millisecond`||!this.isValid())return this;switch(n=this._isUTC?vd:_d,e){case`year`:t=n(this.year()+1,0,1)-1;break;case`quarter`:t=n(this.year(),this.month()-this.month()%3+3,1)-1;break;case`month`:t=n(this.year(),this.month()+1,1)-1;break;case`week`:t=n(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case`isoWeek`:t=n(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case`day`:case`date`:t=n(this.year(),this.month(),this.date()+1)-1;break;case`hour`:t=this._d.valueOf(),t+=md-gd(t+(this._isUTC?0:this.utcOffset()*pd),md)-1;break;case`minute`:t=this._d.valueOf(),t+=pd-gd(t,pd)-1;break;case`second`:t=this._d.valueOf(),t+=fd-gd(t,fd)-1}return this._d.setTime(t),R.updateOffset(this,!0),this}function xd(){return this._d.valueOf()-(this._offset||0)*6e4}function Sd(){return Math.floor(this.valueOf()/1e3)}function Cd(){return new Date(this.valueOf())}function wd(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function Td(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function Ed(){return this.isValid()?this.toISOString():null}function Dd(){return ko(this)}function Od(){return To({},B(this))}function kd(){return B(this).overflow}function Ad(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}H(`N`,0,0,`eraAbbr`),H(`NN`,0,0,`eraAbbr`),H(`NNN`,0,0,`eraAbbr`),H(`NNNN`,0,0,`eraName`),H(`NNNNN`,0,0,`eraNarrow`),H(`y`,[`y`,1],`yo`,`eraYear`),H(`y`,[`yy`,2],0,`eraYear`),H(`y`,[`yyy`,3],0,`eraYear`),H(`y`,[`yyyy`,4],0,`eraYear`),U(`N`,Vd),U(`NN`,Vd),U(`NNN`,Vd),U(`NNNN`,Hd),U(`NNNNN`,Ud),Vs([`N`,`NN`,`NNN`,`NNNN`,`NNNNN`],function(e,t,n,r){var i=n._locale.erasParse(e,r,n._strict);i?B(n).era=i:B(n).invalidEra=e}),U(`y`,Ds),U(`yy`,Ds),U(`yyy`,Ds),U(`yyyy`,Ds),U(`yo`,Wd),Vs([`y`,`yy`,`yyy`,`yyyy`],Gs),Vs([`yo`],function(e,t,n,r){var i;n._locale._eraYearOrdinalRegex&&(i=e.match(n._locale._eraYearOrdinalRegex)),t[Gs]=n._locale.eraYearOrdinalParse?n._locale.eraYearOrdinalParse(e,i):parseInt(e,10)});function jd(e,t){var n,r,i,a=this._eras||Tl(`en`)._eras;for(n=0,r=a.length;n<r;++n)switch(typeof a[n].since==`string`&&(i=R(a[n].since).startOf(`day`),a[n].since=i.valueOf()),typeof a[n].until){case`undefined`:a[n].until=1/0;break;case`string`:i=R(a[n].until).startOf(`day`).valueOf(),a[n].until=i.valueOf()}return a}function Md(e,t,n){var r,i,a=this.eras(),o,s,c;for(e=e.toUpperCase(),r=0,i=a.length;r<i;++r)if(o=a[r].name.toUpperCase(),s=a[r].abbr.toUpperCase(),c=a[r].narrow.toUpperCase(),n)switch(t){case`N`:case`NN`:case`NNN`:if(s===e)return a[r];break;case`NNNN`:if(o===e)return a[r];break;case`NNNNN`:if(c===e)return a[r]}else if([o,s,c].indexOf(e)>=0)return a[r]}function Nd(e,t){var n=e.since<=e.until?1:-1;return t===void 0?R(e.since).year():R(e.since).year()+(t-e.offset)*n}function Pd(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e)if(n=this.clone().startOf(`day`).valueOf(),r[e].since<=n&&n<=r[e].until||r[e].until<=n&&n<=r[e].since)return r[e].name;return``}function Fd(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e)if(n=this.clone().startOf(`day`).valueOf(),r[e].since<=n&&n<=r[e].until||r[e].until<=n&&n<=r[e].since)return r[e].narrow;return``}function Id(){var e,t,n,r=this.localeData().eras();for(e=0,t=r.length;e<t;++e)if(n=this.clone().startOf(`day`).valueOf(),r[e].since<=n&&n<=r[e].until||r[e].until<=n&&n<=r[e].since)return r[e].abbr;return``}function Ld(){var e,t,n,r,i=this.localeData().eras();for(e=0,t=i.length;e<t;++e)if(n=i[e].since<=i[e].until?1:-1,r=this.clone().startOf(`day`).valueOf(),i[e].since<=r&&r<=i[e].until||i[e].until<=r&&r<=i[e].since)return(this.year()-R(i[e].since).year())*n+i[e].offset;return this.year()}function Rd(e){return z(this,`_erasNameRegex`)||Gd.call(this),e?this._erasNameRegex:this._erasRegex}function zd(e){return z(this,`_erasAbbrRegex`)||Gd.call(this),e?this._erasAbbrRegex:this._erasRegex}function Bd(e){return z(this,`_erasNarrowRegex`)||Gd.call(this),e?this._erasNarrowRegex:this._erasRegex}function Vd(e,t){return t.erasAbbrRegex(e)}function Hd(e,t){return t.erasNameRegex(e)}function Ud(e,t){return t.erasNarrowRegex(e)}function Wd(e,t){return t._eraYearOrdinalRegex||Ds}function Gd(){var e=[],t=[],n=[],r=[],i,a,o,s,c,l=this.eras();for(i=0,a=l.length;i<a;++i)o=Rs(l[i].name),s=Rs(l[i].abbr),c=Rs(l[i].narrow),t.push(o),e.push(s),n.push(c),r.push(o),r.push(s),r.push(c);this._erasRegex=RegExp(`^(`+r.join(`|`)+`)`,`i`),this._erasNameRegex=RegExp(`^(`+t.join(`|`)+`)`,`i`),this._erasAbbrRegex=RegExp(`^(`+e.join(`|`)+`)`,`i`),this._erasNarrowRegex=RegExp(`^(`+n.join(`|`)+`)`,`i`)}H(0,[`gg`,2],0,function(){return this.weekYear()%100}),H(0,[`GG`,2],0,function(){return this.isoWeekYear()%100});function Kd(e,t){H(0,[e,e.length],0,t)}Kd(`gggg`,`weekYear`),Kd(`ggggg`,`weekYear`),Kd(`GGGG`,`isoWeekYear`),Kd(`GGGGG`,`isoWeekYear`),U(`G`,Os),U(`g`,Os),U(`GG`,xs,_s),U(`gg`,xs,_s),U(`GGGG`,Ts,ys),U(`gggg`,Ts,ys),U(`GGGGG`,Es,bs),U(`ggggg`,Es,bs),Hs([`gggg`,`ggggg`,`GGGG`,`GGGGG`],function(e,t,n,r){t[r.substr(0,2)]=W(e)}),Hs([`gg`,`GG`],function(e,t,n,r){t[r]=R.parseTwoDigitYear(e)});function qd(e){return $d.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function Jd(e){return $d.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function Yd(){return jc(this.year(),1,4)}function Xd(){return jc(this.isoWeekYear(),1,4)}function Zd(){var e=this.localeData()._week;return jc(this.year(),e.dow,e.doy)}function Qd(){var e=this.localeData()._week;return jc(this.weekYear(),e.dow,e.doy)}function $d(e,t,n,r,i){var a;return e==null?Ac(this,r,i).year:(a=jc(e,r,i),t>a&&(t=a),ef.call(this,e,t,n,r,i))}function ef(e,t,n,r,i){var a=kc(e,t,n,r,i),o=Dc(a.year,0,a.dayOfYear);return this.year(o.getUTCFullYear()),this.month(o.getUTCMonth()),this.date(o.getUTCDate()),this}H(`Q`,0,`Qo`,`quarter`),U(`Q`,gs),Vs(`Q`,function(e,t){t[Ks]=(W(e)-1)*3});function tf(e){return e==null?Math.ceil((this.month()+1)/3):this.month((e-1)*3+this.month()%3)}H(`D`,[`DD`,2],`Do`,`date`),U(`D`,xs,Ns),U(`DD`,xs,_s),U(`Do`,function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient}),Vs([`D`,`DD`],qs),Vs(`Do`,function(e,t){t[qs]=W(e.match(xs)[0])});var nf=rc(`Date`,!0);H(`DDD`,[`DDDD`,3],`DDDo`,`dayOfYear`),U(`DDD`,ws),U(`DDDD`,vs),Vs([`DDD`,`DDDD`],function(e,t,n){n._dayOfYear=W(e)});function rf(e){var t=Math.round((this.clone().startOf(`day`)-this.clone().startOf(`year`))/864e5)+1;return e==null?t:this.add(e-t,`d`)}H(`m`,[`mm`,2],0,`minute`),U(`m`,xs,Ps),U(`mm`,xs,_s),Vs([`m`,`mm`],Ys);var af=rc(`Minutes`,!1);H(`s`,[`ss`,2],0,`second`),U(`s`,xs,Ps),U(`ss`,xs,_s),Vs([`s`,`ss`],Xs);var of=rc(`Seconds`,!1);H(`S`,0,0,function(){return~~(this.millisecond()/100)}),H(0,[`SS`,2],0,function(){return~~(this.millisecond()/10)}),H(0,[`SSS`,3],0,`millisecond`),H(0,[`SSSS`,4],0,function(){return this.millisecond()*10}),H(0,[`SSSSS`,5],0,function(){return this.millisecond()*100}),H(0,[`SSSSSS`,6],0,function(){return this.millisecond()*1e3}),H(0,[`SSSSSSS`,7],0,function(){return this.millisecond()*1e4}),H(0,[`SSSSSSSS`,8],0,function(){return this.millisecond()*1e5}),H(0,[`SSSSSSSSS`,9],0,function(){return this.millisecond()*1e6}),U(`S`,ws,gs),U(`SS`,ws,_s),U(`SSS`,ws,vs);for(var sf=`SSSS`,cf;sf.length<=9;sf+=`S`)U(sf,Ds);function lf(e,t){t[Zs]=W((`0.`+e)*1e3)}for(sf=`S`;sf.length<=9;sf+=`S`)Vs(sf,lf);cf=rc(`Milliseconds`,!1),H(`z`,0,0,`zoneAbbr`),H(`zz`,0,0,`zoneName`);function uf(){return this._isUTC?`UTC`:``}function df(){return this._isUTC?`Coordinated Universal Time`:``}var Y=Po.prototype;Y.add=Ru,Y.calendar=Gu,Y.clone=Ku,Y.diff=$u,Y.endOf=bd,Y.format=id,Y.from=ad,Y.fromNow=od,Y.to=sd,Y.toNow=cd,Y.get=oc,Y.invalidAt=kd,Y.isAfter=qu,Y.isBefore=Ju,Y.isBetween=Yu,Y.isSame=Xu,Y.isSameOrAfter=Zu,Y.isSameOrBefore=Qu,Y.isValid=Dd,Y.lang=ud,Y.locale=ld,Y.localeData=dd,Y.max=nu,Y.min=tu,Y.parsingFlags=Od,Y.set=sc,Y.startOf=yd,Y.subtract=zu,Y.toArray=wd,Y.toObject=Td,Y.toDate=Cd,Y.toISOString=nd,Y.inspect=rd,typeof Symbol<`u`&&Symbol.for!=null&&(Y[Symbol.for(`nodejs.util.inspect.custom`)]=function(){return`Moment<`+this.format()+`>`}),Y.toJSON=Ed,Y.toString=td,Y.unix=Sd,Y.valueOf=xd,Y.creationData=Ad,Y.eraName=Pd,Y.eraNarrow=Fd,Y.eraAbbr=Id,Y.eraYear=Ld,Y.year=tc,Y.isLeapYear=nc,Y.weekYear=qd,Y.isoWeekYear=Jd,Y.quarter=Y.quarters=tf,Y.month=xc,Y.daysInMonth=Sc,Y.week=Y.weeks=Ic,Y.isoWeek=Y.isoWeeks=Lc,Y.weeksInYear=Zd,Y.weeksInWeekYear=Qd,Y.isoWeeksInYear=Yd,Y.isoWeeksInISOWeekYear=Xd,Y.date=nf,Y.day=Y.days=Qc,Y.weekday=$c,Y.isoWeekday=el,Y.dayOfYear=rf,Y.hour=Y.hours=dl,Y.minute=Y.minutes=af,Y.second=Y.seconds=of,Y.millisecond=Y.milliseconds=cf,Y.utcOffset=bu,Y.utc=Su,Y.local=Cu,Y.parseZone=wu,Y.hasAlignedHourOffset=Tu,Y.isDST=Eu,Y.isLocal=Ou,Y.isUtcOffset=ku,Y.isUtc=Au,Y.isUTC=Au,Y.zoneAbbr=uf,Y.zoneName=df,Y.dates=Lo(`dates accessor is deprecated. Use date instead.`,nf),Y.months=Lo(`months accessor is deprecated. Use month instead`,xc),Y.years=Lo(`years accessor is deprecated. Use year instead`,tc),Y.zone=Lo(`moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/`,xu),Y.isDSTShifted=Lo(`isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information`,Du);function ff(e){return K(e*1e3)}function pf(){return K.apply(null,arguments).parseZone()}function mf(e){return e}var X=Ho.prototype;X.calendar=Go,X.longDateFormat=ns,X.invalidDate=is,X.ordinal=ss,X.preparse=mf,X.postformat=mf,X.relativeTime=ls,X.pastFuture=us,X.set=Bo,X.eras=jd,X.erasParse=Md,X.erasConvertYear=Nd,X.erasAbbrRegex=zd,X.erasNameRegex=Rd,X.erasNarrowRegex=Bd,X.months=gc,X.monthsShort=_c,X.monthsParse=yc,X.monthsRegex=wc,X.monthsShortRegex=Cc,X.week=Mc,X.firstDayOfYear=Fc,X.firstDayOfWeek=Pc,X.weekdays=qc,X.weekdaysMin=Yc,X.weekdaysShort=Jc,X.weekdaysParse=Zc,X.weekdaysRegex=tl,X.weekdaysShortRegex=nl,X.weekdaysMinRegex=rl,X.isPM=ll,X.meridiem=fl;function hf(e,t,n,r){var i=Tl(),a=Eo().set(r,t);return i[n](a,e)}function gf(e,t,n){if(So(e)&&(t=e,e=void 0),e||=``,t!=null)return hf(e,t,n,`month`);var r,i=[];for(r=0;r<12;r++)i[r]=hf(e,r,n,`month`);return i}function _f(e,t,n,r){typeof e==`boolean`?(So(t)&&(n=t,t=void 0),t||=``):(t=e,n=t,e=!1,So(t)&&(n=t,t=void 0),t||=``);var i=Tl(),a=e?i._week.dow:0,o,s=[];if(n!=null)return hf(t,(n+a)%7,r,`day`);for(o=0;o<7;o++)s[o]=hf(t,(o+a)%7,r,`day`);return s}function vf(e,t){return gf(e,t,`months`)}function yf(e,t){return gf(e,t,`monthsShort`)}function bf(e,t,n){return _f(e,t,n,`weekdays`)}function xf(e,t,n){return _f(e,t,n,`weekdaysShort`)}function Sf(e,t,n){return _f(e,t,n,`weekdaysMin`)}Sl(`en`,{eras:[{since:`0001-01-01`,until:1/0,offset:1,name:`Anno Domini`,narrow:`AD`,abbr:`AD`},{since:`0000-12-31`,until:-1/0,offset:1,name:`Before Christ`,narrow:`BC`,abbr:`BC`}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10;return e+(W(e%100/10)===1?`th`:t===1?`st`:t===2?`nd`:t===3?`rd`:`th`)}}),R.lang=Lo(`moment.lang is deprecated. Use moment.locale instead.`,Sl),R.langData=Lo(`moment.langData is deprecated. Use moment.localeData instead.`,Tl);var Cf=Math.abs;function wf(){var e=this._data;return this._milliseconds=Cf(this._milliseconds),this._days=Cf(this._days),this._months=Cf(this._months),e.milliseconds=Cf(e.milliseconds),e.seconds=Cf(e.seconds),e.minutes=Cf(e.minutes),e.hours=Cf(e.hours),e.months=Cf(e.months),e.years=Cf(e.years),this}function Tf(e,t,n,r){var i=Nu(t,n);return e._milliseconds+=r*i._milliseconds,e._days+=r*i._days,e._months+=r*i._months,e._bubble()}function Ef(e,t){return Tf(this,e,t,1)}function Df(e,t){return Tf(this,e,t,-1)}function Of(e){return e<0?Math.floor(e):Math.ceil(e)}function kf(){var e=this._milliseconds,t=this._days,n=this._months,r=this._data,i,a,o,s,c;return e>=0&&t>=0&&n>=0||e<=0&&t<=0&&n<=0||(e+=Of(jf(n)+t)*864e5,t=0,n=0),r.milliseconds=e%1e3,i=zs(e/1e3),r.seconds=i%60,a=zs(i/60),r.minutes=a%60,o=zs(a/60),r.hours=o%24,t+=zs(o/24),c=zs(Af(t)),n+=c,t-=Of(jf(c)),s=zs(n/12),n%=12,r.days=t,r.months=n,r.years=s,this}function Af(e){return e*4800/146097}function jf(e){return e*146097/4800}function Mf(e){if(!this.isValid())return NaN;var t,n,r=this._milliseconds;if(e=fs(e),e===`month`||e===`quarter`||e===`year`)switch(t=this._days+r/864e5,n=this._months+Af(t),e){case`month`:return n;case`quarter`:return n/3;case`year`:return n/12}else switch(t=this._days+Math.round(jf(this._months)),e){case`week`:return t/7+r/6048e5;case`day`:return t+r/864e5;case`hour`:return t*24+r/36e5;case`minute`:return t*1440+r/6e4;case`second`:return t*86400+r/1e3;case`millisecond`:return Math.floor(t*864e5)+r;default:throw Error(`Unknown unit `+e)}}function Nf(e){return function(){return this.as(e)}}var Pf=Nf(`ms`),Ff=Nf(`s`),If=Nf(`m`),Lf=Nf(`h`),Rf=Nf(`d`),zf=Nf(`w`),Bf=Nf(`M`),Vf=Nf(`Q`),Hf=Nf(`y`),Uf=Pf;function Wf(){return Nu(this)}function Gf(e){return e=fs(e),this.isValid()?this[e+`s`]():NaN}function Kf(e){return function(){return this.isValid()?this._data[e]:NaN}}var qf=Kf(`milliseconds`),Jf=Kf(`seconds`),Yf=Kf(`minutes`),Xf=Kf(`hours`),Zf=Kf(`days`),Qf=Kf(`months`),$f=Kf(`years`);function ep(){return zs(this.days()/7)}var tp=Math.round,np={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function rp(e,t,n,r,i){return i.relativeTime(t||1,!!n,e,r)}function ip(e,t,n,r){var i=Nu(e).abs(),a=tp(i.as(`s`)),o=tp(i.as(`m`)),s=tp(i.as(`h`)),c=tp(i.as(`d`)),l=tp(i.as(`M`)),u=tp(i.as(`w`)),d=tp(i.as(`y`)),f=a<=n.ss&&[`s`,a]||a<n.s&&[`ss`,a]||o<=1&&[`m`]||o<n.m&&[`mm`,o]||s<=1&&[`h`]||s<n.h&&[`hh`,s]||c<=1&&[`d`]||c<n.d&&[`dd`,c];return n.w!=null&&(f=f||u<=1&&[`w`]||u<n.w&&[`ww`,u]),f=f||l<=1&&[`M`]||l<n.M&&[`MM`,l]||d<=1&&[`y`]||[`yy`,d],f[2]=t,f[3]=+e>0,f[4]=r,rp.apply(null,f)}function ap(e){return e===void 0?tp:typeof e==`function`&&(tp=e,!0)}function op(e,t){return np[e]===void 0?!1:t===void 0?np[e]:(np[e]=t,e===`s`&&(np.ss=t-1),!0)}function sp(e,t){if(!this.isValid())return this.localeData().invalidDate();var n=!1,r=np,i,a;return typeof e==`object`&&(t=e,e=!1),typeof e==`boolean`&&(n=e),typeof t==`object`&&(r=Object.assign({},np,t),t.s!=null&&t.ss==null&&(r.ss=t.s-1)),i=this.localeData(),a=ip(this,!n,r,i),n&&(a=i.pastFuture(+this,a)),i.postformat(a)}var cp=Math.abs;function lp(e){return(e>0)-(e<0)||+e}function up(){if(!this.isValid())return this.localeData().invalidDate();var e=cp(this._milliseconds)/1e3,t=cp(this._days),n=cp(this._months),r,i,a,o,s=this.asSeconds(),c,l,u,d;return s?(r=zs(e/60),i=zs(r/60),e%=60,r%=60,a=zs(n/12),n%=12,o=e?e.toFixed(3).replace(/\.?0+$/,``):``,c=s<0?`-`:``,l=lp(this._months)===lp(s)?``:`-`,u=lp(this._days)===lp(s)?``:`-`,d=lp(this._milliseconds)===lp(s)?``:`-`,c+`P`+(a?l+a+`Y`:``)+(n?l+n+`M`:``)+(t?u+t+`D`:``)+(i||r||e?`T`:``)+(i?d+i+`H`:``)+(r?d+r+`M`:``)+(e?d+o+`S`:``)):`P0D`}var Z=du.prototype;Z.isValid=lu,Z.abs=wf,Z.add=Ef,Z.subtract=Df,Z.as=Mf,Z.asMilliseconds=Pf,Z.asSeconds=Ff,Z.asMinutes=If,Z.asHours=Lf,Z.asDays=Rf,Z.asWeeks=zf,Z.asMonths=Bf,Z.asQuarters=Vf,Z.asYears=Hf,Z.valueOf=Uf,Z._bubble=kf,Z.clone=Wf,Z.get=Gf,Z.milliseconds=qf,Z.seconds=Jf,Z.minutes=Yf,Z.hours=Xf,Z.days=Zf,Z.weeks=ep,Z.months=Qf,Z.years=$f,Z.humanize=sp,Z.toISOString=up,Z.toString=up,Z.toJSON=up,Z.locale=ld,Z.localeData=dd,Z.toIsoString=Lo(`toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)`,up),Z.lang=ud,H(`X`,0,0,`unix`),H(`x`,0,0,`valueOf`),U(`x`,Os),U(`X`,js),Vs(`X`,function(e,t,n){n._d=new Date(parseFloat(e)*1e3)}),Vs(`x`,function(e,t,n){n._d=new Date(W(e))}),R.version=`2.30.1`,_o(K),R.fn=Y,R.min=iu,R.max=au,R.now=ou,R.utc=Eo,R.unix=ff,R.months=vf,R.isDate=Co,R.locale=Sl,R.invalid=Ao,R.duration=Nu,R.isMoment=Fo,R.weekdays=bf,R.parseZone=pf,R.localeData=Tl,R.isDuration=fu,R.monthsShort=yf,R.weekdaysMin=Sf,R.defineLocale=Cl,R.updateLocale=wl,R.locales=El,R.weekdaysShort=xf,R.normalizeUnits=fs,R.relativeTimeRounding=ap,R.relativeTimeThreshold=op,R.calendarFormat=Wu,R.prototype=Y,R.HTML5_FMT={DATETIME_LOCAL:`YYYY-MM-DDTHH:mm`,DATETIME_LOCAL_SECONDS:`YYYY-MM-DDTHH:mm:ss`,DATETIME_LOCAL_MS:`YYYY-MM-DDTHH:mm:ss.SSS`,DATE:`YYYY-MM-DD`,TIME:`HH:mm`,TIME_SECONDS:`HH:mm:ss`,TIME_MS:`HH:mm:ss.SSS`,WEEK:`GGGG-[W]WW`,MONTH:`YYYY-MM`};function dp(e){return e.replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/g,``)}function fp(e){let t=e.replace(/-/g,`+`).replace(/_/g,`/`);return t+(t.length%4==0?``:`=`.repeat(4-t.length%4))}function pp(e){let t=``;for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function mp(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}var hp=60,gp=3600,_p=24*gp,vp=7*_p;function yp(){return new Date().getTime()/1e3}function bp(e){return e.split(``).map(e=>e.charCodeAt(0))}function xp(e){return dp(pp(new TextEncoder().encode(e)))}function Sp(e){let t=mp(fp(e));return new TextDecoder().decode(t)}async function Cp(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n),i=``;for(let e=0;e<r.length;e++)i+=r[e].toString(16).padStart(2,`0`);return i}async function wp(e,t,n=`hex`){let r=await crypto.subtle.importKey(`raw`,new TextEncoder().encode(t),{name:`HMAC`,hash:`SHA-256`},!1,[`sign`]),i=await crypto.subtle.sign(`HMAC`,r,new TextEncoder().encode(e)),a=new Uint8Array(i);if(n===`base64url`)return dp(pp(a));let o=``;for(let e=0;e<a.length;e++)o+=a[e].toString(16).padStart(2,`0`);return o}function Tp(e,t=void 0){return ho.createJWT(e,t)}function Ep(e){return ho.parseJWT(e)}function Dp(e){return ho.jwkToPublicKey(e)}function Op(e,t){return ho.encryptPayload(e,t)}function kp(e){if(Array.isArray(e))return e.map(kp);if(e&&typeof e==`object`&&e.constructor===Object){let t={},n=Object.keys(e),r=n.length;for(let i=0;i<r;i+=1)t[(0,L.camelCase)(n[i])]=kp(e[n[i]]);return t}return e}function Ap(e){if(!e)return!0;try{return JSON.parse(Sp(e.split(`.`)[1])).exp<yp()}catch{return!0}}function jp(e){return zp(`root`,e,`non-nullable object`,!1)}function Mp(e,t){return zp(`root`,e,`object`,t)}function Np(e,t){return zp(`root`,e,`object`,t)}function Pp(e,t){!Array.isArray(e)&&e!=null&&zp(t,e,`array`,!0)}function Fp(e,t,n){typeof e==`string`?e.match(/\d+(\.\d+)?/)||zp(n,e,`string`,t):typeof e!=`number`&&(!t||t&&e!=null)&&zp(n,e,`number`,t)}function Ip(e,t,n){typeof e==`string`?e.match(/\d+(\.\d+)?/)||zp(n,e,`number`,t):typeof e!=`number`&&(!t||t&&e!=null)&&zp(n,e,`number`,t)}function Lp(e,t,n){typeof e!=`boolean`&&(!t||t&&e!=null)&&zp(n,e,`boolean`,t)}function Q(e,t,n){typeof e!=`string`&&(!t||t&&e!=null)&&zp(n,e,`string`,t)}function Rp(e,t){e!=null&&zp(t,e,`null or undefined`,!1)}function zp(e,t,n,r){throw r&&(n+=`, null, or undefined`),TypeError(`Expected `+n+` at `+e+` but found:
|
|
33
|
-
`+JSON.stringify(t))}function $(e){return d.isBigNumber(e)?e:e?new d(e):new d(`0`)}function Bp(e,t){return new d(t).toFixed(e>0?e:0)}function Vp(e){return typeof e==`number`?e:parseFloat(e)}function Hp(e){return typeof e==`number`?e:parseInt(e)}function Up(e){let t=Vp(e);return t<10**10&&(t*=1e3),new Date(t)}function Wp(e){switch(e.toString().toUpperCase()){case`1S`:return 1;case`2S`:return 2;case`3S`:return 3;case`5S`:return 5;case`10S`:return 10;case`15S`:return 15;case`30S`:return 30;case`1`:return 60;case`2`:return 120;case`3`:return 180;case`5`:return 300;case`10`:return 600;case`15`:return 900;case`30`:return 1800;case`60`:return 3600;case`120`:return 7200;case`240`:return 14400;case`360`:return 21600;case`720`:return 43200;case`D`:case`1D`:return _p;case`3D`:return _p*3;case`W`:return vp;case`1W`:return vp;case`2W`:return vp*2;case`1M`:return _p*30}}var Gp=e=>typeof e==`object`?e:new Date(e*1e3),Kp=(e,t)=>{switch(e=R.utc(Gp(e)),t){case`1`:case`2`:case`3`:return e.endOf(`day`).unix();case`5`:case`10`:case`15`:return e.endOf(`isoWeek`).unix();case`30`:case`60`:case`120`:return e.endOf(`month`).unix();case`240`:case`360`:case`720`:case`D`:case`1D`:return e.endOf(`year`).unix()}},qp=(e,t)=>{switch(e=R.utc(Gp(e)),t){case`1`:case`2`:case`3`:return e.startOf(`day`).unix();case`5`:case`10`:case`15`:return e.startOf(`isoWeek`).unix();case`30`:case`60`:case`120`:return e.startOf(`month`).unix();case`240`:case`360`:case`720`:case`D`:case`1D`:return e.startOf(`year`).unix()}};function Jp(e){switch(e){case`1`:case`2`:case`3`:return`day`;case`5`:case`10`:case`15`:return`week`;case`30`:case`60`:case`120`:return`month`;case`240`:case`360`:case`720`:case`D`:case`1D`:return`year`;default:throw Error(`Unsupported resolution: ${e}`)}}function Yp(e,t){let n=R(Gp(t)),r;switch(e){case`day`:r={year:n.year(),month:n.month()+1,day:n.date()};break;case`week`:r={year:n.isoWeekYear(),week:n.isoWeek()};break;case`month`:r={year:n.year(),month:n.month()+1};break;case`year`:r={year:n.year()};break;default:throw Error(`Unsupported bucketType: ${e}`)}return r}function Xp(e,t,n){let r=[],i=R.utc(t*1e3),a=e=>{switch(n){case`day`:return e.startOf(`day`);case`week`:return e.startOf(`isoWeek`);case`month`:return e.startOf(`month`);case`year`:return e.startOf(`year`);default:throw Error(`Unsupported bucketType: ${n}`)}},o=e=>{switch(n){case`day`:return e.subtract(1,`day`);case`week`:return e.subtract(1,`week`);case`month`:return e.subtract(1,`month`);case`year`:return e.subtract(1,`year`);default:throw Error(`Unsupported bucketType: ${n}`)}},s=a(i),c=a(R.utc(e*1e3));for(;s>=c;)r.push(s.clone()),s=o(s);return r}function Zp(e,t,n){let r=Wp(t),i=typeof n==`object`?n.getTime()/1e3:n;return Math.floor(i/r)*r-r*(e-1)}function Qp(e,t){let n=t;if(n=typeof t==`string`?[{query:t,marketProperty:`fullDisplayName`}]:Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{query:e,marketProperty:`fullDisplayName`};if(!Array.isArray(e))return e}):[t],n.length===0||!n.find(({query:e})=>!!e&&!!e.length))return e;let r=e;return n.forEach(({query:e,marketProperty:t})=>{let n;if(e.match(/[-_:\/\\]+/))try{n=new RegExp(e.replace(/\*/g,`.*`),`i`)}catch{}let i=e.toLowerCase().split(/[\s]+/).filter(Boolean);r=L.default.pickBy(r,(e,r)=>{let a=e[t];if(a==null)return!1;let o=a.toLowerCase();return n&&t===`fullDisplayName`?!!n.exec(e[t]):i.filter(e=>o.includes(e)).length===i.length})}),r}var $p=void 0,em=class{static initialize=e=>{$p=e,console.log(`Coinray I18n initialized`)};static t=(e,t)=>$p?$p.t(`coinray:${e}`,t):`i18n uninitialized. Set the Coinray.I18n.instance. Key: ${e}`},tm=10,nm=`\\([A-Za-z0-9_.:]+\\)`,rm=RegExp(`\\s*(?:(\\d+(?:\\.\\d+)?(?![A-Za-z0-9_.]))|([A-Za-z0-9_.:]+(?:-[A-Za-z0-9_.:]+)*(?:${nm})?)|([-+*/()×÷]))\\s*`,`y`),im=RegExp(`(?<=[A-Za-z0-9_.:])${nm}`,`g`),am={"+":`+`,"-":`−`,"*":`×`,"/":`÷`},om=e=>/[\s+*/()×÷]/.test(`${e}`.replace(im,``));function sm(e){let t=[];for(rm.lastIndex=0;rm.lastIndex<e.length;){let n=rm.lastIndex,r=rm.exec(e);if(!r)throw Error(`Invalid formula at "${e.slice(n)}"`);if(r[1]!==void 0)t.push({kind:`num`,value:r[1]});else if(r[2]!==void 0){if(r[2].split(`_`).length<3)throw Error(`Invalid market "${r[2]}" in formula`);t.push({kind:`leg`,value:r[2]})}else t.push({kind:`op`,value:r[3]===`×`?`*`:r[3]===`÷`?`/`:r[3]})}return t}function cm(e){let t=sm(e),n=0,r=()=>t[n]?.kind===`op`?t[n].value:void 0,i=()=>{let e=a();for(;r()===`+`||r()===`-`;)e={type:`op`,op:t[n++].value,left:e,right:a()};return e},a=()=>{let e=o();for(;r()===`*`||r()===`/`;)e={type:`op`,op:t[n++].value,left:e,right:o()};return e},o=()=>r()===`-`?(n++,{type:`neg`,arg:o()}):s(),s=()=>{let e=t[n++];if(!e)throw Error(`Invalid formula: unexpected end`);if(e.kind===`num`)return{type:`num`,value:Number(e.value)};if(e.kind===`leg`)return{type:`leg`,symbol:e.value};if(e.value===`(`){let e=i();if(t[n++]?.value!==`)`)throw Error(`Invalid formula: missing )`);return e}throw Error(`Invalid formula: unexpected "${e.value}"`)},c=i();if(n<t.length)throw Error(`Invalid formula: unexpected "${t[n].value}"`);let l=lm(c);if(l.length===0)throw Error(`Invalid formula: no markets`);if(l.length>tm)throw Error(`Invalid formula: max ${tm} markets`);return c}function lm(e,t=[]){return e.type===`leg`&&!t.includes(e.symbol)&&t.push(e.symbol),e.type===`neg`&&lm(e.arg,t),e.type===`op`&&(lm(e.left,t),lm(e.right,t)),t}function um(e,t){switch(e.type){case`num`:return e.value;case`leg`:return t(e.symbol);case`neg`:return-um(e.arg,t);case`op`:{let n=um(e.left,t),r=um(e.right,t);return e.op===`+`?n+r:e.op===`-`?n-r:e.op===`*`?n*r:r===0?NaN:n/r}}}var dm=(e,t)=>({time:t,open:e.close,high:e.close,low:e.close,close:e.close,baseVolume:0,quoteVolume:0,numTrades:0});function fm(e,t,n){let r=n=>um(e,e=>Number(t[e][n])),i=r(`open`),a=r(`close`),o=r(`high`),s=r(`low`);return[i,a,o,s].every(Number.isFinite)?{time:n,open:i,close:a,high:Math.max(i,a,o,s),low:Math.min(i,a,o,s),baseVolume:0,quoteVolume:0,numTrades:0}:null}function pm(e,t){if(e.some(e=>!t[e]?.length))return[];let n=Math.max(...e.map(e=>t[e][0].time.getTime())),r=[...new Set(e.flatMap(e=>t[e].map(e=>e.time.getTime())))].filter(e=>e>=n).sort((e,t)=>e-t),i={},a={};return r.map(n=>{let r={};for(let o of e){let e=t[o];for(i[o]??=0;i[o]<e.length&&e[i[o]].time.getTime()<=n;)a[o]=e[i[o]++];r[o]=a[o].time.getTime()===n?a[o]:dm(a[o],new Date(n))}return{time:new Date(n),legs:r}})}function mm(e,t){return pm(lm(e),t).map(({time:t,legs:n})=>fm(e,n,t)).filter(e=>e!==null)}function hm(e,t){let n=lm(e);if(n.some(e=>t[e]?.close===void 0))return null;let r=Math.max(...n.map(e=>t[e].time.getTime())),i={};for(let e of n)i[e]=t[e].time.getTime()===r?t[e]:dm(t[e],new Date(r));return fm(e,i,new Date(r))}function gm(e){return!Number.isFinite(e)||e===0?8:Math.min(12,Math.max(2,4-Math.floor(Math.log10(Math.abs(e)))))}function _m(e,t){let n=cm(e),r=lm(n),i={};for(let e of r){let n=t(e);if(!n)throw Error(`Unknown market ${e}`);i[e]=n}let a=new Set(r.map(e=>i[e].exchangeCode)).size>1;return{name:sm(e).map(({kind:e,value:t})=>{if(e===`leg`){let e=i[t];return`${a?`${e.exchangeCode}:`:``}${e.baseCurrency}/${e.quoteCurrency}`}return am[t]?` ${am[t]} `:t}).join(``).replace(/\( /g,`(`).replace(/^ − /,`−`),legs:r,pricePrecision:gm(um(n,e=>i[e].lastPrice?.toNumber()??NaN))}}var vm=e=>om(e)?encodeURIComponent(e):e,ym=`2.0.24`,bm=class extends Error{errorCode;errorMessage;exchange;status;constructor({code:e,message:t,exchange:n}){super(`Request failed`),this.name=`CoinrayError`,this.errorCode=e,this.errorMessage=t,this.exchange=n}},xm=class e{static I18n=em;config;_token;_sessionKey;_credential;_firstOpen;_onTokenExpired;_tokenCheckTimeout;_onError;_onOpen;_socket;_transport;_tickerListeners=new Map;_tickerSymbols=new Map;_tradeListeners={};_tradeSnapshots={};_orderbookListeners={};_orderbookSnapshots={};_candleTradeListeners={};_candleListeners={};_candles={};_timers={};_channels={};_connected;markConnected;_publicKey;_refreshingToken;_nonceOffset;tickersSubscribed=!1;tradesSubscribed=!1;orderBookSubscribed=!1;_timeOffset;_timeOffsetTimeout;_candleCache;_candleCacheCreatedAt;constructor(e,{apiEndpoint:t,orderEndpoint:n,websocketEndpoint:r}={apiEndpoint:`https://api.coinray.eu`,orderEndpoint:`https://api.coinray.eu`,websocketEndpoint:`wss://ws.coinray.eu/v1`}){this._token=e,this._nonceOffset=0,this._timeOffset=0,this._firstOpen=!0,this.config={apiEndpoint:t||`https://api.coinray.eu`,orderEndpoint:n||t||`https://api.coinray.eu`,websocketEndpoint:r||`wss://ws.coinray.eu/v1`},this._candleCache=new Map,this.loadTimeOffset().then()}authenticateDevice=(e,t)=>{this._credential=e,this._sessionKey=t};destroy=()=>{this._tradeListeners={},this._orderbookListeners={},this._tickerListeners=new Map,this._tickerSymbols=new Map,this.tickerSnapshots=new Map,this._channels={},this._timeOffsetTimeout&&clearTimeout(this._timeOffsetTimeout),this._tokenCheckTimeout&&clearInterval(this._tokenCheckTimeout),this.disconnect()};checkToken=async(e=!0)=>{try{if(Ap(this._token)){if(console.log(`Coinray token expired. Can refresh:`,!!this._onTokenExpired),!this._onTokenExpired)return!1;this._refreshingToken||=this._onTokenExpired();try{this._token=await this._refreshingToken}catch(e){return console.log(`Coinray token could not be refreshed`,e),this._refreshingToken=void 0,!1}if(this._refreshingToken=void 0,!Ap(this._token))this.reconnect();else return!1}}catch(e){console.error(e)}return e&&(this._tokenCheckTimeout=setTimeout(this.checkToken,5e3)),!0};setTransport=e=>{this._transport=e};onTokenExpired=e=>{this._tokenCheckTimeout&&clearInterval(this._tokenCheckTimeout),this._onTokenExpired=e,this._tokenCheckTimeout=setTimeout(this.checkToken,5e3)};refreshToken=e=>{this._token=e};getNonce=()=>(this._nonceOffset>900&&(this._nonceOffset=0),this._nonceOffset+=1,this.getTime()+this._nonceOffset);getTime=()=>Math.floor(new Date().getTime()/1e3)*1e3+this._timeOffset;loadTimeOffset=async()=>{try{let{result:e}=await this.get(`/coinray/time`);this._timeOffset=e.time-new Date().getTime()}catch(e){console.error(e)}this._timeOffsetTimeout=setTimeout(this.loadTimeOffset,6e4)};getToken=async()=>{if(await this.checkToken(!1))return this._token;throw Error(`Token is expired. call refreshToken in the onTokenExpired callback`)};reconnect=()=>{this._connected&&this.socket.conn.close()};disconnect=()=>{this._socket&&=(this._socket.disconnect(),void 0),this._connected=void 0};connect=async()=>{if(this._connected){await this._connected;return}this._connected=new Promise(e=>{this.markConnected=e}),this.socket.onOpen(e=>{this._onOpen&&this._onOpen(e)}),this.socket.onError(e=>{this._onError&&this._onError(e)}),this.socket.connect(),this.markConnected()};onOpen=e=>{this._onOpen=e};onError=e=>{this._onError=e};resubscribe=()=>{if(this._firstOpen){this._firstOpen=!1;return}Object.keys(this._tickerListeners).forEach(e=>{this._tickerListeners[e].length>0&&this.getChannel(`tickers`).push(`subscribe`,{exchangeCodes:[e]},5e3)}),Object.keys(this._tradeListeners).forEach(e=>{this._tradeListeners[e].length>0&&this.getChannel(`trades`).push(`subscribe`,{symbols:e,snapshots:!0},5e3)}),Object.keys(this._orderbookListeners).forEach(e=>{this._orderbookListeners[e].length>0&&this.getChannel(`orderbooks`).push(`subscribe`,{symbols:e,snapshots:!0},5e3)})};subscribeTickers=async(t,n=!1,r)=>{if(t.length===0)return!1;if(n&&(this._tickerListeners.clear(),this._tickerSymbols.clear()),this._tickerListeners.has(r)){let e=this._tickerListeners.get(r);t.forEach(t=>e.add(t))}else this._tickerListeners.set(r,new Set(t));t.forEach(e=>{this._tickerSymbols.has(e)||this._tickerSymbols.set(e,new Set),this._tickerSymbols.get(e).add(r)}),await this.connect();let i=this.getChannel(`tickers`);return i.push(`subscribe`,{coinraySymbols:t,reset:n},5e3),this.tickersSubscribed?r:(this.tickersSubscribed=!0,i.on(`update`,t=>{let{exchange_code:n,tickers:r}=t,i=r.map(e._parseTicker);this._tickerListeners.forEach((e,t)=>{let r=i.filter(t=>e.has(t.coinraySymbol));t({type:`tickers:update`,exchangeCode:n,tickers:r})})}),i.on(`error`,e=>console.error(e)),r)};unsubscribeAllTickers=()=>{this._tickerListeners.clear(),this._tickerSymbols.clear(),this.getChannel(`tickers`).push(`unsubscribe`,{all:!0},5e3)};unsubscribeTickers=(e,t)=>{if(t&&this._tickerListeners.has(t)){let n=this._tickerListeners.get(t),r=[];e.forEach(e=>{n.delete(e),this._tickerSymbols.has(e)&&(this._tickerSymbols.get(e).delete(t),this._tickerSymbols.get(e).size===0&&(this._tickerSymbols.delete(e),r.push(e)))}),n.size===0&&this._tickerListeners.delete(t),r.length>0&&this.getChannel(`tickers`).push(`unsubscribe`,{coinraySymbols:r},5e3)}};subscribeTrades=async({coinraySymbol:t},n)=>{if(this._tradeListeners[t]&&this._tradeListeners[t].length>0)return this._tradeListeners[t].includes(n)||this._tradeListeners[t].push(n),n({type:`trades:snapshot`,coinraySymbol:t,trades:this._tradeSnapshots[t]}),n;this._tradeSnapshots[t]=[],this._tradeListeners[t]=[n],await this.connect();let r=this.getChannel(`trades`);return r.push(`subscribe`,{symbols:t,snapshots:!0},5e3),this.tradesSubscribed?n:(this.tradesSubscribed=!0,r.on(`snapshot`,({symbol:t,trades:n})=>{let r=Object.values(this._tradeListeners[t]),i=n.map(e._parseTrade);this._tradeSnapshots[t]=i,r.map(e=>e({type:`trades:snapshot`,coinraySymbol:t,trades:i}))}),r.on(`update`,({symbol:t,trades:n})=>{let r=Object.values(this._tradeListeners[t]),i=n.map(e._parseTrade),a=[...i,...this._tradeSnapshots[t]],o=new Date(new Date().getTime()-12e4),s=a.filter(({time:e})=>e>o);s.length>100?this._tradeSnapshots[t]=s:this._tradeSnapshots[t]=a.slice(0,100),r.map(e=>e({type:`trades:update`,coinraySymbol:t,trades:i}))}),r.on(`error`,e=>console.error(e)),n)};unsubscribeTrades=({coinraySymbol:e},t)=>{t&&this._tradeListeners[e]?(this._tradeListeners[e]=this._tradeListeners[e].filter(e=>e!==t),this._tradeListeners[e].length===0&&this.getChannel(`trades`).push(`unsubscribe`,{symbols:e},5e3)):(this._tradeSnapshots[e]=[],this._tradeListeners[e]=[])};subscribeOrderBook=async({coinraySymbol:t},n)=>{if(this._orderbookListeners[t]&&this._orderbookListeners[t].length>0)return this._orderbookListeners[t].includes(n)||this._orderbookListeners[t].push(n),n({type:`orderBook:snapshot`,coinraySymbol:t,orderBook:this._orderbookSnapshots[t]}),n;this._orderbookSnapshots[t]={minSeq:0,maxSeq:0,bids:{},asks:{}},this._orderbookListeners[t]=[n],await this.connect();let r=this.getChannel(`orderbooks`);return r.push(`subscribe`,{symbols:t},1e4),this.orderBookSubscribed?n:(this.orderBookSubscribed=!0,r.on(`snapshot`,({orderbooks:t})=>{Object.keys(t).forEach(n=>{let r=Object.values(this._orderbookListeners[n]),i=e._parseOrderBookSnapshot(t[n]);this._orderbookSnapshots[n]=i,r.map(e=>e({type:`orderBook:snapshot`,coinraySymbol:n,orderBook:i}))})}),r.on(`update`,({orderbooks:t})=>{let n=Object.keys(t);n.length!==0&&n.forEach(n=>{let r=Object.values(this._orderbookListeners[n]),i=e._parseOrderBookUpdate(t[n]);this._orderbookSnapshots[n]=e._updateOrderBook(this._orderbookSnapshots[n],i),r.map(e=>e({type:`orderBook:update`,coinraySymbol:n,orderBook:i}))})}),r.on(`error`,e=>console.error(e)),n)};unsubscribeOrderBook=({coinraySymbol:e},t)=>{t&&this._orderbookListeners[e]?(this._orderbookListeners[e]=this._orderbookListeners[e].filter(e=>e!==t),this._orderbookListeners[e].length===0&&this.getChannel(`orderbooks`).push(`unsubscribe`,{symbols:e},5e3)):(this._orderbookSnapshots[e]={minSeq:0,maxSeq:0,bids:{},asks:{}},this._orderbookListeners[e]=[])};subscribeCandles=async({coinraySymbol:t,resolution:n,lastCandle:r},i)=>{let a=`${t}-${n}`;if(this._candleListeners[a]&&this._candleListeners[a].length>0)return this._candleListeners[a].push(i),i;this._candleListeners[a]=[i];let o=({type:t,coinraySymbol:r,trades:i})=>{let o=Object.values(this._candleListeners[a]),s=e._tradesToLastCandle(n,i),c=s[s.length-1];c&&(this._candles[a]&&t===`trades:snapshot`&&(this._candles[a].skipVolume=!0),this._candles[a]=e._mergeCandle(this._candles[a],c),o.map(e=>e({coinraySymbol:r,resolution:n,candle:this._candles[a],previousCandles:s})))};return this._candleTradeListeners[t]?this._candleTradeListeners[t][a]=o:this._candleTradeListeners[t]={[a]:o},this._candles[a]=r||{time:new Date(0)},await this.subscribeTrades({coinraySymbol:t},o),this.startNewCandleTimer({candleId:a,resolution:n,coinraySymbol:t}),i};startNewCandleTimer=({candleId:e,resolution:t,coinraySymbol:n})=>{this._timers[e]&&clearTimeout(this._timers[e]);let r=Zp(0,t,new Date)-new Date().getTime()/1e3,i=Object.values(this._candleListeners[e]);this._timers[e]=setTimeout(()=>{let r=Zp(1,t,new Date)*1e3,a=this._candles[e];a&&r>a.time.getTime()&&(this._candles[e]={time:new Date(r),open:a.close,high:a.close,low:a.close,close:a.close,baseVolume:0,quoteVolume:0,numTrades:0},i.map(r=>r({coinraySymbol:n,resolution:t,candle:this._candles[e],previousCandles:[]}))),this.startNewCandleTimer({candleId:e,resolution:t,coinraySymbol:n})},r*1e3)};unsubscribeCandles=({coinraySymbol:e,resolution:t},n)=>{let r=`${e}-${t}`;n&&this._candleListeners[r]?this._candleListeners[r]=this._candleListeners[r].filter(e=>e!==n):this._candleListeners[r]=[],this._candleListeners[r].length===0&&(this.unsubscribeTrades({coinraySymbol:e},this._candleTradeListeners[e][r]),this._timers[r]&&(clearTimeout(this._timers[r]),delete this._timers[r]),delete this._candles[r],delete this._candleTradeListeners[e][r])};fetchFirstCandleTime=async({coinraySymbol:e,resolution:t})=>{let{result:{startTime:n}}=await this.get(`candles/start-time`,{version:om(e)?`v2`:`v1`,params:{symbol:vm(e),resolution:t}});return n};fetchCandles=async({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})=>{if(this.flushCache(),t.endsWith(`S`))return(await this.getWebsocketCandles(e,t)).filter(e=>{let t=e.time.getTime()/1e3;return t>=n&&t<=r});let a=Jp(t),o=new Date().getTime()/1e3,s=[],c=r+1;if(Kp(r,t)>=o){let n=await this.getOpenCandles(i,{version:`v2`,params:{symbol:vm(e),resolution:t}});if(n.length>0)c=Math.min(n[0].time.getTime()/1e3,c),s.push(...n);else return[]}let l=Zp(2,t,c),u=(0,L.chunk)(Xp(n,l,a),10);for(let n=0;n<u.length;n+=1){let r=u[n].map(n=>{let r=Yp(a,n),i={version:`v2`,params:{symbol:vm(e),resolution:t,...r}};return this.getHistoryCandles(i)}),i=await Promise.all(r),o=[];for(let e=0;e<i.length;e+=1)o=i[e].filter(({time:e})=>e.getTime()/1e3<c),o.length>0&&(c=Math.min(o[0].time.getTime()/1e3,c),s.unshift(...o));if(o.length===0)break}return s.filter(({time:e})=>{let t=e.getTime()/1e3;return t>=n&&t<=r}).sort((e,t)=>e.time.getTime()-t.time.getTime())};flushCache=()=>{let e=new Date().getTime()/1e3;(!this._candleCacheCreatedAt||e-this._candleCacheCreatedAt>600)&&(this._candleCacheCreatedAt=e,this._candleCache=new Map)};getWebsocketCandles=async(e,t)=>await new Promise(n=>{let r=setTimeout(()=>{this.unsubscribeCandles({coinraySymbol:e,resolution:t},i),n([])},0),i=({previousCandles:a})=>{clearTimeout(r),this.unsubscribeCandles({coinraySymbol:e,resolution:t},i),n(a)};this.subscribeCandles({coinraySymbol:e,resolution:t},i)});getOpenCandles=async(t,n)=>{let r=this.candleCacheKey({prefix:`O`,...n.params}),i=this._candleCache.get(r);if(!t&&i)return i;let{symbol:a,resolution:o}=n.params,s=om(decodeURIComponent(a))?[]:await this.getWebsocketCandles(a,o),c=L.default.keyBy(s,({time:e})=>e.getTime()),{result:l}=await this.get(`candles/open`,n);if(l.candles){let t=l.candles.map(e._parseCandle).map(t=>{let n=c[t.time.getTime()];return n?e._mergeCandle(t,n):t});return this._candleCache.set(r,t),t}return[]};getHistoryCandles=async t=>{let n=this.candleCacheKey(t.params),r=this._candleCache.get(n);if(r)return r;{if(t.params.year<2018)return new Promise(e=>e([]));let{result:r}=await this.get(`candles/history`,t);if(r.candles){let t=r.candles.map(e._parseCandle);return this._candleCache.set(n,t),t}return[]}};candleCacheKey=({symbol:e,resolution:t,year:n,month:r=``,day:i=``,week:a=``,prefix:o=`C`})=>`${o}/${e}/${t}/${n}/${r}/${i}/${a}`;fetchExchanges=async(e,t)=>{let n=t;return n||({result:{exchanges:n}}=await this.get(`exchanges`,{version:`v1`})),n.map(e)};fetchMarkets=async(e,t)=>{let n=t;return n||({result:{markets:n}}=await this.get(`markets`,{version:`v1`,params:{exchange:e.code}})),n};fetchTickers=async e=>{let{result:{tickers:t}}=await this.get(`tickers`,{version:`v1`,params:{exchanges:[...e].sort().join(`,`)}});return L.default.mapValues(t||{},e=>e.map(this.parseTickerSnapshotReusing))};tickerSnapshots=new Map;parseTickerSnapshotReusing=t=>{let n=e._parseTickerSnapshot(t,this.tickerSnapshots.get(t.s));return this.tickerSnapshots.set(t.s,{raw:t,parsed:n}),n};fetchStaticMarkets=async(e,t)=>{let{result:n,_headers:r,_status:i}=await this.get(`markets/static`,{version:`v1`,params:{exchange:e},headers:t?{"If-None-Match":t}:{}});return i===304?{markets:null,etag:t}:{markets:n.markets,etag:r.etag}};createCredential=async(e,t)=>{let n=await this.publicKey();try{let r=await Op(await Tp({password:t}),n),{result:i}=await this.post(`credentials`,{secret:t,body:{deviceId:e,encryptedPassword:r}});return i}catch(e){throw e}};wrapApiKey=async(e,t)=>{let n=await this.publicKey(),r;try{r=t?e:await Op(await Tp({apiKey:JSON.stringify(e)}),n);let{result:i}=await this.post(`credentials/wrap_api_key`,{secret:this._sessionKey,body:{encryptedApiKey:r,credential:this._credential}});return i}catch(e){throw e}};testAccount=async e=>{try{let{result:t}=await this.post(`account/test`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};createSmartOrderSignature=async e=>{try{let{result:t}=await this.post(`order/smart_order_signature`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{smartOrder:e,credential:this._credential}});return t}catch(e){throw e}};createOrder=async e=>{try{let{result:t}=await this.post(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};updateOrder=async e=>{try{let{result:t}=await this.patch(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};cancelOrder=async e=>{try{let{result:t}=await this.delete(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,orderId:e.orderId.toString(),credential:this._credential}});return t}catch(e){throw e}};createWebSocketToken=async({exchangeCode:e,encryptedApiKey:t})=>{try{let{result:n}=await this.post(`exchanges/ws_token`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{encryptedApiKey:t,exchangeCode:e,credential:this._credential}});return n}catch(e){throw e}};fetchPositions=async({exchangeCode:e,encryptedApiKey:t})=>{try{let{result:n}=await this.get(`futures/positions`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,params:{credential:this._credential,exchangeCode:e,encryptedApiKey:t}});return n}catch(e){throw e}};getBalances=async({exchangeCode:t,encryptedApiKey:n})=>{try{let{result:{balances:r,positions:i}}=await this.get(`account/balances`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,params:{credential:this._credential,exchangeCode:t,encryptedApiKey:n}});return{balances:r.map(e._parseBalance),positions:i}}catch(e){throw e}};setLeverage=async({coinraySymbol:e,leverage:t,encryptedApiKey:n})=>{try{let{result:r}=await this.post(`futures/leverage`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{credential:this._credential,coinraySymbol:e,leverage:t,encryptedApiKey:n}});return r}catch(e){throw e}};setMarginType=async({coinraySymbol:e,marginType:t,encryptedApiKey:n})=>{try{let{result:r}=await this.post(`futures/margin_type`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{credential:this._credential,coinraySymbol:e,marginType:t,encryptedApiKey:n}});return r}catch(e){throw e}};async getProxyList({exchangeCode:e,credentialVersion:t}){let n=``;e&&(n+=`?exchange=${e.toUpperCase()}`,n+=t?`&version=${t}`:``);let{result:{proxies:r}}=await this.get(`credentials/ips`+n);return r}async publicKey(){if(!this._publicKey){let{result:{jwk:e}}=await this.get(`credentials/certificate`);this._publicKey=await Dp(e)}return this._publicKey}get clientId(){return Ep(this._token).header.kid}get socket(){if(!this._token)throw Error(`Token not present`);return this._socket||(this._socket=new mi(this.config.websocketEndpoint,{heartbeatIntervalMs:5e3,transport:this._transport,reconnectAfterMs:()=>Ap(this._token)?3e4:1e3}),this.onOpen(this.resubscribe)),this._socket.params=()=>({reconnect:!0,token:this._token,client:`coinrayjs`,version:ym}),this._socket}getChannel(e){if(this.connect(),this._channels[e])return this._channels[e];let t=this.socket.channel(e,{});return this._channels[e]=t,t.join(),t}get=async(e,{apiEndpoint:t=void 0,version:n=`v2`,headers:r={},params:i={},secret:a=``}={})=>await this._request(e,`GET`,{version:n,apiEndpoint:t,headers:r,secret:a,params:i});post=async(e,t)=>await this._request(e,`POST`,t);patch=async(e,t)=>await this._request(e,`PATCH`,t);delete=async(e,t)=>await this._request(e,`delete`,t);async _request(e,t,{apiEndpoint:n,version:r=`v2`,headers:i={},params:a={},body:o={},secret:s=``}){let c=await this.getToken(),l=Object.entries(a).length>0?`?`+Object.entries(a).map(([e,t])=>t?`${e}=${t}`:void 0).filter(Boolean).join(`&`):``,u=this.getNonce(),d=`/api/${r}/${e}${l}`;if(r===`v2`&&!e.startsWith(`candles`)){let e=[u,t.toUpperCase(),d,t===`GET`?``:JSON.stringify(o)].join(``),n=s==``?``:await wp(e,s);i={...i,"Cr-Access-Token":`${c}`,"Cr-Nonce":u,"Cr-Signature":n}}let f={method:t,url:(n||this.config.apiEndpoint)+d,timeout:2e4,headers:{Accept:`application/json`,"Content-Type":`application/json`,Authorization:`Bearer ${c}`,"Cr-Client-version":ym,...i},data:t===`GET`?void 0:JSON.stringify(o),validateStatus:e=>e>=200&&e<300||e===304};try{let e=await Kr(f),t;t=e.status===200?e.data:e.status===204?{}:e.data;let n=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]));return{result:t,_headers:n,_status:e.status}}catch(e){let{response:t}=e;if(t){let e=new bm(t.data?.error||{});throw e.status=t.status,e}throw e}}static _parseOrderBookSnapshot({asks:t,bids:n,min_seq:r,max_seq:i}){return{minSeq:r,maxSeq:i,asks:e._parseBidAsk(t),bids:e._parseBidAsk(n)}}static _parseOrderBookUpdate({asks_diff:t,bids_diff:n,min_seq:r,max_seq:i}){return{minSeq:r,maxSeq:i,asks:e._parseBidAsk(t),bids:e._parseBidAsk(n)}}static _updateOrderBook(e,{asks:t,bids:n,min_seq:r,max_seq:i}){let a=(e,t)=>{L.default.forEach(t,(t,n)=>{t>0?e[n]=t:delete e[n]})};return e.minSeq=r,e.maxSeq=i,a(e.bids,n),a(e.asks,t),e}static _parseBidAsk(e){return Array.isArray(e)?e.reduce((e,[t,n])=>(e[t]=parseFloat(n),e),{}):Object.keys(e).reduce((t,n)=>(t[n]=parseFloat(e[n]),t),{})}static _parseCandle(e){if(e){let[t,n,r,i,a,o,s]=e;return{time:Up(t),open:parseFloat(n),high:parseFloat(r),low:parseFloat(i),close:parseFloat(a),baseVolume:parseFloat(o),quoteVolume:parseFloat(s),numTrades:0}}throw Error(`Candle`)}static _parseTrade([e,t,n,r,i]){return{id:e,time:Up(t),price:parseFloat(n),quantity:parseFloat(r),type:[`1`,`buy`].includes(i.toString())?`buy`:`sell`}}static _parseTicker(e){return{askPrice:$(e.a),baseVolume:$(e.BV),baseVolume1s:$(e.bv),bidPrice:$(e.b),btcVolume:$(e.B),coinraySymbol:e.s,highPrice1s:$(e.h),highPrice24h:$(e.H),lastPrice:$(e.c),lowPrice1s:$(e.l),lowPrice24h:$(e.L),openPrice1s:$(e.o),openPrice24h:$(e.O),quoteVolume:$(e.QV),quoteVolume1s:$(e.qv),usdVolume:$(e.U)}}static _parseTickerSnapshot(e,t){let n=(n,r)=>t&&t.raw[n]===e[n]?t.parsed[r]:$(e[n]);return{coinraySymbol:e.s,lastPrice:n(`c`,`lastPrice`),askPrice:n(`a`,`askPrice`),bidPrice:n(`b`,`bidPrice`),openPrice24h:n(`O`,`openPrice24h`),highPrice24h:n(`H`,`highPrice24h`),lowPrice24h:n(`L`,`lowPrice24h`),baseVolume:n(`BV`,`baseVolume`),quoteVolume:n(`QV`,`quoteVolume`),btcVolume:n(`B`,`btcVolume`),usdVolume:n(`U`,`usdVolume`),baseToUsd:n(`bu`,`baseToUsd`),quoteToUsd:n(`qu`,`quoteToUsd`),marketCap:n(`mc`,`marketCap`)}}static _parseBalance(e){let t={currency:e.currency,available:$(e.available),inOrders:$(e.inOrders),total:$(e.inOrders)};return e.initialMargin&&(t={...t,initialMargin:$(e.initialMargin),openOrderInitialMargin:$(e.openOrderInitialMargin),positionInitialMargin:$(e.positionInitialMargin),unrealizedProfit:$(e.unrealizedProfit),crossWalletBalance:$(e.crossWalletBalance),crossUnrealizedProfit:$(e.crossUnrealizedProfit)}),t}static _tradesToLastCandle(t,n){n.length>0&&n[0].time>n[n.length-1].time&&(n=n.reverse());let r=e._resolutionToSeconds(t),i=L.default.groupBy(n.reverse(),({time:e})=>Math.floor(e.getTime()/r)*r);return L.default.sortBy(Object.keys(i),e=>parseInt(e)).reduce((e,t)=>{let n=i[t],a=n[0].time.getTime(),o=new Date(a-a%r);if(n.length===0)return e;let s=n[0],c,l,u,d,f=0,p=0;return c=l=u=d=e.length===0?s.price:e[e.length-1].close,n.reverse().map(({price:e,quantity:t})=>{l=Math.min(l,e),u=Math.max(u,e),d=e,f+=t,p+=t*e}),e.push({time:new Date(o),open:c,high:u,low:l,close:d,baseVolume:f,quoteVolume:p,numTrades:n.length}),e},[])}static _mergeCandle(e,t){return!e||e.time<t.time?t:(e.numTrades+=t.numTrades,e.high=Math.max(e.high,t.high),e.low=Math.min(e.low,t.low),e.close=t.close,e.skipVolume?e.skipVolume=!1:(e.baseVolume+=t.baseVolume,e.quoteVolume+=t.quoteVolume),e)}static _resolutionToSeconds(e){return e.indexOf(`W`)>0||e.indexOf(`D`)>0?parseInt(e)*24*60*60*1e3:e.indexOf(`S`)>0?parseInt(e)*1e3:e===`D`?864e5:parseInt(e)*60*1e3}},Sm=class{listeners;constructor(){this.listeners={}}removeAllListeners(){this.listeners={}}on=(e,t)=>(e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push(t),t);off=(e,t)=>{e in this.listeners&&(t?this.listeners[e]=this.listeners[e].filter(e=>e!==t):this.listeners[e]=[])};hasListeners=e=>this.listeners[e]&&this.listeners[e].length>0;dispatchEvent=(e,t={})=>{let n=this.listeners[e];n&&n.length>0&&n.map(n=>n({eventName:e,data:t}))}},Cm=class e extends Sm{getExchange;api;id;coinraySymbol;symbol;symbolAlt;quoteCurrency;underlyingQuoteCurrency;baseLogoUrl;baseCurrency;exchangeCode;volume;quoteVolume;btcVolume;usdVolume;websocket;openPrice;highPrice;lowPrice;precisionBase;precisionQuote;precisionPrice;minBase;maxBase;maxBaseMarket;minQuote;maxQuote;minTrade;maxTrade;makerFee;takerFee;change;delistedOn;exchangeUrl;baseToUsd;quoteToUsd;status;note;_supportedOrderTypes;_lastPrice;_askPrice;_bidPrice;updatedAt;futuresSettings;symbolTv;tradingSessions;syntheticTrades;marketCap;_groupName;getPriceOverrides;static Create(t,n,r){return e.checkStatic(t),e.checkDynamic(t),new e(t,n,r)}static checkStatic(e){if(e==null?jp(e):typeof e==`object`?Array.isArray(e)&&Np(e,!1):Mp(e,!1),Fp(e.id,!1,`id`),Q(e.coinraySymbol,!1,`coinraySymbol`),Q(e.symbol,!1,`symbol`),Q(e.symbolAlt,!1,`symbolAlt`),Q(e.quoteCurrency,!1,`quoteCurrency`),Q(e.underlyingQuoteCurrency,!1,`underlyingQuoteCurrency`),Q(e.baseLogoUrl,!0,`baseLogoUrl`),Q(e.baseCurrency,!1,`baseCurrency`),Q(e.exchangeCode,!1,`exchangeCode`),Q(e.status||``,!1,`status`),Q(e.note||``,!1,`note`),Lp(e.websocket,!1,`websocket`),Fp(e.precisionBase,!1,`precisionBase`),Fp(e.precisionPrice,!1,`precisionPrice`),Fp(e.minBase,!0,`minBase`),Fp(e.precisionQuote,!1,`precisionQuote`),Fp(e.minQuote,!0,`minQuote`),Ip(e.maxBase,!0,`maxBase`),Ip(e.maxBaseMarket,!0,`maxBaseMarket`),Ip(e.maxQuote,!0,`maxQuote`),Ip(e.minTrade,!1,`minTrade`),Fp(e.maxTrade,!0,`maxTrade`),e.maxTrade===void 0&&(e.maxTrade=null),Fp(e.makerFee,!1,`makerFee`),Fp(e.takerFee,!1,`takerFee`),Rp(e.delistedOn,`delistedOn`),e.delistedOn===void 0&&(e.delistedOn=null),Q(e.exchangeUrl,!1,`exchangeUrl`),Q(e.symbolTv,!0,`symbolTv`),Q(e.groupName,!0,`groupName`),e.futuresSettings!==null&&e.futuresSettings!==void 0){let t=e.futuresSettings;Q(t.tenor,!1,`futuresSettings.tenor`),Q(t.margin,!1,`futuresSettings.margin`),Q(t.expiresAt,!0,`futuresSettings.expiresAt`),Fp(t.fundingIntervalSeconds,!0,`futuresSettings.fundingIntervalSeconds`),Ip(t.maxLeverage,!0,`futuresSettings.maxLeverage`),Q(t.groupName,!0,`futuresSettings.groupName`)}}static checkDynamic(e){Ip(e.volume,!0,`volume`),Ip(e.quoteVolume,!0,`quoteVolume`),Ip(e.btcVolume,!0,`btcVolume`),Ip(e.usdVolume,!0,`usdVolume`),Ip(e.openPrice,!0,`openPrice`),Ip(e.highPrice,!0,`highPrice`),Ip(e.lowPrice,!0,`lowPrice`),Fp(e.change,!1,`change`),Ip(e.lastPrice,!0,`lastPrice`),Ip(e.baseToUsd,!1,`baseToUsd`),Ip(e.quoteToUsd,!1,`quoteToUsd`),Ip(e.askPrice,!0,`askPrice`),Ip(e.bidPrice,!0,`bidPrice`),Q(e.updatedAt,!1,`updatedAt`),Ip(e.marketCap,!0,`marketCap`)}constructor(e,t,n){super(),this.getExchange=()=>n,this.api=t,this._assignStatic(e),this.volume=$(e.volume),this.quoteVolume=$(e.quoteVolume),this.btcVolume=$(e.btcVolume),this.usdVolume=$(e.usdVolume),this.openPrice=$(e.openPrice),this.highPrice=$(e.highPrice),this.lowPrice=$(e.lowPrice),this.change=Vp(e.change)||0,this._lastPrice=$(e.lastPrice),this.baseToUsd=$(e.baseToUsd),this.quoteToUsd=$(e.quoteToUsd),this._askPrice=$(e.askPrice),this._bidPrice=$(e.bidPrice),this.updatedAt=e.updatedAt,this.marketCap=$(e.marketCap)}assignStatic=t=>{e.checkStatic(t),this._assignStatic(t)};_assignStatic(e){if(this.id=e.id,this.coinraySymbol=e.coinraySymbol,this.symbol=e.symbol,this.symbolAlt=e.symbolAlt,this.quoteCurrency=e.quoteCurrency.toUpperCase(),this.underlyingQuoteCurrency=e.underlyingQuoteCurrency.toUpperCase(),this.baseLogoUrl=e.baseLogoUrl,this.baseCurrency=e.baseCurrency.toUpperCase(),this.exchangeCode=e.exchangeCode,this.status=e.status,this.note=e.note,this.websocket=e.websocket,this.precisionBase=e.precisionBase,this.precisionPrice=e.precisionPrice,this.precisionQuote=e.precisionQuote,this.minQuote=e.minQuote,this.minBase=e.minBase,this.maxBase=$(e.maxBase),this.maxBaseMarket=$(e.maxBaseMarket).isZero()?this.maxBase:$(e.maxBaseMarket),this.maxQuote=$(e.maxQuote),this.minTrade=$(e.minTrade),this.maxTrade=$(e.maxTrade),this.makerFee=Vp(e.makerFee),this.takerFee=Vp(e.takerFee),this.delistedOn=e.delistedOn,this.exchangeUrl=e.exchangeUrl,this._supportedOrderTypes=e.supportedOrderTypes,this.symbolTv=e.symbolTv,this._groupName=e.groupName,this.tradingSessions=e.tradingSessions??null,this.syntheticTrades=e.syntheticTrades??!1,this.futuresSettings=void 0,e.futuresSettings!==null&&e.futuresSettings!==void 0){let t=e.futuresSettings;this.futuresSettings={tenor:t.tenor,margin:t.margin,expiresAt:t.expiresAt?new Date(t.expiresAt):null,fundingIntervalSeconds:t.fundingIntervalSeconds??null,maxLeverage:t.maxLeverage!==null&&t.maxLeverage!==void 0?$(t.maxLeverage):null,groupName:t.groupName??void 0}}}get tradingDisabled(){return this.status===`INACTIVE`}get tradingEnabled(){return!this.tradingDisabled}get quoteLogoUrl(){return`https://api.coinray.eu/api/v2/explorer/currencies/${this.quoteCurrency}/thumb`}get supportedOrderTypes(){return this._supportedOrderTypes.length>0?this._supportedOrderTypes:this.getExchange().supportedOrderTypes}get isFutures(){return this.getExchange().isFutures}get groupName(){return this._groupName??this.futuresSettings?.groupName}get fullDisplayName(){return[this.exchangeCode,this.displayName].join(`: `)}get displayName(){return[this.baseCurrency,this.quoteCurrency].join(`/`)}get priceOverrides(){return this.getPriceOverrides?this.getPriceOverrides():{}}get lastPrice(){return this.priceOverrides.lastPrice||this._lastPrice}get askPrice(){return this.priceOverrides.askPrice||this._askPrice}get bidPrice(){return this.priceOverrides.bidPrice||this._bidPrice}overridePrices=e=>{this.getPriceOverrides=e};updateLastPrice=e=>{this._lastPrice=e,this.recomputeChange(),this.dispatchEvent(`price`)};recomputeChange(){this.change=this.openPrice.isZero()?0:this.lastPrice.minus(this.openPrice).dividedBy(this.openPrice).multipliedBy(100).toNumber()}updateBidAsk=(e,t)=>{this._bidPrice=e,this._askPrice=t,this.dispatchEvent(`bidask`)};updateTicker=e=>{this.openPrice=e.openPrice24h,this.highPrice=e.highPrice24h,this.lowPrice=e.lowPrice24h,this.volume=e.baseVolume,this.quoteVolume=e.quoteVolume,this.btcVolume=e.btcVolume,this.usdVolume=e.usdVolume,this.updateBidAsk(e.bidPrice,e.askPrice),this.updateLastPrice(e.lastPrice),this.dispatchEvent(`ticker`)};applySnapshot=(e,t=!1)=>{if(!t){let t=e.lastPrice!==this._lastPrice||e.openPrice24h!==this.openPrice;this._lastPrice=e.lastPrice,this._bidPrice=e.bidPrice,this._askPrice=e.askPrice,this.openPrice=e.openPrice24h,this.highPrice=e.highPrice24h,this.lowPrice=e.lowPrice24h,t&&this.recomputeChange()}this.volume=e.baseVolume,this.quoteVolume=e.quoteVolume,this.btcVolume=e.btcVolume,this.usdVolume=e.usdVolume,this.baseToUsd=e.baseToUsd,this.quoteToUsd=e.quoteToUsd,this.marketCap=e.marketCap,this.dispatchEvent(`ticker`)};clone(){let t={...this,volume:this.volume,quoteVolume:this.quoteVolume,btcVolume:this.btcVolume,usdVolume:this.usdVolume,marketCap:this.marketCap,openPrice:this.openPrice,highPrice:this.highPrice,lowPrice:this.lowPrice,lastPrice:this._lastPrice,askPrice:this._askPrice,bidPrice:this._bidPrice,maxBase:this.maxBase,maxBaseMarket:this.maxBaseMarket,maxQuote:this.maxQuote,minTrade:this.minTrade,maxTrade:this.maxTrade,baseToUsd:this.baseToUsd,quoteToUsd:this.quoteToUsd,groupName:this._groupName},n=new e(t,this.api,this.getExchange());return n.getPriceOverrides=this.getPriceOverrides,n.listeners=this.listeners,n}},wm=class e{api;id;name;code;websocket;active;aliasedTo;tradingEnabled;tradingEnabledFrom;isFutures;isDex;virtual;logo;btcVolume;usdVolume;totalMarkets;quoteCurrencies;supportedFeatures;supportedResolutions;supportedOrderTypes;baseCurrencyDominance;apiKeySettings;apiEndpoint;websocketEndpoint;markets;exchangeSymbols;static Create(t,n){return e.check(t),new e(t,n)}static check(e){if(e==null?jp(e):typeof e==`object`?Array.isArray(e)&&Np(e,!1):Mp(e,!1),Fp(e.id,!1,`id`),Q(e.name,!1,`name`),Q(e.code,!1,`code`),Lp(e.websocket,!1,`websocket`),Lp(e.active,!1,`active`),Lp(e.tradingEnabled,!1,`tradingEnabled`),Q(e.tradingEnabledFrom,!1,`tradingEnabledFrom`),Lp(e.isFutures,!0,`isFutures`),Lp(e.isDex,!0,`isDex`),Lp(e.virtual,!0,`virtual`),Q(e.logo,!1,`logo`),Q(e.btcVolume,!1,`btcVolume`),Q(e.usdVolume,!1,`usdVolume`),Fp(e.totalMarkets,!1,`totalMarkets`),Pp(e.quoteCurrencies,`quoteCurrencies`),Q(e.apiEndpoint,!0,`apiEndpoint`),Q(e.websocketEndpoint,!0,`websocketEndpoint`),Q(e.aliasedTo,!0,`aliasedTo`),e.quoteCurrencies)for(let t=0;t<e.quoteCurrencies.length;t++)Q(e.quoteCurrencies[t],!1,`quoteCurrencies[`+t+`]`);if(e.quoteCurrencies===void 0&&(e.quoteCurrencies=null),Pp(e.supportedResolutions,`supportedResolutions`),Pp(e.supportedFeatures,`supportedFeatures`),e.supportedResolutions)for(let t=0;t<e.supportedResolutions.length;t++)Q(e.supportedResolutions[t],!1,`supportedResolutions[`+t+`]`);e.supportedResolutions===void 0&&(e.supportedResolutions=null)}constructor(e,t){this.api=t,this.markets={},this.exchangeSymbols={},this._assign(e)}update(t){e.check(t),this._assign(t)}_assign(e){let t=this.api;this.id=e.id,this.name=e.name,this.code=e.code,this.websocket=e.websocket,this.isFutures=!!e.isFutures,this.isDex=!!e.isDex,this.virtual=!!e.virtual,this.active=e.active,this.tradingEnabled=e.tradingEnabled,this.tradingEnabledFrom=e.tradingEnabledFrom,this.logo=e.logo,this.btcVolume=$(e.btcVolume),this.usdVolume=$(e.usdVolume),this.totalMarkets=Hp(e.totalMarkets),this.quoteCurrencies=e.quoteCurrencies,this.supportedResolutions=e.supportedResolutions,this.supportedFeatures=e.supportedFeatures,this.supportedOrderTypes=e.supportedOrderTypes,this.baseCurrencyDominance=e.baseCurrencyDominance,this.apiKeySettings=e.apiKeySettings,this.apiEndpoint=e.apiEndpoint||t.config.apiEndpoint,this.websocketEndpoint=e.websocketEndpoint||t.config.websocketEndpoint,this.aliasedTo=e.aliasedTo}clone(){return new e({api:this.api,id:this.id,name:this.name,code:this.code,websocket:this.websocket,isFutures:this.isFutures,isDex:this.isDex,virtual:this.virtual,logo:this.logo,btcVolume:this.btcVolume,usdVolume:this.usdVolume,totalMarkets:this.totalMarkets,quoteCurrencies:this.quoteCurrencies,supportedResolutions:this.supportedResolutions,supportedFeatures:this.supportedFeatures,baseCurrencyDominance:this.baseCurrencyDominance,apiKeySettings:this.apiKeySettings,aliasedTo:this.aliasedTo},this.api)}async loadMarkets(e=void 0){let t=await this.api.fetchMarkets(this,e),n=t.map(e=>{try{return Cm.Create(e,this.api,this)}catch{return new Cm(e,this.api,this)}});return n.length>0&&(this.markets=L.default.keyBy(n,`coinraySymbol`),this.exchangeSymbols=L.default.keyBy(n,`symbol`)),t}mergeStatic(e){let t=[],n=[];if(e.length===0)return{added:t,removed:n};let r={};for(let n of e){let e=this.markets[n.coinraySymbol];try{e?(e.assignStatic(n),r[n.coinraySymbol]=e):(Cm.checkStatic(n),r[n.coinraySymbol]=new Cm(n,this.api,this),t.push(n.coinraySymbol))}catch(t){console.error(t),e&&(r[n.coinraySymbol]=e)}}for(let[e,t]of Object.entries(this.markets))r[e]||(t.removeAllListeners(),n.push(e));return this.markets=r,this.exchangeSymbols=L.default.keyBy(Object.values(r),`symbol`),{added:t,removed:n}}getBaseCurrencyDominance(e){return this.baseCurrencyDominance[e]}getMarketByExchangeSymbol(e){return this.exchangeSymbols[e]}getCurrencyPrice(e,t){for(let[n,r]of Object.entries(this.markets))if(r.baseCurrency===t)return $(e).dividedBy(r.baseToUsd);else if(r.quoteCurrency===t)return $(e).dividedBy(r.quoteToUsd);return new d(0)}getUsdPrice(e,t){for(let[n,r]of Object.entries(this.markets))if(r.baseCurrency===t)return r.baseToUsd.multipliedBy(e);else if(r.quoteCurrency===t)return r.quoteToUsd.multipliedBy(e);return new d(0)}getMarket(e){return this.markets[e]}},Tm=class{subscriptions;pendingAdditions;pendingRemovals;constructor(){this.subscriptions=new Map,this.pendingAdditions=new Map,this.pendingRemovals=new Map}has(e){let t=this.subscriptions.get(e);return t!==void 0&&t.size>0}subscribe(e,t,n=!1){n&&this.unsubscribeAll(e);for(let n of t)this.pendingAdditions.has(n)||this.pendingAdditions.set(n,new Set),this.pendingAdditions.get(n).add(e),this.pendingRemovals.has(n)&&(this.pendingRemovals.get(n).delete(e),this.pendingRemovals.get(n).size===0&&this.pendingRemovals.delete(n))}unsubscribe(e,t){for(let n of t)this.pendingAdditions.has(n)&&(this.pendingAdditions.get(n).delete(e),this.pendingAdditions.get(n).size===0&&this.pendingAdditions.delete(n)),this.pendingRemovals.has(n)||this.pendingRemovals.set(n,new Set),this.pendingRemovals.get(n).add(e)}unsubscribeAll(e){for(let[t,n]of this.subscriptions)n.has(e)&&(this.pendingRemovals.has(t)||this.pendingRemovals.set(t,new Set),this.pendingRemovals.get(t).add(e));for(let[t,n]of this.pendingAdditions)n.delete(e),n.size===0&&this.pendingAdditions.delete(t)}exchangeCodes(){let e=new Set;for(let t of this.subscriptions.keys())e.add(t.split(`_`)[0]);return e}processPendingChanges(){for(let[e,t]of this.pendingAdditions){this.subscriptions.has(e)||this.subscriptions.set(e,new Set);let n=this.subscriptions.get(e);for(let e of t)n.add(e)}for(let[e,t]of this.pendingRemovals){if(!this.subscriptions.has(e))continue;let n=this.subscriptions.get(e);for(let e of t)n.delete(e);n.size===0&&this.subscriptions.delete(e)}this.pendingAdditions.clear(),this.pendingRemovals.clear()}},Em=class extends Sm{isFormula=!0;coinraySymbol;legs;exchangeCodes;marketCap=void 0;baseCurrency=void 0;quoteCurrency=void 0;volume=void 0;quoteVolume=void 0;btcVolume=void 0;usdVolume=void 0;node;getMarket;_precisionPrice;constructor(e,t){super(),this.node=cm(e),this.coinraySymbol=e,this.legs=lm(this.node),this.exchangeCodes=[...new Set(this.legs.map(e=>e.split(`_`)[0]))],this.getMarket=t}get missingLegs(){return this.legs.filter(e=>!this.getMarket(e))}get displayName(){return this.missingLegs.length?this.coinraySymbol:_m(this.coinraySymbol,this.getMarket).name}get exchangeCode(){return this.exchangeCodes.length===1?this.exchangeCodes[0]:void 0}get status(){let e=this.legMarkets();if(e)return e.find(e=>e.status!==`ACTIVE`)?.status??`ACTIVE`}get precisionPrice(){return this._precisionPrice===void 0&&this.lastPrice&&(this._precisionPrice=_m(this.coinraySymbol,this.getMarket).pricePrecision),this._precisionPrice}get lastPrice(){return this.evaluate(e=>e.lastPrice)}get openPrice(){return this.evaluate(e=>e.openPrice)}get change(){let e=this.lastPrice,t=this.openPrice;if(e&&t&&!t.isZero())return e.minus(t).dividedBy(t).multipliedBy(100).toNumber()}legMarkets(){let e=this.legs.map(e=>this.getMarket(e));return e.every(Boolean)?e:void 0}evaluate(e){let t=this.legMarkets();if(!t)return;let n={};for(let r=0;r<this.legs.length;r++){let i=e(t[r])?.toNumber();if(!i)return;n[this.legs[r]]=i}let r=um(this.node,e=>n[e]);return Number.isFinite(r)?new d(r):void 0}},Dm=12e4,Om=6e5,km=6e5,Am=6e5,jm=250,Mm=10,Nm=e=>L.default.uniq(e.flatMap(e=>{if(!om(e))return[e];try{return lm(cm(e))}catch{return[]}})),Pm=e=>L.default.uniq(Nm(Array.isArray(e)?e:[e]).map(e=>`${e}`.split(`_`)[0])),Fm=class extends Sm{rootApi;apis;exchanges;initialized;refreshRate;_refreshingToken;tickerSubscriptions;tickerSubscriptionRefeshTimer;_onTokenExpired;onStoreCache;apiCache;rawCache={exchanges:[],markets:{}};destroyed=!1;formulaSubs=new Map;formulaMarkets=new Map;requestedTickers=new Map;loopsStarted=!1;tickersTimer;staticTimer;exchangesTimer;liveLoadTimer;activationTimer;activationPromise=null;activationResolve;pinned=new Set;leases=new Map;graceUntil=new Map;active=new Set;pendingActivation=new Set;liveMarkets=new Map;staticEtags=new Map;staticCheckedAt=new Map;endpointDownUntil={tickers:0,static:0};constructor(e,t,n=3e4,r=void 0){super(),this.rootApi=new xm(e,t),this.apis=new Map,this.exchanges={},this.initialized=!1,this.refreshRate=n,this.tickerSubscriptions=new Tm,this.tickerSubscriptionRefeshTimer=null,this.rootApi.onTokenExpired(this.refreshToken),this.onStoreCache=r?.onStoreCache,this.apiCache=r?.apiCache}async initialize(){this.initialized||=(await this.start(),!0)}getRootApi(){return this.rootApi}authenticateDevice(e,t){this.rootApi.authenticateDevice(e,t)}refreshToken=async()=>{if(this._onTokenExpired){if(this._refreshingToken)return await this._refreshingToken;{this._refreshingToken=this._onTokenExpired();let e=await this._refreshingToken;this._refreshingToken=void 0;for(let t of this.apis.values())t.refreshToken(e);return e}}};onTokenExpired(e){this._onTokenExpired=e}async start(){if(this.apiCache)try{await this.refreshExchanges(this.apiCache),this.liveLoad();return}catch(e){console.error(e)}finally{this.apiCache=void 0}await this.liveLoad()}liveLoad=async()=>{try{await this.refreshExchanges(),this.startLoops()}catch(e){console.error(e),this.destroyed||(this.liveLoadTimer=setTimeout(this.liveLoad,this.refreshRate))}};startLoops(){if(this.destroyed||this.loopsStarted)return;this.recomputeActive(),this.loopsStarted=!0;let e=Date.now();for(let t of Object.keys(this.exchanges))this.staticCheckedAt.set(t,e);this.loop(`tickersTimer`,this.tickersTick,this.refreshRate),this.loop(`staticTimer`,this.staticTick,Om),this.loop(`exchangesTimer`,this.refreshExchangeList,km)}loop(e,t,n){this.destroyed||(this[e]=setTimeout(async()=>{try{await t()}catch(e){console.error(e)}this.loop(e,t,n)},n))}destroy(){this.destroyed=!0;for(let e of this.apis.values())try{e.destroy()}catch(e){console.error(`Could not destroy coinray`,e)}for(let e of[this.tickersTimer,this.staticTimer,this.exchangesTimer,this.liveLoadTimer,this.activationTimer,this.tickerSubscriptionRefeshTimer])clearTimeout(e);this.activationResolve?.(),this.initialized=!1}refreshExchanges=async(e=void 0)=>{let t={exchanges:[],markets:{}},n=await this.rootApi.fetchExchanges(e=>(t.exchanges.push(e),this.apis.has(e.code)||this.apis.set(e.code,this.rootApi),wm.Create(e,this.apis.get(e.code))),e?.exchanges),r=await Promise.all(n.map(async t=>({[t.code]:await t.loadMarkets(e?.markets?.[t.code])})));this.destroyed||(t.markets=r.reduce((e,t)=>({...e,...t}),{}),this.exchanges=n.reduce((e,t)=>(e[t.code]=t,e),{}),this.rawCache=t,this.dispatchEvent(`marketsUpdated`,{exchangeCodes:Object.keys(this.exchanges)}),e||this.storeCache())};storeCache(){this.onStoreCache&&this.onStoreCache(this.rawCache)}setActiveExchanges(e){this.pinned=new Set(Pm(e)),this.recomputeActive()}touchExchange(e){let t=Pm(e);for(let e of t)this.leases.set(e,(this.leases.get(e)||0)+1);this.recomputeActive();let n=!1;return()=>{if(!n){n=!0;for(let e of t){let t=(this.leases.get(e)||0)-1;t>0?this.leases.set(e,t):this.leases.delete(e)}this.recomputeActive()}}}async ensureFresh(e){let t=Pm(e).filter(e=>this.exchanges[e]);if(t.length===0)return;let n=this.touchExchange(t);try{await this.scheduleActivation(t)}finally{n()}}getActiveExchanges(){return[...this.recomputeActive()].sort()}retainLiveMarket(e){this.liveMarkets.set(e,(this.liveMarkets.get(e)||0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this.liveMarkets.get(e)||0)-1;n>0?this.liveMarkets.set(e,n):this.liveMarkets.delete(e)}}isLive(e){return this.tickerSubscriptions.has(e)||this.liveMarkets.has(e)}recomputeActive(){let e=Date.now(),t=new Set([...this.pinned,...this.leases.keys(),...this.tickerSubscriptions.exchangeCodes()]);for(let e of t)this.graceUntil.delete(e);for(let n of this.active)!t.has(n)&&!this.graceUntil.has(n)&&this.graceUntil.set(n,e+Dm);for(let[n,r]of this.graceUntil)r<=e?this.graceUntil.delete(n):t.add(n);let n=new Set([...t].filter(e=>this.exchanges[e]));if(this.loopsStarted){let e=[...n].filter(e=>!this.active.has(e));e.length&&this.scheduleActivation(e)}return this.active=n,n}scheduleActivation(e){if(this.destroyed)return Promise.resolve();for(let t of e)this.pendingActivation.add(t);return this.activationPromise||=new Promise(e=>{this.activationResolve=e,this.activationTimer=setTimeout(async()=>{let t=[...this.pendingActivation];this.pendingActivation.clear(),this.activationPromise=null;try{await this.fetchTickers(t);let e=Date.now(),n=t.filter(t=>e-(this.staticCheckedAt.get(t)||0)>=Om);Promise.all(n.map(this.revalidateStatic)).then(e=>e.some(Boolean)&&this.storeCache()),this.destroyed||this.dispatchEvent(`marketsUpdated`,{exchangeCodes:t})}catch(e){console.error(e)}e()},jm)}),this.activationPromise}tickersTick=async()=>{let e=[...this.recomputeActive()].sort();await this.fetchTickers(e),this.destroyed||this.dispatchEvent(`marketsUpdated`,{exchangeCodes:e})};staticTick=async()=>{(await Promise.all([...this.recomputeActive()].map(this.revalidateStatic))).some(Boolean)&&this.storeCache()};fetchTickers=async e=>{this.destroyed||await Promise.all(L.default.chunk([...e].sort(),Mm).map(async e=>{if(Date.now()<this.endpointDownUntil.tickers)return Promise.all(e.map(this.refreshMarkets));try{let t=await this.rootApi.fetchTickers(e);if(this.endpointDownUntil.tickers=0,this.destroyed)return;for(let[e,n]of Object.entries(t)){let t=this.exchanges[e];if(t)for(let e of n)t.markets[e.coinraySymbol]?.applySnapshot(e,this.isLive(e.coinraySymbol))}}catch(t){this.markEndpointDown(`tickers`,t)?await Promise.all(e.map(this.refreshMarkets)):console.error(t)}}))};revalidateStatic=async e=>{let t=this.exchanges[e];if(!t||this.destroyed)return!1;if(Date.now()<this.endpointDownUntil.static)return await this.refreshMarkets(e),!0;try{let{markets:n,etag:r}=await this.rootApi.fetchStaticMarkets(e,this.staticEtags.get(e));if(this.endpointDownUntil.static=0,this.staticCheckedAt.set(e,Date.now()),this.destroyed||!n)return!1;r&&this.staticEtags.set(e,r);let i=L.default.keyBy(this.rawCache.markets[e]||[],`coinraySymbol`),a=n.map(e=>({...i[e.coinraySymbol],...e})),{added:o}=t.mergeStatic(a);return a.length&&(this.rawCache.markets[e]=a),o.length&&this.scheduleActivation([e]),this.dispatchEvent(`marketsUpdated`,{exchangeCodes:[e]}),!0}catch(t){return this.markEndpointDown(`static`,t)?(await this.refreshMarkets(e),!0):(console.error(t),!1)}};markEndpointDown(e,t){return t?.status===404||t?.isAxiosError&&!t.response?(this.endpointDownUntil[e]||console.warn(`CoinrayCache: ${e} endpoint unavailable (${t?.message}), falling back to /markets`),this.endpointDownUntil[e]=Date.now()+Am,!0):!1}refreshExchangeList=async()=>{let e=await this.rootApi.fetchExchanges(e=>e,void 0);if(this.destroyed)return;let t={},n=[];for(let r of e){this.apis.has(r.code)||this.apis.set(r.code,this.rootApi);let e=this.exchanges[r.code];try{e?(e.update(r),t[r.code]=e):(t[r.code]=wm.Create(r,this.apis.get(r.code)),n.push(r.code))}catch(n){console.error(n),e&&(t[r.code]=e)}}let r=Object.keys(this.exchanges).filter(e=>!t[e]);this.exchanges=t,this.rawCache.exchanges=e;for(let e of r)delete this.rawCache.markets[e];await Promise.all(n.map(this.refreshMarkets)),(n.length||r.length)&&(this.dispatchEvent(`marketsUpdated`,{exchangeCodes:n}),this.storeCache())};getProxyList=async(e={})=>await this.rootApi.getProxyList(e);getExchanges(){if(!this.initialized)throw`The cache is not initialized yet`;return this.exchanges}getExchange(e){return this.getExchanges()[e]||wm.Create({id:-1,name:e,code:e,websocket:!1,active:!1,tradingEnabled:!1,tradingEnabledFrom:``,isFutures:!1,isDex:!1,logo:`data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
|
|
34
|
-
`,btcVolume:`0`,usdVolume:`0`,totalMarkets:0,quoteCurrencies:[]},this.rootApi)}refreshMarkets=async e=>{let t=this.exchanges[e];if(t&&!this.destroyed)try{let n=await t.loadMarkets();n.length&&(this.rawCache.markets[e]=n),this.staticCheckedAt.set(e,Date.now())}catch(e){console.error(e)}};searchMarkets(e){return Object.values(this.exchanges).reduce((t,n)=>(t={...t,...Qp(n.markets,e)},t),{})}getMarkets(e){switch(typeof e){case`string`:return this.getExchange(e).markets;default:return e.reduce((e,t)=>{let n=this.getMarket(t);return n&&(e[t]=n),e},{})}}getMarket=e=>{let t=`${e}`.split(`_`);if(t.length<3)return;let n=this.getExchange(t[0]);if(n)return n.getMarket(e)};async fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i}){if(om(e)){let{node:a,legs:o}=this.parseFormulaSymbol(e),s=t.endsWith(`S`)?void 0:this.formulaApi(o);if(s)try{return await s.fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})}catch{}let c=await Promise.all(o.map(e=>this.fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})));return mm(a,L.default.zipObject(o,c))}return this.apiForSymbol(e).fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})}async fetchFirstCandleTime({coinraySymbol:e,resolution:t}){if(om(e)){let{legs:n}=this.parseFormulaSymbol(e),r=this.formulaApi(n);if(r)try{return await r.fetchFirstCandleTime({coinraySymbol:e,resolution:t})}catch{}let i=await Promise.all(n.map(e=>this.fetchFirstCandleTime({coinraySymbol:e,resolution:t})));return L.default.maxBy(i,e=>new Date(e).getTime())}return this.apiForSymbol(e).fetchFirstCandleTime({coinraySymbol:e,resolution:t})}subscribeTickers(e,t,n=!1){this.updateRequestedTickers(e,e=>{n&&e.clear();for(let n of t)e.add(n)}),this.tickerSubscriptions.subscribe(e,Nm(t)),this.scheduleTickerRefresh()}updateRequestedTickers(e,t){let n=this.requestedTickers.get(e)??new Set,r=Nm([...n]);t(n),n.size?this.requestedTickers.set(e,n):this.requestedTickers.delete(e);let i=L.default.difference(r,Nm([...n]));i.length&&this.tickerSubscriptions.unsubscribe(e,i)}scheduleTickerRefresh(){this.destroyed||(this.tickerSubscriptionRefeshTimer&&clearTimeout(this.tickerSubscriptionRefeshTimer),this.tickerSubscriptionRefeshTimer=setTimeout(async()=>{await this.flushTickerSubscriptions(),this.tickerSubscriptionRefeshTimer=null},1e3))}unsubscribeAllTickers(e){this.requestedTickers.delete(e),this.tickerSubscriptions.unsubscribeAll(e),this.scheduleTickerRefresh()}unsubscribeTickers(e,t){this.updateRequestedTickers(e,e=>{for(let n of t)e.delete(n)}),this.scheduleTickerRefresh()}async flushTickerSubscriptions(){let e=[],t=[];for(let t of this.tickerSubscriptions.pendingAdditions.keys())e.push(t);for(let[e,n]of this.tickerSubscriptions.pendingRemovals.entries()){let r=new Set(this.tickerSubscriptions.subscriptions.get(e)||[]);for(let e of n)r.delete(e);let i=this.tickerSubscriptions.pendingAdditions.get(e);if(i)for(let e of i)r.add(e);r.size===0&&t.push(e)}e.length&&await this.rootApi.subscribeTickers(e,!1,this.refreshMarketsFromTickers),t.length&&this.rootApi.unsubscribeTickers(t,this.refreshMarketsFromTickers),this.tickerSubscriptions.processPendingChanges(),this.recomputeActive()}refreshMarketsFromTickers=async e=>{let{exchangeCode:t,tickers:n}=e,r=this.getExchange(t);if(r){let e=!1;for(let t of n)if(this.tickerSubscriptions.has(t.coinraySymbol)){let n=r.getMarket(t.coinraySymbol);n&&(n.updateTicker(t),e=!0)}e&&this.dispatchEvent(`tickersUpdated`,{exchangeCode:t,coinraySymbols:n.map(e=>e.coinraySymbol)})}};async subscribeCandles({coinraySymbol:e,resolution:t,lastCandle:n},r){if(om(e)){let{node:n,legs:i}=this.parseFormulaSymbol(e),a={},o=i.map(i=>[i,({candle:o})=>{a[i]=o;let s=hm(n,a);s&&r({coinraySymbol:e,resolution:t,candle:s,previousCandles:[]})}]),s=`${e}-${t}`;return this.formulaSubs.has(s)||this.formulaSubs.set(s,new Map),this.formulaSubs.get(s).set(r,o),await Promise.all(o.map(([e,n])=>this.subscribeCandles({coinraySymbol:e,resolution:t},n))),r}return this.apiForSymbol(e).subscribeCandles({coinraySymbol:e,resolution:t,lastCandle:n},r)}async unsubscribeCandles({coinraySymbol:e,resolution:t},n){if(om(e)){let r=this.formulaSubs.get(`${e}-${t}`);if(!r)return;for(let e of n?[n]:[...r.keys()]){for(let[n,i]of r.get(e)??[])await this.unsubscribeCandles({coinraySymbol:n,resolution:t},i);r.delete(e)}return}await this.apiForSymbol(e).unsubscribeCandles({coinraySymbol:e,resolution:t},n)}async subscribeOrderBook({coinraySymbol:e},t){if(om(e))throw Error(`Not supported for formula symbols`);await this.apiForSymbol(e).subscribeOrderBook({coinraySymbol:e},t)}async unsubscribeOrderBook({coinraySymbol:e},t){await this.apiForSymbol(e).unsubscribeOrderBook({coinraySymbol:e},t)}async subscribeTrades({coinraySymbol:e},t){if(om(e))throw Error(`Not supported for formula symbols`);await this.apiForSymbol(e).subscribeTrades({coinraySymbol:e},t)}async unsubscribeTrades({coinraySymbol:e},t){await this.apiForSymbol(e).unsubscribeTrades({coinraySymbol:e},t)}getFormulaMarket(e){if(!om(e))return;let t=this.formulaMarkets.get(e);if(!t){try{t=new Em(e,this.getMarket)}catch{return}this.formulaMarkets.set(e,t)}return t}getMarketOrFormula(e){return om(e)?this.getFormulaMarket(e):this.getMarket(e)}formulaSymbolInfo(e){return _m(e,this.getMarket)}parseFormulaSymbol(e){let t=cm(e),n=lm(t),r=n.find(e=>!this.apiForSymbol(e));if(r)throw Error(`Unknown exchange for ${r}`);return{node:t,legs:n}}formulaApi(e){let t=new Set(e.map(e=>this.apiForSymbol(e)));return t.size===1?[...t][0]:void 0}apiForSymbol(e){let t=`${e}`.split(`_`);if(t.length<3)return;let n=t[0];return this.apis.get(n)}},Im=class extends Error{constructor(e){super(e),this.name=`MarketNotFoundError`}},Lm=class extends Sm{coinrayCache;getPriceOverrides;coinraySymbol;orderBook;trades;tradesDelayed;maxTrades;releaseLiveMarket;prevTickers={lastPrice:new d(0),askPrice:new d(0),bidPrice:new d(0)};constructor(e,t={}){super(),this.coinrayCache=e,this.maxTrades=t.maxTrades||100,t.getPriceOverrides&&(this.getPriceOverrides=t.getPriceOverrides),this.destroy()}setCoinraySymbol(e){this.dispatchEvent(`coinraySymbolWillChange`,{coinraySymbol:e}),this.stop(),this.releaseLiveMarket?.(),this.releaseLiveMarket=e?this.coinrayCache.retainLiveMarket?.(e):void 0,this.coinraySymbol=e,this.startOrderBook(),this.startTrades(),this.dispatchEvent(`coinraySymbolChanged`,{coinraySymbol:e})}destroy(){this.releaseLiveMarket?.(),this.releaseLiveMarket=void 0,this.coinraySymbol=null,this.removeAllListeners(),this.stop()}stop(){this.stopOrderBook(),this.stopTrades()}getExchange(){return this.coinrayCache.getExchange(this.getMarket().exchangeCode)}getMarket(){if(this.coinraySymbol){let e=this.coinrayCache.getMarket(this.coinraySymbol);return e.overridePrices(this.getPriceOverrides),e}throw new Im(`Market not found: ${this.coinraySymbol}`)}subscribeCoinraySymbolWillChange(e){return this.on(`coinraySymbolWillChange`,e)}unsubscribeCoinraySymbolWillChange(e){this.off(`coinraySymbolWillChange`,e)}subscribeCoinraySymbolChange(e){return this.on(`coinraySymbolChanged`,e)}unsubscribeCoinraySymbolChange(e){this.off(`coinraySymbolChanged`,e)}subscribeMarketUpdates=e=>(this.on(`marketUpdated`,e),this.subscribeOrderBook(this.handleMarketUpdate),this.subscribeTrades(this.handleMarketUpdate),e);updatePrevTicker=({lastPrice:e,bidPrice:t,askPrice:n})=>{e&&(this.prevTickers.lastPrice=$(e)),n&&(this.prevTickers.askPrice=$(n)),t&&(this.prevTickers.bidPrice=$(t))};handleMarketUpdate=({data:{type:e,coinraySymbol:t,...n}})=>{if(this.coinraySymbol!==t){this.unsubscribeOrderBook(this.handleOrderBook),this.unsubscribeTrades(this.handleOrderBook);return}switch(e){case`trades:snapshot`:case`trades:update`:{let{trades:e}=n;if(e.length===0)break;let t=this.getMarket(),r=$(e[0].price);(!t._lastPrice.eq(r)||!this.prevTickers.lastPrice.eq(r))&&(t.updateLastPrice(r),this.updatePrevTicker({lastPrice:r}),this.dispatchEvent(`marketUpdated`,{market:t}));break}case`orderBook:snapshot`:case`orderBook:update`:{let{orderBook:{bids:e,asks:t}}=n,r=this.getMarket();if(e.length===0||t.length===0)break;let i=t[0].price,a=e[0].price,o=!r._askPrice.eq(i)||!r._bidPrice.eq(a),s=!this.prevTickers.askPrice.eq(i)||!this.prevTickers.bidPrice.eq(a);(o||s)&&(r.updateBidAsk(a,i),this.updatePrevTicker({askPrice:i,bidPrice:a}),this.dispatchEvent(`marketUpdated`,{market:r}));break}}};unsubscribeMarketUpdates=e=>{this.off(`marketUpdated`,e),this.hasListeners(`marketUpdated`)||(this.unsubscribeOrderBook(this.handleMarketUpdate),this.unsubscribeTrades(this.handleMarketUpdate))};subscribeOrderBook=e=>(this.on(`orderBookUpdated`,e),this.startOrderBook(),e);startOrderBook=()=>{this.coinraySymbol&&this.hasListeners(`orderBookUpdated`)&&this.coinrayCache.subscribeOrderBook({coinraySymbol:this.coinraySymbol},this.handleOrderBook)};stopOrderBook=()=>{this.coinraySymbol&&this.coinrayCache.unsubscribeOrderBook({coinraySymbol:this.coinraySymbol},this.handleOrderBook),this.orderBook={minSeq:void 0,maxSeq:void 0,bids:{},asks:{}}};handleOrderBook=async({type:e,coinraySymbol:t,orderBook:n})=>{if(this.coinraySymbol!==t){this.coinrayCache.unsubscribeOrderBook({coinraySymbol:t},this.handleOrderBook);return}e===`orderBook:snapshot`&&(this.orderBook={minSeq:void 0,maxSeq:void 0,bids:{},asks:{}});let{minSeq:r,maxSeq:i,bids:a,asks:o}=n,s=(e,t)=>{L.default.forEach(t,(t,n)=>{t>0?e[n]={price:new d(n),quantity:t}:delete e[n]})};if(r-this.orderBook.maxSeq>1){this.stopOrderBook(),this.startOrderBook();return}this.orderBook.minSeq=r,this.orderBook.maxSeq=i,s(this.orderBook.bids,a),s(this.orderBook.asks,o),this.dispatchEvent(`orderBookUpdated`,{type:e,coinraySymbol:t,orderBook:{minSeq:r,maxSeq:i,bids:Object.values(this.orderBook.bids).sort(({price:e},{price:t})=>t.minus(e)),asks:Object.values(this.orderBook.asks).sort(({price:e},{price:t})=>e.minus(t))}})};unsubscribeOrderBook=e=>{this.off(`orderBookUpdated`,e),this.hasListeners(`orderBookUpdated`)||this.stopOrderBook()};subscribeTrades=e=>(this.on(`tradesUpdated`,e),this.startTrades(),e);startTrades=()=>{this.coinraySymbol&&this.hasListeners(`tradesUpdated`)&&this.coinrayCache.subscribeTrades({coinraySymbol:this.coinraySymbol},this.handleTrades)};stopTrades=()=>{this.coinraySymbol&&this.coinrayCache.unsubscribeTrades({coinraySymbol:this.coinraySymbol},this.handleTrades),this.trades=[]};handleTrades=({type:e,coinraySymbol:t,trades:n})=>{if(this.coinraySymbol!==t){this.coinrayCache.unsubscribeTrades({coinraySymbol:t},this.handleTrades);return}if(e===`trades:snapshot`&&(this.trades=[]),this.trades=[...n,...this.trades].sort((e,t)=>t.time.getTime()-e.time.getTime()).slice(0,this.maxTrades),this.dispatchEvent(`tradesUpdated`,{type:e,coinraySymbol:t,trades:this.trades}),!this.trades.length)return;let r=Date.now()-this.trades[0].time.getTime();e===`trades:snapshot`&&this.tradesDelayed?this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!1,delayInMs:r}):e===`trades:update`&&(this.tradesDelayed&&r<3e4?this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!1,delayInMs:r}):!this.tradesDelayed&&r>=3e4&&this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!0,delayInMs:r}))};dispatchTradesDelayed=({type:e,coinraySymbol:t,tradesDelayed:n,delayInMs:r})=>{this.tradesDelayed=n,this.dispatchEvent(`tradesDelayed`,{type:e,coinraySymbol:t,tradesDelayed:n,delayInMs:r})};unsubscribeTrades=e=>{this.off(`tradesUpdated`,e),this.hasListeners(`tradesUpdated`)||this.stopTrades()};subscribeTradesDelayed=e=>(this.on(`tradesDelayed`,e),e);unsubscribeTradesDelayed=e=>{this.off(`tradesDelayed`,e)}},Rm={"en-US":{validation:{notGreaterThanOrEqualTo:`Can't be less than {{min}}`,insufficientFunds:`Insufficient funds`}},nl:{validation:{notGreaterThanOrEqualTo:`Kan niet minder zijn dan {{min}}`,insufficientFunds:`Onvoldoende balans`}},ru:{validation:{notGreaterThanOrEqualTo:`Не может быть меньше {{min}}`,insufficientFunds:`Недостаточно средств`}}},zm=u(s(((e,t)=>{(function(e,t,n){"use strict";var r=function(e,t,n){n=i.extend({},i.options,n);var a=i.runValidations(e,t,n);if(a.some(function(e){return i.isPromise(e.error)}))throw Error(`Use validate.async if you want support for promises`);return r.processValidationResults(a,n)},i=r;i.extend=function(e){return[].slice.call(arguments,1).forEach(function(t){for(var n in t)e[n]=t[n]}),e},i.extend(r,{version:{major:0,minor:13,patch:1,metadata:null,toString:function(){var e=i.format(`%{major}.%{minor}.%{patch}`,i.version);return i.isEmpty(i.version.metadata)||(e+=`+`+i.version.metadata),e}},Promise:typeof Promise<`u`?Promise:null,EMPTY_STRING_REGEXP:/^\s*$/,runValidations:function(e,t,n){var r=[],a,o,s,c,l,u,d;for(a in(i.isDomElement(e)||i.isJqueryElement(e))&&(e=i.collectFormValues(e)),t)for(o in s=i.getDeepObjectValue(e,a),c=i.result(t[a],s,e,a,n,t),c){if(l=i.validators[o],!l)throw d=i.format(`Unknown validator %{name}`,{name:o}),Error(d);u=c[o],u=i.result(u,s,e,a,n,t),u&&r.push({attribute:a,value:s,validator:o,globalOptions:n,attributes:e,options:u,error:l.call(l,s,u,a,e,n)})}return r},processValidationResults:function(e,t){e=i.pruneEmptyErrors(e,t),e=i.expandMultipleErrors(e,t),e=i.convertErrorMessages(e,t);var n=t.format||`grouped`;if(typeof i.formatters[n]==`function`)e=i.formatters[n](e);else throw Error(i.format(`Unknown format %{format}`,t));return i.isEmpty(e)?void 0:e},async:function(e,t,n){n=i.extend({},i.async.options,n);var r=n.wrapErrors||function(e){return e};n.cleanAttributes!==!1&&(e=i.cleanAttributes(e,t));var a=i.runValidations(e,t,n);return new i.Promise(function(o,s){i.waitForResults(a).then(function(){var c=i.processValidationResults(a,n);c?s(new r(c,n,e,t)):o(e)},function(e){s(e)})})},single:function(e,t,n){return n=i.extend({},i.single.options,n,{format:`flat`,fullMessages:!1}),i({single:e},{single:t},n)},waitForResults:function(e){return e.reduce(function(e,t){return i.isPromise(t.error)?e.then(function(){return t.error.then(function(e){t.error=e||null})}):e},new i.Promise(function(e){e()}))},result:function(e){var t=[].slice.call(arguments,1);return typeof e==`function`&&(e=e.apply(null,t)),e},isNumber:function(e){return typeof e==`number`&&!isNaN(e)},isFunction:function(e){return typeof e==`function`},isInteger:function(e){return i.isNumber(e)&&e%1==0},isBoolean:function(e){return typeof e==`boolean`},isObject:function(e){return e===Object(e)},isDate:function(e){return e instanceof Date},isDefined:function(e){return e!=null},isPromise:function(e){return!!e&&i.isFunction(e.then)},isJqueryElement:function(e){return e&&i.isString(e.jquery)},isDomElement:function(e){return!e||!e.querySelectorAll||!e.querySelector?!1:i.isObject(document)&&e===document?!0:typeof HTMLElement==`object`?e instanceof HTMLElement:e&&typeof e==`object`&&!!e&&e.nodeType===1&&typeof e.nodeName==`string`},isEmpty:function(e){var t;if(!i.isDefined(e))return!0;if(i.isFunction(e))return!1;if(i.isString(e))return i.EMPTY_STRING_REGEXP.test(e);if(i.isArray(e))return e.length===0;if(i.isDate(e))return!1;if(i.isObject(e)){for(t in e)return!1;return!0}return!1},format:i.extend(function(e,t){return i.isString(e)?e.replace(i.format.FORMAT_REGEXP,function(e,n,r){return n===`%`?`%{`+r+`}`:String(t[r])}):e},{FORMAT_REGEXP:/(%?)%\{([^\}]+)\}/g}),prettify:function(e){return i.isNumber(e)?e*100%1==0?``+e:parseFloat(Math.round(e*100)/100).toFixed(2):i.isArray(e)?e.map(function(e){return i.prettify(e)}).join(`, `):i.isObject(e)?i.isDefined(e.toString)?e.toString():JSON.stringify(e):(e=``+e,e.replace(/([^\s])\.([^\s])/g,`$1 $2`).replace(/\\+/g,``).replace(/[_-]/g,` `).replace(/([a-z])([A-Z])/g,function(e,t,n){return``+t+` `+n.toLowerCase()}).toLowerCase())},stringifyValue:function(e,t){return(t&&t.prettify||i.prettify)(e)},isString:function(e){return typeof e==`string`},isArray:function(e){return{}.toString.call(e)===`[object Array]`},isHash:function(e){return i.isObject(e)&&!i.isArray(e)&&!i.isFunction(e)},contains:function(e,t){return i.isDefined(e)?i.isArray(e)?e.indexOf(t)!==-1:t in e:!1},unique:function(e){return i.isArray(e)?e.filter(function(e,t,n){return n.indexOf(e)==t}):e},forEachKeyInKeypath:function(e,t,n){if(i.isString(t)){var r=``,a,o=!1;for(a=0;a<t.length;++a)switch(t[a]){case`.`:o?(o=!1,r+=`.`):(e=n(e,r,!1),r=``);break;case`\\`:o?(o=!1,r+=`\\`):o=!0;break;default:o=!1,r+=t[a]}return n(e,r,!0)}},getDeepObjectValue:function(e,t){if(i.isObject(e))return i.forEachKeyInKeypath(e,t,function(e,t){if(i.isObject(e))return e[t]})},collectFormValues:function(e,t){var n={},r,a,o,s,c,l;if(i.isJqueryElement(e)&&(e=e[0]),!e)return n;for(t||={},s=e.querySelectorAll(`input[name], textarea[name]`),r=0;r<s.length;++r)if(o=s.item(r),!i.isDefined(o.getAttribute(`data-ignored`))){var u=o.name.replace(/\./g,`\\\\.`);l=i.sanitizeFormValue(o.value,t),o.type===`number`?l=l?+l:null:o.type===`checkbox`?o.attributes.value?o.checked||(l=n[u]||null):l=o.checked:o.type===`radio`&&(o.checked||(l=n[u]||null)),n[u]=l}for(s=e.querySelectorAll(`select[name]`),r=0;r<s.length;++r)if(o=s.item(r),!i.isDefined(o.getAttribute(`data-ignored`))){if(o.multiple)for(a in l=[],o.options)c=o.options[a],c&&c.selected&&l.push(i.sanitizeFormValue(c.value,t));else{var d=o.options[o.selectedIndex]===void 0?``:o.options[o.selectedIndex].value;l=i.sanitizeFormValue(d,t)}n[o.name]=l}return n},sanitizeFormValue:function(e,t){return t.trim&&i.isString(e)&&(e=e.trim()),t.nullify!==!1&&e===``?null:e},capitalize:function(e){return i.isString(e)?e[0].toUpperCase()+e.slice(1):e},pruneEmptyErrors:function(e){return e.filter(function(e){return!i.isEmpty(e.error)})},expandMultipleErrors:function(e){var t=[];return e.forEach(function(e){i.isArray(e.error)?e.error.forEach(function(n){t.push(i.extend({},e,{error:n}))}):t.push(e)}),t},convertErrorMessages:function(e,t){t||={};var n=[],r=t.prettify||i.prettify;return e.forEach(function(e){var a=i.result(e.error,e.value,e.attribute,e.options,e.attributes,e.globalOptions);if(!i.isString(a)){n.push(e);return}a[0]===`^`?a=a.slice(1):t.fullMessages!==!1&&(a=i.capitalize(r(e.attribute))+` `+a),a=a.replace(/\\\^/g,`^`),a=i.format(a,{value:i.stringifyValue(e.value,t)}),n.push(i.extend({},e,{error:a}))}),n},groupErrorsByAttribute:function(e){var t={};return e.forEach(function(e){var n=t[e.attribute];n?n.push(e):t[e.attribute]=[e]}),t},flattenErrorsToArray:function(e){return e.map(function(e){return e.error}).filter(function(e,t,n){return n.indexOf(e)===t})},cleanAttributes:function(e,t){function n(e,t,n){return i.isObject(e[t])?e[t]:e[t]=n?!0:{}}function r(e){var t={},r;for(r in e)e[r]&&i.forEachKeyInKeypath(t,r,n);return t}function a(e,t){if(!i.isObject(e))return e;var n=i.extend({},e),r,o;for(o in e)r=t[o],i.isObject(r)?n[o]=a(n[o],r):r||delete n[o];return n}return!i.isObject(t)||!i.isObject(e)?{}:(t=r(t),a(e,t))},exposeModule:function(e,t,n,r,i){n?(r&&r.exports&&(n=r.exports=e),n.validate=e):(t.validate=e,e.isFunction(i)&&i.amd&&i([],function(){return e}))},warn:function(e){typeof console<`u`&&console.warn&&console.warn(`[validate.js] `+e)},error:function(e){typeof console<`u`&&console.error&&console.error(`[validate.js] `+e)}}),r.validators={presence:function(e,t){if(t=i.extend({},this.options,t),t.allowEmpty===!1?i.isEmpty(e):!i.isDefined(e))return t.message||this.message||`can't be blank`},length:function(e,t,n){if(i.isDefined(e)){t=i.extend({},this.options,t);var r=t.is,a=t.maximum,o=t.minimum,s=t.tokenizer||function(e){return e},c,l=[];e=s(e);var u=e.length;if(!i.isNumber(u))return t.message||this.notValid||`has an incorrect length`;if(i.isNumber(r)&&u!==r&&(c=t.wrongLength||this.wrongLength||`is the wrong length (should be %{count} characters)`,l.push(i.format(c,{count:r}))),i.isNumber(o)&&u<o&&(c=t.tooShort||this.tooShort||`is too short (minimum is %{count} characters)`,l.push(i.format(c,{count:o}))),i.isNumber(a)&&u>a&&(c=t.tooLong||this.tooLong||`is too long (maximum is %{count} characters)`,l.push(i.format(c,{count:a}))),l.length>0)return t.message||l}},numericality:function(e,t,n,r,a){if(i.isDefined(e)){t=i.extend({},this.options,t);var o=[],s,c,l={greaterThan:function(e,t){return e>t},greaterThanOrEqualTo:function(e,t){return e>=t},equalTo:function(e,t){return e===t},lessThan:function(e,t){return e<t},lessThanOrEqualTo:function(e,t){return e<=t},divisibleBy:function(e,t){return e%t===0}},u=t.prettify||a&&a.prettify||i.prettify;if(i.isString(e)&&t.strict){var d=`^-?(0|[1-9]\\d*)`;if(t.onlyInteger||(d+=`(\\.\\d+)?`),d+=`$`,!new RegExp(d).test(e))return t.message||t.notValid||this.notValid||this.message||`must be a valid number`}if(t.noStrings!==!0&&i.isString(e)&&!i.isEmpty(e)&&(e=+e),!i.isNumber(e))return t.message||t.notValid||this.notValid||this.message||`is not a number`;if(t.onlyInteger&&!i.isInteger(e))return t.message||t.notInteger||this.notInteger||this.message||`must be an integer`;for(s in l)if(c=t[s],i.isNumber(c)&&!l[s](e,c)){var f=`not`+i.capitalize(s),p=t[f]||this[f]||this.message||`must be %{type} %{count}`;o.push(i.format(p,{count:c,type:u(s)}))}if(t.odd&&e%2!=1&&o.push(t.notOdd||this.notOdd||this.message||`must be odd`),t.even&&e%2!=0&&o.push(t.notEven||this.notEven||this.message||`must be even`),o.length)return t.message||o}},datetime:i.extend(function(e,t){if(!i.isFunction(this.parse)||!i.isFunction(this.format))throw Error(`Both the parse and format functions needs to be set to use the datetime/date validator`);if(i.isDefined(e)){t=i.extend({},this.options,t);var n,r=[],a=t.earliest?this.parse(t.earliest,t):NaN,o=t.latest?this.parse(t.latest,t):NaN;if(e=this.parse(e,t),isNaN(e)||t.dateOnly&&e%864e5!=0)return n=t.notValid||t.message||this.notValid||`must be a valid date`,i.format(n,{value:arguments[0]});if(!isNaN(a)&&e<a&&(n=t.tooEarly||t.message||this.tooEarly||`must be no earlier than %{date}`,n=i.format(n,{value:this.format(e,t),date:this.format(a,t)}),r.push(n)),!isNaN(o)&&e>o&&(n=t.tooLate||t.message||this.tooLate||`must be no later than %{date}`,n=i.format(n,{date:this.format(o,t),value:this.format(e,t)}),r.push(n)),r.length)return i.unique(r)}},{parse:null,format:null}),date:function(e,t){return t=i.extend({},t,{dateOnly:!0}),i.validators.datetime.call(i.validators.datetime,e,t)},format:function(e,t){(i.isString(t)||t instanceof RegExp)&&(t={pattern:t}),t=i.extend({},this.options,t);var n=t.message||this.message||`is invalid`,r=t.pattern,a;if(i.isDefined(e)&&(!i.isString(e)||(i.isString(r)&&(r=new RegExp(t.pattern,t.flags)),a=r.exec(e),!a||a[0].length!=e.length)))return n},inclusion:function(e,t){if(i.isDefined(e)&&(i.isArray(t)&&(t={within:t}),t=i.extend({},this.options,t),!i.contains(t.within,e))){var n=t.message||this.message||`^%{value} is not included in the list`;return i.format(n,{value:e})}},exclusion:function(e,t){if(i.isDefined(e)&&(i.isArray(t)&&(t={within:t}),t=i.extend({},this.options,t),i.contains(t.within,e))){var n=t.message||this.message||`^%{value} is restricted`;return i.isString(t.within[e])&&(e=t.within[e]),i.format(n,{value:e})}},email:i.extend(function(e,t){t=i.extend({},this.options,t);var n=t.message||this.message||`is not a valid email`;if(i.isDefined(e)&&(!i.isString(e)||!this.PATTERN.exec(e)))return n},{PATTERN:/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i}),equality:function(e,t,n,r,a){if(i.isDefined(e)){i.isString(t)&&(t={attribute:t}),t=i.extend({},this.options,t);var o=t.message||this.message||`is not equal to %{attribute}`;if(i.isEmpty(t.attribute)||!i.isString(t.attribute))throw Error(`The attribute must be a non empty string`);var s=i.getDeepObjectValue(r,t.attribute),c=t.comparator||function(e,t){return e===t},l=t.prettify||a&&a.prettify||i.prettify;if(!c(e,s,t,n,r))return i.format(o,{attribute:l(t.attribute)})}},url:function(e,t){if(i.isDefined(e)){t=i.extend({},this.options,t);var n=t.message||this.message||`is not a valid url`,r=t.schemes||this.schemes||[`http`,`https`],a=t.allowLocal||this.allowLocal||!1,o=t.allowDataUrl||this.allowDataUrl||!1;if(!i.isString(e))return n;var s=`^(?:(?:`+r.join(`|`)+`)://)(?:\\S+(?::\\S*)?@)?(?:`,c=`(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))`;if(a?c+=`?`:s+=`(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})`,s+=`(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*`+c+`)(?::\\d{2,5})?(?:[/?#]\\S*)?$`,o&&(s=`(?:`+s+`)|(?:^data:(?:\\w+\\/[-+.\\w]+(?:;[\\w=]+)*)?(?:;base64)?,[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*$)`),!new RegExp(s,`i`).exec(e))return n}},type:i.extend(function(e,t,n,r,a){if(i.isString(t)&&(t={type:t}),i.isDefined(e)){var o=i.extend({},this.options,t),s=o.type;if(!i.isDefined(s))throw Error(`No type was specified`);var c=i.isFunction(s)?s:this.types[s];if(!i.isFunction(c))throw Error(`validate.validators.type.types.`+s+` must be a function.`);if(!c(e,o,n,r,a)){var l=t.message||this.messages[s]||this.message||o.message||(i.isFunction(s)?`must be of the correct type`:`must be of type %{type}`);return i.isFunction(l)&&(l=l(e,t,n,r,a)),i.format(l,{attribute:i.prettify(n),type:s})}}},{types:{object:function(e){return i.isObject(e)&&!i.isArray(e)},array:i.isArray,integer:i.isInteger,number:i.isNumber,string:i.isString,date:i.isDate,boolean:i.isBoolean},messages:{}})},r.formatters={detailed:function(e){return e},flat:i.flattenErrorsToArray,grouped:function(e){for(var t in e=i.groupErrorsByAttribute(e),e)e[t]=i.flattenErrorsToArray(e[t]);return e},constraint:function(e){for(var t in e=i.groupErrorsByAttribute(e),e)e[t]=e[t].map(function(e){return e.validator}).sort();return e}},r.exposeModule(r,this,e,t,n)}).call(e,e===void 0?null:e,t===void 0?null:t,typeof define<`u`?define:null)}))(),1);zm.default.validators.bigNumericality=(e,t,n,r)=>zm.default.validators.numericality(e&&e.toNumber(),t,r);var Bm=zm.default,Vm=c({BalanceLimit:()=>Ym,ExchangeFeatures:()=>Um,IpWhiteList:()=>Wm,MarginType:()=>Gm,OrderSide:()=>qm,OrderStatus:()=>Km,OrderType:()=>Hm,TimeInForce:()=>Jm}),Hm=function(e){return e.MARKET=`MARKET`,e.LIMIT=`LIMIT`,e.LIMIT_LADDER=`LIMIT_LADDER`,e.STOP_LOSS=`STOP_LOSS`,e.OCO=`OCO`,e.STOP_LOSS_LIMIT=`STOP_LOSS_LIMIT`,e.STOP_LOSS_MARKET=`STOP_LOSS_MARKET`,e.TAKE_PROFIT=`TAKE_PROFIT`,e.TAKE_PROFIT_LIMIT=`TAKE_PROFIT_LIMIT`,e.TAKE_PROFIT_MARKET=`TAKE_PROFIT_MARKET`,e}({}),Um=function(e){return e.HEDGE_MODE=`hedgeMode`,e.HEDGE_MODE_ONLY=`hedgeModeOnly`,e.ORDER_QUOTE_AMOUNT=`orderQuoteAmount`,e.MARKET_BUY_QUOTE_ONLY=`marketBuyQuoteOnly`,e.UPDATE_LEVERAGE_ONLY_ON_OPEN_POSITIONS=`updateLeverageOnlyOnOpenPositions`,e.IGNORE_LEVERAGE_ON_QUICK_SYNC=`ignoreLeverageOnQuickSync`,e.MULTIPLE_MARGIN_TYPE_POSITIONS=`multipleMarginTypePositions`,e.SET_LEVERAGE_NOT_AVAILABLE=`setLeverageNotAvailable`,e.SET_MARGIN_TYPE_NOT_AVAILABLE=`setMarginTypeNotAvailable`,e.FIXED_CROSSED_LEVERAGE=`fixedCrossedLeverage`,e.FAST_CONNECT=`fastConnect`,e.UNIFIED_BALANCE=`unifiedBalance`,e.NO_API_KEY_LINK=`noApiKeyLink`,e}({}),Wm=function(e){return e.NONE=`NONE`,e.LIST=`LIST`,e.COMMA=`COMMA`,e.COMMA_SPACE=`COMMA_SPACE`,e.SPACE=`SPACE`,e}({}),Gm=function(e){return e.CROSSED=`CROSSED`,e.ISOLATED=`ISOLATED`,e}({}),Km=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CANCELED=`canceled`,e}({}),qm=function(e){return e.BUY=`buy`,e.SELL=`sell`,e}({}),Jm=function(e){return e.GTC=`gtc`,e.FOK=`fok`,e.IOC=`ioc`,e}({}),Ym=function(e){return e.QUOTE=`quote`,e.BASE=`base`,e.NONE=`none`,e}({}),Xm=[];for(let e=0;e<256;++e)Xm.push((e+256).toString(16).slice(1));function Zm(e,t=0){return(Xm[e[t+0]]+Xm[e[t+1]]+Xm[e[t+2]]+Xm[e[t+3]]+`-`+Xm[e[t+4]]+Xm[e[t+5]]+`-`+Xm[e[t+6]]+Xm[e[t+7]]+`-`+Xm[e[t+8]]+Xm[e[t+9]]+`-`+Xm[e[t+10]]+Xm[e[t+11]]+Xm[e[t+12]]+Xm[e[t+13]]+Xm[e[t+14]]+Xm[e[t+15]]).toLowerCase()}var Qm=new Uint8Array(16);function $m(){return crypto.getRandomValues(Qm)}function eh(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():th(e,t,n)}function th(e,t,n){e||={};let r=e.random??e.rng?.()??$m();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Zm(r)}var nh=class{id=eh();coinraySymbol;precisionBase;precisionQuote;precisionPrice;minBase;minQuote;makerFee;takerFee;balances;balanceLimit;side;errors;isValid;orderExternalId;reduceOnly;postOnly;timeInForce;constructor(e){this.coinraySymbol=e.coinraySymbol,this.precisionBase=Hp(e.precisionBase),this.precisionQuote=Hp(e.precisionQuote),this.precisionPrice=Hp(e.precisionPrice),this.minBase=$(e.minBase),this.minQuote=$(e.minQuote),this.makerFee=$(e.makerFee),this.takerFee=$(e.takerFee),this.balances=e.balances,this.balanceLimit=e.balanceLimit||Ym.NONE,this.side=e.side,this.orderExternalId=e.externalId,this.errors={},this.isValid=!0,this.reduceOnly=e.reduceOnly,this.postOnly=e.postOnly,this.timeInForce=e.timeInForce}startEdit(e){this.orderExternalId=e}updateLockedOn(e){}resetError(){this.errors={},this.isValid=!0}validate(){let e=Bm(this,this.constraints());return e?(this.errors=e,this.isValid=!1):this.resetError(),!e}},rh=class extends nh{baseAmount;quoteAmount;price;lockedOn;orderType=Hm.LIMIT;constraints(){let e,t;return this.balanceLimit===Ym.QUOTE?t=this.balances.quote||0:this.balanceLimit===Ym.BASE&&(e=this.balances.base||0),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:this.minBase.toNumber(),notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:this.minQuote.toNumber(),notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}},price:{bigNumericality:{greaterThan:0}}}}constructor(e,t=!0){super(e),this.price=$(e.price||`0`),this.lockedOn=e.lockedOn,this.baseAmount=$(e.baseAmount),this.quoteAmount=$(e.quoteAmount),t&&(this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount))}updateBaseAmount(e){this.baseAmount=e,this.quoteAmount=this.price.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,this.baseAmount=e.dividedBy(this.price).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN),this.validate()}updateLockedOn(e){this.lockedOn=e,this.validate()}quoteFee(){return this.quoteAmount.multipliedBy(this.takerFee)}updatePrice(e){this.price=e.decimalPlaces(this.precisionPrice),this.lockedOn===`baseAmount`?this.updateBaseAmount(this.baseAmount):this.updateQuoteAmount(this.quoteAmount)}getOrders(){return[this]}},ih=class extends nh{baseAmount;quoteAmount;price;orderType=Hm.MARKET;constraints=()=>{let e,t;return this.balanceLimit===Ym.QUOTE?t=this.balances.quote||0:this.balanceLimit===Ym.BASE&&(e=this.balances.base||0),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:e?this.minBase.toNumber():void 0,notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:t?this.minQuote.toNumber():void 0,notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}}}};constructor(e){super(e),this.updateQuoteAmount(e.quoteAmount),this.updateBaseAmount(e.baseAmount)}updateBaseAmount(e){this.baseAmount=e,e&&(this.quoteAmount=this.price.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN)),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,e&&(this.baseAmount=e.dividedBy(this.price).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN)),this.validate()}updatePrice(e){this.price=e.decimalPlaces(this.precisionPrice)}getOrders(){return[this]}},ah=function(e){return e.LINEAR=`LINEAR`,e.EXPONENTIAL=`EXPONENTIAL`,e.FIBONACCI=`FIBONACCI`,e.CUSTOM=`CUSTOM`,e}({}),oh=function(e){return e.EQUAL=`EQUAL`,e.LINEAR=`LINEAR`,e.LINEAR_REVERSE=`LINEAR_REVERSE`,e.EXPONENTIAL=`EXPONENTIAL`,e.EXPONENTIAL_REVERSE=`EXPONENTIAL_REVERSE`,e.CUSTOM=`CUSTOM`,e}({}),sh={[ah.LINEAR]:e=>L.default.times(e,t=>1/(e-1)*t),[ah.EXPONENTIAL]:e=>{let t=2**(e-1);return L.default.times(e,e=>e==0?0:2**e/t)},[ah.FIBONACCI]:e=>[0,.09,.146,.236,.382,.5,.618,.788,.886].slice(0,e-1).concat([1]),[ah.CUSTOM]:e=>[]},ch=e=>{let t=L.default.sum(e);return e.map(e=>e/t)},lh={[oh.EQUAL]:e=>ch(L.default.times(e,()=>1)),[oh.LINEAR]:e=>ch(L.default.times(e,t=>1/e*(t+1))),[oh.EXPONENTIAL]:e=>{let t=2**e-1;return ch(L.default.times(e,e=>2**e/t))},[oh.LINEAR_REVERSE]:e=>lh[oh.LINEAR](e).reverse(),[oh.EXPONENTIAL_REVERSE]:e=>lh[oh.EXPONENTIAL](e).reverse(),[oh.CUSTOM]:e=>[]},uh=class extends nh{baseAmount;quoteAmount;price;lockedOn;otherPrice;numOrders;priceScale;sizeScale;priceScales;sizeScales;orderType=Hm.LIMIT_LADDER;constraints(){let e,t;return this.balanceLimit===Ym.QUOTE?t=this.balances.quote:this.balanceLimit===Ym.BASE&&(e=this.balances.base),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:this.minBase.toNumber(),notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:this.minQuote.toNumber(),notGreaterThanOrEqualTo:`^${xm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${xm.I18n.t(`validation.insufficientFunds`)}`}},price:{bigNumericality:{greaterThan:0}},otherPrice:{bigNumericality:{greaterThan:0}},numOrders:{numericality:{greaterThanOrEqualTo:2}}}}constructor(e){super(e),this.otherPrice=$(e.otherPrice),this.numOrders=Hp(e.numOrders),this.priceScale=e.priceScale||ah.CUSTOM,this.sizeScale=e.sizeScale||oh.CUSTOM,this.price=$(e.price||`0`),this.lockedOn=e.lockedOn,this.baseAmount=$(e.baseAmount||`0`),this.quoteAmount=$(e.quoteAmount||`0`),this.priceScales=e.priceScales||sh[this.priceScale](this.numOrders),this.sizeScales=e.sizeScales||lh[this.sizeScale](this.numOrders),this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount)}updateNumOrders(e){this.numOrders=e}updatePrice(e,t=.05){if(this.price=e.decimalPlaces(this.precisionPrice),e&&this.otherPrice.eq(0)){let n=this.side===qm.BUY?1+t:1-t;this.otherPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}this.recalculate()}updateOtherPrice(e,t=.05){if(this.otherPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===qm.BUY?1-t:1+t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}this.recalculate()}updatePriceScales(e){this.priceScales=e,this.priceScale=ah.CUSTOM,this.recalculate()}updatePriceScale(e){this.priceScales=sh[e](this.numOrders),this.priceScale=e,this.recalculate()}updateSizeScales(e){this.sizeScales=e,this.sizeScale=oh.CUSTOM,this.recalculate()}updateSizeScale(e){this.sizeScales=lh[e](this.numOrders),this.sizeScale=e,this.recalculate()}updateLockedOn(e){this.lockedOn=e}recalculate(){this.lockedOn===`baseAmount`?this.updateBaseAmount(this.baseAmount):this.updateQuoteAmount(this.quoteAmount),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,this.numOrders=Math.max(2,+this.numOrders);let t=this.getOrders(`quoteAmount`);this.baseAmount=t.length>0?L.default.reduce(t,(e,t)=>e.plus(t.baseAmount),new d(0)):new d(0)}updateBaseAmount(e){this.baseAmount=e,this.numOrders=Math.max(2,+this.numOrders);let t=this.getOrders(`baseAmount`);this.quoteAmount=t.length>0?L.default.reduce(t,(e,t)=>e.plus(t.quoteAmount),new d(0)):new d(0)}getOrders(e=this.lockedOn){let t=e===`baseAmount`?this.baseAmount:this.quoteAmount,n=e===`baseAmount`?this.precisionBase:this.precisionQuote;if(!(this.priceScales&&this.priceScales.length>0&&this.sizeScales.length>0&&t.gt(0)))return[];let r=this.priceScales.slice(0,this.numOrders),i=this.sizeScales.slice(0,this.numOrders),a=this.otherPrice.minus(this.price),o=t;return L.default.times(this.numOrders,s=>{let c=t.multipliedBy(i[s]).decimalPlaces(n>0?n:0,d.ROUND_DOWN);return o=o.minus(c),s===this.numOrders-1&&(c=c.plus(o)),new rh({...this,[e]:c,lockedOn:e,price:this.price.plus(a.multipliedBy(r[s])).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)})})}},dh=class extends rh{stopPrice;orderType=Hm.STOP_LOSS_LIMIT;constraints(){return{...super.constraints(),stopPrice:{bigNumericality:{greaterThan:0}}}}constructor(e){super(e),this.stopPrice=$(e.stopPrice)}updatePrice(e,t=.05){if(super.updatePrice(e),e&&this.stopPrice.eq(0)){let n=this.side===qm.BUY?1-t:1+t;this.stopPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateStopPrice(e,t=.05){if(this.stopPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===qm.BUY?1+t:1-t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}},fh=class extends rh{linkedOrderId;otherPrice;stopPrice;orderType=Hm.OCO;constraints(){return{...super.constraints(),otherPrice:{bigNumericality:{greaterThan:0}},stopPrice:{bigNumericality:{greaterThan:0}}}}constructor(e){super(e,!1),this.otherPrice=$(e.otherPrice),this.stopPrice=$(e.stopPrice),this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount)}updateQuoteAmount(e){this.quoteAmount=e;let t=this.side===qm.BUY?this.otherPrice:this.price;this.baseAmount=e.dividedBy(t).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN),this.validate()}updateBaseAmount(e){this.baseAmount=e;let t=this.side===qm.BUY?this.otherPrice:this.price;this.quoteAmount=t.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN),this.validate()}updatePrice(e,t=.05){if(super.updatePrice(e),e&&this.otherPrice.eq(0)){let n=this.side===qm.BUY?1+t*2:1-t*2,r=this.side===qm.BUY?1+t:1-t;this.otherPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.stopPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateOtherPrice(e,t=.05){if(this.otherPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===qm.BUY?1-t*2:1+t*2,r=this.side===qm.BUY?1-t:1+t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.stopPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateStopPrice(e,t=.05){if(this.stopPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===qm.BUY?1-t:1+t,r=this.side===qm.BUY?1+t:1-t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.otherPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}};d.set({STRICT:!1});var ph=xm;return e.BalanceLimit=Ym,e.CoinrayCache=Fm,e.CurrentMarket=Lm,e.DAYS=_p,e.ExchangeFeatures=Um,e.FormulaMarket=Em,e.HOURS=gp,e.IpWhiteList=Wm,e.LimitLadderOrder=uh,e.LimitOrder=rh,e.MINUTES=hp,e.MarginType=Gm,e.MarketOrder=ih,e.OcoOrder=fh,e.OrderSide=qm,e.OrderStatus=Km,e.OrderType=Hm,e.PriceScales=ah,e.SizeScales=oh,e.StopLimitOrder=dh,e.TimeInForce=Jm,e.WEEK=vp,e.alignCandles=pm,e.base64UrlDecode=Sp,e.base64UrlEncode=xp,e.camelize=kp,e.candleTime=Zp,e.checkArray=Pp,e.checkBigNumber=Ip,e.checkBoolean=Lp,e.checkNull=Rp,e.checkNumber=Fp,e.checkString=Q,e.combineCandles=fm,e.correctNumberPrecision=Bp,e.createJWT=Tp,e.default=ph,e.encryptPayload=Op,e.errorHelper=zp,e.evalFormula=um,e.filterMarkets=Qp,e.formulaCandles=mm,e.formulaLegs=lm,e.formulaPrecision=gm,e.formulaSymbolInfo=_m,e.getBucketStartDates=Xp,e.getTimeParams=Yp,e.isFormula=om,e.jwkToPublicKey=Dp,e.jwtExpired=Ap,e.latestFormulaCandle=hm,e.locales=Rm,e.parseFormula=cm,e.parseJWT=Ep,e.resolutionToBucketType=Jp,e.resolutionToDuration=Wp,e.safeBigNumber=$,e.safeFloat=Vp,e.safeInteger=Hp,e.safeTime=Up,e.sha256hexdigest=Cp,e.signHMAC=wp,e.strToArray=bp,e.throwIsArray=Np,e.throwNotObject=Mp,e.throwNull2NonNull=jp,e.toBucketEnd=Kp,e.toBucketStart=qp,e.toSafeDate=Gp,Object.defineProperty(e,"types",{enumerable:!0,get:function(){return Vm}}),e.unix=yp,e})({});
|
|
33
|
+
`+JSON.stringify(t))}function $(e){return d.isBigNumber(e)?e:e?new d(e):new d(`0`)}function Bp(e,t){return new d(t).toFixed(e>0?e:0)}function Vp(e){return typeof e==`number`?e:parseFloat(e)}function Hp(e){return typeof e==`number`?e:parseInt(e)}function Up(e){let t=Vp(e);return t<10**10&&(t*=1e3),new Date(t)}function Wp(e){switch(e.toString().toUpperCase()){case`1S`:return 1;case`2S`:return 2;case`3S`:return 3;case`5S`:return 5;case`10S`:return 10;case`15S`:return 15;case`30S`:return 30;case`1`:return 60;case`2`:return 120;case`3`:return 180;case`5`:return 300;case`10`:return 600;case`15`:return 900;case`30`:return 1800;case`60`:return 3600;case`120`:return 7200;case`240`:return 14400;case`360`:return 21600;case`720`:return 43200;case`D`:case`1D`:return _p;case`3D`:return _p*3;case`W`:return vp;case`1W`:return vp;case`2W`:return vp*2;case`1M`:return _p*30}}var Gp=e=>typeof e==`object`?e:new Date(e*1e3),Kp=(e,t)=>{switch(e=R.utc(Gp(e)),t){case`1`:case`2`:case`3`:return e.endOf(`day`).unix();case`5`:case`10`:case`15`:return e.endOf(`isoWeek`).unix();case`30`:case`60`:case`120`:return e.endOf(`month`).unix();case`240`:case`360`:case`720`:case`D`:case`1D`:return e.endOf(`year`).unix()}},qp=(e,t)=>{switch(e=R.utc(Gp(e)),t){case`1`:case`2`:case`3`:return e.startOf(`day`).unix();case`5`:case`10`:case`15`:return e.startOf(`isoWeek`).unix();case`30`:case`60`:case`120`:return e.startOf(`month`).unix();case`240`:case`360`:case`720`:case`D`:case`1D`:return e.startOf(`year`).unix()}};function Jp(e){switch(e){case`1`:case`2`:case`3`:return`day`;case`5`:case`10`:case`15`:return`week`;case`30`:case`60`:case`120`:return`month`;case`240`:case`360`:case`720`:case`D`:case`1D`:return`year`;default:throw Error(`Unsupported resolution: ${e}`)}}function Yp(e,t){let n=R(Gp(t)),r;switch(e){case`day`:r={year:n.year(),month:n.month()+1,day:n.date()};break;case`week`:r={year:n.isoWeekYear(),week:n.isoWeek()};break;case`month`:r={year:n.year(),month:n.month()+1};break;case`year`:r={year:n.year()};break;default:throw Error(`Unsupported bucketType: ${e}`)}return r}function Xp(e,t,n){let r=[],i=R.utc(t*1e3),a=e=>{switch(n){case`day`:return e.startOf(`day`);case`week`:return e.startOf(`isoWeek`);case`month`:return e.startOf(`month`);case`year`:return e.startOf(`year`);default:throw Error(`Unsupported bucketType: ${n}`)}},o=e=>{switch(n){case`day`:return e.subtract(1,`day`);case`week`:return e.subtract(1,`week`);case`month`:return e.subtract(1,`month`);case`year`:return e.subtract(1,`year`);default:throw Error(`Unsupported bucketType: ${n}`)}},s=a(i),c=a(R.utc(e*1e3));for(;s>=c;)r.push(s.clone()),s=o(s);return r}function Zp(e,t,n){let r=Wp(t),i=typeof n==`object`?n.getTime()/1e3:n;return Math.floor(i/r)*r-r*(e-1)}function Qp(e,t){let n=t;if(n=typeof t==`string`?[{query:t,marketProperty:`fullDisplayName`}]:Array.isArray(t)?t.map(e=>{if(typeof e==`string`)return{query:e,marketProperty:`fullDisplayName`};if(!Array.isArray(e))return e}):[t],n.length===0||!n.find(({query:e})=>!!e&&!!e.length))return e;let r=e;return n.forEach(({query:e,marketProperty:t})=>{let n;if(e.match(/[-_:\/\\]+/))try{n=new RegExp(e.replace(/\*/g,`.*`),`i`)}catch{}let i=e.toLowerCase().split(/[\s]+/).filter(Boolean);r=L.default.pickBy(r,(e,r)=>{let a=e[t];if(a==null)return!1;let o=a.toLowerCase();return n&&t===`fullDisplayName`?!!n.exec(e[t]):i.filter(e=>o.includes(e)).length===i.length})}),r}var $p=void 0,em=class{static initialize=e=>{$p=e,console.log(`Coinray I18n initialized`)};static t=(e,t)=>$p?$p.t(`coinray:${e}`,t):`i18n uninitialized. Set the Coinray.I18n.instance. Key: ${e}`},tm=10,nm=`\\([A-Za-z0-9_.:]+\\)`,rm=RegExp(`\\s*(?:(\\d+(?:\\.\\d+)?(?![A-Za-z0-9_.]))|([A-Za-z0-9_.:]+(?:-[A-Za-z0-9_.:]+)*(?:${nm})?)|([-+*/()×÷]))\\s*`,`y`),im=RegExp(`(?<=[A-Za-z0-9_.:])${nm}`,`g`),am={"+":`+`,"-":`−`,"*":`×`,"/":`÷`},om=e=>/[\s+*/()×÷]/.test(`${e}`.replace(im,``));function sm(e){let t=[];for(rm.lastIndex=0;rm.lastIndex<e.length;){let n=rm.lastIndex,r=rm.exec(e);if(!r)throw Error(`Invalid formula at "${e.slice(n)}"`);if(r[1]!==void 0)t.push({kind:`num`,value:r[1]});else if(r[2]!==void 0){if(r[2].split(`_`).length<3)throw Error(`Invalid market "${r[2]}" in formula`);t.push({kind:`leg`,value:r[2]})}else t.push({kind:`op`,value:r[3]===`×`?`*`:r[3]===`÷`?`/`:r[3]})}return t}function cm(e){let t=sm(e),n=0,r=()=>t[n]?.kind===`op`?t[n].value:void 0,i=()=>{let e=a();for(;r()===`+`||r()===`-`;)e={type:`op`,op:t[n++].value,left:e,right:a()};return e},a=()=>{let e=o();for(;r()===`*`||r()===`/`;)e={type:`op`,op:t[n++].value,left:e,right:o()};return e},o=()=>r()===`-`?(n++,{type:`neg`,arg:o()}):s(),s=()=>{let e=t[n++];if(!e)throw Error(`Invalid formula: unexpected end`);if(e.kind===`num`)return{type:`num`,value:Number(e.value)};if(e.kind===`leg`)return{type:`leg`,symbol:e.value};if(e.value===`(`){let e=i();if(t[n++]?.value!==`)`)throw Error(`Invalid formula: missing )`);return e}throw Error(`Invalid formula: unexpected "${e.value}"`)},c=i();if(n<t.length)throw Error(`Invalid formula: unexpected "${t[n].value}"`);let l=lm(c);if(l.length===0)throw Error(`Invalid formula: no markets`);if(l.length>tm)throw Error(`Invalid formula: max ${tm} markets`);return c}function lm(e,t=[]){return e.type===`leg`&&!t.includes(e.symbol)&&t.push(e.symbol),e.type===`neg`&&lm(e.arg,t),e.type===`op`&&(lm(e.left,t),lm(e.right,t)),t}function um(e,t){switch(e.type){case`num`:return e.value;case`leg`:return t(e.symbol);case`neg`:return-um(e.arg,t);case`op`:{let n=um(e.left,t),r=um(e.right,t);return e.op===`+`?n+r:e.op===`-`?n-r:e.op===`*`?n*r:r===0?NaN:n/r}}}var dm=(e,t)=>({time:t,open:e.close,high:e.close,low:e.close,close:e.close,baseVolume:0,quoteVolume:0,numTrades:0});function fm(e,t,n){let r=n=>um(e,e=>Number(t[e][n])),i=r(`open`),a=r(`close`),o=r(`high`),s=r(`low`);return[i,a,o,s].every(Number.isFinite)?{time:n,open:i,close:a,high:Math.max(i,a,o,s),low:Math.min(i,a,o,s),baseVolume:0,quoteVolume:0,numTrades:0}:null}function pm(e,t){if(e.some(e=>!t[e]?.length))return[];let n=Math.max(...e.map(e=>t[e][0].time.getTime())),r=[...new Set(e.flatMap(e=>t[e].map(e=>e.time.getTime())))].filter(e=>e>=n).sort((e,t)=>e-t),i={},a={};return r.map(n=>{let r={};for(let o of e){let e=t[o];for(i[o]??=0;i[o]<e.length&&e[i[o]].time.getTime()<=n;)a[o]=e[i[o]++];r[o]=a[o].time.getTime()===n?a[o]:dm(a[o],new Date(n))}return{time:new Date(n),legs:r}})}function mm(e,t){return pm(lm(e),t).map(({time:t,legs:n})=>fm(e,n,t)).filter(e=>e!==null)}function hm(e,t){let n=lm(e);if(n.some(e=>t[e]?.close===void 0))return null;let r=Math.max(...n.map(e=>t[e].time.getTime())),i={};for(let e of n)i[e]=t[e].time.getTime()===r?t[e]:dm(t[e],new Date(r));return fm(e,i,new Date(r))}function gm(e){return!Number.isFinite(e)||e===0?8:Math.min(12,Math.max(2,4-Math.floor(Math.log10(Math.abs(e)))))}function _m(e,t){let n=cm(e),r=lm(n),i={};for(let e of r){let n=t(e);if(!n)throw Error(`Unknown market ${e}`);i[e]=n}let a=new Set(r.map(e=>i[e].exchangeCode)).size>1;return{name:sm(e).map(({kind:e,value:t})=>{if(e===`leg`){let e=i[t];return`${a?`${e.exchangeCode}:`:``}${e.baseCurrency}/${e.quoteCurrency}`}return am[t]?` ${am[t]} `:t}).join(``).replace(/\( /g,`(`).replace(/^ − /,`−`),legs:r,pricePrecision:gm(um(n,e=>i[e].lastPrice?.toNumber()??NaN))}}var vm=e=>om(e)?encodeURIComponent(e):e,ym=`2.0.26`,bm=class extends Error{errorCode;errorMessage;exchange;status;constructor({code:e,message:t,exchange:n}){super(`Request failed`),this.name=`CoinrayError`,this.errorCode=e,this.errorMessage=t,this.exchange=n}},xm=3e3,Sm=class e{static I18n=em;config;_token;_sessionKey;_credential;_firstOpen;_onTokenExpired;_tokenCheckTimeout;_onError;_onOpen;_socket;_transport;_tickerListeners=new Map;_tickerSymbols=new Map;_tradeListeners={};_tradeSnapshots={};_orderbookListeners={};_orderbookSnapshots={};_candleTradeListeners={};_candleListeners={};_candles={};_timers={};_channels={};_connected;markConnected;_publicKey;_refreshingToken;_nonceOffset;tickersSubscribed=!1;tradesSubscribed=!1;orderBookSubscribed=!1;_timeOffset;_timeOffsetTimeout;_candleCache;_candleCacheCreatedAt;constructor(e,{apiEndpoint:t,orderEndpoint:n,websocketEndpoint:r}={apiEndpoint:`https://api.coinray.eu`,orderEndpoint:`https://api.coinray.eu`,websocketEndpoint:`wss://ws.coinray.eu/v1`}){this._token=e,this._nonceOffset=0,this._timeOffset=0,this._firstOpen=!0,this.config={apiEndpoint:t||`https://api.coinray.eu`,orderEndpoint:n||t||`https://api.coinray.eu`,websocketEndpoint:r||`wss://ws.coinray.eu/v1`},this._candleCache=new Map,this.loadTimeOffset().then()}authenticateDevice=(e,t)=>{this._credential=e,this._sessionKey=t};destroy=()=>{this._tradeListeners={},this._orderbookListeners={},this._tickerListeners=new Map,this._tickerSymbols=new Map,this.tickerSnapshots=new Map,this._channels={},this._timeOffsetTimeout&&clearTimeout(this._timeOffsetTimeout),this._tokenCheckTimeout&&clearInterval(this._tokenCheckTimeout),this.disconnect()};checkToken=async(e=!0)=>{try{if(Ap(this._token)){if(console.log(`Coinray token expired. Can refresh:`,!!this._onTokenExpired),!this._onTokenExpired)return!1;this._refreshingToken||=this._onTokenExpired();try{this._token=await this._refreshingToken}catch(e){return console.log(`Coinray token could not be refreshed`,e),this._refreshingToken=void 0,!1}if(this._refreshingToken=void 0,!Ap(this._token))this.reconnect();else return!1}}catch(e){console.error(e)}return e&&(this._tokenCheckTimeout=setTimeout(this.checkToken,5e3)),!0};setTransport=e=>{this._transport=e};onTokenExpired=e=>{this._tokenCheckTimeout&&clearInterval(this._tokenCheckTimeout),this._onTokenExpired=e,this._tokenCheckTimeout=setTimeout(this.checkToken,5e3)};refreshToken=e=>{this._token=e};getNonce=()=>(this._nonceOffset>900&&(this._nonceOffset=0),this._nonceOffset+=1,this.getTime()+this._nonceOffset);getTime=()=>Math.floor(new Date().getTime()/1e3)*1e3+this._timeOffset;loadTimeOffset=async()=>{try{let{result:e}=await this.get(`/coinray/time`);this._timeOffset=e.time-new Date().getTime()}catch(e){console.error(e)}this._timeOffsetTimeout=setTimeout(this.loadTimeOffset,6e4)};getToken=async()=>{if(await this.checkToken(!1))return this._token;throw Error(`Token is expired. call refreshToken in the onTokenExpired callback`)};reconnect=()=>{this._connected&&this.socket.conn.close()};disconnect=()=>{this._socket&&=(this._socket.disconnect(),void 0),this._connected=void 0};connect=async()=>{if(this._connected){await this._connected;return}this._connected=new Promise(e=>{this.markConnected=e}),this.socket.onOpen(e=>{this._onOpen&&this._onOpen(e)}),this.socket.onError(e=>{this._onError&&this._onError(e)}),this.socket.connect(),this.markConnected()};onOpen=e=>{this._onOpen=e};onError=e=>{this._onError=e};resubscribe=()=>{if(this._firstOpen){this._firstOpen=!1;return}Object.keys(this._tickerListeners).forEach(e=>{this._tickerListeners[e].length>0&&this.getChannel(`tickers`).push(`subscribe`,{exchangeCodes:[e]},5e3)}),Object.keys(this._tradeListeners).forEach(e=>{this._tradeListeners[e].length>0&&this.getChannel(`trades`).push(`subscribe`,{symbols:e,snapshots:!0},5e3)}),Object.keys(this._orderbookListeners).forEach(e=>{this._orderbookListeners[e].length>0&&this.getChannel(`orderbooks`).push(`subscribe`,{symbols:e,snapshots:!0},5e3)})};subscribeTickers=async(t,n=!1,r)=>{if(t.length===0)return!1;if(n&&(this._tickerListeners.clear(),this._tickerSymbols.clear()),this._tickerListeners.has(r)){let e=this._tickerListeners.get(r);t.forEach(t=>e.add(t))}else this._tickerListeners.set(r,new Set(t));t.forEach(e=>{this._tickerSymbols.has(e)||this._tickerSymbols.set(e,new Set),this._tickerSymbols.get(e).add(r)}),await this.connect();let i=this.getChannel(`tickers`);return i.push(`subscribe`,{coinraySymbols:t,reset:n},5e3),this.tickersSubscribed?r:(this.tickersSubscribed=!0,i.on(`update`,t=>{let{exchange_code:n,tickers:r}=t,i=r.map(e._parseTicker);this._tickerListeners.forEach((e,t)=>{let r=i.filter(t=>e.has(t.coinraySymbol));t({type:`tickers:update`,exchangeCode:n,tickers:r})})}),i.on(`error`,e=>console.error(e)),r)};unsubscribeAllTickers=()=>{this._tickerListeners.clear(),this._tickerSymbols.clear(),this.getChannel(`tickers`).push(`unsubscribe`,{all:!0},5e3)};unsubscribeTickers=(e,t)=>{if(t&&this._tickerListeners.has(t)){let n=this._tickerListeners.get(t),r=[];e.forEach(e=>{n.delete(e),this._tickerSymbols.has(e)&&(this._tickerSymbols.get(e).delete(t),this._tickerSymbols.get(e).size===0&&(this._tickerSymbols.delete(e),r.push(e)))}),n.size===0&&this._tickerListeners.delete(t),r.length>0&&this.getChannel(`tickers`).push(`unsubscribe`,{coinraySymbols:r},5e3)}};subscribeTrades=async({coinraySymbol:t},n)=>{if(this._tradeListeners[t]&&this._tradeListeners[t].length>0)return this._tradeListeners[t].includes(n)||this._tradeListeners[t].push(n),n({type:`trades:snapshot`,coinraySymbol:t,trades:this._tradeSnapshots[t]}),n;this._tradeSnapshots[t]=[],this._tradeListeners[t]=[n],await this.connect();let r=this.getChannel(`trades`);return r.push(`subscribe`,{symbols:t,snapshots:!0},5e3),this.tradesSubscribed?n:(this.tradesSubscribed=!0,r.on(`snapshot`,({symbol:t,trades:n})=>{let r=Object.values(this._tradeListeners[t]),i=n.map(e._parseTrade);this._tradeSnapshots[t]=i,r.map(e=>e({type:`trades:snapshot`,coinraySymbol:t,trades:i}))}),r.on(`update`,({symbol:t,trades:n})=>{let r=Object.values(this._tradeListeners[t]),i=n.map(e._parseTrade),a=[...i,...this._tradeSnapshots[t]],o=new Date(new Date().getTime()-12e4),s=a.filter(({time:e})=>e>o);s.length>100?this._tradeSnapshots[t]=s:this._tradeSnapshots[t]=a.slice(0,100),r.map(e=>e({type:`trades:update`,coinraySymbol:t,trades:i}))}),r.on(`error`,e=>console.error(e)),n)};unsubscribeTrades=({coinraySymbol:e},t)=>{t&&this._tradeListeners[e]?(this._tradeListeners[e]=this._tradeListeners[e].filter(e=>e!==t),this._tradeListeners[e].length===0&&this.getChannel(`trades`).push(`unsubscribe`,{symbols:e},5e3)):(this._tradeSnapshots[e]=[],this._tradeListeners[e]=[])};subscribeOrderBook=async({coinraySymbol:t},n)=>{if(this._orderbookListeners[t]&&this._orderbookListeners[t].length>0)return this._orderbookListeners[t].includes(n)||this._orderbookListeners[t].push(n),n({type:`orderBook:snapshot`,coinraySymbol:t,orderBook:this._orderbookSnapshots[t]}),n;this._orderbookSnapshots[t]={minSeq:0,maxSeq:0,bids:{},asks:{}},this._orderbookListeners[t]=[n],await this.connect();let r=this.getChannel(`orderbooks`);return r.push(`subscribe`,{symbols:t},1e4),this.orderBookSubscribed?n:(this.orderBookSubscribed=!0,r.on(`snapshot`,({orderbooks:t})=>{Object.keys(t).forEach(n=>{let r=Object.values(this._orderbookListeners[n]),i=e._parseOrderBookSnapshot(t[n]);this._orderbookSnapshots[n]=i,r.map(e=>e({type:`orderBook:snapshot`,coinraySymbol:n,orderBook:i}))})}),r.on(`update`,({orderbooks:t})=>{let n=Object.keys(t);n.length!==0&&n.forEach(n=>{let r=Object.values(this._orderbookListeners[n]),i=e._parseOrderBookUpdate(t[n]);this._orderbookSnapshots[n]=e._updateOrderBook(this._orderbookSnapshots[n],i),r.map(e=>e({type:`orderBook:update`,coinraySymbol:n,orderBook:i}))})}),r.on(`error`,e=>console.error(e)),n)};unsubscribeOrderBook=({coinraySymbol:e},t)=>{t&&this._orderbookListeners[e]?(this._orderbookListeners[e]=this._orderbookListeners[e].filter(e=>e!==t),this._orderbookListeners[e].length===0&&this.getChannel(`orderbooks`).push(`unsubscribe`,{symbols:e},5e3)):(this._orderbookSnapshots[e]={minSeq:0,maxSeq:0,bids:{},asks:{}},this._orderbookListeners[e]=[])};subscribeCandles=async({coinraySymbol:t,resolution:n,lastCandle:r},i)=>{let a=`${t}-${n}`;if(this._candleListeners[a]&&this._candleListeners[a].length>0)return this._candleListeners[a].push(i),this.replayCandleSnapshot({coinraySymbol:t,resolution:n,candleId:a},i),i;this._candleListeners[a]=[i];let o=({type:t,coinraySymbol:r,trades:i})=>{let o=Object.values(this._candleListeners[a]),s=e._tradesToLastCandle(n,i),c=s[s.length-1];c&&(this._candles[a]&&t===`trades:snapshot`&&(this._candles[a].skipVolume=!0),this._candles[a]=e._mergeCandle(this._candles[a],c),o.map(e=>e({coinraySymbol:r,resolution:n,candle:this._candles[a],previousCandles:s})))};return this._candleTradeListeners[t]?this._candleTradeListeners[t][a]=o:this._candleTradeListeners[t]={[a]:o},this._candles[a]=r||{time:new Date(0)},await this.subscribeTrades({coinraySymbol:t},o),this.startNewCandleTimer({candleId:a,resolution:n,coinraySymbol:t}),i};replayCandleSnapshot=({coinraySymbol:t,resolution:n,candleId:r},i)=>{queueMicrotask(()=>{if(!this._candleListeners[r]?.includes(i))return;let a=[...this._tradeSnapshots[t]||[]],o=e._tradesToLastCandle(n,a);o.length!==0&&this._candles[r]&&i({coinraySymbol:t,resolution:n,candle:this._candles[r],previousCandles:o})})};startNewCandleTimer=({candleId:e,resolution:t,coinraySymbol:n})=>{this._timers[e]&&clearTimeout(this._timers[e]);let r=Zp(0,t,new Date)-new Date().getTime()/1e3;this._timers[e]=setTimeout(()=>{let r=Object.values(this._candleListeners[e]||[]),i=Zp(1,t,new Date)*1e3,a=this._candles[e];a&&i>a.time.getTime()&&(this._candles[e]={time:new Date(i),open:a.close,high:a.close,low:a.close,close:a.close,baseVolume:0,quoteVolume:0,numTrades:0},r.map(r=>r({coinraySymbol:n,resolution:t,candle:this._candles[e],previousCandles:[]}))),this.startNewCandleTimer({candleId:e,resolution:t,coinraySymbol:n})},r*1e3)};unsubscribeCandles=({coinraySymbol:e,resolution:t},n)=>{let r=`${e}-${t}`;n&&this._candleListeners[r]?this._candleListeners[r]=this._candleListeners[r].filter(e=>e!==n):this._candleListeners[r]=[],this._candleListeners[r].length===0&&(this.unsubscribeTrades({coinraySymbol:e},this._candleTradeListeners[e][r]),this._timers[r]&&(clearTimeout(this._timers[r]),delete this._timers[r]),delete this._candles[r],delete this._candleTradeListeners[e][r])};fetchFirstCandleTime=async({coinraySymbol:e,resolution:t})=>{let{result:{startTime:n}}=await this.get(`candles/start-time`,{version:om(e)?`v2`:`v1`,params:{symbol:vm(e),resolution:t}});return n};fetchCandles=async({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})=>{if(this.flushCache(),t.endsWith(`S`))return(await this.getWebsocketCandles(e,t,xm)).filter(e=>{let t=e.time.getTime()/1e3;return t>=n&&t<=r});let a=Jp(t),o=new Date().getTime()/1e3,s=[],c=r+1;if(Kp(r,t)>=o){let n=await this.getOpenCandles(i,{version:`v2`,params:{symbol:vm(e),resolution:t}});if(n.length>0)c=Math.min(n[0].time.getTime()/1e3,c),s.push(...n);else return[]}let l=Zp(2,t,c),u=(0,L.chunk)(Xp(n,l,a),10);for(let n=0;n<u.length;n+=1){let r=u[n].map(n=>{let r=Yp(a,n),i={version:`v2`,params:{symbol:vm(e),resolution:t,...r}};return this.getHistoryCandles(i)}),i=await Promise.all(r),o=[];for(let e=0;e<i.length;e+=1)o=i[e].filter(({time:e})=>e.getTime()/1e3<c),o.length>0&&(c=Math.min(o[0].time.getTime()/1e3,c),s.unshift(...o));if(o.length===0)break}return s.filter(({time:e})=>{let t=e.getTime()/1e3;return t>=n&&t<=r}).sort((e,t)=>e.time.getTime()-t.time.getTime())};flushCache=()=>{let e=new Date().getTime()/1e3;(!this._candleCacheCreatedAt||e-this._candleCacheCreatedAt>600)&&(this._candleCacheCreatedAt=e,this._candleCache=new Map)};getWebsocketCandles=async(e,t,n=0)=>await new Promise(r=>{let i=setTimeout(()=>{this.unsubscribeCandles({coinraySymbol:e,resolution:t},a),r([])},n),a=({previousCandles:n})=>{n?.length&&(clearTimeout(i),this.unsubscribeCandles({coinraySymbol:e,resolution:t},a),r(n))};this.subscribeCandles({coinraySymbol:e,resolution:t},a)});getOpenCandles=async(t,n)=>{let r=this.candleCacheKey({prefix:`O`,...n.params}),i=this._candleCache.get(r);if(!t&&i)return i;let{symbol:a,resolution:o}=n.params,s=om(decodeURIComponent(a))?[]:await this.getWebsocketCandles(a,o),c=L.default.keyBy(s,({time:e})=>e.getTime()),{result:l}=await this.get(`candles/open`,n);if(l.candles){let t=l.candles.map(e._parseCandle).map(t=>{let n=c[t.time.getTime()];return n?e._mergeCandle(t,n):t});return this._candleCache.set(r,t),t}return[]};getHistoryCandles=async t=>{let n=this.candleCacheKey(t.params),r=this._candleCache.get(n);if(r)return r;{if(t.params.year<2018)return new Promise(e=>e([]));let{result:r}=await this.get(`candles/history`,t);if(r.candles){let t=r.candles.map(e._parseCandle);return this._candleCache.set(n,t),t}return[]}};candleCacheKey=({symbol:e,resolution:t,year:n,month:r=``,day:i=``,week:a=``,prefix:o=`C`})=>`${o}/${e}/${t}/${n}/${r}/${i}/${a}`;fetchExchanges=async(e,t)=>{let n=t;return n||({result:{exchanges:n}}=await this.get(`exchanges`,{version:`v1`})),n.map(e)};fetchMarkets=async(e,t)=>{let n=t;return n||({result:{markets:n}}=await this.get(`markets`,{version:`v1`,params:{exchange:e.code}})),n};fetchTickers=async e=>{let{result:{tickers:t}}=await this.get(`tickers`,{version:`v1`,params:{exchanges:[...e].sort().join(`,`)}});return L.default.mapValues(t||{},e=>e.map(this.parseTickerSnapshotReusing))};tickerSnapshots=new Map;parseTickerSnapshotReusing=t=>{let n=e._parseTickerSnapshot(t,this.tickerSnapshots.get(t.s));return this.tickerSnapshots.set(t.s,{raw:t,parsed:n}),n};fetchStaticMarkets=async(e,t)=>{let{result:n,_headers:r,_status:i}=await this.get(`markets/static`,{version:`v1`,params:{exchange:e},headers:t?{"If-None-Match":t}:{}});return i===304?{markets:null,etag:t}:{markets:n.markets,etag:r.etag}};createCredential=async(e,t)=>{let n=await this.publicKey();try{let r=await Op(await Tp({password:t}),n),{result:i}=await this.post(`credentials`,{secret:t,body:{deviceId:e,encryptedPassword:r}});return i}catch(e){throw e}};wrapApiKey=async(e,t)=>{let n=await this.publicKey(),r;try{r=t?e:await Op(await Tp({apiKey:JSON.stringify(e)}),n);let{result:i}=await this.post(`credentials/wrap_api_key`,{secret:this._sessionKey,body:{encryptedApiKey:r,credential:this._credential}});return i}catch(e){throw e}};testAccount=async e=>{try{let{result:t}=await this.post(`account/test`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};createSmartOrderSignature=async e=>{try{let{result:t}=await this.post(`order/smart_order_signature`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{smartOrder:e,credential:this._credential}});return t}catch(e){throw e}};createOrder=async e=>{try{let{result:t}=await this.post(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};updateOrder=async e=>{try{let{result:t}=await this.patch(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,credential:this._credential}});return t}catch(e){throw e}};cancelOrder=async e=>{try{let{result:t}=await this.delete(`order`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{...e,orderId:e.orderId.toString(),credential:this._credential}});return t}catch(e){throw e}};createWebSocketToken=async({exchangeCode:e,encryptedApiKey:t})=>{try{let{result:n}=await this.post(`exchanges/ws_token`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{encryptedApiKey:t,exchangeCode:e,credential:this._credential}});return n}catch(e){throw e}};fetchPositions=async({exchangeCode:e,encryptedApiKey:t})=>{try{let{result:n}=await this.get(`futures/positions`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,params:{credential:this._credential,exchangeCode:e,encryptedApiKey:t}});return n}catch(e){throw e}};getBalances=async({exchangeCode:t,encryptedApiKey:n})=>{try{let{result:{balances:r,positions:i}}=await this.get(`account/balances`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,params:{credential:this._credential,exchangeCode:t,encryptedApiKey:n}});return{balances:r.map(e._parseBalance),positions:i}}catch(e){throw e}};setLeverage=async({coinraySymbol:e,leverage:t,encryptedApiKey:n})=>{try{let{result:r}=await this.post(`futures/leverage`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{credential:this._credential,coinraySymbol:e,leverage:t,encryptedApiKey:n}});return r}catch(e){throw e}};setMarginType=async({coinraySymbol:e,marginType:t,encryptedApiKey:n})=>{try{let{result:r}=await this.post(`futures/margin_type`,{secret:this._sessionKey,apiEndpoint:this.config.orderEndpoint,body:{credential:this._credential,coinraySymbol:e,marginType:t,encryptedApiKey:n}});return r}catch(e){throw e}};async getProxyList({exchangeCode:e,credentialVersion:t}){let n=``;e&&(n+=`?exchange=${e.toUpperCase()}`,n+=t?`&version=${t}`:``);let{result:{proxies:r}}=await this.get(`credentials/ips`+n);return r}async publicKey(){if(!this._publicKey){let{result:{jwk:e}}=await this.get(`credentials/certificate`);this._publicKey=await Dp(e)}return this._publicKey}get clientId(){return Ep(this._token).header.kid}get socket(){if(!this._token)throw Error(`Token not present`);return this._socket||(this._socket=new mi(this.config.websocketEndpoint,{heartbeatIntervalMs:5e3,transport:this._transport,reconnectAfterMs:()=>Ap(this._token)?3e4:1e3}),this.onOpen(this.resubscribe)),this._socket.params=()=>({reconnect:!0,token:this._token,client:`coinrayjs`,version:ym}),this._socket}getChannel(e){if(this.connect(),this._channels[e])return this._channels[e];let t=this.socket.channel(e,{});return this._channels[e]=t,t.join(),t}get=async(e,{apiEndpoint:t=void 0,version:n=`v2`,headers:r={},params:i={},secret:a=``}={})=>await this._request(e,`GET`,{version:n,apiEndpoint:t,headers:r,secret:a,params:i});post=async(e,t)=>await this._request(e,`POST`,t);patch=async(e,t)=>await this._request(e,`PATCH`,t);delete=async(e,t)=>await this._request(e,`delete`,t);async _request(e,t,{apiEndpoint:n,version:r=`v2`,headers:i={},params:a={},body:o={},secret:s=``}){let c=await this.getToken(),l=Object.entries(a).length>0?`?`+Object.entries(a).map(([e,t])=>t?`${e}=${t}`:void 0).filter(Boolean).join(`&`):``,u=this.getNonce(),d=`/api/${r}/${e}${l}`;if(r===`v2`&&!e.startsWith(`candles`)){let e=[u,t.toUpperCase(),d,t===`GET`?``:JSON.stringify(o)].join(``),n=s==``?``:await wp(e,s);i={...i,"Cr-Access-Token":`${c}`,"Cr-Nonce":u,"Cr-Signature":n}}let f={method:t,url:(n||this.config.apiEndpoint)+d,timeout:2e4,headers:{Accept:`application/json`,"Content-Type":`application/json`,Authorization:`Bearer ${c}`,"Cr-Client-version":ym,...i},data:t===`GET`?void 0:JSON.stringify(o),validateStatus:e=>e>=200&&e<300||e===304};try{let e=await Kr(f),t;t=e.status===200?e.data:e.status===204?{}:e.data;let n=Object.fromEntries(Object.entries(e.headers).map(([e,t])=>[e,Array.isArray(t)?t.join(`, `):String(t)]));return{result:t,_headers:n,_status:e.status}}catch(e){let{response:t}=e;if(t){let e=new bm(t.data?.error||{});throw e.status=t.status,e}throw e}}static _parseOrderBookSnapshot({asks:t,bids:n,min_seq:r,max_seq:i}){return{minSeq:r,maxSeq:i,asks:e._parseBidAsk(t),bids:e._parseBidAsk(n)}}static _parseOrderBookUpdate({asks_diff:t,bids_diff:n,min_seq:r,max_seq:i}){return{minSeq:r,maxSeq:i,asks:e._parseBidAsk(t),bids:e._parseBidAsk(n)}}static _updateOrderBook(e,{asks:t,bids:n,min_seq:r,max_seq:i}){let a=(e,t)=>{L.default.forEach(t,(t,n)=>{t>0?e[n]=t:delete e[n]})};return e.minSeq=r,e.maxSeq=i,a(e.bids,n),a(e.asks,t),e}static _parseBidAsk(e){return Array.isArray(e)?e.reduce((e,[t,n])=>(e[t]=parseFloat(n),e),{}):Object.keys(e).reduce((t,n)=>(t[n]=parseFloat(e[n]),t),{})}static _parseCandle(e){if(e){let[t,n,r,i,a,o,s]=e;return{time:Up(t),open:parseFloat(n),high:parseFloat(r),low:parseFloat(i),close:parseFloat(a),baseVolume:parseFloat(o),quoteVolume:parseFloat(s),numTrades:0}}throw Error(`Candle`)}static _parseTrade([e,t,n,r,i]){return{id:e,time:Up(t),price:parseFloat(n),quantity:parseFloat(r),type:[`1`,`buy`].includes(i.toString())?`buy`:`sell`}}static _parseTicker(e){return{askPrice:$(e.a),baseVolume:$(e.BV),baseVolume1s:$(e.bv),bidPrice:$(e.b),btcVolume:$(e.B),coinraySymbol:e.s,highPrice1s:$(e.h),highPrice24h:$(e.H),lastPrice:$(e.c),lowPrice1s:$(e.l),lowPrice24h:$(e.L),openPrice1s:$(e.o),openPrice24h:$(e.O),quoteVolume:$(e.QV),quoteVolume1s:$(e.qv),usdVolume:$(e.U)}}static _parseTickerSnapshot(e,t){let n=(n,r)=>t&&t.raw[n]===e[n]?t.parsed[r]:$(e[n]);return{coinraySymbol:e.s,lastPrice:n(`c`,`lastPrice`),askPrice:n(`a`,`askPrice`),bidPrice:n(`b`,`bidPrice`),openPrice24h:n(`O`,`openPrice24h`),highPrice24h:n(`H`,`highPrice24h`),lowPrice24h:n(`L`,`lowPrice24h`),baseVolume:n(`BV`,`baseVolume`),quoteVolume:n(`QV`,`quoteVolume`),btcVolume:n(`B`,`btcVolume`),usdVolume:n(`U`,`usdVolume`),baseToUsd:n(`bu`,`baseToUsd`),quoteToUsd:n(`qu`,`quoteToUsd`),marketCap:n(`mc`,`marketCap`)}}static _parseBalance(e){let t={currency:e.currency,available:$(e.available),inOrders:$(e.inOrders),total:$(e.inOrders)};return e.initialMargin&&(t={...t,initialMargin:$(e.initialMargin),openOrderInitialMargin:$(e.openOrderInitialMargin),positionInitialMargin:$(e.positionInitialMargin),unrealizedProfit:$(e.unrealizedProfit),crossWalletBalance:$(e.crossWalletBalance),crossUnrealizedProfit:$(e.crossUnrealizedProfit)}),t}static _tradesToLastCandle(t,n){n.length>0&&n[0].time>n[n.length-1].time&&(n=n.reverse());let r=e._resolutionToSeconds(t),i=L.default.groupBy(n.reverse(),({time:e})=>Math.floor(e.getTime()/r)*r);return L.default.sortBy(Object.keys(i),e=>parseInt(e)).reduce((e,t)=>{let n=i[t],a=n[0].time.getTime(),o=new Date(a-a%r);if(n.length===0)return e;let s=n[0],c,l,u,d,f=0,p=0;return c=l=u=d=e.length===0?s.price:e[e.length-1].close,n.reverse().map(({price:e,quantity:t})=>{l=Math.min(l,e),u=Math.max(u,e),d=e,f+=t,p+=t*e}),e.push({time:new Date(o),open:c,high:u,low:l,close:d,baseVolume:f,quoteVolume:p,numTrades:n.length}),e},[])}static _mergeCandle(e,t){return!e||e.time<t.time?t:(e.numTrades+=t.numTrades,e.high=Math.max(e.high,t.high),e.low=Math.min(e.low,t.low),e.close=t.close,e.skipVolume?e.skipVolume=!1:(e.baseVolume+=t.baseVolume,e.quoteVolume+=t.quoteVolume),e)}static _resolutionToSeconds(e){return e.indexOf(`W`)>0||e.indexOf(`D`)>0?parseInt(e)*24*60*60*1e3:e.indexOf(`S`)>0?parseInt(e)*1e3:e===`D`?864e5:parseInt(e)*60*1e3}},Cm=class{listeners;constructor(){this.listeners={}}removeAllListeners(){this.listeners={}}on=(e,t)=>(e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push(t),t);off=(e,t)=>{e in this.listeners&&(t?this.listeners[e]=this.listeners[e].filter(e=>e!==t):this.listeners[e]=[])};hasListeners=e=>this.listeners[e]&&this.listeners[e].length>0;dispatchEvent=(e,t={})=>{let n=this.listeners[e];n&&n.length>0&&n.map(n=>n({eventName:e,data:t}))}},wm=class e extends Cm{getExchange;api;id;coinraySymbol;symbol;symbolAlt;quoteCurrency;underlyingQuoteCurrency;baseLogoUrl;baseCurrency;exchangeCode;volume;quoteVolume;btcVolume;usdVolume;websocket;openPrice;highPrice;lowPrice;precisionBase;precisionQuote;precisionPrice;minBase;maxBase;maxBaseMarket;minQuote;maxQuote;minTrade;maxTrade;makerFee;takerFee;change;delistedOn;exchangeUrl;baseToUsd;quoteToUsd;status;note;_supportedOrderTypes;_lastPrice;_askPrice;_bidPrice;updatedAt;futuresSettings;symbolTv;tradingSessions;syntheticTrades;marketCap;_groupName;getPriceOverrides;static Create(t,n,r){return e.checkStatic(t),e.checkDynamic(t),new e(t,n,r)}static checkStatic(e){if(e==null?jp(e):typeof e==`object`?Array.isArray(e)&&Np(e,!1):Mp(e,!1),Fp(e.id,!1,`id`),Q(e.coinraySymbol,!1,`coinraySymbol`),Q(e.symbol,!1,`symbol`),Q(e.symbolAlt,!1,`symbolAlt`),Q(e.quoteCurrency,!1,`quoteCurrency`),Q(e.underlyingQuoteCurrency,!1,`underlyingQuoteCurrency`),Q(e.baseLogoUrl,!0,`baseLogoUrl`),Q(e.baseCurrency,!1,`baseCurrency`),Q(e.exchangeCode,!1,`exchangeCode`),Q(e.status||``,!1,`status`),Q(e.note||``,!1,`note`),Lp(e.websocket,!1,`websocket`),Fp(e.precisionBase,!1,`precisionBase`),Fp(e.precisionPrice,!1,`precisionPrice`),Fp(e.minBase,!0,`minBase`),Fp(e.precisionQuote,!1,`precisionQuote`),Fp(e.minQuote,!0,`minQuote`),Ip(e.maxBase,!0,`maxBase`),Ip(e.maxBaseMarket,!0,`maxBaseMarket`),Ip(e.maxQuote,!0,`maxQuote`),Ip(e.minTrade,!1,`minTrade`),Fp(e.maxTrade,!0,`maxTrade`),e.maxTrade===void 0&&(e.maxTrade=null),Fp(e.makerFee,!1,`makerFee`),Fp(e.takerFee,!1,`takerFee`),Rp(e.delistedOn,`delistedOn`),e.delistedOn===void 0&&(e.delistedOn=null),Q(e.exchangeUrl,!1,`exchangeUrl`),Q(e.symbolTv,!0,`symbolTv`),Q(e.groupName,!0,`groupName`),e.futuresSettings!==null&&e.futuresSettings!==void 0){let t=e.futuresSettings;Q(t.tenor,!1,`futuresSettings.tenor`),Q(t.margin,!1,`futuresSettings.margin`),Q(t.expiresAt,!0,`futuresSettings.expiresAt`),Fp(t.fundingIntervalSeconds,!0,`futuresSettings.fundingIntervalSeconds`),Ip(t.maxLeverage,!0,`futuresSettings.maxLeverage`),Q(t.groupName,!0,`futuresSettings.groupName`)}}static checkDynamic(e){Ip(e.volume,!0,`volume`),Ip(e.quoteVolume,!0,`quoteVolume`),Ip(e.btcVolume,!0,`btcVolume`),Ip(e.usdVolume,!0,`usdVolume`),Ip(e.openPrice,!0,`openPrice`),Ip(e.highPrice,!0,`highPrice`),Ip(e.lowPrice,!0,`lowPrice`),Fp(e.change,!1,`change`),Ip(e.lastPrice,!0,`lastPrice`),Ip(e.baseToUsd,!1,`baseToUsd`),Ip(e.quoteToUsd,!1,`quoteToUsd`),Ip(e.askPrice,!0,`askPrice`),Ip(e.bidPrice,!0,`bidPrice`),Q(e.updatedAt,!1,`updatedAt`),Ip(e.marketCap,!0,`marketCap`)}constructor(e,t,n){super(),this.getExchange=()=>n,this.api=t,this._assignStatic(e),this.volume=$(e.volume),this.quoteVolume=$(e.quoteVolume),this.btcVolume=$(e.btcVolume),this.usdVolume=$(e.usdVolume),this.openPrice=$(e.openPrice),this.highPrice=$(e.highPrice),this.lowPrice=$(e.lowPrice),this.change=Vp(e.change)||0,this._lastPrice=$(e.lastPrice),this.baseToUsd=$(e.baseToUsd),this.quoteToUsd=$(e.quoteToUsd),this._askPrice=$(e.askPrice),this._bidPrice=$(e.bidPrice),this.updatedAt=e.updatedAt,this.marketCap=$(e.marketCap)}assignStatic=t=>{e.checkStatic(t),this._assignStatic(t)};_assignStatic(e){if(this.id=e.id,this.coinraySymbol=e.coinraySymbol,this.symbol=e.symbol,this.symbolAlt=e.symbolAlt,this.quoteCurrency=e.quoteCurrency.toUpperCase(),this.underlyingQuoteCurrency=e.underlyingQuoteCurrency.toUpperCase(),this.baseLogoUrl=e.baseLogoUrl,this.baseCurrency=e.baseCurrency.toUpperCase(),this.exchangeCode=e.exchangeCode,this.status=e.status,this.note=e.note,this.websocket=e.websocket,this.precisionBase=e.precisionBase,this.precisionPrice=e.precisionPrice,this.precisionQuote=e.precisionQuote,this.minQuote=e.minQuote,this.minBase=e.minBase,this.maxBase=$(e.maxBase),this.maxBaseMarket=$(e.maxBaseMarket).isZero()?this.maxBase:$(e.maxBaseMarket),this.maxQuote=$(e.maxQuote),this.minTrade=$(e.minTrade),this.maxTrade=$(e.maxTrade),this.makerFee=Vp(e.makerFee),this.takerFee=Vp(e.takerFee),this.delistedOn=e.delistedOn,this.exchangeUrl=e.exchangeUrl,this._supportedOrderTypes=e.supportedOrderTypes,this.symbolTv=e.symbolTv,this._groupName=e.groupName,this.tradingSessions=e.tradingSessions??null,this.syntheticTrades=e.syntheticTrades??!1,this.futuresSettings=void 0,e.futuresSettings!==null&&e.futuresSettings!==void 0){let t=e.futuresSettings;this.futuresSettings={tenor:t.tenor,margin:t.margin,expiresAt:t.expiresAt?new Date(t.expiresAt):null,fundingIntervalSeconds:t.fundingIntervalSeconds??null,maxLeverage:t.maxLeverage!==null&&t.maxLeverage!==void 0?$(t.maxLeverage):null,groupName:t.groupName??void 0}}}get tradingDisabled(){return this.status===`INACTIVE`}get tradingEnabled(){return!this.tradingDisabled}get quoteLogoUrl(){return`https://api.coinray.eu/api/v2/explorer/currencies/${this.quoteCurrency}/thumb`}get supportedOrderTypes(){return this._supportedOrderTypes.length>0?this._supportedOrderTypes:this.getExchange().supportedOrderTypes}get isFutures(){return this.getExchange().isFutures}get groupName(){return this._groupName??this.futuresSettings?.groupName}get fullDisplayName(){return[this.exchangeCode,this.displayName].join(`: `)}get displayName(){return[this.baseCurrency,this.quoteCurrency].join(`/`)}get priceOverrides(){return this.getPriceOverrides?this.getPriceOverrides():{}}get lastPrice(){return this.priceOverrides.lastPrice||this._lastPrice}get askPrice(){return this.priceOverrides.askPrice||this._askPrice}get bidPrice(){return this.priceOverrides.bidPrice||this._bidPrice}overridePrices=e=>{this.getPriceOverrides=e};updateLastPrice=e=>{this._lastPrice=e,this.recomputeChange(),this.dispatchEvent(`price`)};recomputeChange(){this.change=this.openPrice.isZero()?0:this.lastPrice.minus(this.openPrice).dividedBy(this.openPrice).multipliedBy(100).toNumber()}updateBidAsk=(e,t)=>{this._bidPrice=e,this._askPrice=t,this.dispatchEvent(`bidask`)};updateTicker=e=>{this.openPrice=e.openPrice24h,this.highPrice=e.highPrice24h,this.lowPrice=e.lowPrice24h,this.volume=e.baseVolume,this.quoteVolume=e.quoteVolume,this.btcVolume=e.btcVolume,this.usdVolume=e.usdVolume,this.updateBidAsk(e.bidPrice,e.askPrice),this.updateLastPrice(e.lastPrice),this.dispatchEvent(`ticker`)};applySnapshot=(e,t=!1)=>{if(!t){let t=e.lastPrice!==this._lastPrice||e.openPrice24h!==this.openPrice;this._lastPrice=e.lastPrice,this._bidPrice=e.bidPrice,this._askPrice=e.askPrice,this.openPrice=e.openPrice24h,this.highPrice=e.highPrice24h,this.lowPrice=e.lowPrice24h,t&&this.recomputeChange()}this.volume=e.baseVolume,this.quoteVolume=e.quoteVolume,this.btcVolume=e.btcVolume,this.usdVolume=e.usdVolume,this.baseToUsd=e.baseToUsd,this.quoteToUsd=e.quoteToUsd,this.marketCap=e.marketCap,this.dispatchEvent(`ticker`)};clone(){let t={...this,volume:this.volume,quoteVolume:this.quoteVolume,btcVolume:this.btcVolume,usdVolume:this.usdVolume,marketCap:this.marketCap,openPrice:this.openPrice,highPrice:this.highPrice,lowPrice:this.lowPrice,lastPrice:this._lastPrice,askPrice:this._askPrice,bidPrice:this._bidPrice,maxBase:this.maxBase,maxBaseMarket:this.maxBaseMarket,maxQuote:this.maxQuote,minTrade:this.minTrade,maxTrade:this.maxTrade,baseToUsd:this.baseToUsd,quoteToUsd:this.quoteToUsd,groupName:this._groupName},n=new e(t,this.api,this.getExchange());return n.getPriceOverrides=this.getPriceOverrides,n.listeners=this.listeners,n}},Tm=class e{api;id;name;code;websocket;active;aliasedTo;tradingEnabled;tradingEnabledFrom;isFutures;isDex;virtual;logo;btcVolume;usdVolume;totalMarkets;quoteCurrencies;supportedFeatures;supportedResolutions;supportedOrderTypes;baseCurrencyDominance;apiKeySettings;apiEndpoint;websocketEndpoint;markets;exchangeSymbols;static Create(t,n){return e.check(t),new e(t,n)}static check(e){if(e==null?jp(e):typeof e==`object`?Array.isArray(e)&&Np(e,!1):Mp(e,!1),Fp(e.id,!1,`id`),Q(e.name,!1,`name`),Q(e.code,!1,`code`),Lp(e.websocket,!1,`websocket`),Lp(e.active,!1,`active`),Lp(e.tradingEnabled,!1,`tradingEnabled`),Q(e.tradingEnabledFrom,!1,`tradingEnabledFrom`),Lp(e.isFutures,!0,`isFutures`),Lp(e.isDex,!0,`isDex`),Lp(e.virtual,!0,`virtual`),Q(e.logo,!1,`logo`),Q(e.btcVolume,!1,`btcVolume`),Q(e.usdVolume,!1,`usdVolume`),Fp(e.totalMarkets,!1,`totalMarkets`),Pp(e.quoteCurrencies,`quoteCurrencies`),Q(e.apiEndpoint,!0,`apiEndpoint`),Q(e.websocketEndpoint,!0,`websocketEndpoint`),Q(e.aliasedTo,!0,`aliasedTo`),e.quoteCurrencies)for(let t=0;t<e.quoteCurrencies.length;t++)Q(e.quoteCurrencies[t],!1,`quoteCurrencies[`+t+`]`);if(e.quoteCurrencies===void 0&&(e.quoteCurrencies=null),Pp(e.supportedResolutions,`supportedResolutions`),Pp(e.supportedFeatures,`supportedFeatures`),e.supportedResolutions)for(let t=0;t<e.supportedResolutions.length;t++)Q(e.supportedResolutions[t],!1,`supportedResolutions[`+t+`]`);e.supportedResolutions===void 0&&(e.supportedResolutions=null)}constructor(e,t){this.api=t,this.markets={},this.exchangeSymbols={},this._assign(e)}update(t){e.check(t),this._assign(t)}_assign(e){let t=this.api;this.id=e.id,this.name=e.name,this.code=e.code,this.websocket=e.websocket,this.isFutures=!!e.isFutures,this.isDex=!!e.isDex,this.virtual=!!e.virtual,this.active=e.active,this.tradingEnabled=e.tradingEnabled,this.tradingEnabledFrom=e.tradingEnabledFrom,this.logo=e.logo,this.btcVolume=$(e.btcVolume),this.usdVolume=$(e.usdVolume),this.totalMarkets=Hp(e.totalMarkets),this.quoteCurrencies=e.quoteCurrencies,this.supportedResolutions=e.supportedResolutions,this.supportedFeatures=e.supportedFeatures,this.supportedOrderTypes=e.supportedOrderTypes,this.baseCurrencyDominance=e.baseCurrencyDominance,this.apiKeySettings=e.apiKeySettings,this.apiEndpoint=e.apiEndpoint||t.config.apiEndpoint,this.websocketEndpoint=e.websocketEndpoint||t.config.websocketEndpoint,this.aliasedTo=e.aliasedTo}clone(){return new e({api:this.api,id:this.id,name:this.name,code:this.code,websocket:this.websocket,isFutures:this.isFutures,isDex:this.isDex,virtual:this.virtual,logo:this.logo,btcVolume:this.btcVolume,usdVolume:this.usdVolume,totalMarkets:this.totalMarkets,quoteCurrencies:this.quoteCurrencies,supportedResolutions:this.supportedResolutions,supportedFeatures:this.supportedFeatures,baseCurrencyDominance:this.baseCurrencyDominance,apiKeySettings:this.apiKeySettings,aliasedTo:this.aliasedTo},this.api)}async loadMarkets(e=void 0){let t=await this.api.fetchMarkets(this,e),n=t.map(e=>{try{return wm.Create(e,this.api,this)}catch{return new wm(e,this.api,this)}});return n.length>0&&(this.markets=L.default.keyBy(n,`coinraySymbol`),this.exchangeSymbols=L.default.keyBy(n,`symbol`)),t}mergeStatic(e){let t=[],n=[];if(e.length===0)return{added:t,removed:n};let r={};for(let n of e){let e=this.markets[n.coinraySymbol];try{e?(e.assignStatic(n),r[n.coinraySymbol]=e):(wm.checkStatic(n),r[n.coinraySymbol]=new wm(n,this.api,this),t.push(n.coinraySymbol))}catch(t){console.error(t),e&&(r[n.coinraySymbol]=e)}}for(let[e,t]of Object.entries(this.markets))r[e]||(t.removeAllListeners(),n.push(e));return this.markets=r,this.exchangeSymbols=L.default.keyBy(Object.values(r),`symbol`),{added:t,removed:n}}getBaseCurrencyDominance(e){return this.baseCurrencyDominance[e]}getMarketByExchangeSymbol(e){return this.exchangeSymbols[e]}getCurrencyPrice(e,t){for(let[n,r]of Object.entries(this.markets))if(r.baseCurrency===t)return $(e).dividedBy(r.baseToUsd);else if(r.quoteCurrency===t)return $(e).dividedBy(r.quoteToUsd);return new d(0)}getUsdPrice(e,t){for(let[n,r]of Object.entries(this.markets))if(r.baseCurrency===t)return r.baseToUsd.multipliedBy(e);else if(r.quoteCurrency===t)return r.quoteToUsd.multipliedBy(e);return new d(0)}getMarket(e){return this.markets[e]}},Em=class{subscriptions;pendingAdditions;pendingRemovals;constructor(){this.subscriptions=new Map,this.pendingAdditions=new Map,this.pendingRemovals=new Map}has(e){let t=this.subscriptions.get(e);return t!==void 0&&t.size>0}subscribe(e,t,n=!1){n&&this.unsubscribeAll(e);for(let n of t)this.pendingAdditions.has(n)||this.pendingAdditions.set(n,new Set),this.pendingAdditions.get(n).add(e),this.pendingRemovals.has(n)&&(this.pendingRemovals.get(n).delete(e),this.pendingRemovals.get(n).size===0&&this.pendingRemovals.delete(n))}unsubscribe(e,t){for(let n of t)this.pendingAdditions.has(n)&&(this.pendingAdditions.get(n).delete(e),this.pendingAdditions.get(n).size===0&&this.pendingAdditions.delete(n)),this.pendingRemovals.has(n)||this.pendingRemovals.set(n,new Set),this.pendingRemovals.get(n).add(e)}unsubscribeAll(e){for(let[t,n]of this.subscriptions)n.has(e)&&(this.pendingRemovals.has(t)||this.pendingRemovals.set(t,new Set),this.pendingRemovals.get(t).add(e));for(let[t,n]of this.pendingAdditions)n.delete(e),n.size===0&&this.pendingAdditions.delete(t)}exchangeCodes(){let e=new Set;for(let t of this.subscriptions.keys())e.add(t.split(`_`)[0]);return e}processPendingChanges(){for(let[e,t]of this.pendingAdditions){this.subscriptions.has(e)||this.subscriptions.set(e,new Set);let n=this.subscriptions.get(e);for(let e of t)n.add(e)}for(let[e,t]of this.pendingRemovals){if(!this.subscriptions.has(e))continue;let n=this.subscriptions.get(e);for(let e of t)n.delete(e);n.size===0&&this.subscriptions.delete(e)}this.pendingAdditions.clear(),this.pendingRemovals.clear()}},Dm=class extends Cm{isFormula=!0;coinraySymbol;legs;exchangeCodes;marketCap=void 0;baseCurrency=void 0;quoteCurrency=void 0;volume=void 0;quoteVolume=void 0;btcVolume=void 0;usdVolume=void 0;node;getMarket;_precisionPrice;constructor(e,t){super(),this.node=cm(e),this.coinraySymbol=e,this.legs=lm(this.node),this.exchangeCodes=[...new Set(this.legs.map(e=>e.split(`_`)[0]))],this.getMarket=t}get missingLegs(){return this.legs.filter(e=>!this.getMarket(e))}get displayName(){return this.missingLegs.length?this.coinraySymbol:_m(this.coinraySymbol,this.getMarket).name}get exchangeCode(){return this.exchangeCodes.length===1?this.exchangeCodes[0]:void 0}get status(){let e=this.legMarkets();if(e)return e.find(e=>e.status!==`ACTIVE`)?.status??`ACTIVE`}get precisionPrice(){return this._precisionPrice===void 0&&this.lastPrice&&(this._precisionPrice=_m(this.coinraySymbol,this.getMarket).pricePrecision),this._precisionPrice}get lastPrice(){return this.evaluate(e=>e.lastPrice)}get openPrice(){return this.evaluate(e=>e.openPrice)}get change(){let e=this.lastPrice,t=this.openPrice;if(e&&t&&!t.isZero())return e.minus(t).dividedBy(t).multipliedBy(100).toNumber()}legMarkets(){let e=this.legs.map(e=>this.getMarket(e));return e.every(Boolean)?e:void 0}evaluate(e){let t=this.legMarkets();if(!t)return;let n={};for(let r=0;r<this.legs.length;r++){let i=e(t[r])?.toNumber();if(!i)return;n[this.legs[r]]=i}let r=um(this.node,e=>n[e]);return Number.isFinite(r)?new d(r):void 0}},Om=12e4,km=6e5,Am=6e5,jm=6e5,Mm=250,Nm=10,Pm=e=>L.default.uniq(e.flatMap(e=>{if(!om(e))return[e];try{return lm(cm(e))}catch{return[]}})),Fm=e=>L.default.uniq(Pm(Array.isArray(e)?e:[e]).map(e=>`${e}`.split(`_`)[0])),Im=class extends Cm{rootApi;apis;exchanges;initialized;refreshRate;_refreshingToken;tickerSubscriptions;tickerSubscriptionRefeshTimer;_onTokenExpired;onStoreCache;apiCache;rawCache={exchanges:[],markets:{}};destroyed=!1;formulaSubs=new Map;formulaMarkets=new Map;requestedTickers=new Map;loopsStarted=!1;tickersTimer;staticTimer;exchangesTimer;liveLoadTimer;activationTimer;activationPromise=null;activationResolve;pinned=new Set;leases=new Map;graceUntil=new Map;active=new Set;pendingActivation=new Set;liveMarkets=new Map;staticEtags=new Map;staticCheckedAt=new Map;endpointDownUntil={tickers:0,static:0};constructor(e,t,n=3e4,r=void 0){super(),this.rootApi=new Sm(e,t),this.apis=new Map,this.exchanges={},this.initialized=!1,this.refreshRate=n,this.tickerSubscriptions=new Em,this.tickerSubscriptionRefeshTimer=null,this.rootApi.onTokenExpired(this.refreshToken),this.onStoreCache=r?.onStoreCache,this.apiCache=r?.apiCache}async initialize(){this.initialized||=(await this.start(),!0)}getRootApi(){return this.rootApi}authenticateDevice(e,t){this.rootApi.authenticateDevice(e,t)}refreshToken=async()=>{if(this._onTokenExpired){if(this._refreshingToken)return await this._refreshingToken;{this._refreshingToken=this._onTokenExpired();let e=await this._refreshingToken;this._refreshingToken=void 0;for(let t of this.apis.values())t.refreshToken(e);return e}}};onTokenExpired(e){this._onTokenExpired=e}async start(){if(this.apiCache)try{await this.refreshExchanges(this.apiCache),this.liveLoad();return}catch(e){console.error(e)}finally{this.apiCache=void 0}await this.liveLoad()}liveLoad=async()=>{try{await this.refreshExchanges(),this.startLoops()}catch(e){console.error(e),this.destroyed||(this.liveLoadTimer=setTimeout(this.liveLoad,this.refreshRate))}};startLoops(){if(this.destroyed||this.loopsStarted)return;this.recomputeActive(),this.loopsStarted=!0;let e=Date.now();for(let t of Object.keys(this.exchanges))this.staticCheckedAt.set(t,e);this.loop(`tickersTimer`,this.tickersTick,this.refreshRate),this.loop(`staticTimer`,this.staticTick,km),this.loop(`exchangesTimer`,this.refreshExchangeList,Am)}loop(e,t,n){this.destroyed||(this[e]=setTimeout(async()=>{try{await t()}catch(e){console.error(e)}this.loop(e,t,n)},n))}destroy(){this.destroyed=!0;for(let e of this.apis.values())try{e.destroy()}catch(e){console.error(`Could not destroy coinray`,e)}for(let e of[this.tickersTimer,this.staticTimer,this.exchangesTimer,this.liveLoadTimer,this.activationTimer,this.tickerSubscriptionRefeshTimer])clearTimeout(e);this.activationResolve?.(),this.initialized=!1}refreshExchanges=async(e=void 0)=>{let t={exchanges:[],markets:{}},n=await this.rootApi.fetchExchanges(e=>(t.exchanges.push(e),this.apis.has(e.code)||this.apis.set(e.code,this.rootApi),Tm.Create(e,this.apis.get(e.code))),e?.exchanges),r=await Promise.all(n.map(async t=>({[t.code]:await t.loadMarkets(e?.markets?.[t.code])})));this.destroyed||(t.markets=r.reduce((e,t)=>({...e,...t}),{}),this.exchanges=n.reduce((e,t)=>(e[t.code]=t,e),{}),this.rawCache=t,this.dispatchEvent(`marketsUpdated`,{exchangeCodes:Object.keys(this.exchanges)}),e||this.storeCache())};storeCache(){this.onStoreCache&&this.onStoreCache(this.rawCache)}setActiveExchanges(e){this.pinned=new Set(Fm(e)),this.recomputeActive()}touchExchange(e){let t=Fm(e);for(let e of t)this.leases.set(e,(this.leases.get(e)||0)+1);this.recomputeActive();let n=!1;return()=>{if(!n){n=!0;for(let e of t){let t=(this.leases.get(e)||0)-1;t>0?this.leases.set(e,t):this.leases.delete(e)}this.recomputeActive()}}}async ensureFresh(e){let t=Fm(e).filter(e=>this.exchanges[e]);if(t.length===0)return;let n=this.touchExchange(t);try{await this.scheduleActivation(t)}finally{n()}}getActiveExchanges(){return[...this.recomputeActive()].sort()}retainLiveMarket(e){this.liveMarkets.set(e,(this.liveMarkets.get(e)||0)+1);let t=!1;return()=>{if(t)return;t=!0;let n=(this.liveMarkets.get(e)||0)-1;n>0?this.liveMarkets.set(e,n):this.liveMarkets.delete(e)}}isLive(e){return this.tickerSubscriptions.has(e)||this.liveMarkets.has(e)}recomputeActive(){let e=Date.now(),t=new Set([...this.pinned,...this.leases.keys(),...this.tickerSubscriptions.exchangeCodes()]);for(let e of t)this.graceUntil.delete(e);for(let n of this.active)!t.has(n)&&!this.graceUntil.has(n)&&this.graceUntil.set(n,e+Om);for(let[n,r]of this.graceUntil)r<=e?this.graceUntil.delete(n):t.add(n);let n=new Set([...t].filter(e=>this.exchanges[e]));if(this.loopsStarted){let e=[...n].filter(e=>!this.active.has(e));e.length&&this.scheduleActivation(e)}return this.active=n,n}scheduleActivation(e){if(this.destroyed)return Promise.resolve();for(let t of e)this.pendingActivation.add(t);return this.activationPromise||=new Promise(e=>{this.activationResolve=e,this.activationTimer=setTimeout(async()=>{let t=[...this.pendingActivation];this.pendingActivation.clear(),this.activationPromise=null;try{await this.fetchTickers(t);let e=Date.now(),n=t.filter(t=>e-(this.staticCheckedAt.get(t)||0)>=km);Promise.all(n.map(this.revalidateStatic)).then(e=>e.some(Boolean)&&this.storeCache()),this.destroyed||this.dispatchEvent(`marketsUpdated`,{exchangeCodes:t})}catch(e){console.error(e)}e()},Mm)}),this.activationPromise}tickersTick=async()=>{let e=[...this.recomputeActive()].sort();await this.fetchTickers(e),this.destroyed||this.dispatchEvent(`marketsUpdated`,{exchangeCodes:e})};staticTick=async()=>{(await Promise.all([...this.recomputeActive()].map(this.revalidateStatic))).some(Boolean)&&this.storeCache()};fetchTickers=async e=>{this.destroyed||await Promise.all(L.default.chunk([...e].sort(),Nm).map(async e=>{if(Date.now()<this.endpointDownUntil.tickers)return Promise.all(e.map(this.refreshMarkets));try{let t=await this.rootApi.fetchTickers(e);if(this.endpointDownUntil.tickers=0,this.destroyed)return;for(let[e,n]of Object.entries(t)){let t=this.exchanges[e];if(t)for(let e of n)t.markets[e.coinraySymbol]?.applySnapshot(e,this.isLive(e.coinraySymbol))}}catch(t){this.markEndpointDown(`tickers`,t)?await Promise.all(e.map(this.refreshMarkets)):console.error(t)}}))};revalidateStatic=async e=>{let t=this.exchanges[e];if(!t||this.destroyed)return!1;if(Date.now()<this.endpointDownUntil.static)return await this.refreshMarkets(e),!0;try{let{markets:n,etag:r}=await this.rootApi.fetchStaticMarkets(e,this.staticEtags.get(e));if(this.endpointDownUntil.static=0,this.staticCheckedAt.set(e,Date.now()),this.destroyed||!n)return!1;r&&this.staticEtags.set(e,r);let i=L.default.keyBy(this.rawCache.markets[e]||[],`coinraySymbol`),a=n.map(e=>({...i[e.coinraySymbol],...e})),{added:o}=t.mergeStatic(a);return a.length&&(this.rawCache.markets[e]=a),o.length&&this.scheduleActivation([e]),this.dispatchEvent(`marketsUpdated`,{exchangeCodes:[e]}),!0}catch(t){return this.markEndpointDown(`static`,t)?(await this.refreshMarkets(e),!0):(console.error(t),!1)}};markEndpointDown(e,t){return t?.status===404||t?.isAxiosError&&!t.response?(this.endpointDownUntil[e]||console.warn(`CoinrayCache: ${e} endpoint unavailable (${t?.message}), falling back to /markets`),this.endpointDownUntil[e]=Date.now()+jm,!0):!1}refreshExchangeList=async()=>{let e=await this.rootApi.fetchExchanges(e=>e,void 0);if(this.destroyed)return;let t={},n=[];for(let r of e){this.apis.has(r.code)||this.apis.set(r.code,this.rootApi);let e=this.exchanges[r.code];try{e?(e.update(r),t[r.code]=e):(t[r.code]=Tm.Create(r,this.apis.get(r.code)),n.push(r.code))}catch(n){console.error(n),e&&(t[r.code]=e)}}let r=Object.keys(this.exchanges).filter(e=>!t[e]);this.exchanges=t,this.rawCache.exchanges=e;for(let e of r)delete this.rawCache.markets[e];await Promise.all(n.map(this.refreshMarkets)),(n.length||r.length)&&(this.dispatchEvent(`marketsUpdated`,{exchangeCodes:n}),this.storeCache())};getProxyList=async(e={})=>await this.rootApi.getProxyList(e);getExchanges(){if(!this.initialized)throw`The cache is not initialized yet`;return this.exchanges}getExchange(e){return this.getExchanges()[e]||Tm.Create({id:-1,name:e,code:e,websocket:!1,active:!1,tradingEnabled:!1,tradingEnabledFrom:``,isFutures:!1,isDex:!1,logo:`data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==
|
|
34
|
+
`,btcVolume:`0`,usdVolume:`0`,totalMarkets:0,quoteCurrencies:[]},this.rootApi)}refreshMarkets=async e=>{let t=this.exchanges[e];if(t&&!this.destroyed)try{let n=await t.loadMarkets();n.length&&(this.rawCache.markets[e]=n),this.staticCheckedAt.set(e,Date.now())}catch(e){console.error(e)}};searchMarkets(e){return Object.values(this.exchanges).reduce((t,n)=>(t={...t,...Qp(n.markets,e)},t),{})}getMarkets(e){switch(typeof e){case`string`:return this.getExchange(e).markets;default:return e.reduce((e,t)=>{let n=this.getMarket(t);return n&&(e[t]=n),e},{})}}getMarket=e=>{let t=`${e}`.split(`_`);if(t.length<3)return;let n=this.getExchange(t[0]);if(n)return n.getMarket(e)};async fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i}){if(om(e)){let{node:a,legs:o}=this.parseFormulaSymbol(e),s=t.endsWith(`S`)?void 0:this.formulaApi(o);if(s)try{return await s.fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})}catch{}let c=await Promise.all(o.map(e=>this.fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})));return mm(a,L.default.zipObject(o,c))}return this.apiForSymbol(e).fetchCandles({coinraySymbol:e,resolution:t,start:n,end:r,useWebSocket:i})}async fetchFirstCandleTime({coinraySymbol:e,resolution:t}){if(om(e)){let{legs:n}=this.parseFormulaSymbol(e),r=this.formulaApi(n);if(r)try{return await r.fetchFirstCandleTime({coinraySymbol:e,resolution:t})}catch{}let i=await Promise.all(n.map(e=>this.fetchFirstCandleTime({coinraySymbol:e,resolution:t})));return L.default.maxBy(i,e=>new Date(e).getTime())}return this.apiForSymbol(e).fetchFirstCandleTime({coinraySymbol:e,resolution:t})}subscribeTickers(e,t,n=!1){this.updateRequestedTickers(e,e=>{n&&e.clear();for(let n of t)e.add(n)}),this.tickerSubscriptions.subscribe(e,Pm(t)),this.scheduleTickerRefresh()}updateRequestedTickers(e,t){let n=this.requestedTickers.get(e)??new Set,r=Pm([...n]);t(n),n.size?this.requestedTickers.set(e,n):this.requestedTickers.delete(e);let i=L.default.difference(r,Pm([...n]));i.length&&this.tickerSubscriptions.unsubscribe(e,i)}scheduleTickerRefresh(){this.destroyed||(this.tickerSubscriptionRefeshTimer&&clearTimeout(this.tickerSubscriptionRefeshTimer),this.tickerSubscriptionRefeshTimer=setTimeout(async()=>{await this.flushTickerSubscriptions(),this.tickerSubscriptionRefeshTimer=null},1e3))}unsubscribeAllTickers(e){this.requestedTickers.delete(e),this.tickerSubscriptions.unsubscribeAll(e),this.scheduleTickerRefresh()}unsubscribeTickers(e,t){this.updateRequestedTickers(e,e=>{for(let n of t)e.delete(n)}),this.scheduleTickerRefresh()}async flushTickerSubscriptions(){let e=[],t=[];for(let t of this.tickerSubscriptions.pendingAdditions.keys())e.push(t);for(let[e,n]of this.tickerSubscriptions.pendingRemovals.entries()){let r=new Set(this.tickerSubscriptions.subscriptions.get(e)||[]);for(let e of n)r.delete(e);let i=this.tickerSubscriptions.pendingAdditions.get(e);if(i)for(let e of i)r.add(e);r.size===0&&t.push(e)}e.length&&await this.rootApi.subscribeTickers(e,!1,this.refreshMarketsFromTickers),t.length&&this.rootApi.unsubscribeTickers(t,this.refreshMarketsFromTickers),this.tickerSubscriptions.processPendingChanges(),this.recomputeActive()}refreshMarketsFromTickers=async e=>{let{exchangeCode:t,tickers:n}=e,r=this.getExchange(t);if(r){let e=!1;for(let t of n)if(this.tickerSubscriptions.has(t.coinraySymbol)){let n=r.getMarket(t.coinraySymbol);n&&(n.updateTicker(t),e=!0)}e&&this.dispatchEvent(`tickersUpdated`,{exchangeCode:t,coinraySymbols:n.map(e=>e.coinraySymbol)})}};async subscribeCandles({coinraySymbol:e,resolution:t,lastCandle:n},r){if(om(e)){let{node:n,legs:i}=this.parseFormulaSymbol(e),a={},o=i.map(i=>[i,({candle:o})=>{a[i]=o;let s=hm(n,a);s&&r({coinraySymbol:e,resolution:t,candle:s,previousCandles:[]})}]),s=`${e}-${t}`;return this.formulaSubs.has(s)||this.formulaSubs.set(s,new Map),this.formulaSubs.get(s).set(r,o),await Promise.all(o.map(([e,n])=>this.subscribeCandles({coinraySymbol:e,resolution:t},n))),r}return this.apiForSymbol(e).subscribeCandles({coinraySymbol:e,resolution:t,lastCandle:n},r)}async unsubscribeCandles({coinraySymbol:e,resolution:t},n){if(om(e)){let r=this.formulaSubs.get(`${e}-${t}`);if(!r)return;for(let e of n?[n]:[...r.keys()]){for(let[n,i]of r.get(e)??[])await this.unsubscribeCandles({coinraySymbol:n,resolution:t},i);r.delete(e)}return}await this.apiForSymbol(e).unsubscribeCandles({coinraySymbol:e,resolution:t},n)}async subscribeOrderBook({coinraySymbol:e},t){if(om(e))throw Error(`Not supported for formula symbols`);await this.apiForSymbol(e).subscribeOrderBook({coinraySymbol:e},t)}async unsubscribeOrderBook({coinraySymbol:e},t){await this.apiForSymbol(e).unsubscribeOrderBook({coinraySymbol:e},t)}async subscribeTrades({coinraySymbol:e},t){if(om(e))throw Error(`Not supported for formula symbols`);await this.apiForSymbol(e).subscribeTrades({coinraySymbol:e},t)}async unsubscribeTrades({coinraySymbol:e},t){await this.apiForSymbol(e).unsubscribeTrades({coinraySymbol:e},t)}getFormulaMarket(e){if(!om(e))return;let t=this.formulaMarkets.get(e);if(!t){try{t=new Dm(e,this.getMarket)}catch{return}this.formulaMarkets.set(e,t)}return t}getMarketOrFormula(e){return om(e)?this.getFormulaMarket(e):this.getMarket(e)}formulaSymbolInfo(e){return _m(e,this.getMarket)}parseFormulaSymbol(e){let t=cm(e),n=lm(t),r=n.find(e=>!this.apiForSymbol(e));if(r)throw Error(`Unknown exchange for ${r}`);return{node:t,legs:n}}formulaApi(e){let t=new Set(e.map(e=>this.apiForSymbol(e)));return t.size===1?[...t][0]:void 0}apiForSymbol(e){let t=`${e}`.split(`_`);if(t.length<3)return;let n=t[0];return this.apis.get(n)}},Lm=class extends Error{constructor(e){super(e),this.name=`MarketNotFoundError`}},Rm=class extends Cm{coinrayCache;getPriceOverrides;coinraySymbol;orderBook;trades;tradesDelayed;maxTrades;releaseLiveMarket;prevTickers={lastPrice:new d(0),askPrice:new d(0),bidPrice:new d(0)};constructor(e,t={}){super(),this.coinrayCache=e,this.maxTrades=t.maxTrades||100,t.getPriceOverrides&&(this.getPriceOverrides=t.getPriceOverrides),this.destroy()}setCoinraySymbol(e){this.dispatchEvent(`coinraySymbolWillChange`,{coinraySymbol:e}),this.stop(),this.releaseLiveMarket?.(),this.releaseLiveMarket=e?this.coinrayCache.retainLiveMarket?.(e):void 0,this.coinraySymbol=e,this.startOrderBook(),this.startTrades(),this.dispatchEvent(`coinraySymbolChanged`,{coinraySymbol:e})}destroy(){this.releaseLiveMarket?.(),this.releaseLiveMarket=void 0,this.coinraySymbol=null,this.removeAllListeners(),this.stop()}stop(){this.stopOrderBook(),this.stopTrades()}getExchange(){return this.coinrayCache.getExchange(this.getMarket().exchangeCode)}getMarket(){if(this.coinraySymbol){let e=this.coinrayCache.getMarket(this.coinraySymbol);return e?.overridePrices(this.getPriceOverrides),e}throw new Lm(`Market not found: ${this.coinraySymbol}`)}subscribeCoinraySymbolWillChange(e){return this.on(`coinraySymbolWillChange`,e)}unsubscribeCoinraySymbolWillChange(e){this.off(`coinraySymbolWillChange`,e)}subscribeCoinraySymbolChange(e){return this.on(`coinraySymbolChanged`,e)}unsubscribeCoinraySymbolChange(e){this.off(`coinraySymbolChanged`,e)}subscribeMarketUpdates=e=>(this.on(`marketUpdated`,e),this.subscribeOrderBook(this.handleMarketUpdate),this.subscribeTrades(this.handleMarketUpdate),e);updatePrevTicker=({lastPrice:e,bidPrice:t,askPrice:n})=>{e&&(this.prevTickers.lastPrice=$(e)),n&&(this.prevTickers.askPrice=$(n)),t&&(this.prevTickers.bidPrice=$(t))};handleMarketUpdate=({data:{type:e,coinraySymbol:t,...n}})=>{if(this.coinraySymbol!==t){this.unsubscribeOrderBook(this.handleOrderBook),this.unsubscribeTrades(this.handleOrderBook);return}switch(e){case`trades:snapshot`:case`trades:update`:{let{trades:e}=n;if(e.length===0)break;let t=this.getMarket(),r=$(e[0].price);(!t._lastPrice.eq(r)||!this.prevTickers.lastPrice.eq(r))&&(t.updateLastPrice(r),this.updatePrevTicker({lastPrice:r}),this.dispatchEvent(`marketUpdated`,{market:t}));break}case`orderBook:snapshot`:case`orderBook:update`:{let{orderBook:{bids:e,asks:t}}=n,r=this.getMarket();if(e.length===0||t.length===0)break;let i=t[0].price,a=e[0].price,o=!r._askPrice.eq(i)||!r._bidPrice.eq(a),s=!this.prevTickers.askPrice.eq(i)||!this.prevTickers.bidPrice.eq(a);(o||s)&&(r.updateBidAsk(a,i),this.updatePrevTicker({askPrice:i,bidPrice:a}),this.dispatchEvent(`marketUpdated`,{market:r}));break}}};unsubscribeMarketUpdates=e=>{this.off(`marketUpdated`,e),this.hasListeners(`marketUpdated`)||(this.unsubscribeOrderBook(this.handleMarketUpdate),this.unsubscribeTrades(this.handleMarketUpdate))};subscribeOrderBook=e=>(this.on(`orderBookUpdated`,e),this.startOrderBook(),e);startOrderBook=()=>{this.coinraySymbol&&this.hasListeners(`orderBookUpdated`)&&this.coinrayCache.subscribeOrderBook({coinraySymbol:this.coinraySymbol},this.handleOrderBook)};stopOrderBook=()=>{this.coinraySymbol&&this.coinrayCache.unsubscribeOrderBook({coinraySymbol:this.coinraySymbol},this.handleOrderBook),this.orderBook={minSeq:void 0,maxSeq:void 0,bids:{},asks:{}}};handleOrderBook=async({type:e,coinraySymbol:t,orderBook:n})=>{if(this.coinraySymbol!==t){this.coinrayCache.unsubscribeOrderBook({coinraySymbol:t},this.handleOrderBook);return}e===`orderBook:snapshot`&&(this.orderBook={minSeq:void 0,maxSeq:void 0,bids:{},asks:{}});let{minSeq:r,maxSeq:i,bids:a,asks:o}=n,s=(e,t)=>{L.default.forEach(t,(t,n)=>{t>0?e[n]={price:new d(n),quantity:t}:delete e[n]})};if(r-this.orderBook.maxSeq>1){this.stopOrderBook(),this.startOrderBook();return}this.orderBook.minSeq=r,this.orderBook.maxSeq=i,s(this.orderBook.bids,a),s(this.orderBook.asks,o),this.dispatchEvent(`orderBookUpdated`,{type:e,coinraySymbol:t,orderBook:{minSeq:r,maxSeq:i,bids:Object.values(this.orderBook.bids).sort(({price:e},{price:t})=>t.minus(e)),asks:Object.values(this.orderBook.asks).sort(({price:e},{price:t})=>e.minus(t))}})};unsubscribeOrderBook=e=>{this.off(`orderBookUpdated`,e),this.hasListeners(`orderBookUpdated`)||this.stopOrderBook()};subscribeTrades=e=>(this.on(`tradesUpdated`,e),this.startTrades(),e);startTrades=()=>{this.coinraySymbol&&this.hasListeners(`tradesUpdated`)&&this.coinrayCache.subscribeTrades({coinraySymbol:this.coinraySymbol},this.handleTrades)};stopTrades=()=>{this.coinraySymbol&&this.coinrayCache.unsubscribeTrades({coinraySymbol:this.coinraySymbol},this.handleTrades),this.trades=[]};handleTrades=({type:e,coinraySymbol:t,trades:n})=>{if(this.coinraySymbol!==t){this.coinrayCache.unsubscribeTrades({coinraySymbol:t},this.handleTrades);return}if(e===`trades:snapshot`&&(this.trades=[]),this.trades=[...n,...this.trades].sort((e,t)=>t.time.getTime()-e.time.getTime()).slice(0,this.maxTrades),this.dispatchEvent(`tradesUpdated`,{type:e,coinraySymbol:t,trades:this.trades}),!this.trades.length)return;let r=Date.now()-this.trades[0].time.getTime();e===`trades:snapshot`&&this.tradesDelayed?this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!1,delayInMs:r}):e===`trades:update`&&(this.tradesDelayed&&r<3e4?this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!1,delayInMs:r}):!this.tradesDelayed&&r>=3e4&&this.dispatchTradesDelayed({type:e,coinraySymbol:t,tradesDelayed:!0,delayInMs:r}))};dispatchTradesDelayed=({type:e,coinraySymbol:t,tradesDelayed:n,delayInMs:r})=>{this.tradesDelayed=n,this.dispatchEvent(`tradesDelayed`,{type:e,coinraySymbol:t,tradesDelayed:n,delayInMs:r})};unsubscribeTrades=e=>{this.off(`tradesUpdated`,e),this.hasListeners(`tradesUpdated`)||this.stopTrades()};subscribeTradesDelayed=e=>(this.on(`tradesDelayed`,e),e);unsubscribeTradesDelayed=e=>{this.off(`tradesDelayed`,e)}},zm={"en-US":{validation:{notGreaterThanOrEqualTo:`Can't be less than {{min}}`,insufficientFunds:`Insufficient funds`}},nl:{validation:{notGreaterThanOrEqualTo:`Kan niet minder zijn dan {{min}}`,insufficientFunds:`Onvoldoende balans`}},ru:{validation:{notGreaterThanOrEqualTo:`Не может быть меньше {{min}}`,insufficientFunds:`Недостаточно средств`}}},Bm=u(s(((e,t)=>{(function(e,t,n){"use strict";var r=function(e,t,n){n=i.extend({},i.options,n);var a=i.runValidations(e,t,n);if(a.some(function(e){return i.isPromise(e.error)}))throw Error(`Use validate.async if you want support for promises`);return r.processValidationResults(a,n)},i=r;i.extend=function(e){return[].slice.call(arguments,1).forEach(function(t){for(var n in t)e[n]=t[n]}),e},i.extend(r,{version:{major:0,minor:13,patch:1,metadata:null,toString:function(){var e=i.format(`%{major}.%{minor}.%{patch}`,i.version);return i.isEmpty(i.version.metadata)||(e+=`+`+i.version.metadata),e}},Promise:typeof Promise<`u`?Promise:null,EMPTY_STRING_REGEXP:/^\s*$/,runValidations:function(e,t,n){var r=[],a,o,s,c,l,u,d;for(a in(i.isDomElement(e)||i.isJqueryElement(e))&&(e=i.collectFormValues(e)),t)for(o in s=i.getDeepObjectValue(e,a),c=i.result(t[a],s,e,a,n,t),c){if(l=i.validators[o],!l)throw d=i.format(`Unknown validator %{name}`,{name:o}),Error(d);u=c[o],u=i.result(u,s,e,a,n,t),u&&r.push({attribute:a,value:s,validator:o,globalOptions:n,attributes:e,options:u,error:l.call(l,s,u,a,e,n)})}return r},processValidationResults:function(e,t){e=i.pruneEmptyErrors(e,t),e=i.expandMultipleErrors(e,t),e=i.convertErrorMessages(e,t);var n=t.format||`grouped`;if(typeof i.formatters[n]==`function`)e=i.formatters[n](e);else throw Error(i.format(`Unknown format %{format}`,t));return i.isEmpty(e)?void 0:e},async:function(e,t,n){n=i.extend({},i.async.options,n);var r=n.wrapErrors||function(e){return e};n.cleanAttributes!==!1&&(e=i.cleanAttributes(e,t));var a=i.runValidations(e,t,n);return new i.Promise(function(o,s){i.waitForResults(a).then(function(){var c=i.processValidationResults(a,n);c?s(new r(c,n,e,t)):o(e)},function(e){s(e)})})},single:function(e,t,n){return n=i.extend({},i.single.options,n,{format:`flat`,fullMessages:!1}),i({single:e},{single:t},n)},waitForResults:function(e){return e.reduce(function(e,t){return i.isPromise(t.error)?e.then(function(){return t.error.then(function(e){t.error=e||null})}):e},new i.Promise(function(e){e()}))},result:function(e){var t=[].slice.call(arguments,1);return typeof e==`function`&&(e=e.apply(null,t)),e},isNumber:function(e){return typeof e==`number`&&!isNaN(e)},isFunction:function(e){return typeof e==`function`},isInteger:function(e){return i.isNumber(e)&&e%1==0},isBoolean:function(e){return typeof e==`boolean`},isObject:function(e){return e===Object(e)},isDate:function(e){return e instanceof Date},isDefined:function(e){return e!=null},isPromise:function(e){return!!e&&i.isFunction(e.then)},isJqueryElement:function(e){return e&&i.isString(e.jquery)},isDomElement:function(e){return!e||!e.querySelectorAll||!e.querySelector?!1:i.isObject(document)&&e===document?!0:typeof HTMLElement==`object`?e instanceof HTMLElement:e&&typeof e==`object`&&!!e&&e.nodeType===1&&typeof e.nodeName==`string`},isEmpty:function(e){var t;if(!i.isDefined(e))return!0;if(i.isFunction(e))return!1;if(i.isString(e))return i.EMPTY_STRING_REGEXP.test(e);if(i.isArray(e))return e.length===0;if(i.isDate(e))return!1;if(i.isObject(e)){for(t in e)return!1;return!0}return!1},format:i.extend(function(e,t){return i.isString(e)?e.replace(i.format.FORMAT_REGEXP,function(e,n,r){return n===`%`?`%{`+r+`}`:String(t[r])}):e},{FORMAT_REGEXP:/(%?)%\{([^\}]+)\}/g}),prettify:function(e){return i.isNumber(e)?e*100%1==0?``+e:parseFloat(Math.round(e*100)/100).toFixed(2):i.isArray(e)?e.map(function(e){return i.prettify(e)}).join(`, `):i.isObject(e)?i.isDefined(e.toString)?e.toString():JSON.stringify(e):(e=``+e,e.replace(/([^\s])\.([^\s])/g,`$1 $2`).replace(/\\+/g,``).replace(/[_-]/g,` `).replace(/([a-z])([A-Z])/g,function(e,t,n){return``+t+` `+n.toLowerCase()}).toLowerCase())},stringifyValue:function(e,t){return(t&&t.prettify||i.prettify)(e)},isString:function(e){return typeof e==`string`},isArray:function(e){return{}.toString.call(e)===`[object Array]`},isHash:function(e){return i.isObject(e)&&!i.isArray(e)&&!i.isFunction(e)},contains:function(e,t){return i.isDefined(e)?i.isArray(e)?e.indexOf(t)!==-1:t in e:!1},unique:function(e){return i.isArray(e)?e.filter(function(e,t,n){return n.indexOf(e)==t}):e},forEachKeyInKeypath:function(e,t,n){if(i.isString(t)){var r=``,a,o=!1;for(a=0;a<t.length;++a)switch(t[a]){case`.`:o?(o=!1,r+=`.`):(e=n(e,r,!1),r=``);break;case`\\`:o?(o=!1,r+=`\\`):o=!0;break;default:o=!1,r+=t[a]}return n(e,r,!0)}},getDeepObjectValue:function(e,t){if(i.isObject(e))return i.forEachKeyInKeypath(e,t,function(e,t){if(i.isObject(e))return e[t]})},collectFormValues:function(e,t){var n={},r,a,o,s,c,l;if(i.isJqueryElement(e)&&(e=e[0]),!e)return n;for(t||={},s=e.querySelectorAll(`input[name], textarea[name]`),r=0;r<s.length;++r)if(o=s.item(r),!i.isDefined(o.getAttribute(`data-ignored`))){var u=o.name.replace(/\./g,`\\\\.`);l=i.sanitizeFormValue(o.value,t),o.type===`number`?l=l?+l:null:o.type===`checkbox`?o.attributes.value?o.checked||(l=n[u]||null):l=o.checked:o.type===`radio`&&(o.checked||(l=n[u]||null)),n[u]=l}for(s=e.querySelectorAll(`select[name]`),r=0;r<s.length;++r)if(o=s.item(r),!i.isDefined(o.getAttribute(`data-ignored`))){if(o.multiple)for(a in l=[],o.options)c=o.options[a],c&&c.selected&&l.push(i.sanitizeFormValue(c.value,t));else{var d=o.options[o.selectedIndex]===void 0?``:o.options[o.selectedIndex].value;l=i.sanitizeFormValue(d,t)}n[o.name]=l}return n},sanitizeFormValue:function(e,t){return t.trim&&i.isString(e)&&(e=e.trim()),t.nullify!==!1&&e===``?null:e},capitalize:function(e){return i.isString(e)?e[0].toUpperCase()+e.slice(1):e},pruneEmptyErrors:function(e){return e.filter(function(e){return!i.isEmpty(e.error)})},expandMultipleErrors:function(e){var t=[];return e.forEach(function(e){i.isArray(e.error)?e.error.forEach(function(n){t.push(i.extend({},e,{error:n}))}):t.push(e)}),t},convertErrorMessages:function(e,t){t||={};var n=[],r=t.prettify||i.prettify;return e.forEach(function(e){var a=i.result(e.error,e.value,e.attribute,e.options,e.attributes,e.globalOptions);if(!i.isString(a)){n.push(e);return}a[0]===`^`?a=a.slice(1):t.fullMessages!==!1&&(a=i.capitalize(r(e.attribute))+` `+a),a=a.replace(/\\\^/g,`^`),a=i.format(a,{value:i.stringifyValue(e.value,t)}),n.push(i.extend({},e,{error:a}))}),n},groupErrorsByAttribute:function(e){var t={};return e.forEach(function(e){var n=t[e.attribute];n?n.push(e):t[e.attribute]=[e]}),t},flattenErrorsToArray:function(e){return e.map(function(e){return e.error}).filter(function(e,t,n){return n.indexOf(e)===t})},cleanAttributes:function(e,t){function n(e,t,n){return i.isObject(e[t])?e[t]:e[t]=n?!0:{}}function r(e){var t={},r;for(r in e)e[r]&&i.forEachKeyInKeypath(t,r,n);return t}function a(e,t){if(!i.isObject(e))return e;var n=i.extend({},e),r,o;for(o in e)r=t[o],i.isObject(r)?n[o]=a(n[o],r):r||delete n[o];return n}return!i.isObject(t)||!i.isObject(e)?{}:(t=r(t),a(e,t))},exposeModule:function(e,t,n,r,i){n?(r&&r.exports&&(n=r.exports=e),n.validate=e):(t.validate=e,e.isFunction(i)&&i.amd&&i([],function(){return e}))},warn:function(e){typeof console<`u`&&console.warn&&console.warn(`[validate.js] `+e)},error:function(e){typeof console<`u`&&console.error&&console.error(`[validate.js] `+e)}}),r.validators={presence:function(e,t){if(t=i.extend({},this.options,t),t.allowEmpty===!1?i.isEmpty(e):!i.isDefined(e))return t.message||this.message||`can't be blank`},length:function(e,t,n){if(i.isDefined(e)){t=i.extend({},this.options,t);var r=t.is,a=t.maximum,o=t.minimum,s=t.tokenizer||function(e){return e},c,l=[];e=s(e);var u=e.length;if(!i.isNumber(u))return t.message||this.notValid||`has an incorrect length`;if(i.isNumber(r)&&u!==r&&(c=t.wrongLength||this.wrongLength||`is the wrong length (should be %{count} characters)`,l.push(i.format(c,{count:r}))),i.isNumber(o)&&u<o&&(c=t.tooShort||this.tooShort||`is too short (minimum is %{count} characters)`,l.push(i.format(c,{count:o}))),i.isNumber(a)&&u>a&&(c=t.tooLong||this.tooLong||`is too long (maximum is %{count} characters)`,l.push(i.format(c,{count:a}))),l.length>0)return t.message||l}},numericality:function(e,t,n,r,a){if(i.isDefined(e)){t=i.extend({},this.options,t);var o=[],s,c,l={greaterThan:function(e,t){return e>t},greaterThanOrEqualTo:function(e,t){return e>=t},equalTo:function(e,t){return e===t},lessThan:function(e,t){return e<t},lessThanOrEqualTo:function(e,t){return e<=t},divisibleBy:function(e,t){return e%t===0}},u=t.prettify||a&&a.prettify||i.prettify;if(i.isString(e)&&t.strict){var d=`^-?(0|[1-9]\\d*)`;if(t.onlyInteger||(d+=`(\\.\\d+)?`),d+=`$`,!new RegExp(d).test(e))return t.message||t.notValid||this.notValid||this.message||`must be a valid number`}if(t.noStrings!==!0&&i.isString(e)&&!i.isEmpty(e)&&(e=+e),!i.isNumber(e))return t.message||t.notValid||this.notValid||this.message||`is not a number`;if(t.onlyInteger&&!i.isInteger(e))return t.message||t.notInteger||this.notInteger||this.message||`must be an integer`;for(s in l)if(c=t[s],i.isNumber(c)&&!l[s](e,c)){var f=`not`+i.capitalize(s),p=t[f]||this[f]||this.message||`must be %{type} %{count}`;o.push(i.format(p,{count:c,type:u(s)}))}if(t.odd&&e%2!=1&&o.push(t.notOdd||this.notOdd||this.message||`must be odd`),t.even&&e%2!=0&&o.push(t.notEven||this.notEven||this.message||`must be even`),o.length)return t.message||o}},datetime:i.extend(function(e,t){if(!i.isFunction(this.parse)||!i.isFunction(this.format))throw Error(`Both the parse and format functions needs to be set to use the datetime/date validator`);if(i.isDefined(e)){t=i.extend({},this.options,t);var n,r=[],a=t.earliest?this.parse(t.earliest,t):NaN,o=t.latest?this.parse(t.latest,t):NaN;if(e=this.parse(e,t),isNaN(e)||t.dateOnly&&e%864e5!=0)return n=t.notValid||t.message||this.notValid||`must be a valid date`,i.format(n,{value:arguments[0]});if(!isNaN(a)&&e<a&&(n=t.tooEarly||t.message||this.tooEarly||`must be no earlier than %{date}`,n=i.format(n,{value:this.format(e,t),date:this.format(a,t)}),r.push(n)),!isNaN(o)&&e>o&&(n=t.tooLate||t.message||this.tooLate||`must be no later than %{date}`,n=i.format(n,{date:this.format(o,t),value:this.format(e,t)}),r.push(n)),r.length)return i.unique(r)}},{parse:null,format:null}),date:function(e,t){return t=i.extend({},t,{dateOnly:!0}),i.validators.datetime.call(i.validators.datetime,e,t)},format:function(e,t){(i.isString(t)||t instanceof RegExp)&&(t={pattern:t}),t=i.extend({},this.options,t);var n=t.message||this.message||`is invalid`,r=t.pattern,a;if(i.isDefined(e)&&(!i.isString(e)||(i.isString(r)&&(r=new RegExp(t.pattern,t.flags)),a=r.exec(e),!a||a[0].length!=e.length)))return n},inclusion:function(e,t){if(i.isDefined(e)&&(i.isArray(t)&&(t={within:t}),t=i.extend({},this.options,t),!i.contains(t.within,e))){var n=t.message||this.message||`^%{value} is not included in the list`;return i.format(n,{value:e})}},exclusion:function(e,t){if(i.isDefined(e)&&(i.isArray(t)&&(t={within:t}),t=i.extend({},this.options,t),i.contains(t.within,e))){var n=t.message||this.message||`^%{value} is restricted`;return i.isString(t.within[e])&&(e=t.within[e]),i.format(n,{value:e})}},email:i.extend(function(e,t){t=i.extend({},this.options,t);var n=t.message||this.message||`is not a valid email`;if(i.isDefined(e)&&(!i.isString(e)||!this.PATTERN.exec(e)))return n},{PATTERN:/^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i}),equality:function(e,t,n,r,a){if(i.isDefined(e)){i.isString(t)&&(t={attribute:t}),t=i.extend({},this.options,t);var o=t.message||this.message||`is not equal to %{attribute}`;if(i.isEmpty(t.attribute)||!i.isString(t.attribute))throw Error(`The attribute must be a non empty string`);var s=i.getDeepObjectValue(r,t.attribute),c=t.comparator||function(e,t){return e===t},l=t.prettify||a&&a.prettify||i.prettify;if(!c(e,s,t,n,r))return i.format(o,{attribute:l(t.attribute)})}},url:function(e,t){if(i.isDefined(e)){t=i.extend({},this.options,t);var n=t.message||this.message||`is not a valid url`,r=t.schemes||this.schemes||[`http`,`https`],a=t.allowLocal||this.allowLocal||!1,o=t.allowDataUrl||this.allowDataUrl||!1;if(!i.isString(e))return n;var s=`^(?:(?:`+r.join(`|`)+`)://)(?:\\S+(?::\\S*)?@)?(?:`,c=`(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))`;if(a?c+=`?`:s+=`(?!(?:10|127)(?:\\.\\d{1,3}){3})(?!(?:169\\.254|192\\.168)(?:\\.\\d{1,3}){2})(?!172\\.(?:1[6-9]|2\\d|3[0-1])(?:\\.\\d{1,3}){2})`,s+=`(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*`+c+`)(?::\\d{2,5})?(?:[/?#]\\S*)?$`,o&&(s=`(?:`+s+`)|(?:^data:(?:\\w+\\/[-+.\\w]+(?:;[\\w=]+)*)?(?:;base64)?,[A-Za-z0-9-_.!~\\*'();\\/?:@&=+$,%]*$)`),!new RegExp(s,`i`).exec(e))return n}},type:i.extend(function(e,t,n,r,a){if(i.isString(t)&&(t={type:t}),i.isDefined(e)){var o=i.extend({},this.options,t),s=o.type;if(!i.isDefined(s))throw Error(`No type was specified`);var c=i.isFunction(s)?s:this.types[s];if(!i.isFunction(c))throw Error(`validate.validators.type.types.`+s+` must be a function.`);if(!c(e,o,n,r,a)){var l=t.message||this.messages[s]||this.message||o.message||(i.isFunction(s)?`must be of the correct type`:`must be of type %{type}`);return i.isFunction(l)&&(l=l(e,t,n,r,a)),i.format(l,{attribute:i.prettify(n),type:s})}}},{types:{object:function(e){return i.isObject(e)&&!i.isArray(e)},array:i.isArray,integer:i.isInteger,number:i.isNumber,string:i.isString,date:i.isDate,boolean:i.isBoolean},messages:{}})},r.formatters={detailed:function(e){return e},flat:i.flattenErrorsToArray,grouped:function(e){for(var t in e=i.groupErrorsByAttribute(e),e)e[t]=i.flattenErrorsToArray(e[t]);return e},constraint:function(e){for(var t in e=i.groupErrorsByAttribute(e),e)e[t]=e[t].map(function(e){return e.validator}).sort();return e}},r.exposeModule(r,this,e,t,n)}).call(e,e===void 0?null:e,t===void 0?null:t,typeof define<`u`?define:null)}))(),1);Bm.default.validators.bigNumericality=(e,t,n,r)=>Bm.default.validators.numericality(e&&e.toNumber(),t,r);var Vm=Bm.default,Hm=c({BalanceLimit:()=>Xm,ExchangeFeatures:()=>Wm,IpWhiteList:()=>Gm,MarginType:()=>Km,OrderSide:()=>Jm,OrderStatus:()=>qm,OrderType:()=>Um,TimeInForce:()=>Ym}),Um=function(e){return e.MARKET=`MARKET`,e.LIMIT=`LIMIT`,e.LIMIT_LADDER=`LIMIT_LADDER`,e.STOP_LOSS=`STOP_LOSS`,e.OCO=`OCO`,e.STOP_LOSS_LIMIT=`STOP_LOSS_LIMIT`,e.STOP_LOSS_MARKET=`STOP_LOSS_MARKET`,e.TAKE_PROFIT=`TAKE_PROFIT`,e.TAKE_PROFIT_LIMIT=`TAKE_PROFIT_LIMIT`,e.TAKE_PROFIT_MARKET=`TAKE_PROFIT_MARKET`,e}({}),Wm=function(e){return e.HEDGE_MODE=`hedgeMode`,e.HEDGE_MODE_ONLY=`hedgeModeOnly`,e.ORDER_QUOTE_AMOUNT=`orderQuoteAmount`,e.MARKET_BUY_QUOTE_ONLY=`marketBuyQuoteOnly`,e.UPDATE_LEVERAGE_ONLY_ON_OPEN_POSITIONS=`updateLeverageOnlyOnOpenPositions`,e.IGNORE_LEVERAGE_ON_QUICK_SYNC=`ignoreLeverageOnQuickSync`,e.MULTIPLE_MARGIN_TYPE_POSITIONS=`multipleMarginTypePositions`,e.SET_LEVERAGE_NOT_AVAILABLE=`setLeverageNotAvailable`,e.SET_MARGIN_TYPE_NOT_AVAILABLE=`setMarginTypeNotAvailable`,e.FIXED_CROSSED_LEVERAGE=`fixedCrossedLeverage`,e.FAST_CONNECT=`fastConnect`,e.UNIFIED_BALANCE=`unifiedBalance`,e.NO_API_KEY_LINK=`noApiKeyLink`,e}({}),Gm=function(e){return e.NONE=`NONE`,e.LIST=`LIST`,e.COMMA=`COMMA`,e.COMMA_SPACE=`COMMA_SPACE`,e.SPACE=`SPACE`,e}({}),Km=function(e){return e.CROSSED=`CROSSED`,e.ISOLATED=`ISOLATED`,e}({}),qm=function(e){return e.OPEN=`open`,e.CLOSED=`closed`,e.CANCELED=`canceled`,e}({}),Jm=function(e){return e.BUY=`buy`,e.SELL=`sell`,e}({}),Ym=function(e){return e.GTC=`gtc`,e.FOK=`fok`,e.IOC=`ioc`,e}({}),Xm=function(e){return e.QUOTE=`quote`,e.BASE=`base`,e.NONE=`none`,e}({}),Zm=[];for(let e=0;e<256;++e)Zm.push((e+256).toString(16).slice(1));function Qm(e,t=0){return(Zm[e[t+0]]+Zm[e[t+1]]+Zm[e[t+2]]+Zm[e[t+3]]+`-`+Zm[e[t+4]]+Zm[e[t+5]]+`-`+Zm[e[t+6]]+Zm[e[t+7]]+`-`+Zm[e[t+8]]+Zm[e[t+9]]+`-`+Zm[e[t+10]]+Zm[e[t+11]]+Zm[e[t+12]]+Zm[e[t+13]]+Zm[e[t+14]]+Zm[e[t+15]]).toLowerCase()}var $m=new Uint8Array(16);function eh(){return crypto.getRandomValues($m)}function th(e,t,n){return!t&&!e&&crypto.randomUUID?crypto.randomUUID():nh(e,t,n)}function nh(e,t,n){e||={};let r=e.random??e.rng?.()??eh();if(r.length<16)throw Error(`Random bytes length must be >= 16`);if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){if(n||=0,n<0||n+16>t.length)throw RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let e=0;e<16;++e)t[n+e]=r[e];return t}return Qm(r)}var rh=class{id=th();coinraySymbol;precisionBase;precisionQuote;precisionPrice;minBase;minQuote;makerFee;takerFee;balances;balanceLimit;side;errors;isValid;orderExternalId;reduceOnly;postOnly;timeInForce;constructor(e){this.coinraySymbol=e.coinraySymbol,this.precisionBase=Hp(e.precisionBase),this.precisionQuote=Hp(e.precisionQuote),this.precisionPrice=Hp(e.precisionPrice),this.minBase=$(e.minBase),this.minQuote=$(e.minQuote),this.makerFee=$(e.makerFee),this.takerFee=$(e.takerFee),this.balances=e.balances,this.balanceLimit=e.balanceLimit||Xm.NONE,this.side=e.side,this.orderExternalId=e.externalId,this.errors={},this.isValid=!0,this.reduceOnly=e.reduceOnly,this.postOnly=e.postOnly,this.timeInForce=e.timeInForce}startEdit(e){this.orderExternalId=e}updateLockedOn(e){}resetError(){this.errors={},this.isValid=!0}validate(){let e=Vm(this,this.constraints());return e?(this.errors=e,this.isValid=!1):this.resetError(),!e}},ih=class extends rh{baseAmount;quoteAmount;price;lockedOn;orderType=Um.LIMIT;constraints(){let e,t;return this.balanceLimit===Xm.QUOTE?t=this.balances.quote||0:this.balanceLimit===Xm.BASE&&(e=this.balances.base||0),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:this.minBase.toNumber(),notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:this.minQuote.toNumber(),notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}},price:{bigNumericality:{greaterThan:0}}}}constructor(e,t=!0){super(e),this.price=$(e.price||`0`),this.lockedOn=e.lockedOn,this.baseAmount=$(e.baseAmount),this.quoteAmount=$(e.quoteAmount),t&&(this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount))}updateBaseAmount(e){this.baseAmount=e,this.quoteAmount=this.price.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,this.baseAmount=e.dividedBy(this.price).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN),this.validate()}updateLockedOn(e){this.lockedOn=e,this.validate()}quoteFee(){return this.quoteAmount.multipliedBy(this.takerFee)}updatePrice(e){this.price=e.decimalPlaces(this.precisionPrice),this.lockedOn===`baseAmount`?this.updateBaseAmount(this.baseAmount):this.updateQuoteAmount(this.quoteAmount)}getOrders(){return[this]}},ah=class extends rh{baseAmount;quoteAmount;price;orderType=Um.MARKET;constraints=()=>{let e,t;return this.balanceLimit===Xm.QUOTE?t=this.balances.quote||0:this.balanceLimit===Xm.BASE&&(e=this.balances.base||0),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:e?this.minBase.toNumber():void 0,notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:t?this.minQuote.toNumber():void 0,notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}}}};constructor(e){super(e),this.updateQuoteAmount(e.quoteAmount),this.updateBaseAmount(e.baseAmount)}updateBaseAmount(e){this.baseAmount=e,e&&(this.quoteAmount=this.price.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN)),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,e&&(this.baseAmount=e.dividedBy(this.price).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN)),this.validate()}updatePrice(e){this.price=e.decimalPlaces(this.precisionPrice)}getOrders(){return[this]}},oh=function(e){return e.LINEAR=`LINEAR`,e.EXPONENTIAL=`EXPONENTIAL`,e.FIBONACCI=`FIBONACCI`,e.CUSTOM=`CUSTOM`,e}({}),sh=function(e){return e.EQUAL=`EQUAL`,e.LINEAR=`LINEAR`,e.LINEAR_REVERSE=`LINEAR_REVERSE`,e.EXPONENTIAL=`EXPONENTIAL`,e.EXPONENTIAL_REVERSE=`EXPONENTIAL_REVERSE`,e.CUSTOM=`CUSTOM`,e}({}),ch={[oh.LINEAR]:e=>L.default.times(e,t=>1/(e-1)*t),[oh.EXPONENTIAL]:e=>{let t=2**(e-1);return L.default.times(e,e=>e==0?0:2**e/t)},[oh.FIBONACCI]:e=>[0,.09,.146,.236,.382,.5,.618,.788,.886].slice(0,e-1).concat([1]),[oh.CUSTOM]:e=>[]},lh=e=>{let t=L.default.sum(e);return e.map(e=>e/t)},uh={[sh.EQUAL]:e=>lh(L.default.times(e,()=>1)),[sh.LINEAR]:e=>lh(L.default.times(e,t=>1/e*(t+1))),[sh.EXPONENTIAL]:e=>{let t=2**e-1;return lh(L.default.times(e,e=>2**e/t))},[sh.LINEAR_REVERSE]:e=>uh[sh.LINEAR](e).reverse(),[sh.EXPONENTIAL_REVERSE]:e=>uh[sh.EXPONENTIAL](e).reverse(),[sh.CUSTOM]:e=>[]},dh=class extends rh{baseAmount;quoteAmount;price;lockedOn;otherPrice;numOrders;priceScale;sizeScale;priceScales;sizeScales;orderType=Um.LIMIT_LADDER;constraints(){let e,t;return this.balanceLimit===Xm.QUOTE?t=this.balances.quote:this.balanceLimit===Xm.BASE&&(e=this.balances.base),{baseAmount:{bigNumericality:{greaterThanOrEqualTo:this.minBase.toNumber(),notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionBase,this.minBase)})}`,lessThanOrEqualTo:e?e.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}},quoteAmount:{bigNumericality:{greaterThanOrEqualTo:this.minQuote.toNumber(),notGreaterThanOrEqualTo:`^${Sm.I18n.t(`validation.notGreaterThanOrEqualTo`,{min:Bp(this.precisionQuote,this.minQuote)})}`,lessThanOrEqualTo:t?t.toNumber():void 0,notLessThanOrEqualTo:`^${Sm.I18n.t(`validation.insufficientFunds`)}`}},price:{bigNumericality:{greaterThan:0}},otherPrice:{bigNumericality:{greaterThan:0}},numOrders:{numericality:{greaterThanOrEqualTo:2}}}}constructor(e){super(e),this.otherPrice=$(e.otherPrice),this.numOrders=Hp(e.numOrders),this.priceScale=e.priceScale||oh.CUSTOM,this.sizeScale=e.sizeScale||sh.CUSTOM,this.price=$(e.price||`0`),this.lockedOn=e.lockedOn,this.baseAmount=$(e.baseAmount||`0`),this.quoteAmount=$(e.quoteAmount||`0`),this.priceScales=e.priceScales||ch[this.priceScale](this.numOrders),this.sizeScales=e.sizeScales||uh[this.sizeScale](this.numOrders),this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount)}updateNumOrders(e){this.numOrders=e}updatePrice(e,t=.05){if(this.price=e.decimalPlaces(this.precisionPrice),e&&this.otherPrice.eq(0)){let n=this.side===Jm.BUY?1+t:1-t;this.otherPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}this.recalculate()}updateOtherPrice(e,t=.05){if(this.otherPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===Jm.BUY?1-t:1+t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}this.recalculate()}updatePriceScales(e){this.priceScales=e,this.priceScale=oh.CUSTOM,this.recalculate()}updatePriceScale(e){this.priceScales=ch[e](this.numOrders),this.priceScale=e,this.recalculate()}updateSizeScales(e){this.sizeScales=e,this.sizeScale=sh.CUSTOM,this.recalculate()}updateSizeScale(e){this.sizeScales=uh[e](this.numOrders),this.sizeScale=e,this.recalculate()}updateLockedOn(e){this.lockedOn=e}recalculate(){this.lockedOn===`baseAmount`?this.updateBaseAmount(this.baseAmount):this.updateQuoteAmount(this.quoteAmount),this.validate()}updateQuoteAmount(e){this.quoteAmount=e,this.numOrders=Math.max(2,+this.numOrders);let t=this.getOrders(`quoteAmount`);this.baseAmount=t.length>0?L.default.reduce(t,(e,t)=>e.plus(t.baseAmount),new d(0)):new d(0)}updateBaseAmount(e){this.baseAmount=e,this.numOrders=Math.max(2,+this.numOrders);let t=this.getOrders(`baseAmount`);this.quoteAmount=t.length>0?L.default.reduce(t,(e,t)=>e.plus(t.quoteAmount),new d(0)):new d(0)}getOrders(e=this.lockedOn){let t=e===`baseAmount`?this.baseAmount:this.quoteAmount,n=e===`baseAmount`?this.precisionBase:this.precisionQuote;if(!(this.priceScales&&this.priceScales.length>0&&this.sizeScales.length>0&&t.gt(0)))return[];let r=this.priceScales.slice(0,this.numOrders),i=this.sizeScales.slice(0,this.numOrders),a=this.otherPrice.minus(this.price),o=t;return L.default.times(this.numOrders,s=>{let c=t.multipliedBy(i[s]).decimalPlaces(n>0?n:0,d.ROUND_DOWN);return o=o.minus(c),s===this.numOrders-1&&(c=c.plus(o)),new ih({...this,[e]:c,lockedOn:e,price:this.price.plus(a.multipliedBy(r[s])).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)})})}},fh=class extends ih{stopPrice;orderType=Um.STOP_LOSS_LIMIT;constraints(){return{...super.constraints(),stopPrice:{bigNumericality:{greaterThan:0}}}}constructor(e){super(e),this.stopPrice=$(e.stopPrice)}updatePrice(e,t=.05){if(super.updatePrice(e),e&&this.stopPrice.eq(0)){let n=this.side===Jm.BUY?1-t:1+t;this.stopPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateStopPrice(e,t=.05){if(this.stopPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===Jm.BUY?1+t:1-t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}},ph=class extends ih{linkedOrderId;otherPrice;stopPrice;orderType=Um.OCO;constraints(){return{...super.constraints(),otherPrice:{bigNumericality:{greaterThan:0}},stopPrice:{bigNumericality:{greaterThan:0}}}}constructor(e){super(e,!1),this.otherPrice=$(e.otherPrice),this.stopPrice=$(e.stopPrice),this.quoteAmount.gt(0)&&this.lockedOn===`quoteAmount`?this.updateQuoteAmount(this.quoteAmount):this.updateBaseAmount(this.baseAmount)}updateQuoteAmount(e){this.quoteAmount=e;let t=this.side===Jm.BUY?this.otherPrice:this.price;this.baseAmount=e.dividedBy(t).decimalPlaces(this.precisionBase>0?this.precisionBase:0,d.ROUND_DOWN),this.validate()}updateBaseAmount(e){this.baseAmount=e;let t=this.side===Jm.BUY?this.otherPrice:this.price;this.quoteAmount=t.multipliedBy(this.baseAmount).decimalPlaces(this.precisionQuote>0?this.precisionQuote:0,d.ROUND_DOWN),this.validate()}updatePrice(e,t=.05){if(super.updatePrice(e),e&&this.otherPrice.eq(0)){let n=this.side===Jm.BUY?1+t*2:1-t*2,r=this.side===Jm.BUY?1+t:1-t;this.otherPrice=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.stopPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateOtherPrice(e,t=.05){if(this.otherPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===Jm.BUY?1-t*2:1+t*2,r=this.side===Jm.BUY?1-t:1+t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.stopPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}updateStopPrice(e,t=.05){if(this.stopPrice=e.decimalPlaces(this.precisionPrice),e&&this.price.eq(0)){let n=this.side===Jm.BUY?1-t:1+t,r=this.side===Jm.BUY?1+t:1-t;this.price=e.multipliedBy(n).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0),this.otherPrice=e.multipliedBy(r).decimalPlaces(this.precisionPrice>0?this.precisionPrice:0)}}};d.set({STRICT:!1});var mh=Sm;return e.BalanceLimit=Xm,e.CoinrayCache=Im,e.CurrentMarket=Rm,e.DAYS=_p,e.ExchangeFeatures=Wm,e.FormulaMarket=Dm,e.HOURS=gp,e.IpWhiteList=Gm,e.LimitLadderOrder=dh,e.LimitOrder=ih,e.MINUTES=hp,e.MarginType=Km,e.MarketOrder=ah,e.OcoOrder=ph,e.OrderSide=Jm,e.OrderStatus=qm,e.OrderType=Um,e.PriceScales=oh,e.SizeScales=sh,e.StopLimitOrder=fh,e.TimeInForce=Ym,e.WEEK=vp,e.alignCandles=pm,e.base64UrlDecode=Sp,e.base64UrlEncode=xp,e.camelize=kp,e.candleTime=Zp,e.checkArray=Pp,e.checkBigNumber=Ip,e.checkBoolean=Lp,e.checkNull=Rp,e.checkNumber=Fp,e.checkString=Q,e.combineCandles=fm,e.correctNumberPrecision=Bp,e.createJWT=Tp,e.default=mh,e.encryptPayload=Op,e.errorHelper=zp,e.evalFormula=um,e.filterMarkets=Qp,e.formulaCandles=mm,e.formulaLegs=lm,e.formulaPrecision=gm,e.formulaSymbolInfo=_m,e.getBucketStartDates=Xp,e.getTimeParams=Yp,e.isFormula=om,e.jwkToPublicKey=Dp,e.jwtExpired=Ap,e.latestFormulaCandle=hm,e.locales=zm,e.parseFormula=cm,e.parseJWT=Ep,e.resolutionToBucketType=Jp,e.resolutionToDuration=Wp,e.safeBigNumber=$,e.safeFloat=Vp,e.safeInteger=Hp,e.safeTime=Up,e.sha256hexdigest=Cp,e.signHMAC=wp,e.strToArray=bp,e.throwIsArray=Np,e.throwNotObject=Mp,e.throwNull2NonNull=jp,e.toBucketEnd=Kp,e.toBucketStart=qp,e.toSafeDate=Gp,Object.defineProperty(e,"types",{enumerable:!0,get:function(){return Hm}}),e.unix=yp,e})({});
|
|
35
35
|
//# sourceMappingURL=coinrayjs.js.map
|